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 /// Vector of declare variant construct traits. 314 SmallVector<llvm::omp::TraitProperty, 8> ConstructTraits; 315 316 public: 317 explicit DSAStackTy(Sema &S) : SemaRef(S) {} 318 319 /// Sets omp_allocator_handle_t type. 320 void setOMPAllocatorHandleT(QualType Ty) { OMPAllocatorHandleT = Ty; } 321 /// Gets omp_allocator_handle_t type. 322 QualType getOMPAllocatorHandleT() const { return OMPAllocatorHandleT; } 323 /// Sets omp_alloctrait_t type. 324 void setOMPAlloctraitT(QualType Ty) { OMPAlloctraitT = Ty; } 325 /// Gets omp_alloctrait_t type. 326 QualType getOMPAlloctraitT() const { return OMPAlloctraitT; } 327 /// Sets the given default allocator. 328 void setAllocator(OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind, 329 Expr *Allocator) { 330 OMPPredefinedAllocators[AllocatorKind] = Allocator; 331 } 332 /// Returns the specified default allocator. 333 Expr *getAllocator(OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind) const { 334 return OMPPredefinedAllocators[AllocatorKind]; 335 } 336 /// Sets omp_depend_t type. 337 void setOMPDependT(QualType Ty) { OMPDependT = Ty; } 338 /// Gets omp_depend_t type. 339 QualType getOMPDependT() const { return OMPDependT; } 340 341 /// Sets omp_event_handle_t type. 342 void setOMPEventHandleT(QualType Ty) { OMPEventHandleT = Ty; } 343 /// Gets omp_event_handle_t type. 344 QualType getOMPEventHandleT() const { return OMPEventHandleT; } 345 346 bool isClauseParsingMode() const { return ClauseKindMode != OMPC_unknown; } 347 OpenMPClauseKind getClauseParsingMode() const { 348 assert(isClauseParsingMode() && "Must be in clause parsing mode."); 349 return ClauseKindMode; 350 } 351 void setClauseParsingMode(OpenMPClauseKind K) { ClauseKindMode = K; } 352 353 bool isBodyComplete() const { 354 const SharingMapTy *Top = getTopOfStackOrNull(); 355 return Top && Top->BodyComplete; 356 } 357 void setBodyComplete() { 358 getTopOfStack().BodyComplete = true; 359 } 360 361 bool isForceVarCapturing() const { return ForceCapturing; } 362 void setForceVarCapturing(bool V) { ForceCapturing = V; } 363 364 void setForceCaptureByReferenceInTargetExecutable(bool V) { 365 ForceCaptureByReferenceInTargetExecutable = V; 366 } 367 bool isForceCaptureByReferenceInTargetExecutable() const { 368 return ForceCaptureByReferenceInTargetExecutable; 369 } 370 371 void push(OpenMPDirectiveKind DKind, const DeclarationNameInfo &DirName, 372 Scope *CurScope, SourceLocation Loc) { 373 assert(!IgnoredStackElements && 374 "cannot change stack while ignoring elements"); 375 if (Stack.empty() || 376 Stack.back().second != CurrentNonCapturingFunctionScope) 377 Stack.emplace_back(StackTy(), CurrentNonCapturingFunctionScope); 378 Stack.back().first.emplace_back(DKind, DirName, CurScope, Loc); 379 Stack.back().first.back().DefaultAttrLoc = Loc; 380 } 381 382 void pop() { 383 assert(!IgnoredStackElements && 384 "cannot change stack while ignoring elements"); 385 assert(!Stack.back().first.empty() && 386 "Data-sharing attributes stack is empty!"); 387 Stack.back().first.pop_back(); 388 } 389 390 /// RAII object to temporarily leave the scope of a directive when we want to 391 /// logically operate in its parent. 392 class ParentDirectiveScope { 393 DSAStackTy &Self; 394 bool Active; 395 public: 396 ParentDirectiveScope(DSAStackTy &Self, bool Activate) 397 : Self(Self), Active(false) { 398 if (Activate) 399 enable(); 400 } 401 ~ParentDirectiveScope() { disable(); } 402 void disable() { 403 if (Active) { 404 --Self.IgnoredStackElements; 405 Active = false; 406 } 407 } 408 void enable() { 409 if (!Active) { 410 ++Self.IgnoredStackElements; 411 Active = true; 412 } 413 } 414 }; 415 416 /// Marks that we're started loop parsing. 417 void loopInit() { 418 assert(isOpenMPLoopDirective(getCurrentDirective()) && 419 "Expected loop-based directive."); 420 getTopOfStack().LoopStart = true; 421 } 422 /// Start capturing of the variables in the loop context. 423 void loopStart() { 424 assert(isOpenMPLoopDirective(getCurrentDirective()) && 425 "Expected loop-based directive."); 426 getTopOfStack().LoopStart = false; 427 } 428 /// true, if variables are captured, false otherwise. 429 bool isLoopStarted() const { 430 assert(isOpenMPLoopDirective(getCurrentDirective()) && 431 "Expected loop-based directive."); 432 return !getTopOfStack().LoopStart; 433 } 434 /// Marks (or clears) declaration as possibly loop counter. 435 void resetPossibleLoopCounter(const Decl *D = nullptr) { 436 getTopOfStack().PossiblyLoopCounter = 437 D ? D->getCanonicalDecl() : D; 438 } 439 /// Gets the possible loop counter decl. 440 const Decl *getPossiblyLoopCunter() const { 441 return getTopOfStack().PossiblyLoopCounter; 442 } 443 /// Start new OpenMP region stack in new non-capturing function. 444 void pushFunction() { 445 assert(!IgnoredStackElements && 446 "cannot change stack while ignoring elements"); 447 const FunctionScopeInfo *CurFnScope = SemaRef.getCurFunction(); 448 assert(!isa<CapturingScopeInfo>(CurFnScope)); 449 CurrentNonCapturingFunctionScope = CurFnScope; 450 } 451 /// Pop region stack for non-capturing function. 452 void popFunction(const FunctionScopeInfo *OldFSI) { 453 assert(!IgnoredStackElements && 454 "cannot change stack while ignoring elements"); 455 if (!Stack.empty() && Stack.back().second == OldFSI) { 456 assert(Stack.back().first.empty()); 457 Stack.pop_back(); 458 } 459 CurrentNonCapturingFunctionScope = nullptr; 460 for (const FunctionScopeInfo *FSI : llvm::reverse(SemaRef.FunctionScopes)) { 461 if (!isa<CapturingScopeInfo>(FSI)) { 462 CurrentNonCapturingFunctionScope = FSI; 463 break; 464 } 465 } 466 } 467 468 void addCriticalWithHint(const OMPCriticalDirective *D, llvm::APSInt Hint) { 469 Criticals.try_emplace(D->getDirectiveName().getAsString(), D, Hint); 470 } 471 const std::pair<const OMPCriticalDirective *, llvm::APSInt> 472 getCriticalWithHint(const DeclarationNameInfo &Name) const { 473 auto I = Criticals.find(Name.getAsString()); 474 if (I != Criticals.end()) 475 return I->second; 476 return std::make_pair(nullptr, llvm::APSInt()); 477 } 478 /// If 'aligned' declaration for given variable \a D was not seen yet, 479 /// add it and return NULL; otherwise return previous occurrence's expression 480 /// for diagnostics. 481 const Expr *addUniqueAligned(const ValueDecl *D, const Expr *NewDE); 482 /// If 'nontemporal' declaration for given variable \a D was not seen yet, 483 /// add it and return NULL; otherwise return previous occurrence's expression 484 /// for diagnostics. 485 const Expr *addUniqueNontemporal(const ValueDecl *D, const Expr *NewDE); 486 487 /// Register specified variable as loop control variable. 488 void addLoopControlVariable(const ValueDecl *D, VarDecl *Capture); 489 /// Check if the specified variable is a loop control variable for 490 /// current region. 491 /// \return The index of the loop control variable in the list of associated 492 /// for-loops (from outer to inner). 493 const LCDeclInfo isLoopControlVariable(const ValueDecl *D) const; 494 /// Check if the specified variable is a loop control variable for 495 /// parent region. 496 /// \return The index of the loop control variable in the list of associated 497 /// for-loops (from outer to inner). 498 const LCDeclInfo isParentLoopControlVariable(const ValueDecl *D) const; 499 /// Check if the specified variable is a loop control variable for 500 /// current region. 501 /// \return The index of the loop control variable in the list of associated 502 /// for-loops (from outer to inner). 503 const LCDeclInfo isLoopControlVariable(const ValueDecl *D, 504 unsigned Level) const; 505 /// Get the loop control variable for the I-th loop (or nullptr) in 506 /// parent directive. 507 const ValueDecl *getParentLoopControlVariable(unsigned I) const; 508 509 /// Marks the specified decl \p D as used in scan directive. 510 void markDeclAsUsedInScanDirective(ValueDecl *D) { 511 if (SharingMapTy *Stack = getSecondOnStackOrNull()) 512 Stack->UsedInScanDirective.insert(D); 513 } 514 515 /// Checks if the specified declaration was used in the inner scan directive. 516 bool isUsedInScanDirective(ValueDecl *D) const { 517 if (const SharingMapTy *Stack = getTopOfStackOrNull()) 518 return Stack->UsedInScanDirective.count(D) > 0; 519 return false; 520 } 521 522 /// Adds explicit data sharing attribute to the specified declaration. 523 void addDSA(const ValueDecl *D, const Expr *E, OpenMPClauseKind A, 524 DeclRefExpr *PrivateCopy = nullptr, unsigned Modifier = 0, 525 bool AppliedToPointee = false); 526 527 /// Adds additional information for the reduction items with the reduction id 528 /// represented as an operator. 529 void addTaskgroupReductionData(const ValueDecl *D, SourceRange SR, 530 BinaryOperatorKind BOK); 531 /// Adds additional information for the reduction items with the reduction id 532 /// represented as reduction identifier. 533 void addTaskgroupReductionData(const ValueDecl *D, SourceRange SR, 534 const Expr *ReductionRef); 535 /// Returns the location and reduction operation from the innermost parent 536 /// region for the given \p D. 537 const DSAVarData 538 getTopMostTaskgroupReductionData(const ValueDecl *D, SourceRange &SR, 539 BinaryOperatorKind &BOK, 540 Expr *&TaskgroupDescriptor) const; 541 /// Returns the location and reduction operation from the innermost parent 542 /// region for the given \p D. 543 const DSAVarData 544 getTopMostTaskgroupReductionData(const ValueDecl *D, SourceRange &SR, 545 const Expr *&ReductionRef, 546 Expr *&TaskgroupDescriptor) const; 547 /// Return reduction reference expression for the current taskgroup or 548 /// parallel/worksharing directives with task reductions. 549 Expr *getTaskgroupReductionRef() const { 550 assert((getTopOfStack().Directive == OMPD_taskgroup || 551 ((isOpenMPParallelDirective(getTopOfStack().Directive) || 552 isOpenMPWorksharingDirective(getTopOfStack().Directive)) && 553 !isOpenMPSimdDirective(getTopOfStack().Directive))) && 554 "taskgroup reference expression requested for non taskgroup or " 555 "parallel/worksharing directive."); 556 return getTopOfStack().TaskgroupReductionRef; 557 } 558 /// Checks if the given \p VD declaration is actually a taskgroup reduction 559 /// descriptor variable at the \p Level of OpenMP regions. 560 bool isTaskgroupReductionRef(const ValueDecl *VD, unsigned Level) const { 561 return getStackElemAtLevel(Level).TaskgroupReductionRef && 562 cast<DeclRefExpr>(getStackElemAtLevel(Level).TaskgroupReductionRef) 563 ->getDecl() == VD; 564 } 565 566 /// Returns data sharing attributes from top of the stack for the 567 /// specified declaration. 568 const DSAVarData getTopDSA(ValueDecl *D, bool FromParent); 569 /// Returns data-sharing attributes for the specified declaration. 570 const DSAVarData getImplicitDSA(ValueDecl *D, bool FromParent) const; 571 /// Returns data-sharing attributes for the specified declaration. 572 const DSAVarData getImplicitDSA(ValueDecl *D, unsigned Level) const; 573 /// Checks if the specified variables has data-sharing attributes which 574 /// match specified \a CPred predicate in any directive which matches \a DPred 575 /// predicate. 576 const DSAVarData 577 hasDSA(ValueDecl *D, 578 const llvm::function_ref<bool(OpenMPClauseKind, bool)> CPred, 579 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred, 580 bool FromParent) const; 581 /// Checks if the specified variables has data-sharing attributes which 582 /// match specified \a CPred predicate in any innermost directive which 583 /// matches \a DPred predicate. 584 const DSAVarData 585 hasInnermostDSA(ValueDecl *D, 586 const llvm::function_ref<bool(OpenMPClauseKind, bool)> CPred, 587 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred, 588 bool FromParent) const; 589 /// Checks if the specified variables has explicit data-sharing 590 /// attributes which match specified \a CPred predicate at the specified 591 /// OpenMP region. 592 bool 593 hasExplicitDSA(const ValueDecl *D, 594 const llvm::function_ref<bool(OpenMPClauseKind, bool)> CPred, 595 unsigned Level, bool NotLastprivate = false) const; 596 597 /// Returns true if the directive at level \Level matches in the 598 /// specified \a DPred predicate. 599 bool hasExplicitDirective( 600 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred, 601 unsigned Level) const; 602 603 /// Finds a directive which matches specified \a DPred predicate. 604 bool hasDirective( 605 const llvm::function_ref<bool( 606 OpenMPDirectiveKind, const DeclarationNameInfo &, SourceLocation)> 607 DPred, 608 bool FromParent) const; 609 610 /// Returns currently analyzed directive. 611 OpenMPDirectiveKind getCurrentDirective() const { 612 const SharingMapTy *Top = getTopOfStackOrNull(); 613 return Top ? Top->Directive : OMPD_unknown; 614 } 615 /// Returns directive kind at specified level. 616 OpenMPDirectiveKind getDirective(unsigned Level) const { 617 assert(!isStackEmpty() && "No directive at specified level."); 618 return getStackElemAtLevel(Level).Directive; 619 } 620 /// Returns the capture region at the specified level. 621 OpenMPDirectiveKind getCaptureRegion(unsigned Level, 622 unsigned OpenMPCaptureLevel) const { 623 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions; 624 getOpenMPCaptureRegions(CaptureRegions, getDirective(Level)); 625 return CaptureRegions[OpenMPCaptureLevel]; 626 } 627 /// Returns parent directive. 628 OpenMPDirectiveKind getParentDirective() const { 629 const SharingMapTy *Parent = getSecondOnStackOrNull(); 630 return Parent ? Parent->Directive : OMPD_unknown; 631 } 632 633 /// Add requires decl to internal vector 634 void addRequiresDecl(OMPRequiresDecl *RD) { 635 RequiresDecls.push_back(RD); 636 } 637 638 /// Checks if the defined 'requires' directive has specified type of clause. 639 template <typename ClauseType> 640 bool hasRequiresDeclWithClause() const { 641 return llvm::any_of(RequiresDecls, [](const OMPRequiresDecl *D) { 642 return llvm::any_of(D->clauselists(), [](const OMPClause *C) { 643 return isa<ClauseType>(C); 644 }); 645 }); 646 } 647 648 /// Checks for a duplicate clause amongst previously declared requires 649 /// directives 650 bool hasDuplicateRequiresClause(ArrayRef<OMPClause *> ClauseList) const { 651 bool IsDuplicate = false; 652 for (OMPClause *CNew : ClauseList) { 653 for (const OMPRequiresDecl *D : RequiresDecls) { 654 for (const OMPClause *CPrev : D->clauselists()) { 655 if (CNew->getClauseKind() == CPrev->getClauseKind()) { 656 SemaRef.Diag(CNew->getBeginLoc(), 657 diag::err_omp_requires_clause_redeclaration) 658 << getOpenMPClauseName(CNew->getClauseKind()); 659 SemaRef.Diag(CPrev->getBeginLoc(), 660 diag::note_omp_requires_previous_clause) 661 << getOpenMPClauseName(CPrev->getClauseKind()); 662 IsDuplicate = true; 663 } 664 } 665 } 666 } 667 return IsDuplicate; 668 } 669 670 /// Add location of previously encountered target to internal vector 671 void addTargetDirLocation(SourceLocation LocStart) { 672 TargetLocations.push_back(LocStart); 673 } 674 675 /// Add location for the first encountered atomicc directive. 676 void addAtomicDirectiveLoc(SourceLocation Loc) { 677 if (AtomicLocation.isInvalid()) 678 AtomicLocation = Loc; 679 } 680 681 /// Returns the location of the first encountered atomic directive in the 682 /// module. 683 SourceLocation getAtomicDirectiveLoc() const { 684 return AtomicLocation; 685 } 686 687 // Return previously encountered target region locations. 688 ArrayRef<SourceLocation> getEncounteredTargetLocs() const { 689 return TargetLocations; 690 } 691 692 /// Set default data sharing attribute to none. 693 void setDefaultDSANone(SourceLocation Loc) { 694 getTopOfStack().DefaultAttr = DSA_none; 695 getTopOfStack().DefaultAttrLoc = Loc; 696 } 697 /// Set default data sharing attribute to shared. 698 void setDefaultDSAShared(SourceLocation Loc) { 699 getTopOfStack().DefaultAttr = DSA_shared; 700 getTopOfStack().DefaultAttrLoc = Loc; 701 } 702 /// Set default data sharing attribute to firstprivate. 703 void setDefaultDSAFirstPrivate(SourceLocation Loc) { 704 getTopOfStack().DefaultAttr = DSA_firstprivate; 705 getTopOfStack().DefaultAttrLoc = Loc; 706 } 707 /// Set default data mapping attribute to Modifier:Kind 708 void setDefaultDMAAttr(OpenMPDefaultmapClauseModifier M, 709 OpenMPDefaultmapClauseKind Kind, 710 SourceLocation Loc) { 711 DefaultmapInfo &DMI = getTopOfStack().DefaultmapMap[Kind]; 712 DMI.ImplicitBehavior = M; 713 DMI.SLoc = Loc; 714 } 715 /// Check whether the implicit-behavior has been set in defaultmap 716 bool checkDefaultmapCategory(OpenMPDefaultmapClauseKind VariableCategory) { 717 if (VariableCategory == OMPC_DEFAULTMAP_unknown) 718 return getTopOfStack() 719 .DefaultmapMap[OMPC_DEFAULTMAP_aggregate] 720 .ImplicitBehavior != OMPC_DEFAULTMAP_MODIFIER_unknown || 721 getTopOfStack() 722 .DefaultmapMap[OMPC_DEFAULTMAP_scalar] 723 .ImplicitBehavior != OMPC_DEFAULTMAP_MODIFIER_unknown || 724 getTopOfStack() 725 .DefaultmapMap[OMPC_DEFAULTMAP_pointer] 726 .ImplicitBehavior != OMPC_DEFAULTMAP_MODIFIER_unknown; 727 return getTopOfStack().DefaultmapMap[VariableCategory].ImplicitBehavior != 728 OMPC_DEFAULTMAP_MODIFIER_unknown; 729 } 730 731 ArrayRef<llvm::omp::TraitProperty> getConstructTraits() { 732 return ConstructTraits; 733 } 734 void handleConstructTrait(ArrayRef<llvm::omp::TraitProperty> Traits, 735 bool ScopeEntry) { 736 if (ScopeEntry) 737 ConstructTraits.append(Traits.begin(), Traits.end()); 738 else 739 for (llvm::omp::TraitProperty Trait : llvm::reverse(Traits)) { 740 llvm::omp::TraitProperty Top = ConstructTraits.pop_back_val(); 741 assert(Top == Trait && "Something left a trait on the stack!"); 742 (void)Trait; 743 (void)Top; 744 } 745 } 746 747 DefaultDataSharingAttributes getDefaultDSA(unsigned Level) const { 748 return getStackSize() <= Level ? DSA_unspecified 749 : getStackElemAtLevel(Level).DefaultAttr; 750 } 751 DefaultDataSharingAttributes getDefaultDSA() const { 752 return isStackEmpty() ? DSA_unspecified 753 : getTopOfStack().DefaultAttr; 754 } 755 SourceLocation getDefaultDSALocation() const { 756 return isStackEmpty() ? SourceLocation() 757 : getTopOfStack().DefaultAttrLoc; 758 } 759 OpenMPDefaultmapClauseModifier 760 getDefaultmapModifier(OpenMPDefaultmapClauseKind Kind) const { 761 return isStackEmpty() 762 ? OMPC_DEFAULTMAP_MODIFIER_unknown 763 : getTopOfStack().DefaultmapMap[Kind].ImplicitBehavior; 764 } 765 OpenMPDefaultmapClauseModifier 766 getDefaultmapModifierAtLevel(unsigned Level, 767 OpenMPDefaultmapClauseKind Kind) const { 768 return getStackElemAtLevel(Level).DefaultmapMap[Kind].ImplicitBehavior; 769 } 770 bool isDefaultmapCapturedByRef(unsigned Level, 771 OpenMPDefaultmapClauseKind Kind) const { 772 OpenMPDefaultmapClauseModifier M = 773 getDefaultmapModifierAtLevel(Level, Kind); 774 if (Kind == OMPC_DEFAULTMAP_scalar || Kind == OMPC_DEFAULTMAP_pointer) { 775 return (M == OMPC_DEFAULTMAP_MODIFIER_alloc) || 776 (M == OMPC_DEFAULTMAP_MODIFIER_to) || 777 (M == OMPC_DEFAULTMAP_MODIFIER_from) || 778 (M == OMPC_DEFAULTMAP_MODIFIER_tofrom); 779 } 780 return true; 781 } 782 static bool mustBeFirstprivateBase(OpenMPDefaultmapClauseModifier M, 783 OpenMPDefaultmapClauseKind Kind) { 784 switch (Kind) { 785 case OMPC_DEFAULTMAP_scalar: 786 case OMPC_DEFAULTMAP_pointer: 787 return (M == OMPC_DEFAULTMAP_MODIFIER_unknown) || 788 (M == OMPC_DEFAULTMAP_MODIFIER_firstprivate) || 789 (M == OMPC_DEFAULTMAP_MODIFIER_default); 790 case OMPC_DEFAULTMAP_aggregate: 791 return M == OMPC_DEFAULTMAP_MODIFIER_firstprivate; 792 default: 793 break; 794 } 795 llvm_unreachable("Unexpected OpenMPDefaultmapClauseKind enum"); 796 } 797 bool mustBeFirstprivateAtLevel(unsigned Level, 798 OpenMPDefaultmapClauseKind Kind) const { 799 OpenMPDefaultmapClauseModifier M = 800 getDefaultmapModifierAtLevel(Level, Kind); 801 return mustBeFirstprivateBase(M, Kind); 802 } 803 bool mustBeFirstprivate(OpenMPDefaultmapClauseKind Kind) const { 804 OpenMPDefaultmapClauseModifier M = getDefaultmapModifier(Kind); 805 return mustBeFirstprivateBase(M, Kind); 806 } 807 808 /// Checks if the specified variable is a threadprivate. 809 bool isThreadPrivate(VarDecl *D) { 810 const DSAVarData DVar = getTopDSA(D, false); 811 return isOpenMPThreadPrivate(DVar.CKind); 812 } 813 814 /// Marks current region as ordered (it has an 'ordered' clause). 815 void setOrderedRegion(bool IsOrdered, const Expr *Param, 816 OMPOrderedClause *Clause) { 817 if (IsOrdered) 818 getTopOfStack().OrderedRegion.emplace(Param, Clause); 819 else 820 getTopOfStack().OrderedRegion.reset(); 821 } 822 /// Returns true, if region is ordered (has associated 'ordered' clause), 823 /// false - otherwise. 824 bool isOrderedRegion() const { 825 if (const SharingMapTy *Top = getTopOfStackOrNull()) 826 return Top->OrderedRegion.hasValue(); 827 return false; 828 } 829 /// Returns optional parameter for the ordered region. 830 std::pair<const Expr *, OMPOrderedClause *> getOrderedRegionParam() const { 831 if (const SharingMapTy *Top = getTopOfStackOrNull()) 832 if (Top->OrderedRegion.hasValue()) 833 return Top->OrderedRegion.getValue(); 834 return std::make_pair(nullptr, nullptr); 835 } 836 /// Returns true, if parent region is ordered (has associated 837 /// 'ordered' clause), false - otherwise. 838 bool isParentOrderedRegion() const { 839 if (const SharingMapTy *Parent = getSecondOnStackOrNull()) 840 return Parent->OrderedRegion.hasValue(); 841 return false; 842 } 843 /// Returns optional parameter for the ordered region. 844 std::pair<const Expr *, OMPOrderedClause *> 845 getParentOrderedRegionParam() const { 846 if (const SharingMapTy *Parent = getSecondOnStackOrNull()) 847 if (Parent->OrderedRegion.hasValue()) 848 return Parent->OrderedRegion.getValue(); 849 return std::make_pair(nullptr, nullptr); 850 } 851 /// Marks current region as nowait (it has a 'nowait' clause). 852 void setNowaitRegion(bool IsNowait = true) { 853 getTopOfStack().NowaitRegion = IsNowait; 854 } 855 /// Returns true, if parent region is nowait (has associated 856 /// 'nowait' clause), false - otherwise. 857 bool isParentNowaitRegion() const { 858 if (const SharingMapTy *Parent = getSecondOnStackOrNull()) 859 return Parent->NowaitRegion; 860 return false; 861 } 862 /// Marks parent region as cancel region. 863 void setParentCancelRegion(bool Cancel = true) { 864 if (SharingMapTy *Parent = getSecondOnStackOrNull()) 865 Parent->CancelRegion |= Cancel; 866 } 867 /// Return true if current region has inner cancel construct. 868 bool isCancelRegion() const { 869 const SharingMapTy *Top = getTopOfStackOrNull(); 870 return Top ? Top->CancelRegion : false; 871 } 872 873 /// Mark that parent region already has scan directive. 874 void setParentHasScanDirective(SourceLocation Loc) { 875 if (SharingMapTy *Parent = getSecondOnStackOrNull()) 876 Parent->PrevScanLocation = Loc; 877 } 878 /// Return true if current region has inner cancel construct. 879 bool doesParentHasScanDirective() const { 880 const SharingMapTy *Top = getSecondOnStackOrNull(); 881 return Top ? Top->PrevScanLocation.isValid() : false; 882 } 883 /// Return true if current region has inner cancel construct. 884 SourceLocation getParentScanDirectiveLoc() const { 885 const SharingMapTy *Top = getSecondOnStackOrNull(); 886 return Top ? Top->PrevScanLocation : SourceLocation(); 887 } 888 /// Mark that parent region already has ordered directive. 889 void setParentHasOrderedDirective(SourceLocation Loc) { 890 if (SharingMapTy *Parent = getSecondOnStackOrNull()) 891 Parent->PrevOrderedLocation = Loc; 892 } 893 /// Return true if current region has inner ordered construct. 894 bool doesParentHasOrderedDirective() const { 895 const SharingMapTy *Top = getSecondOnStackOrNull(); 896 return Top ? Top->PrevOrderedLocation.isValid() : false; 897 } 898 /// Returns the location of the previously specified ordered directive. 899 SourceLocation getParentOrderedDirectiveLoc() const { 900 const SharingMapTy *Top = getSecondOnStackOrNull(); 901 return Top ? Top->PrevOrderedLocation : SourceLocation(); 902 } 903 904 /// Set collapse value for the region. 905 void setAssociatedLoops(unsigned Val) { 906 getTopOfStack().AssociatedLoops = Val; 907 if (Val > 1) 908 getTopOfStack().HasMutipleLoops = true; 909 } 910 /// Return collapse value for region. 911 unsigned getAssociatedLoops() const { 912 const SharingMapTy *Top = getTopOfStackOrNull(); 913 return Top ? Top->AssociatedLoops : 0; 914 } 915 /// Returns true if the construct is associated with multiple loops. 916 bool hasMutipleLoops() const { 917 const SharingMapTy *Top = getTopOfStackOrNull(); 918 return Top ? Top->HasMutipleLoops : false; 919 } 920 921 /// Marks current target region as one with closely nested teams 922 /// region. 923 void setParentTeamsRegionLoc(SourceLocation TeamsRegionLoc) { 924 if (SharingMapTy *Parent = getSecondOnStackOrNull()) 925 Parent->InnerTeamsRegionLoc = TeamsRegionLoc; 926 } 927 /// Returns true, if current region has closely nested teams region. 928 bool hasInnerTeamsRegion() const { 929 return getInnerTeamsRegionLoc().isValid(); 930 } 931 /// Returns location of the nested teams region (if any). 932 SourceLocation getInnerTeamsRegionLoc() const { 933 const SharingMapTy *Top = getTopOfStackOrNull(); 934 return Top ? Top->InnerTeamsRegionLoc : SourceLocation(); 935 } 936 937 Scope *getCurScope() const { 938 const SharingMapTy *Top = getTopOfStackOrNull(); 939 return Top ? Top->CurScope : nullptr; 940 } 941 void setContext(DeclContext *DC) { getTopOfStack().Context = DC; } 942 SourceLocation getConstructLoc() const { 943 const SharingMapTy *Top = getTopOfStackOrNull(); 944 return Top ? Top->ConstructLoc : SourceLocation(); 945 } 946 947 /// Do the check specified in \a Check to all component lists and return true 948 /// if any issue is found. 949 bool checkMappableExprComponentListsForDecl( 950 const ValueDecl *VD, bool CurrentRegionOnly, 951 const llvm::function_ref< 952 bool(OMPClauseMappableExprCommon::MappableExprComponentListRef, 953 OpenMPClauseKind)> 954 Check) const { 955 if (isStackEmpty()) 956 return false; 957 auto SI = begin(); 958 auto SE = end(); 959 960 if (SI == SE) 961 return false; 962 963 if (CurrentRegionOnly) 964 SE = std::next(SI); 965 else 966 std::advance(SI, 1); 967 968 for (; SI != SE; ++SI) { 969 auto MI = SI->MappedExprComponents.find(VD); 970 if (MI != SI->MappedExprComponents.end()) 971 for (OMPClauseMappableExprCommon::MappableExprComponentListRef L : 972 MI->second.Components) 973 if (Check(L, MI->second.Kind)) 974 return true; 975 } 976 return false; 977 } 978 979 /// Do the check specified in \a Check to all component lists at a given level 980 /// and return true if any issue is found. 981 bool checkMappableExprComponentListsForDeclAtLevel( 982 const ValueDecl *VD, unsigned Level, 983 const llvm::function_ref< 984 bool(OMPClauseMappableExprCommon::MappableExprComponentListRef, 985 OpenMPClauseKind)> 986 Check) const { 987 if (getStackSize() <= Level) 988 return false; 989 990 const SharingMapTy &StackElem = getStackElemAtLevel(Level); 991 auto MI = StackElem.MappedExprComponents.find(VD); 992 if (MI != StackElem.MappedExprComponents.end()) 993 for (OMPClauseMappableExprCommon::MappableExprComponentListRef L : 994 MI->second.Components) 995 if (Check(L, MI->second.Kind)) 996 return true; 997 return false; 998 } 999 1000 /// Create a new mappable expression component list associated with a given 1001 /// declaration and initialize it with the provided list of components. 1002 void addMappableExpressionComponents( 1003 const ValueDecl *VD, 1004 OMPClauseMappableExprCommon::MappableExprComponentListRef Components, 1005 OpenMPClauseKind WhereFoundClauseKind) { 1006 MappedExprComponentTy &MEC = getTopOfStack().MappedExprComponents[VD]; 1007 // Create new entry and append the new components there. 1008 MEC.Components.resize(MEC.Components.size() + 1); 1009 MEC.Components.back().append(Components.begin(), Components.end()); 1010 MEC.Kind = WhereFoundClauseKind; 1011 } 1012 1013 unsigned getNestingLevel() const { 1014 assert(!isStackEmpty()); 1015 return getStackSize() - 1; 1016 } 1017 void addDoacrossDependClause(OMPDependClause *C, 1018 const OperatorOffsetTy &OpsOffs) { 1019 SharingMapTy *Parent = getSecondOnStackOrNull(); 1020 assert(Parent && isOpenMPWorksharingDirective(Parent->Directive)); 1021 Parent->DoacrossDepends.try_emplace(C, OpsOffs); 1022 } 1023 llvm::iterator_range<DoacrossDependMapTy::const_iterator> 1024 getDoacrossDependClauses() const { 1025 const SharingMapTy &StackElem = getTopOfStack(); 1026 if (isOpenMPWorksharingDirective(StackElem.Directive)) { 1027 const DoacrossDependMapTy &Ref = StackElem.DoacrossDepends; 1028 return llvm::make_range(Ref.begin(), Ref.end()); 1029 } 1030 return llvm::make_range(StackElem.DoacrossDepends.end(), 1031 StackElem.DoacrossDepends.end()); 1032 } 1033 1034 // Store types of classes which have been explicitly mapped 1035 void addMappedClassesQualTypes(QualType QT) { 1036 SharingMapTy &StackElem = getTopOfStack(); 1037 StackElem.MappedClassesQualTypes.insert(QT); 1038 } 1039 1040 // Return set of mapped classes types 1041 bool isClassPreviouslyMapped(QualType QT) const { 1042 const SharingMapTy &StackElem = getTopOfStack(); 1043 return StackElem.MappedClassesQualTypes.count(QT) != 0; 1044 } 1045 1046 /// Adds global declare target to the parent target region. 1047 void addToParentTargetRegionLinkGlobals(DeclRefExpr *E) { 1048 assert(*OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration( 1049 E->getDecl()) == OMPDeclareTargetDeclAttr::MT_Link && 1050 "Expected declare target link global."); 1051 for (auto &Elem : *this) { 1052 if (isOpenMPTargetExecutionDirective(Elem.Directive)) { 1053 Elem.DeclareTargetLinkVarDecls.push_back(E); 1054 return; 1055 } 1056 } 1057 } 1058 1059 /// Returns the list of globals with declare target link if current directive 1060 /// is target. 1061 ArrayRef<DeclRefExpr *> getLinkGlobals() const { 1062 assert(isOpenMPTargetExecutionDirective(getCurrentDirective()) && 1063 "Expected target executable directive."); 1064 return getTopOfStack().DeclareTargetLinkVarDecls; 1065 } 1066 1067 /// Adds list of allocators expressions. 1068 void addInnerAllocatorExpr(Expr *E) { 1069 getTopOfStack().InnerUsedAllocators.push_back(E); 1070 } 1071 /// Return list of used allocators. 1072 ArrayRef<Expr *> getInnerAllocators() const { 1073 return getTopOfStack().InnerUsedAllocators; 1074 } 1075 /// Marks the declaration as implicitly firstprivate nin the task-based 1076 /// regions. 1077 void addImplicitTaskFirstprivate(unsigned Level, Decl *D) { 1078 getStackElemAtLevel(Level).ImplicitTaskFirstprivates.insert(D); 1079 } 1080 /// Checks if the decl is implicitly firstprivate in the task-based region. 1081 bool isImplicitTaskFirstprivate(Decl *D) const { 1082 return getTopOfStack().ImplicitTaskFirstprivates.count(D) > 0; 1083 } 1084 1085 /// Marks decl as used in uses_allocators clause as the allocator. 1086 void addUsesAllocatorsDecl(const Decl *D, UsesAllocatorsDeclKind Kind) { 1087 getTopOfStack().UsesAllocatorsDecls.try_emplace(D, Kind); 1088 } 1089 /// Checks if specified decl is used in uses allocator clause as the 1090 /// allocator. 1091 Optional<UsesAllocatorsDeclKind> isUsesAllocatorsDecl(unsigned Level, 1092 const Decl *D) const { 1093 const SharingMapTy &StackElem = getTopOfStack(); 1094 auto I = StackElem.UsesAllocatorsDecls.find(D); 1095 if (I == StackElem.UsesAllocatorsDecls.end()) 1096 return None; 1097 return I->getSecond(); 1098 } 1099 Optional<UsesAllocatorsDeclKind> isUsesAllocatorsDecl(const Decl *D) const { 1100 const SharingMapTy &StackElem = getTopOfStack(); 1101 auto I = StackElem.UsesAllocatorsDecls.find(D); 1102 if (I == StackElem.UsesAllocatorsDecls.end()) 1103 return None; 1104 return I->getSecond(); 1105 } 1106 1107 void addDeclareMapperVarRef(Expr *Ref) { 1108 SharingMapTy &StackElem = getTopOfStack(); 1109 StackElem.DeclareMapperVar = Ref; 1110 } 1111 const Expr *getDeclareMapperVarRef() const { 1112 const SharingMapTy *Top = getTopOfStackOrNull(); 1113 return Top ? Top->DeclareMapperVar : nullptr; 1114 } 1115 }; 1116 1117 bool isImplicitTaskingRegion(OpenMPDirectiveKind DKind) { 1118 return isOpenMPParallelDirective(DKind) || isOpenMPTeamsDirective(DKind); 1119 } 1120 1121 bool isImplicitOrExplicitTaskingRegion(OpenMPDirectiveKind DKind) { 1122 return isImplicitTaskingRegion(DKind) || isOpenMPTaskingDirective(DKind) || 1123 DKind == OMPD_unknown; 1124 } 1125 1126 } // namespace 1127 1128 static const Expr *getExprAsWritten(const Expr *E) { 1129 if (const auto *FE = dyn_cast<FullExpr>(E)) 1130 E = FE->getSubExpr(); 1131 1132 if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) 1133 E = MTE->getSubExpr(); 1134 1135 while (const auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E)) 1136 E = Binder->getSubExpr(); 1137 1138 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 1139 E = ICE->getSubExprAsWritten(); 1140 return E->IgnoreParens(); 1141 } 1142 1143 static Expr *getExprAsWritten(Expr *E) { 1144 return const_cast<Expr *>(getExprAsWritten(const_cast<const Expr *>(E))); 1145 } 1146 1147 static const ValueDecl *getCanonicalDecl(const ValueDecl *D) { 1148 if (const auto *CED = dyn_cast<OMPCapturedExprDecl>(D)) 1149 if (const auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit()))) 1150 D = ME->getMemberDecl(); 1151 const auto *VD = dyn_cast<VarDecl>(D); 1152 const auto *FD = dyn_cast<FieldDecl>(D); 1153 if (VD != nullptr) { 1154 VD = VD->getCanonicalDecl(); 1155 D = VD; 1156 } else { 1157 assert(FD); 1158 FD = FD->getCanonicalDecl(); 1159 D = FD; 1160 } 1161 return D; 1162 } 1163 1164 static ValueDecl *getCanonicalDecl(ValueDecl *D) { 1165 return const_cast<ValueDecl *>( 1166 getCanonicalDecl(const_cast<const ValueDecl *>(D))); 1167 } 1168 1169 DSAStackTy::DSAVarData DSAStackTy::getDSA(const_iterator &Iter, 1170 ValueDecl *D) const { 1171 D = getCanonicalDecl(D); 1172 auto *VD = dyn_cast<VarDecl>(D); 1173 const auto *FD = dyn_cast<FieldDecl>(D); 1174 DSAVarData DVar; 1175 if (Iter == end()) { 1176 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 1177 // in a region but not in construct] 1178 // File-scope or namespace-scope variables referenced in called routines 1179 // in the region are shared unless they appear in a threadprivate 1180 // directive. 1181 if (VD && !VD->isFunctionOrMethodVarDecl() && !isa<ParmVarDecl>(VD)) 1182 DVar.CKind = OMPC_shared; 1183 1184 // OpenMP [2.9.1.2, Data-sharing Attribute Rules for Variables Referenced 1185 // in a region but not in construct] 1186 // Variables with static storage duration that are declared in called 1187 // routines in the region are shared. 1188 if (VD && VD->hasGlobalStorage()) 1189 DVar.CKind = OMPC_shared; 1190 1191 // Non-static data members are shared by default. 1192 if (FD) 1193 DVar.CKind = OMPC_shared; 1194 1195 return DVar; 1196 } 1197 1198 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 1199 // in a Construct, C/C++, predetermined, p.1] 1200 // Variables with automatic storage duration that are declared in a scope 1201 // inside the construct are private. 1202 if (VD && isOpenMPLocal(VD, Iter) && VD->isLocalVarDecl() && 1203 (VD->getStorageClass() == SC_Auto || VD->getStorageClass() == SC_None)) { 1204 DVar.CKind = OMPC_private; 1205 return DVar; 1206 } 1207 1208 DVar.DKind = Iter->Directive; 1209 // Explicitly specified attributes and local variables with predetermined 1210 // attributes. 1211 if (Iter->SharingMap.count(D)) { 1212 const DSAInfo &Data = Iter->SharingMap.lookup(D); 1213 DVar.RefExpr = Data.RefExpr.getPointer(); 1214 DVar.PrivateCopy = Data.PrivateCopy; 1215 DVar.CKind = Data.Attributes; 1216 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc; 1217 DVar.Modifier = Data.Modifier; 1218 DVar.AppliedToPointee = Data.AppliedToPointee; 1219 return DVar; 1220 } 1221 1222 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 1223 // in a Construct, C/C++, implicitly determined, p.1] 1224 // In a parallel or task construct, the data-sharing attributes of these 1225 // variables are determined by the default clause, if present. 1226 switch (Iter->DefaultAttr) { 1227 case DSA_shared: 1228 DVar.CKind = OMPC_shared; 1229 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc; 1230 return DVar; 1231 case DSA_none: 1232 return DVar; 1233 case DSA_firstprivate: 1234 if (VD->getStorageDuration() == SD_Static && 1235 VD->getDeclContext()->isFileContext()) { 1236 DVar.CKind = OMPC_unknown; 1237 } else { 1238 DVar.CKind = OMPC_firstprivate; 1239 } 1240 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc; 1241 return DVar; 1242 case DSA_unspecified: 1243 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 1244 // in a Construct, implicitly determined, p.2] 1245 // In a parallel construct, if no default clause is present, these 1246 // variables are shared. 1247 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc; 1248 if ((isOpenMPParallelDirective(DVar.DKind) && 1249 !isOpenMPTaskLoopDirective(DVar.DKind)) || 1250 isOpenMPTeamsDirective(DVar.DKind)) { 1251 DVar.CKind = OMPC_shared; 1252 return DVar; 1253 } 1254 1255 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 1256 // in a Construct, implicitly determined, p.4] 1257 // In a task construct, if no default clause is present, a variable that in 1258 // the enclosing context is determined to be shared by all implicit tasks 1259 // bound to the current team is shared. 1260 if (isOpenMPTaskingDirective(DVar.DKind)) { 1261 DSAVarData DVarTemp; 1262 const_iterator I = Iter, E = end(); 1263 do { 1264 ++I; 1265 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables 1266 // Referenced in a Construct, implicitly determined, p.6] 1267 // In a task construct, if no default clause is present, a variable 1268 // whose data-sharing attribute is not determined by the rules above is 1269 // firstprivate. 1270 DVarTemp = getDSA(I, D); 1271 if (DVarTemp.CKind != OMPC_shared) { 1272 DVar.RefExpr = nullptr; 1273 DVar.CKind = OMPC_firstprivate; 1274 return DVar; 1275 } 1276 } while (I != E && !isImplicitTaskingRegion(I->Directive)); 1277 DVar.CKind = 1278 (DVarTemp.CKind == OMPC_unknown) ? OMPC_firstprivate : OMPC_shared; 1279 return DVar; 1280 } 1281 } 1282 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 1283 // in a Construct, implicitly determined, p.3] 1284 // For constructs other than task, if no default clause is present, these 1285 // variables inherit their data-sharing attributes from the enclosing 1286 // context. 1287 return getDSA(++Iter, D); 1288 } 1289 1290 const Expr *DSAStackTy::addUniqueAligned(const ValueDecl *D, 1291 const Expr *NewDE) { 1292 assert(!isStackEmpty() && "Data sharing attributes stack is empty"); 1293 D = getCanonicalDecl(D); 1294 SharingMapTy &StackElem = getTopOfStack(); 1295 auto It = StackElem.AlignedMap.find(D); 1296 if (It == StackElem.AlignedMap.end()) { 1297 assert(NewDE && "Unexpected nullptr expr to be added into aligned map"); 1298 StackElem.AlignedMap[D] = NewDE; 1299 return nullptr; 1300 } 1301 assert(It->second && "Unexpected nullptr expr in the aligned map"); 1302 return It->second; 1303 } 1304 1305 const Expr *DSAStackTy::addUniqueNontemporal(const ValueDecl *D, 1306 const Expr *NewDE) { 1307 assert(!isStackEmpty() && "Data sharing attributes stack is empty"); 1308 D = getCanonicalDecl(D); 1309 SharingMapTy &StackElem = getTopOfStack(); 1310 auto It = StackElem.NontemporalMap.find(D); 1311 if (It == StackElem.NontemporalMap.end()) { 1312 assert(NewDE && "Unexpected nullptr expr to be added into aligned map"); 1313 StackElem.NontemporalMap[D] = NewDE; 1314 return nullptr; 1315 } 1316 assert(It->second && "Unexpected nullptr expr in the aligned map"); 1317 return It->second; 1318 } 1319 1320 void DSAStackTy::addLoopControlVariable(const ValueDecl *D, VarDecl *Capture) { 1321 assert(!isStackEmpty() && "Data-sharing attributes stack is empty"); 1322 D = getCanonicalDecl(D); 1323 SharingMapTy &StackElem = getTopOfStack(); 1324 StackElem.LCVMap.try_emplace( 1325 D, LCDeclInfo(StackElem.LCVMap.size() + 1, Capture)); 1326 } 1327 1328 const DSAStackTy::LCDeclInfo 1329 DSAStackTy::isLoopControlVariable(const ValueDecl *D) const { 1330 assert(!isStackEmpty() && "Data-sharing attributes stack is empty"); 1331 D = getCanonicalDecl(D); 1332 const SharingMapTy &StackElem = getTopOfStack(); 1333 auto It = StackElem.LCVMap.find(D); 1334 if (It != StackElem.LCVMap.end()) 1335 return It->second; 1336 return {0, nullptr}; 1337 } 1338 1339 const DSAStackTy::LCDeclInfo 1340 DSAStackTy::isLoopControlVariable(const ValueDecl *D, unsigned Level) const { 1341 assert(!isStackEmpty() && "Data-sharing attributes stack is empty"); 1342 D = getCanonicalDecl(D); 1343 for (unsigned I = Level + 1; I > 0; --I) { 1344 const SharingMapTy &StackElem = getStackElemAtLevel(I - 1); 1345 auto It = StackElem.LCVMap.find(D); 1346 if (It != StackElem.LCVMap.end()) 1347 return It->second; 1348 } 1349 return {0, nullptr}; 1350 } 1351 1352 const DSAStackTy::LCDeclInfo 1353 DSAStackTy::isParentLoopControlVariable(const ValueDecl *D) const { 1354 const SharingMapTy *Parent = getSecondOnStackOrNull(); 1355 assert(Parent && "Data-sharing attributes stack is empty"); 1356 D = getCanonicalDecl(D); 1357 auto It = Parent->LCVMap.find(D); 1358 if (It != Parent->LCVMap.end()) 1359 return It->second; 1360 return {0, nullptr}; 1361 } 1362 1363 const ValueDecl *DSAStackTy::getParentLoopControlVariable(unsigned I) const { 1364 const SharingMapTy *Parent = getSecondOnStackOrNull(); 1365 assert(Parent && "Data-sharing attributes stack is empty"); 1366 if (Parent->LCVMap.size() < I) 1367 return nullptr; 1368 for (const auto &Pair : Parent->LCVMap) 1369 if (Pair.second.first == I) 1370 return Pair.first; 1371 return nullptr; 1372 } 1373 1374 void DSAStackTy::addDSA(const ValueDecl *D, const Expr *E, OpenMPClauseKind A, 1375 DeclRefExpr *PrivateCopy, unsigned Modifier, 1376 bool AppliedToPointee) { 1377 D = getCanonicalDecl(D); 1378 if (A == OMPC_threadprivate) { 1379 DSAInfo &Data = Threadprivates[D]; 1380 Data.Attributes = A; 1381 Data.RefExpr.setPointer(E); 1382 Data.PrivateCopy = nullptr; 1383 Data.Modifier = Modifier; 1384 } else { 1385 DSAInfo &Data = getTopOfStack().SharingMap[D]; 1386 assert(Data.Attributes == OMPC_unknown || (A == Data.Attributes) || 1387 (A == OMPC_firstprivate && Data.Attributes == OMPC_lastprivate) || 1388 (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) || 1389 (isLoopControlVariable(D).first && A == OMPC_private)); 1390 Data.Modifier = Modifier; 1391 if (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) { 1392 Data.RefExpr.setInt(/*IntVal=*/true); 1393 return; 1394 } 1395 const bool IsLastprivate = 1396 A == OMPC_lastprivate || Data.Attributes == OMPC_lastprivate; 1397 Data.Attributes = A; 1398 Data.RefExpr.setPointerAndInt(E, IsLastprivate); 1399 Data.PrivateCopy = PrivateCopy; 1400 Data.AppliedToPointee = AppliedToPointee; 1401 if (PrivateCopy) { 1402 DSAInfo &Data = getTopOfStack().SharingMap[PrivateCopy->getDecl()]; 1403 Data.Modifier = Modifier; 1404 Data.Attributes = A; 1405 Data.RefExpr.setPointerAndInt(PrivateCopy, IsLastprivate); 1406 Data.PrivateCopy = nullptr; 1407 Data.AppliedToPointee = AppliedToPointee; 1408 } 1409 } 1410 } 1411 1412 /// Build a variable declaration for OpenMP loop iteration variable. 1413 static VarDecl *buildVarDecl(Sema &SemaRef, SourceLocation Loc, QualType Type, 1414 StringRef Name, const AttrVec *Attrs = nullptr, 1415 DeclRefExpr *OrigRef = nullptr) { 1416 DeclContext *DC = SemaRef.CurContext; 1417 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name); 1418 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc); 1419 auto *Decl = 1420 VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, TInfo, SC_None); 1421 if (Attrs) { 1422 for (specific_attr_iterator<AlignedAttr> I(Attrs->begin()), E(Attrs->end()); 1423 I != E; ++I) 1424 Decl->addAttr(*I); 1425 } 1426 Decl->setImplicit(); 1427 if (OrigRef) { 1428 Decl->addAttr( 1429 OMPReferencedVarAttr::CreateImplicit(SemaRef.Context, OrigRef)); 1430 } 1431 return Decl; 1432 } 1433 1434 static DeclRefExpr *buildDeclRefExpr(Sema &S, VarDecl *D, QualType Ty, 1435 SourceLocation Loc, 1436 bool RefersToCapture = false) { 1437 D->setReferenced(); 1438 D->markUsed(S.Context); 1439 return DeclRefExpr::Create(S.getASTContext(), NestedNameSpecifierLoc(), 1440 SourceLocation(), D, RefersToCapture, Loc, Ty, 1441 VK_LValue); 1442 } 1443 1444 void DSAStackTy::addTaskgroupReductionData(const ValueDecl *D, SourceRange SR, 1445 BinaryOperatorKind BOK) { 1446 D = getCanonicalDecl(D); 1447 assert(!isStackEmpty() && "Data-sharing attributes stack is empty"); 1448 assert( 1449 getTopOfStack().SharingMap[D].Attributes == OMPC_reduction && 1450 "Additional reduction info may be specified only for reduction items."); 1451 ReductionData &ReductionData = getTopOfStack().ReductionMap[D]; 1452 assert(ReductionData.ReductionRange.isInvalid() && 1453 (getTopOfStack().Directive == OMPD_taskgroup || 1454 ((isOpenMPParallelDirective(getTopOfStack().Directive) || 1455 isOpenMPWorksharingDirective(getTopOfStack().Directive)) && 1456 !isOpenMPSimdDirective(getTopOfStack().Directive))) && 1457 "Additional reduction info may be specified only once for reduction " 1458 "items."); 1459 ReductionData.set(BOK, SR); 1460 Expr *&TaskgroupReductionRef = 1461 getTopOfStack().TaskgroupReductionRef; 1462 if (!TaskgroupReductionRef) { 1463 VarDecl *VD = buildVarDecl(SemaRef, SR.getBegin(), 1464 SemaRef.Context.VoidPtrTy, ".task_red."); 1465 TaskgroupReductionRef = 1466 buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin()); 1467 } 1468 } 1469 1470 void DSAStackTy::addTaskgroupReductionData(const ValueDecl *D, SourceRange SR, 1471 const Expr *ReductionRef) { 1472 D = getCanonicalDecl(D); 1473 assert(!isStackEmpty() && "Data-sharing attributes stack is empty"); 1474 assert( 1475 getTopOfStack().SharingMap[D].Attributes == OMPC_reduction && 1476 "Additional reduction info may be specified only for reduction items."); 1477 ReductionData &ReductionData = getTopOfStack().ReductionMap[D]; 1478 assert(ReductionData.ReductionRange.isInvalid() && 1479 (getTopOfStack().Directive == OMPD_taskgroup || 1480 ((isOpenMPParallelDirective(getTopOfStack().Directive) || 1481 isOpenMPWorksharingDirective(getTopOfStack().Directive)) && 1482 !isOpenMPSimdDirective(getTopOfStack().Directive))) && 1483 "Additional reduction info may be specified only once for reduction " 1484 "items."); 1485 ReductionData.set(ReductionRef, SR); 1486 Expr *&TaskgroupReductionRef = 1487 getTopOfStack().TaskgroupReductionRef; 1488 if (!TaskgroupReductionRef) { 1489 VarDecl *VD = buildVarDecl(SemaRef, SR.getBegin(), 1490 SemaRef.Context.VoidPtrTy, ".task_red."); 1491 TaskgroupReductionRef = 1492 buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin()); 1493 } 1494 } 1495 1496 const DSAStackTy::DSAVarData DSAStackTy::getTopMostTaskgroupReductionData( 1497 const ValueDecl *D, SourceRange &SR, BinaryOperatorKind &BOK, 1498 Expr *&TaskgroupDescriptor) const { 1499 D = getCanonicalDecl(D); 1500 assert(!isStackEmpty() && "Data-sharing attributes stack is empty."); 1501 for (const_iterator I = begin() + 1, E = end(); I != E; ++I) { 1502 const DSAInfo &Data = I->SharingMap.lookup(D); 1503 if (Data.Attributes != OMPC_reduction || 1504 Data.Modifier != OMPC_REDUCTION_task) 1505 continue; 1506 const ReductionData &ReductionData = I->ReductionMap.lookup(D); 1507 if (!ReductionData.ReductionOp || 1508 ReductionData.ReductionOp.is<const Expr *>()) 1509 return DSAVarData(); 1510 SR = ReductionData.ReductionRange; 1511 BOK = ReductionData.ReductionOp.get<ReductionData::BOKPtrType>(); 1512 assert(I->TaskgroupReductionRef && "taskgroup reduction reference " 1513 "expression for the descriptor is not " 1514 "set."); 1515 TaskgroupDescriptor = I->TaskgroupReductionRef; 1516 return DSAVarData(I->Directive, OMPC_reduction, Data.RefExpr.getPointer(), 1517 Data.PrivateCopy, I->DefaultAttrLoc, OMPC_REDUCTION_task, 1518 /*AppliedToPointee=*/false); 1519 } 1520 return DSAVarData(); 1521 } 1522 1523 const DSAStackTy::DSAVarData DSAStackTy::getTopMostTaskgroupReductionData( 1524 const ValueDecl *D, SourceRange &SR, const Expr *&ReductionRef, 1525 Expr *&TaskgroupDescriptor) const { 1526 D = getCanonicalDecl(D); 1527 assert(!isStackEmpty() && "Data-sharing attributes stack is empty."); 1528 for (const_iterator I = begin() + 1, E = end(); I != E; ++I) { 1529 const DSAInfo &Data = I->SharingMap.lookup(D); 1530 if (Data.Attributes != OMPC_reduction || 1531 Data.Modifier != OMPC_REDUCTION_task) 1532 continue; 1533 const ReductionData &ReductionData = I->ReductionMap.lookup(D); 1534 if (!ReductionData.ReductionOp || 1535 !ReductionData.ReductionOp.is<const Expr *>()) 1536 return DSAVarData(); 1537 SR = ReductionData.ReductionRange; 1538 ReductionRef = ReductionData.ReductionOp.get<const Expr *>(); 1539 assert(I->TaskgroupReductionRef && "taskgroup reduction reference " 1540 "expression for the descriptor is not " 1541 "set."); 1542 TaskgroupDescriptor = I->TaskgroupReductionRef; 1543 return DSAVarData(I->Directive, OMPC_reduction, Data.RefExpr.getPointer(), 1544 Data.PrivateCopy, I->DefaultAttrLoc, OMPC_REDUCTION_task, 1545 /*AppliedToPointee=*/false); 1546 } 1547 return DSAVarData(); 1548 } 1549 1550 bool DSAStackTy::isOpenMPLocal(VarDecl *D, const_iterator I) const { 1551 D = D->getCanonicalDecl(); 1552 for (const_iterator E = end(); I != E; ++I) { 1553 if (isImplicitOrExplicitTaskingRegion(I->Directive) || 1554 isOpenMPTargetExecutionDirective(I->Directive)) { 1555 if (I->CurScope) { 1556 Scope *TopScope = I->CurScope->getParent(); 1557 Scope *CurScope = getCurScope(); 1558 while (CurScope && CurScope != TopScope && !CurScope->isDeclScope(D)) 1559 CurScope = CurScope->getParent(); 1560 return CurScope != TopScope; 1561 } 1562 for (DeclContext *DC = D->getDeclContext(); DC; DC = DC->getParent()) 1563 if (I->Context == DC) 1564 return true; 1565 return false; 1566 } 1567 } 1568 return false; 1569 } 1570 1571 static bool isConstNotMutableType(Sema &SemaRef, QualType Type, 1572 bool AcceptIfMutable = true, 1573 bool *IsClassType = nullptr) { 1574 ASTContext &Context = SemaRef.getASTContext(); 1575 Type = Type.getNonReferenceType().getCanonicalType(); 1576 bool IsConstant = Type.isConstant(Context); 1577 Type = Context.getBaseElementType(Type); 1578 const CXXRecordDecl *RD = AcceptIfMutable && SemaRef.getLangOpts().CPlusPlus 1579 ? Type->getAsCXXRecordDecl() 1580 : nullptr; 1581 if (const auto *CTSD = dyn_cast_or_null<ClassTemplateSpecializationDecl>(RD)) 1582 if (const ClassTemplateDecl *CTD = CTSD->getSpecializedTemplate()) 1583 RD = CTD->getTemplatedDecl(); 1584 if (IsClassType) 1585 *IsClassType = RD; 1586 return IsConstant && !(SemaRef.getLangOpts().CPlusPlus && RD && 1587 RD->hasDefinition() && RD->hasMutableFields()); 1588 } 1589 1590 static bool rejectConstNotMutableType(Sema &SemaRef, const ValueDecl *D, 1591 QualType Type, OpenMPClauseKind CKind, 1592 SourceLocation ELoc, 1593 bool AcceptIfMutable = true, 1594 bool ListItemNotVar = false) { 1595 ASTContext &Context = SemaRef.getASTContext(); 1596 bool IsClassType; 1597 if (isConstNotMutableType(SemaRef, Type, AcceptIfMutable, &IsClassType)) { 1598 unsigned Diag = ListItemNotVar 1599 ? diag::err_omp_const_list_item 1600 : IsClassType ? diag::err_omp_const_not_mutable_variable 1601 : diag::err_omp_const_variable; 1602 SemaRef.Diag(ELoc, Diag) << getOpenMPClauseName(CKind); 1603 if (!ListItemNotVar && D) { 1604 const VarDecl *VD = dyn_cast<VarDecl>(D); 1605 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) == 1606 VarDecl::DeclarationOnly; 1607 SemaRef.Diag(D->getLocation(), 1608 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 1609 << D; 1610 } 1611 return true; 1612 } 1613 return false; 1614 } 1615 1616 const DSAStackTy::DSAVarData DSAStackTy::getTopDSA(ValueDecl *D, 1617 bool FromParent) { 1618 D = getCanonicalDecl(D); 1619 DSAVarData DVar; 1620 1621 auto *VD = dyn_cast<VarDecl>(D); 1622 auto TI = Threadprivates.find(D); 1623 if (TI != Threadprivates.end()) { 1624 DVar.RefExpr = TI->getSecond().RefExpr.getPointer(); 1625 DVar.CKind = OMPC_threadprivate; 1626 DVar.Modifier = TI->getSecond().Modifier; 1627 return DVar; 1628 } 1629 if (VD && VD->hasAttr<OMPThreadPrivateDeclAttr>()) { 1630 DVar.RefExpr = buildDeclRefExpr( 1631 SemaRef, VD, D->getType().getNonReferenceType(), 1632 VD->getAttr<OMPThreadPrivateDeclAttr>()->getLocation()); 1633 DVar.CKind = OMPC_threadprivate; 1634 addDSA(D, DVar.RefExpr, OMPC_threadprivate); 1635 return DVar; 1636 } 1637 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 1638 // in a Construct, C/C++, predetermined, p.1] 1639 // Variables appearing in threadprivate directives are threadprivate. 1640 if ((VD && VD->getTLSKind() != VarDecl::TLS_None && 1641 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() && 1642 SemaRef.getLangOpts().OpenMPUseTLS && 1643 SemaRef.getASTContext().getTargetInfo().isTLSSupported())) || 1644 (VD && VD->getStorageClass() == SC_Register && 1645 VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())) { 1646 DVar.RefExpr = buildDeclRefExpr( 1647 SemaRef, VD, D->getType().getNonReferenceType(), D->getLocation()); 1648 DVar.CKind = OMPC_threadprivate; 1649 addDSA(D, DVar.RefExpr, OMPC_threadprivate); 1650 return DVar; 1651 } 1652 if (SemaRef.getLangOpts().OpenMPCUDAMode && VD && 1653 VD->isLocalVarDeclOrParm() && !isStackEmpty() && 1654 !isLoopControlVariable(D).first) { 1655 const_iterator IterTarget = 1656 std::find_if(begin(), end(), [](const SharingMapTy &Data) { 1657 return isOpenMPTargetExecutionDirective(Data.Directive); 1658 }); 1659 if (IterTarget != end()) { 1660 const_iterator ParentIterTarget = IterTarget + 1; 1661 for (const_iterator Iter = begin(); 1662 Iter != ParentIterTarget; ++Iter) { 1663 if (isOpenMPLocal(VD, Iter)) { 1664 DVar.RefExpr = 1665 buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(), 1666 D->getLocation()); 1667 DVar.CKind = OMPC_threadprivate; 1668 return DVar; 1669 } 1670 } 1671 if (!isClauseParsingMode() || IterTarget != begin()) { 1672 auto DSAIter = IterTarget->SharingMap.find(D); 1673 if (DSAIter != IterTarget->SharingMap.end() && 1674 isOpenMPPrivate(DSAIter->getSecond().Attributes)) { 1675 DVar.RefExpr = DSAIter->getSecond().RefExpr.getPointer(); 1676 DVar.CKind = OMPC_threadprivate; 1677 return DVar; 1678 } 1679 const_iterator End = end(); 1680 if (!SemaRef.isOpenMPCapturedByRef( 1681 D, std::distance(ParentIterTarget, End), 1682 /*OpenMPCaptureLevel=*/0)) { 1683 DVar.RefExpr = 1684 buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(), 1685 IterTarget->ConstructLoc); 1686 DVar.CKind = OMPC_threadprivate; 1687 return DVar; 1688 } 1689 } 1690 } 1691 } 1692 1693 if (isStackEmpty()) 1694 // Not in OpenMP execution region and top scope was already checked. 1695 return DVar; 1696 1697 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 1698 // in a Construct, C/C++, predetermined, p.4] 1699 // Static data members are shared. 1700 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 1701 // in a Construct, C/C++, predetermined, p.7] 1702 // Variables with static storage duration that are declared in a scope 1703 // inside the construct are shared. 1704 if (VD && VD->isStaticDataMember()) { 1705 // Check for explicitly specified attributes. 1706 const_iterator I = begin(); 1707 const_iterator EndI = end(); 1708 if (FromParent && I != EndI) 1709 ++I; 1710 if (I != EndI) { 1711 auto It = I->SharingMap.find(D); 1712 if (It != I->SharingMap.end()) { 1713 const DSAInfo &Data = It->getSecond(); 1714 DVar.RefExpr = Data.RefExpr.getPointer(); 1715 DVar.PrivateCopy = Data.PrivateCopy; 1716 DVar.CKind = Data.Attributes; 1717 DVar.ImplicitDSALoc = I->DefaultAttrLoc; 1718 DVar.DKind = I->Directive; 1719 DVar.Modifier = Data.Modifier; 1720 DVar.AppliedToPointee = Data.AppliedToPointee; 1721 return DVar; 1722 } 1723 } 1724 1725 DVar.CKind = OMPC_shared; 1726 return DVar; 1727 } 1728 1729 auto &&MatchesAlways = [](OpenMPDirectiveKind) { return true; }; 1730 // The predetermined shared attribute for const-qualified types having no 1731 // mutable members was removed after OpenMP 3.1. 1732 if (SemaRef.LangOpts.OpenMP <= 31) { 1733 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 1734 // in a Construct, C/C++, predetermined, p.6] 1735 // Variables with const qualified type having no mutable member are 1736 // shared. 1737 if (isConstNotMutableType(SemaRef, D->getType())) { 1738 // Variables with const-qualified type having no mutable member may be 1739 // listed in a firstprivate clause, even if they are static data members. 1740 DSAVarData DVarTemp = hasInnermostDSA( 1741 D, 1742 [](OpenMPClauseKind C, bool) { 1743 return C == OMPC_firstprivate || C == OMPC_shared; 1744 }, 1745 MatchesAlways, FromParent); 1746 if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr) 1747 return DVarTemp; 1748 1749 DVar.CKind = OMPC_shared; 1750 return DVar; 1751 } 1752 } 1753 1754 // Explicitly specified attributes and local variables with predetermined 1755 // attributes. 1756 const_iterator I = begin(); 1757 const_iterator EndI = end(); 1758 if (FromParent && I != EndI) 1759 ++I; 1760 if (I == EndI) 1761 return DVar; 1762 auto It = I->SharingMap.find(D); 1763 if (It != I->SharingMap.end()) { 1764 const DSAInfo &Data = It->getSecond(); 1765 DVar.RefExpr = Data.RefExpr.getPointer(); 1766 DVar.PrivateCopy = Data.PrivateCopy; 1767 DVar.CKind = Data.Attributes; 1768 DVar.ImplicitDSALoc = I->DefaultAttrLoc; 1769 DVar.DKind = I->Directive; 1770 DVar.Modifier = Data.Modifier; 1771 DVar.AppliedToPointee = Data.AppliedToPointee; 1772 } 1773 1774 return DVar; 1775 } 1776 1777 const DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(ValueDecl *D, 1778 bool FromParent) const { 1779 if (isStackEmpty()) { 1780 const_iterator I; 1781 return getDSA(I, D); 1782 } 1783 D = getCanonicalDecl(D); 1784 const_iterator StartI = begin(); 1785 const_iterator EndI = end(); 1786 if (FromParent && StartI != EndI) 1787 ++StartI; 1788 return getDSA(StartI, D); 1789 } 1790 1791 const DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(ValueDecl *D, 1792 unsigned Level) const { 1793 if (getStackSize() <= Level) 1794 return DSAVarData(); 1795 D = getCanonicalDecl(D); 1796 const_iterator StartI = std::next(begin(), getStackSize() - 1 - Level); 1797 return getDSA(StartI, D); 1798 } 1799 1800 const DSAStackTy::DSAVarData 1801 DSAStackTy::hasDSA(ValueDecl *D, 1802 const llvm::function_ref<bool(OpenMPClauseKind, bool)> CPred, 1803 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred, 1804 bool FromParent) const { 1805 if (isStackEmpty()) 1806 return {}; 1807 D = getCanonicalDecl(D); 1808 const_iterator I = begin(); 1809 const_iterator EndI = end(); 1810 if (FromParent && I != EndI) 1811 ++I; 1812 for (; I != EndI; ++I) { 1813 if (!DPred(I->Directive) && 1814 !isImplicitOrExplicitTaskingRegion(I->Directive)) 1815 continue; 1816 const_iterator NewI = I; 1817 DSAVarData DVar = getDSA(NewI, D); 1818 if (I == NewI && CPred(DVar.CKind, DVar.AppliedToPointee)) 1819 return DVar; 1820 } 1821 return {}; 1822 } 1823 1824 const DSAStackTy::DSAVarData DSAStackTy::hasInnermostDSA( 1825 ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind, bool)> CPred, 1826 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred, 1827 bool FromParent) const { 1828 if (isStackEmpty()) 1829 return {}; 1830 D = getCanonicalDecl(D); 1831 const_iterator StartI = begin(); 1832 const_iterator EndI = end(); 1833 if (FromParent && StartI != EndI) 1834 ++StartI; 1835 if (StartI == EndI || !DPred(StartI->Directive)) 1836 return {}; 1837 const_iterator NewI = StartI; 1838 DSAVarData DVar = getDSA(NewI, D); 1839 return (NewI == StartI && CPred(DVar.CKind, DVar.AppliedToPointee)) 1840 ? DVar 1841 : DSAVarData(); 1842 } 1843 1844 bool DSAStackTy::hasExplicitDSA( 1845 const ValueDecl *D, 1846 const llvm::function_ref<bool(OpenMPClauseKind, bool)> CPred, 1847 unsigned Level, bool NotLastprivate) const { 1848 if (getStackSize() <= Level) 1849 return false; 1850 D = getCanonicalDecl(D); 1851 const SharingMapTy &StackElem = getStackElemAtLevel(Level); 1852 auto I = StackElem.SharingMap.find(D); 1853 if (I != StackElem.SharingMap.end() && I->getSecond().RefExpr.getPointer() && 1854 CPred(I->getSecond().Attributes, I->getSecond().AppliedToPointee) && 1855 (!NotLastprivate || !I->getSecond().RefExpr.getInt())) 1856 return true; 1857 // Check predetermined rules for the loop control variables. 1858 auto LI = StackElem.LCVMap.find(D); 1859 if (LI != StackElem.LCVMap.end()) 1860 return CPred(OMPC_private, /*AppliedToPointee=*/false); 1861 return false; 1862 } 1863 1864 bool DSAStackTy::hasExplicitDirective( 1865 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred, 1866 unsigned Level) const { 1867 if (getStackSize() <= Level) 1868 return false; 1869 const SharingMapTy &StackElem = getStackElemAtLevel(Level); 1870 return DPred(StackElem.Directive); 1871 } 1872 1873 bool DSAStackTy::hasDirective( 1874 const llvm::function_ref<bool(OpenMPDirectiveKind, 1875 const DeclarationNameInfo &, SourceLocation)> 1876 DPred, 1877 bool FromParent) const { 1878 // We look only in the enclosing region. 1879 size_t Skip = FromParent ? 2 : 1; 1880 for (const_iterator I = begin() + std::min(Skip, getStackSize()), E = end(); 1881 I != E; ++I) { 1882 if (DPred(I->Directive, I->DirectiveName, I->ConstructLoc)) 1883 return true; 1884 } 1885 return false; 1886 } 1887 1888 void Sema::InitDataSharingAttributesStack() { 1889 VarDataSharingAttributesStack = new DSAStackTy(*this); 1890 } 1891 1892 #define DSAStack static_cast<DSAStackTy *>(VarDataSharingAttributesStack) 1893 1894 void Sema::pushOpenMPFunctionRegion() { 1895 DSAStack->pushFunction(); 1896 } 1897 1898 void Sema::popOpenMPFunctionRegion(const FunctionScopeInfo *OldFSI) { 1899 DSAStack->popFunction(OldFSI); 1900 } 1901 1902 static bool isOpenMPDeviceDelayedContext(Sema &S) { 1903 assert(S.LangOpts.OpenMP && S.LangOpts.OpenMPIsDevice && 1904 "Expected OpenMP device compilation."); 1905 return !S.isInOpenMPTargetExecutionDirective(); 1906 } 1907 1908 namespace { 1909 /// Status of the function emission on the host/device. 1910 enum class FunctionEmissionStatus { 1911 Emitted, 1912 Discarded, 1913 Unknown, 1914 }; 1915 } // anonymous namespace 1916 1917 Sema::SemaDiagnosticBuilder Sema::diagIfOpenMPDeviceCode(SourceLocation Loc, 1918 unsigned DiagID, 1919 FunctionDecl *FD) { 1920 assert(LangOpts.OpenMP && LangOpts.OpenMPIsDevice && 1921 "Expected OpenMP device compilation."); 1922 1923 SemaDiagnosticBuilder::Kind Kind = SemaDiagnosticBuilder::K_Nop; 1924 if (FD) { 1925 FunctionEmissionStatus FES = getEmissionStatus(FD); 1926 switch (FES) { 1927 case FunctionEmissionStatus::Emitted: 1928 Kind = SemaDiagnosticBuilder::K_Immediate; 1929 break; 1930 case FunctionEmissionStatus::Unknown: 1931 // TODO: We should always delay diagnostics here in case a target 1932 // region is in a function we do not emit. However, as the 1933 // current diagnostics are associated with the function containing 1934 // the target region and we do not emit that one, we would miss out 1935 // on diagnostics for the target region itself. We need to anchor 1936 // the diagnostics with the new generated function *or* ensure we 1937 // emit diagnostics associated with the surrounding function. 1938 Kind = isOpenMPDeviceDelayedContext(*this) 1939 ? SemaDiagnosticBuilder::K_Deferred 1940 : SemaDiagnosticBuilder::K_Immediate; 1941 break; 1942 case FunctionEmissionStatus::TemplateDiscarded: 1943 case FunctionEmissionStatus::OMPDiscarded: 1944 Kind = SemaDiagnosticBuilder::K_Nop; 1945 break; 1946 case FunctionEmissionStatus::CUDADiscarded: 1947 llvm_unreachable("CUDADiscarded unexpected in OpenMP device compilation"); 1948 break; 1949 } 1950 } 1951 1952 return SemaDiagnosticBuilder(Kind, Loc, DiagID, FD, *this); 1953 } 1954 1955 Sema::SemaDiagnosticBuilder Sema::diagIfOpenMPHostCode(SourceLocation Loc, 1956 unsigned DiagID, 1957 FunctionDecl *FD) { 1958 assert(LangOpts.OpenMP && !LangOpts.OpenMPIsDevice && 1959 "Expected OpenMP host compilation."); 1960 1961 SemaDiagnosticBuilder::Kind Kind = SemaDiagnosticBuilder::K_Nop; 1962 if (FD) { 1963 FunctionEmissionStatus FES = getEmissionStatus(FD); 1964 switch (FES) { 1965 case FunctionEmissionStatus::Emitted: 1966 Kind = SemaDiagnosticBuilder::K_Immediate; 1967 break; 1968 case FunctionEmissionStatus::Unknown: 1969 Kind = SemaDiagnosticBuilder::K_Deferred; 1970 break; 1971 case FunctionEmissionStatus::TemplateDiscarded: 1972 case FunctionEmissionStatus::OMPDiscarded: 1973 case FunctionEmissionStatus::CUDADiscarded: 1974 Kind = SemaDiagnosticBuilder::K_Nop; 1975 break; 1976 } 1977 } 1978 1979 return SemaDiagnosticBuilder(Kind, Loc, DiagID, FD, *this); 1980 } 1981 1982 static OpenMPDefaultmapClauseKind 1983 getVariableCategoryFromDecl(const LangOptions &LO, const ValueDecl *VD) { 1984 if (LO.OpenMP <= 45) { 1985 if (VD->getType().getNonReferenceType()->isScalarType()) 1986 return OMPC_DEFAULTMAP_scalar; 1987 return OMPC_DEFAULTMAP_aggregate; 1988 } 1989 if (VD->getType().getNonReferenceType()->isAnyPointerType()) 1990 return OMPC_DEFAULTMAP_pointer; 1991 if (VD->getType().getNonReferenceType()->isScalarType()) 1992 return OMPC_DEFAULTMAP_scalar; 1993 return OMPC_DEFAULTMAP_aggregate; 1994 } 1995 1996 bool Sema::isOpenMPCapturedByRef(const ValueDecl *D, unsigned Level, 1997 unsigned OpenMPCaptureLevel) const { 1998 assert(LangOpts.OpenMP && "OpenMP is not allowed"); 1999 2000 ASTContext &Ctx = getASTContext(); 2001 bool IsByRef = true; 2002 2003 // Find the directive that is associated with the provided scope. 2004 D = cast<ValueDecl>(D->getCanonicalDecl()); 2005 QualType Ty = D->getType(); 2006 2007 bool IsVariableUsedInMapClause = false; 2008 if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, Level)) { 2009 // This table summarizes how a given variable should be passed to the device 2010 // given its type and the clauses where it appears. This table is based on 2011 // the description in OpenMP 4.5 [2.10.4, target Construct] and 2012 // OpenMP 4.5 [2.15.5, Data-mapping Attribute Rules and Clauses]. 2013 // 2014 // ========================================================================= 2015 // | type | defaultmap | pvt | first | is_device_ptr | map | res. | 2016 // | |(tofrom:scalar)| | pvt | | | | 2017 // ========================================================================= 2018 // | scl | | | | - | | bycopy| 2019 // | scl | | - | x | - | - | bycopy| 2020 // | scl | | x | - | - | - | null | 2021 // | scl | x | | | - | | byref | 2022 // | scl | x | - | x | - | - | bycopy| 2023 // | scl | x | x | - | - | - | null | 2024 // | scl | | - | - | - | x | byref | 2025 // | scl | x | - | - | - | x | byref | 2026 // 2027 // | agg | n.a. | | | - | | byref | 2028 // | agg | n.a. | - | x | - | - | byref | 2029 // | agg | n.a. | x | - | - | - | null | 2030 // | agg | n.a. | - | - | - | x | byref | 2031 // | agg | n.a. | - | - | - | x[] | byref | 2032 // 2033 // | ptr | n.a. | | | - | | bycopy| 2034 // | ptr | n.a. | - | x | - | - | bycopy| 2035 // | ptr | n.a. | x | - | - | - | null | 2036 // | ptr | n.a. | - | - | - | x | byref | 2037 // | ptr | n.a. | - | - | - | x[] | bycopy| 2038 // | ptr | n.a. | - | - | x | | bycopy| 2039 // | ptr | n.a. | - | - | x | x | bycopy| 2040 // | ptr | n.a. | - | - | x | x[] | bycopy| 2041 // ========================================================================= 2042 // Legend: 2043 // scl - scalar 2044 // ptr - pointer 2045 // agg - aggregate 2046 // x - applies 2047 // - - invalid in this combination 2048 // [] - mapped with an array section 2049 // byref - should be mapped by reference 2050 // byval - should be mapped by value 2051 // null - initialize a local variable to null on the device 2052 // 2053 // Observations: 2054 // - All scalar declarations that show up in a map clause have to be passed 2055 // by reference, because they may have been mapped in the enclosing data 2056 // environment. 2057 // - If the scalar value does not fit the size of uintptr, it has to be 2058 // passed by reference, regardless the result in the table above. 2059 // - For pointers mapped by value that have either an implicit map or an 2060 // array section, the runtime library may pass the NULL value to the 2061 // device instead of the value passed to it by the compiler. 2062 2063 if (Ty->isReferenceType()) 2064 Ty = Ty->castAs<ReferenceType>()->getPointeeType(); 2065 2066 // Locate map clauses and see if the variable being captured is referred to 2067 // in any of those clauses. Here we only care about variables, not fields, 2068 // because fields are part of aggregates. 2069 bool IsVariableAssociatedWithSection = false; 2070 2071 DSAStack->checkMappableExprComponentListsForDeclAtLevel( 2072 D, Level, 2073 [&IsVariableUsedInMapClause, &IsVariableAssociatedWithSection, D]( 2074 OMPClauseMappableExprCommon::MappableExprComponentListRef 2075 MapExprComponents, 2076 OpenMPClauseKind WhereFoundClauseKind) { 2077 // Only the map clause information influences how a variable is 2078 // captured. E.g. is_device_ptr does not require changing the default 2079 // behavior. 2080 if (WhereFoundClauseKind != OMPC_map) 2081 return false; 2082 2083 auto EI = MapExprComponents.rbegin(); 2084 auto EE = MapExprComponents.rend(); 2085 2086 assert(EI != EE && "Invalid map expression!"); 2087 2088 if (isa<DeclRefExpr>(EI->getAssociatedExpression())) 2089 IsVariableUsedInMapClause |= EI->getAssociatedDeclaration() == D; 2090 2091 ++EI; 2092 if (EI == EE) 2093 return false; 2094 2095 if (isa<ArraySubscriptExpr>(EI->getAssociatedExpression()) || 2096 isa<OMPArraySectionExpr>(EI->getAssociatedExpression()) || 2097 isa<MemberExpr>(EI->getAssociatedExpression()) || 2098 isa<OMPArrayShapingExpr>(EI->getAssociatedExpression())) { 2099 IsVariableAssociatedWithSection = true; 2100 // There is nothing more we need to know about this variable. 2101 return true; 2102 } 2103 2104 // Keep looking for more map info. 2105 return false; 2106 }); 2107 2108 if (IsVariableUsedInMapClause) { 2109 // If variable is identified in a map clause it is always captured by 2110 // reference except if it is a pointer that is dereferenced somehow. 2111 IsByRef = !(Ty->isPointerType() && IsVariableAssociatedWithSection); 2112 } else { 2113 // By default, all the data that has a scalar type is mapped by copy 2114 // (except for reduction variables). 2115 // Defaultmap scalar is mutual exclusive to defaultmap pointer 2116 IsByRef = (DSAStack->isForceCaptureByReferenceInTargetExecutable() && 2117 !Ty->isAnyPointerType()) || 2118 !Ty->isScalarType() || 2119 DSAStack->isDefaultmapCapturedByRef( 2120 Level, getVariableCategoryFromDecl(LangOpts, D)) || 2121 DSAStack->hasExplicitDSA( 2122 D, 2123 [](OpenMPClauseKind K, bool AppliedToPointee) { 2124 return K == OMPC_reduction && !AppliedToPointee; 2125 }, 2126 Level); 2127 } 2128 } 2129 2130 if (IsByRef && Ty.getNonReferenceType()->isScalarType()) { 2131 IsByRef = 2132 ((IsVariableUsedInMapClause && 2133 DSAStack->getCaptureRegion(Level, OpenMPCaptureLevel) == 2134 OMPD_target) || 2135 !(DSAStack->hasExplicitDSA( 2136 D, 2137 [](OpenMPClauseKind K, bool AppliedToPointee) -> bool { 2138 return K == OMPC_firstprivate || 2139 (K == OMPC_reduction && AppliedToPointee); 2140 }, 2141 Level, /*NotLastprivate=*/true) || 2142 DSAStack->isUsesAllocatorsDecl(Level, D))) && 2143 // If the variable is artificial and must be captured by value - try to 2144 // capture by value. 2145 !(isa<OMPCapturedExprDecl>(D) && !D->hasAttr<OMPCaptureNoInitAttr>() && 2146 !cast<OMPCapturedExprDecl>(D)->getInit()->isGLValue()) && 2147 // If the variable is implicitly firstprivate and scalar - capture by 2148 // copy 2149 !(DSAStack->getDefaultDSA() == DSA_firstprivate && 2150 !DSAStack->hasExplicitDSA( 2151 D, [](OpenMPClauseKind K, bool) { return K != OMPC_unknown; }, 2152 Level) && 2153 !DSAStack->isLoopControlVariable(D, Level).first); 2154 } 2155 2156 // When passing data by copy, we need to make sure it fits the uintptr size 2157 // and alignment, because the runtime library only deals with uintptr types. 2158 // If it does not fit the uintptr size, we need to pass the data by reference 2159 // instead. 2160 if (!IsByRef && 2161 (Ctx.getTypeSizeInChars(Ty) > 2162 Ctx.getTypeSizeInChars(Ctx.getUIntPtrType()) || 2163 Ctx.getDeclAlign(D) > Ctx.getTypeAlignInChars(Ctx.getUIntPtrType()))) { 2164 IsByRef = true; 2165 } 2166 2167 return IsByRef; 2168 } 2169 2170 unsigned Sema::getOpenMPNestingLevel() const { 2171 assert(getLangOpts().OpenMP); 2172 return DSAStack->getNestingLevel(); 2173 } 2174 2175 bool Sema::isInOpenMPTargetExecutionDirective() const { 2176 return (isOpenMPTargetExecutionDirective(DSAStack->getCurrentDirective()) && 2177 !DSAStack->isClauseParsingMode()) || 2178 DSAStack->hasDirective( 2179 [](OpenMPDirectiveKind K, const DeclarationNameInfo &, 2180 SourceLocation) -> bool { 2181 return isOpenMPTargetExecutionDirective(K); 2182 }, 2183 false); 2184 } 2185 2186 VarDecl *Sema::isOpenMPCapturedDecl(ValueDecl *D, bool CheckScopeInfo, 2187 unsigned StopAt) { 2188 assert(LangOpts.OpenMP && "OpenMP is not allowed"); 2189 D = getCanonicalDecl(D); 2190 2191 auto *VD = dyn_cast<VarDecl>(D); 2192 // Do not capture constexpr variables. 2193 if (VD && VD->isConstexpr()) 2194 return nullptr; 2195 2196 // If we want to determine whether the variable should be captured from the 2197 // perspective of the current capturing scope, and we've already left all the 2198 // capturing scopes of the top directive on the stack, check from the 2199 // perspective of its parent directive (if any) instead. 2200 DSAStackTy::ParentDirectiveScope InParentDirectiveRAII( 2201 *DSAStack, CheckScopeInfo && DSAStack->isBodyComplete()); 2202 2203 // If we are attempting to capture a global variable in a directive with 2204 // 'target' we return true so that this global is also mapped to the device. 2205 // 2206 if (VD && !VD->hasLocalStorage() && 2207 (getCurCapturedRegion() || getCurBlock() || getCurLambda())) { 2208 if (isInOpenMPTargetExecutionDirective()) { 2209 DSAStackTy::DSAVarData DVarTop = 2210 DSAStack->getTopDSA(D, DSAStack->isClauseParsingMode()); 2211 if (DVarTop.CKind != OMPC_unknown && DVarTop.RefExpr) 2212 return VD; 2213 // If the declaration is enclosed in a 'declare target' directive, 2214 // then it should not be captured. 2215 // 2216 if (OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) 2217 return nullptr; 2218 CapturedRegionScopeInfo *CSI = nullptr; 2219 for (FunctionScopeInfo *FSI : llvm::drop_begin( 2220 llvm::reverse(FunctionScopes), 2221 CheckScopeInfo ? (FunctionScopes.size() - (StopAt + 1)) : 0)) { 2222 if (!isa<CapturingScopeInfo>(FSI)) 2223 return nullptr; 2224 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(FSI)) 2225 if (RSI->CapRegionKind == CR_OpenMP) { 2226 CSI = RSI; 2227 break; 2228 } 2229 } 2230 assert(CSI && "Failed to find CapturedRegionScopeInfo"); 2231 SmallVector<OpenMPDirectiveKind, 4> Regions; 2232 getOpenMPCaptureRegions(Regions, 2233 DSAStack->getDirective(CSI->OpenMPLevel)); 2234 if (Regions[CSI->OpenMPCaptureLevel] != OMPD_task) 2235 return VD; 2236 } 2237 if (isInOpenMPDeclareTargetContext()) { 2238 // Try to mark variable as declare target if it is used in capturing 2239 // regions. 2240 if (LangOpts.OpenMP <= 45 && 2241 !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) 2242 checkDeclIsAllowedInOpenMPTarget(nullptr, VD); 2243 return nullptr; 2244 } 2245 } 2246 2247 if (CheckScopeInfo) { 2248 bool OpenMPFound = false; 2249 for (unsigned I = StopAt + 1; I > 0; --I) { 2250 FunctionScopeInfo *FSI = FunctionScopes[I - 1]; 2251 if(!isa<CapturingScopeInfo>(FSI)) 2252 return nullptr; 2253 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(FSI)) 2254 if (RSI->CapRegionKind == CR_OpenMP) { 2255 OpenMPFound = true; 2256 break; 2257 } 2258 } 2259 if (!OpenMPFound) 2260 return nullptr; 2261 } 2262 2263 if (DSAStack->getCurrentDirective() != OMPD_unknown && 2264 (!DSAStack->isClauseParsingMode() || 2265 DSAStack->getParentDirective() != OMPD_unknown)) { 2266 auto &&Info = DSAStack->isLoopControlVariable(D); 2267 if (Info.first || 2268 (VD && VD->hasLocalStorage() && 2269 isImplicitOrExplicitTaskingRegion(DSAStack->getCurrentDirective())) || 2270 (VD && DSAStack->isForceVarCapturing())) 2271 return VD ? VD : Info.second; 2272 DSAStackTy::DSAVarData DVarTop = 2273 DSAStack->getTopDSA(D, DSAStack->isClauseParsingMode()); 2274 if (DVarTop.CKind != OMPC_unknown && isOpenMPPrivate(DVarTop.CKind) && 2275 (!VD || VD->hasLocalStorage() || !DVarTop.AppliedToPointee)) 2276 return VD ? VD : cast<VarDecl>(DVarTop.PrivateCopy->getDecl()); 2277 // Threadprivate variables must not be captured. 2278 if (isOpenMPThreadPrivate(DVarTop.CKind)) 2279 return nullptr; 2280 // The variable is not private or it is the variable in the directive with 2281 // default(none) clause and not used in any clause. 2282 DSAStackTy::DSAVarData DVarPrivate = DSAStack->hasDSA( 2283 D, 2284 [](OpenMPClauseKind C, bool AppliedToPointee) { 2285 return isOpenMPPrivate(C) && !AppliedToPointee; 2286 }, 2287 [](OpenMPDirectiveKind) { return true; }, 2288 DSAStack->isClauseParsingMode()); 2289 // Global shared must not be captured. 2290 if (VD && !VD->hasLocalStorage() && DVarPrivate.CKind == OMPC_unknown && 2291 ((DSAStack->getDefaultDSA() != DSA_none && 2292 DSAStack->getDefaultDSA() != DSA_firstprivate) || 2293 DVarTop.CKind == OMPC_shared)) 2294 return nullptr; 2295 if (DVarPrivate.CKind != OMPC_unknown || 2296 (VD && (DSAStack->getDefaultDSA() == DSA_none || 2297 DSAStack->getDefaultDSA() == DSA_firstprivate))) 2298 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl()); 2299 } 2300 return nullptr; 2301 } 2302 2303 void Sema::adjustOpenMPTargetScopeIndex(unsigned &FunctionScopesIndex, 2304 unsigned Level) const { 2305 FunctionScopesIndex -= getOpenMPCaptureLevels(DSAStack->getDirective(Level)); 2306 } 2307 2308 void Sema::startOpenMPLoop() { 2309 assert(LangOpts.OpenMP && "OpenMP must be enabled."); 2310 if (isOpenMPLoopDirective(DSAStack->getCurrentDirective())) 2311 DSAStack->loopInit(); 2312 } 2313 2314 void Sema::startOpenMPCXXRangeFor() { 2315 assert(LangOpts.OpenMP && "OpenMP must be enabled."); 2316 if (isOpenMPLoopDirective(DSAStack->getCurrentDirective())) { 2317 DSAStack->resetPossibleLoopCounter(); 2318 DSAStack->loopStart(); 2319 } 2320 } 2321 2322 OpenMPClauseKind Sema::isOpenMPPrivateDecl(ValueDecl *D, unsigned Level, 2323 unsigned CapLevel) const { 2324 assert(LangOpts.OpenMP && "OpenMP is not allowed"); 2325 if (DSAStack->hasExplicitDirective( 2326 [](OpenMPDirectiveKind K) { return isOpenMPTaskingDirective(K); }, 2327 Level)) { 2328 bool IsTriviallyCopyable = 2329 D->getType().getNonReferenceType().isTriviallyCopyableType(Context) && 2330 !D->getType() 2331 .getNonReferenceType() 2332 .getCanonicalType() 2333 ->getAsCXXRecordDecl(); 2334 OpenMPDirectiveKind DKind = DSAStack->getDirective(Level); 2335 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions; 2336 getOpenMPCaptureRegions(CaptureRegions, DKind); 2337 if (isOpenMPTaskingDirective(CaptureRegions[CapLevel]) && 2338 (IsTriviallyCopyable || 2339 !isOpenMPTaskLoopDirective(CaptureRegions[CapLevel]))) { 2340 if (DSAStack->hasExplicitDSA( 2341 D, 2342 [](OpenMPClauseKind K, bool) { return K == OMPC_firstprivate; }, 2343 Level, /*NotLastprivate=*/true)) 2344 return OMPC_firstprivate; 2345 DSAStackTy::DSAVarData DVar = DSAStack->getImplicitDSA(D, Level); 2346 if (DVar.CKind != OMPC_shared && 2347 !DSAStack->isLoopControlVariable(D, Level).first && !DVar.RefExpr) { 2348 DSAStack->addImplicitTaskFirstprivate(Level, D); 2349 return OMPC_firstprivate; 2350 } 2351 } 2352 } 2353 if (isOpenMPLoopDirective(DSAStack->getCurrentDirective())) { 2354 if (DSAStack->getAssociatedLoops() > 0 && 2355 !DSAStack->isLoopStarted()) { 2356 DSAStack->resetPossibleLoopCounter(D); 2357 DSAStack->loopStart(); 2358 return OMPC_private; 2359 } 2360 if ((DSAStack->getPossiblyLoopCunter() == D->getCanonicalDecl() || 2361 DSAStack->isLoopControlVariable(D).first) && 2362 !DSAStack->hasExplicitDSA( 2363 D, [](OpenMPClauseKind K, bool) { return K != OMPC_private; }, 2364 Level) && 2365 !isOpenMPSimdDirective(DSAStack->getCurrentDirective())) 2366 return OMPC_private; 2367 } 2368 if (const auto *VD = dyn_cast<VarDecl>(D)) { 2369 if (DSAStack->isThreadPrivate(const_cast<VarDecl *>(VD)) && 2370 DSAStack->isForceVarCapturing() && 2371 !DSAStack->hasExplicitDSA( 2372 D, [](OpenMPClauseKind K, bool) { return K == OMPC_copyin; }, 2373 Level)) 2374 return OMPC_private; 2375 } 2376 // User-defined allocators are private since they must be defined in the 2377 // context of target region. 2378 if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, Level) && 2379 DSAStack->isUsesAllocatorsDecl(Level, D).getValueOr( 2380 DSAStackTy::UsesAllocatorsDeclKind::AllocatorTrait) == 2381 DSAStackTy::UsesAllocatorsDeclKind::UserDefinedAllocator) 2382 return OMPC_private; 2383 return (DSAStack->hasExplicitDSA( 2384 D, [](OpenMPClauseKind K, bool) { return K == OMPC_private; }, 2385 Level) || 2386 (DSAStack->isClauseParsingMode() && 2387 DSAStack->getClauseParsingMode() == OMPC_private) || 2388 // Consider taskgroup reduction descriptor variable a private 2389 // to avoid possible capture in the region. 2390 (DSAStack->hasExplicitDirective( 2391 [](OpenMPDirectiveKind K) { 2392 return K == OMPD_taskgroup || 2393 ((isOpenMPParallelDirective(K) || 2394 isOpenMPWorksharingDirective(K)) && 2395 !isOpenMPSimdDirective(K)); 2396 }, 2397 Level) && 2398 DSAStack->isTaskgroupReductionRef(D, Level))) 2399 ? OMPC_private 2400 : OMPC_unknown; 2401 } 2402 2403 void Sema::setOpenMPCaptureKind(FieldDecl *FD, const ValueDecl *D, 2404 unsigned Level) { 2405 assert(LangOpts.OpenMP && "OpenMP is not allowed"); 2406 D = getCanonicalDecl(D); 2407 OpenMPClauseKind OMPC = OMPC_unknown; 2408 for (unsigned I = DSAStack->getNestingLevel() + 1; I > Level; --I) { 2409 const unsigned NewLevel = I - 1; 2410 if (DSAStack->hasExplicitDSA( 2411 D, 2412 [&OMPC](const OpenMPClauseKind K, bool AppliedToPointee) { 2413 if (isOpenMPPrivate(K) && !AppliedToPointee) { 2414 OMPC = K; 2415 return true; 2416 } 2417 return false; 2418 }, 2419 NewLevel)) 2420 break; 2421 if (DSAStack->checkMappableExprComponentListsForDeclAtLevel( 2422 D, NewLevel, 2423 [](OMPClauseMappableExprCommon::MappableExprComponentListRef, 2424 OpenMPClauseKind) { return true; })) { 2425 OMPC = OMPC_map; 2426 break; 2427 } 2428 if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, 2429 NewLevel)) { 2430 OMPC = OMPC_map; 2431 if (DSAStack->mustBeFirstprivateAtLevel( 2432 NewLevel, getVariableCategoryFromDecl(LangOpts, D))) 2433 OMPC = OMPC_firstprivate; 2434 break; 2435 } 2436 } 2437 if (OMPC != OMPC_unknown) 2438 FD->addAttr(OMPCaptureKindAttr::CreateImplicit(Context, unsigned(OMPC))); 2439 } 2440 2441 bool Sema::isOpenMPTargetCapturedDecl(const ValueDecl *D, unsigned Level, 2442 unsigned CaptureLevel) const { 2443 assert(LangOpts.OpenMP && "OpenMP is not allowed"); 2444 // Return true if the current level is no longer enclosed in a target region. 2445 2446 SmallVector<OpenMPDirectiveKind, 4> Regions; 2447 getOpenMPCaptureRegions(Regions, DSAStack->getDirective(Level)); 2448 const auto *VD = dyn_cast<VarDecl>(D); 2449 return VD && !VD->hasLocalStorage() && 2450 DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, 2451 Level) && 2452 Regions[CaptureLevel] != OMPD_task; 2453 } 2454 2455 bool Sema::isOpenMPGlobalCapturedDecl(ValueDecl *D, unsigned Level, 2456 unsigned CaptureLevel) const { 2457 assert(LangOpts.OpenMP && "OpenMP is not allowed"); 2458 // Return true if the current level is no longer enclosed in a target region. 2459 2460 if (const auto *VD = dyn_cast<VarDecl>(D)) { 2461 if (!VD->hasLocalStorage()) { 2462 if (isInOpenMPTargetExecutionDirective()) 2463 return true; 2464 DSAStackTy::DSAVarData TopDVar = 2465 DSAStack->getTopDSA(D, /*FromParent=*/false); 2466 unsigned NumLevels = 2467 getOpenMPCaptureLevels(DSAStack->getDirective(Level)); 2468 if (Level == 0) 2469 return (NumLevels == CaptureLevel + 1) && TopDVar.CKind != OMPC_shared; 2470 do { 2471 --Level; 2472 DSAStackTy::DSAVarData DVar = DSAStack->getImplicitDSA(D, Level); 2473 if (DVar.CKind != OMPC_shared) 2474 return true; 2475 } while (Level > 0); 2476 } 2477 } 2478 return true; 2479 } 2480 2481 void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; } 2482 2483 void Sema::ActOnOpenMPBeginDeclareVariant(SourceLocation Loc, 2484 OMPTraitInfo &TI) { 2485 OMPDeclareVariantScopes.push_back(OMPDeclareVariantScope(TI)); 2486 } 2487 2488 void Sema::ActOnOpenMPEndDeclareVariant() { 2489 assert(isInOpenMPDeclareVariantScope() && 2490 "Not in OpenMP declare variant scope!"); 2491 2492 OMPDeclareVariantScopes.pop_back(); 2493 } 2494 2495 void Sema::finalizeOpenMPDelayedAnalysis(const FunctionDecl *Caller, 2496 const FunctionDecl *Callee, 2497 SourceLocation Loc) { 2498 assert(LangOpts.OpenMP && "Expected OpenMP compilation mode."); 2499 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy = 2500 OMPDeclareTargetDeclAttr::getDeviceType(Caller->getMostRecentDecl()); 2501 // Ignore host functions during device analyzis. 2502 if (LangOpts.OpenMPIsDevice && 2503 (!DevTy || *DevTy == OMPDeclareTargetDeclAttr::DT_Host)) 2504 return; 2505 // Ignore nohost functions during host analyzis. 2506 if (!LangOpts.OpenMPIsDevice && DevTy && 2507 *DevTy == OMPDeclareTargetDeclAttr::DT_NoHost) 2508 return; 2509 const FunctionDecl *FD = Callee->getMostRecentDecl(); 2510 DevTy = OMPDeclareTargetDeclAttr::getDeviceType(FD); 2511 if (LangOpts.OpenMPIsDevice && DevTy && 2512 *DevTy == OMPDeclareTargetDeclAttr::DT_Host) { 2513 // Diagnose host function called during device codegen. 2514 StringRef HostDevTy = 2515 getOpenMPSimpleClauseTypeName(OMPC_device_type, OMPC_DEVICE_TYPE_host); 2516 Diag(Loc, diag::err_omp_wrong_device_function_call) << HostDevTy << 0; 2517 Diag(*OMPDeclareTargetDeclAttr::getLocation(FD), 2518 diag::note_omp_marked_device_type_here) 2519 << HostDevTy; 2520 return; 2521 } 2522 if (!LangOpts.OpenMPIsDevice && DevTy && 2523 *DevTy == OMPDeclareTargetDeclAttr::DT_NoHost) { 2524 // Diagnose nohost function called during host codegen. 2525 StringRef NoHostDevTy = getOpenMPSimpleClauseTypeName( 2526 OMPC_device_type, OMPC_DEVICE_TYPE_nohost); 2527 Diag(Loc, diag::err_omp_wrong_device_function_call) << NoHostDevTy << 1; 2528 Diag(*OMPDeclareTargetDeclAttr::getLocation(FD), 2529 diag::note_omp_marked_device_type_here) 2530 << NoHostDevTy; 2531 } 2532 } 2533 2534 void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind, 2535 const DeclarationNameInfo &DirName, 2536 Scope *CurScope, SourceLocation Loc) { 2537 DSAStack->push(DKind, DirName, CurScope, Loc); 2538 PushExpressionEvaluationContext( 2539 ExpressionEvaluationContext::PotentiallyEvaluated); 2540 } 2541 2542 void Sema::StartOpenMPClause(OpenMPClauseKind K) { 2543 DSAStack->setClauseParsingMode(K); 2544 } 2545 2546 void Sema::EndOpenMPClause() { 2547 DSAStack->setClauseParsingMode(/*K=*/OMPC_unknown); 2548 CleanupVarDeclMarking(); 2549 } 2550 2551 static std::pair<ValueDecl *, bool> 2552 getPrivateItem(Sema &S, Expr *&RefExpr, SourceLocation &ELoc, 2553 SourceRange &ERange, bool AllowArraySection = false); 2554 2555 /// Check consistency of the reduction clauses. 2556 static void checkReductionClauses(Sema &S, DSAStackTy *Stack, 2557 ArrayRef<OMPClause *> Clauses) { 2558 bool InscanFound = false; 2559 SourceLocation InscanLoc; 2560 // OpenMP 5.0, 2.19.5.4 reduction Clause, Restrictions. 2561 // A reduction clause without the inscan reduction-modifier may not appear on 2562 // a construct on which a reduction clause with the inscan reduction-modifier 2563 // appears. 2564 for (OMPClause *C : Clauses) { 2565 if (C->getClauseKind() != OMPC_reduction) 2566 continue; 2567 auto *RC = cast<OMPReductionClause>(C); 2568 if (RC->getModifier() == OMPC_REDUCTION_inscan) { 2569 InscanFound = true; 2570 InscanLoc = RC->getModifierLoc(); 2571 continue; 2572 } 2573 if (RC->getModifier() == OMPC_REDUCTION_task) { 2574 // OpenMP 5.0, 2.19.5.4 reduction Clause. 2575 // A reduction clause with the task reduction-modifier may only appear on 2576 // a parallel construct, a worksharing construct or a combined or 2577 // composite construct for which any of the aforementioned constructs is a 2578 // constituent construct and simd or loop are not constituent constructs. 2579 OpenMPDirectiveKind CurDir = Stack->getCurrentDirective(); 2580 if (!(isOpenMPParallelDirective(CurDir) || 2581 isOpenMPWorksharingDirective(CurDir)) || 2582 isOpenMPSimdDirective(CurDir)) 2583 S.Diag(RC->getModifierLoc(), 2584 diag::err_omp_reduction_task_not_parallel_or_worksharing); 2585 continue; 2586 } 2587 } 2588 if (InscanFound) { 2589 for (OMPClause *C : Clauses) { 2590 if (C->getClauseKind() != OMPC_reduction) 2591 continue; 2592 auto *RC = cast<OMPReductionClause>(C); 2593 if (RC->getModifier() != OMPC_REDUCTION_inscan) { 2594 S.Diag(RC->getModifier() == OMPC_REDUCTION_unknown 2595 ? RC->getBeginLoc() 2596 : RC->getModifierLoc(), 2597 diag::err_omp_inscan_reduction_expected); 2598 S.Diag(InscanLoc, diag::note_omp_previous_inscan_reduction); 2599 continue; 2600 } 2601 for (Expr *Ref : RC->varlists()) { 2602 assert(Ref && "NULL expr in OpenMP nontemporal clause."); 2603 SourceLocation ELoc; 2604 SourceRange ERange; 2605 Expr *SimpleRefExpr = Ref; 2606 auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange, 2607 /*AllowArraySection=*/true); 2608 ValueDecl *D = Res.first; 2609 if (!D) 2610 continue; 2611 if (!Stack->isUsedInScanDirective(getCanonicalDecl(D))) { 2612 S.Diag(Ref->getExprLoc(), 2613 diag::err_omp_reduction_not_inclusive_exclusive) 2614 << Ref->getSourceRange(); 2615 } 2616 } 2617 } 2618 } 2619 } 2620 2621 static void checkAllocateClauses(Sema &S, DSAStackTy *Stack, 2622 ArrayRef<OMPClause *> Clauses); 2623 static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr, 2624 bool WithInit); 2625 2626 static void reportOriginalDsa(Sema &SemaRef, const DSAStackTy *Stack, 2627 const ValueDecl *D, 2628 const DSAStackTy::DSAVarData &DVar, 2629 bool IsLoopIterVar = false); 2630 2631 void Sema::EndOpenMPDSABlock(Stmt *CurDirective) { 2632 // OpenMP [2.14.3.5, Restrictions, C/C++, p.1] 2633 // A variable of class type (or array thereof) that appears in a lastprivate 2634 // clause requires an accessible, unambiguous default constructor for the 2635 // class type, unless the list item is also specified in a firstprivate 2636 // clause. 2637 if (const auto *D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) { 2638 for (OMPClause *C : D->clauses()) { 2639 if (auto *Clause = dyn_cast<OMPLastprivateClause>(C)) { 2640 SmallVector<Expr *, 8> PrivateCopies; 2641 for (Expr *DE : Clause->varlists()) { 2642 if (DE->isValueDependent() || DE->isTypeDependent()) { 2643 PrivateCopies.push_back(nullptr); 2644 continue; 2645 } 2646 auto *DRE = cast<DeclRefExpr>(DE->IgnoreParens()); 2647 auto *VD = cast<VarDecl>(DRE->getDecl()); 2648 QualType Type = VD->getType().getNonReferenceType(); 2649 const DSAStackTy::DSAVarData DVar = 2650 DSAStack->getTopDSA(VD, /*FromParent=*/false); 2651 if (DVar.CKind == OMPC_lastprivate) { 2652 // Generate helper private variable and initialize it with the 2653 // default value. The address of the original variable is replaced 2654 // by the address of the new private variable in CodeGen. This new 2655 // variable is not added to IdResolver, so the code in the OpenMP 2656 // region uses original variable for proper diagnostics. 2657 VarDecl *VDPrivate = buildVarDecl( 2658 *this, DE->getExprLoc(), Type.getUnqualifiedType(), 2659 VD->getName(), VD->hasAttrs() ? &VD->getAttrs() : nullptr, DRE); 2660 ActOnUninitializedDecl(VDPrivate); 2661 if (VDPrivate->isInvalidDecl()) { 2662 PrivateCopies.push_back(nullptr); 2663 continue; 2664 } 2665 PrivateCopies.push_back(buildDeclRefExpr( 2666 *this, VDPrivate, DE->getType(), DE->getExprLoc())); 2667 } else { 2668 // The variable is also a firstprivate, so initialization sequence 2669 // for private copy is generated already. 2670 PrivateCopies.push_back(nullptr); 2671 } 2672 } 2673 Clause->setPrivateCopies(PrivateCopies); 2674 continue; 2675 } 2676 // Finalize nontemporal clause by handling private copies, if any. 2677 if (auto *Clause = dyn_cast<OMPNontemporalClause>(C)) { 2678 SmallVector<Expr *, 8> PrivateRefs; 2679 for (Expr *RefExpr : Clause->varlists()) { 2680 assert(RefExpr && "NULL expr in OpenMP nontemporal clause."); 2681 SourceLocation ELoc; 2682 SourceRange ERange; 2683 Expr *SimpleRefExpr = RefExpr; 2684 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 2685 if (Res.second) 2686 // It will be analyzed later. 2687 PrivateRefs.push_back(RefExpr); 2688 ValueDecl *D = Res.first; 2689 if (!D) 2690 continue; 2691 2692 const DSAStackTy::DSAVarData DVar = 2693 DSAStack->getTopDSA(D, /*FromParent=*/false); 2694 PrivateRefs.push_back(DVar.PrivateCopy ? DVar.PrivateCopy 2695 : SimpleRefExpr); 2696 } 2697 Clause->setPrivateRefs(PrivateRefs); 2698 continue; 2699 } 2700 if (auto *Clause = dyn_cast<OMPUsesAllocatorsClause>(C)) { 2701 for (unsigned I = 0, E = Clause->getNumberOfAllocators(); I < E; ++I) { 2702 OMPUsesAllocatorsClause::Data D = Clause->getAllocatorData(I); 2703 auto *DRE = dyn_cast<DeclRefExpr>(D.Allocator->IgnoreParenImpCasts()); 2704 if (!DRE) 2705 continue; 2706 ValueDecl *VD = DRE->getDecl(); 2707 if (!VD || !isa<VarDecl>(VD)) 2708 continue; 2709 DSAStackTy::DSAVarData DVar = 2710 DSAStack->getTopDSA(VD, /*FromParent=*/false); 2711 // OpenMP [2.12.5, target Construct] 2712 // Memory allocators that appear in a uses_allocators clause cannot 2713 // appear in other data-sharing attribute clauses or data-mapping 2714 // attribute clauses in the same construct. 2715 Expr *MapExpr = nullptr; 2716 if (DVar.RefExpr || 2717 DSAStack->checkMappableExprComponentListsForDecl( 2718 VD, /*CurrentRegionOnly=*/true, 2719 [VD, &MapExpr]( 2720 OMPClauseMappableExprCommon::MappableExprComponentListRef 2721 MapExprComponents, 2722 OpenMPClauseKind C) { 2723 auto MI = MapExprComponents.rbegin(); 2724 auto ME = MapExprComponents.rend(); 2725 if (MI != ME && 2726 MI->getAssociatedDeclaration()->getCanonicalDecl() == 2727 VD->getCanonicalDecl()) { 2728 MapExpr = MI->getAssociatedExpression(); 2729 return true; 2730 } 2731 return false; 2732 })) { 2733 Diag(D.Allocator->getExprLoc(), 2734 diag::err_omp_allocator_used_in_clauses) 2735 << D.Allocator->getSourceRange(); 2736 if (DVar.RefExpr) 2737 reportOriginalDsa(*this, DSAStack, VD, DVar); 2738 else 2739 Diag(MapExpr->getExprLoc(), diag::note_used_here) 2740 << MapExpr->getSourceRange(); 2741 } 2742 } 2743 continue; 2744 } 2745 } 2746 // Check allocate clauses. 2747 if (!CurContext->isDependentContext()) 2748 checkAllocateClauses(*this, DSAStack, D->clauses()); 2749 checkReductionClauses(*this, DSAStack, D->clauses()); 2750 } 2751 2752 DSAStack->pop(); 2753 DiscardCleanupsInEvaluationContext(); 2754 PopExpressionEvaluationContext(); 2755 } 2756 2757 static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV, 2758 Expr *NumIterations, Sema &SemaRef, 2759 Scope *S, DSAStackTy *Stack); 2760 2761 namespace { 2762 2763 class VarDeclFilterCCC final : public CorrectionCandidateCallback { 2764 private: 2765 Sema &SemaRef; 2766 2767 public: 2768 explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {} 2769 bool ValidateCandidate(const TypoCorrection &Candidate) override { 2770 NamedDecl *ND = Candidate.getCorrectionDecl(); 2771 if (const auto *VD = dyn_cast_or_null<VarDecl>(ND)) { 2772 return VD->hasGlobalStorage() && 2773 SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(), 2774 SemaRef.getCurScope()); 2775 } 2776 return false; 2777 } 2778 2779 std::unique_ptr<CorrectionCandidateCallback> clone() override { 2780 return std::make_unique<VarDeclFilterCCC>(*this); 2781 } 2782 2783 }; 2784 2785 class VarOrFuncDeclFilterCCC final : public CorrectionCandidateCallback { 2786 private: 2787 Sema &SemaRef; 2788 2789 public: 2790 explicit VarOrFuncDeclFilterCCC(Sema &S) : SemaRef(S) {} 2791 bool ValidateCandidate(const TypoCorrection &Candidate) override { 2792 NamedDecl *ND = Candidate.getCorrectionDecl(); 2793 if (ND && ((isa<VarDecl>(ND) && ND->getKind() == Decl::Var) || 2794 isa<FunctionDecl>(ND))) { 2795 return SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(), 2796 SemaRef.getCurScope()); 2797 } 2798 return false; 2799 } 2800 2801 std::unique_ptr<CorrectionCandidateCallback> clone() override { 2802 return std::make_unique<VarOrFuncDeclFilterCCC>(*this); 2803 } 2804 }; 2805 2806 } // namespace 2807 2808 ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope, 2809 CXXScopeSpec &ScopeSpec, 2810 const DeclarationNameInfo &Id, 2811 OpenMPDirectiveKind Kind) { 2812 LookupResult Lookup(*this, Id, LookupOrdinaryName); 2813 LookupParsedName(Lookup, CurScope, &ScopeSpec, true); 2814 2815 if (Lookup.isAmbiguous()) 2816 return ExprError(); 2817 2818 VarDecl *VD; 2819 if (!Lookup.isSingleResult()) { 2820 VarDeclFilterCCC CCC(*this); 2821 if (TypoCorrection Corrected = 2822 CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr, CCC, 2823 CTK_ErrorRecovery)) { 2824 diagnoseTypo(Corrected, 2825 PDiag(Lookup.empty() 2826 ? diag::err_undeclared_var_use_suggest 2827 : diag::err_omp_expected_var_arg_suggest) 2828 << Id.getName()); 2829 VD = Corrected.getCorrectionDeclAs<VarDecl>(); 2830 } else { 2831 Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use 2832 : diag::err_omp_expected_var_arg) 2833 << Id.getName(); 2834 return ExprError(); 2835 } 2836 } else if (!(VD = Lookup.getAsSingle<VarDecl>())) { 2837 Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName(); 2838 Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at); 2839 return ExprError(); 2840 } 2841 Lookup.suppressDiagnostics(); 2842 2843 // OpenMP [2.9.2, Syntax, C/C++] 2844 // Variables must be file-scope, namespace-scope, or static block-scope. 2845 if (Kind == OMPD_threadprivate && !VD->hasGlobalStorage()) { 2846 Diag(Id.getLoc(), diag::err_omp_global_var_arg) 2847 << getOpenMPDirectiveName(Kind) << !VD->isStaticLocal(); 2848 bool IsDecl = 2849 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 2850 Diag(VD->getLocation(), 2851 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 2852 << VD; 2853 return ExprError(); 2854 } 2855 2856 VarDecl *CanonicalVD = VD->getCanonicalDecl(); 2857 NamedDecl *ND = CanonicalVD; 2858 // OpenMP [2.9.2, Restrictions, C/C++, p.2] 2859 // A threadprivate directive for file-scope variables must appear outside 2860 // any definition or declaration. 2861 if (CanonicalVD->getDeclContext()->isTranslationUnit() && 2862 !getCurLexicalContext()->isTranslationUnit()) { 2863 Diag(Id.getLoc(), diag::err_omp_var_scope) 2864 << getOpenMPDirectiveName(Kind) << VD; 2865 bool IsDecl = 2866 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 2867 Diag(VD->getLocation(), 2868 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 2869 << VD; 2870 return ExprError(); 2871 } 2872 // OpenMP [2.9.2, Restrictions, C/C++, p.3] 2873 // A threadprivate directive for static class member variables must appear 2874 // in the class definition, in the same scope in which the member 2875 // variables are declared. 2876 if (CanonicalVD->isStaticDataMember() && 2877 !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) { 2878 Diag(Id.getLoc(), diag::err_omp_var_scope) 2879 << getOpenMPDirectiveName(Kind) << VD; 2880 bool IsDecl = 2881 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 2882 Diag(VD->getLocation(), 2883 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 2884 << VD; 2885 return ExprError(); 2886 } 2887 // OpenMP [2.9.2, Restrictions, C/C++, p.4] 2888 // A threadprivate directive for namespace-scope variables must appear 2889 // outside any definition or declaration other than the namespace 2890 // definition itself. 2891 if (CanonicalVD->getDeclContext()->isNamespace() && 2892 (!getCurLexicalContext()->isFileContext() || 2893 !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) { 2894 Diag(Id.getLoc(), diag::err_omp_var_scope) 2895 << getOpenMPDirectiveName(Kind) << VD; 2896 bool IsDecl = 2897 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 2898 Diag(VD->getLocation(), 2899 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 2900 << VD; 2901 return ExprError(); 2902 } 2903 // OpenMP [2.9.2, Restrictions, C/C++, p.6] 2904 // A threadprivate directive for static block-scope variables must appear 2905 // in the scope of the variable and not in a nested scope. 2906 if (CanonicalVD->isLocalVarDecl() && CurScope && 2907 !isDeclInScope(ND, getCurLexicalContext(), CurScope)) { 2908 Diag(Id.getLoc(), diag::err_omp_var_scope) 2909 << getOpenMPDirectiveName(Kind) << VD; 2910 bool IsDecl = 2911 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 2912 Diag(VD->getLocation(), 2913 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 2914 << VD; 2915 return ExprError(); 2916 } 2917 2918 // OpenMP [2.9.2, Restrictions, C/C++, p.2-6] 2919 // A threadprivate directive must lexically precede all references to any 2920 // of the variables in its list. 2921 if (Kind == OMPD_threadprivate && VD->isUsed() && 2922 !DSAStack->isThreadPrivate(VD)) { 2923 Diag(Id.getLoc(), diag::err_omp_var_used) 2924 << getOpenMPDirectiveName(Kind) << VD; 2925 return ExprError(); 2926 } 2927 2928 QualType ExprType = VD->getType().getNonReferenceType(); 2929 return DeclRefExpr::Create(Context, NestedNameSpecifierLoc(), 2930 SourceLocation(), VD, 2931 /*RefersToEnclosingVariableOrCapture=*/false, 2932 Id.getLoc(), ExprType, VK_LValue); 2933 } 2934 2935 Sema::DeclGroupPtrTy 2936 Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc, 2937 ArrayRef<Expr *> VarList) { 2938 if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) { 2939 CurContext->addDecl(D); 2940 return DeclGroupPtrTy::make(DeclGroupRef(D)); 2941 } 2942 return nullptr; 2943 } 2944 2945 namespace { 2946 class LocalVarRefChecker final 2947 : public ConstStmtVisitor<LocalVarRefChecker, bool> { 2948 Sema &SemaRef; 2949 2950 public: 2951 bool VisitDeclRefExpr(const DeclRefExpr *E) { 2952 if (const auto *VD = dyn_cast<VarDecl>(E->getDecl())) { 2953 if (VD->hasLocalStorage()) { 2954 SemaRef.Diag(E->getBeginLoc(), 2955 diag::err_omp_local_var_in_threadprivate_init) 2956 << E->getSourceRange(); 2957 SemaRef.Diag(VD->getLocation(), diag::note_defined_here) 2958 << VD << VD->getSourceRange(); 2959 return true; 2960 } 2961 } 2962 return false; 2963 } 2964 bool VisitStmt(const Stmt *S) { 2965 for (const Stmt *Child : S->children()) { 2966 if (Child && Visit(Child)) 2967 return true; 2968 } 2969 return false; 2970 } 2971 explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {} 2972 }; 2973 } // namespace 2974 2975 OMPThreadPrivateDecl * 2976 Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) { 2977 SmallVector<Expr *, 8> Vars; 2978 for (Expr *RefExpr : VarList) { 2979 auto *DE = cast<DeclRefExpr>(RefExpr); 2980 auto *VD = cast<VarDecl>(DE->getDecl()); 2981 SourceLocation ILoc = DE->getExprLoc(); 2982 2983 // Mark variable as used. 2984 VD->setReferenced(); 2985 VD->markUsed(Context); 2986 2987 QualType QType = VD->getType(); 2988 if (QType->isDependentType() || QType->isInstantiationDependentType()) { 2989 // It will be analyzed later. 2990 Vars.push_back(DE); 2991 continue; 2992 } 2993 2994 // OpenMP [2.9.2, Restrictions, C/C++, p.10] 2995 // A threadprivate variable must not have an incomplete type. 2996 if (RequireCompleteType(ILoc, VD->getType(), 2997 diag::err_omp_threadprivate_incomplete_type)) { 2998 continue; 2999 } 3000 3001 // OpenMP [2.9.2, Restrictions, C/C++, p.10] 3002 // A threadprivate variable must not have a reference type. 3003 if (VD->getType()->isReferenceType()) { 3004 Diag(ILoc, diag::err_omp_ref_type_arg) 3005 << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType(); 3006 bool IsDecl = 3007 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 3008 Diag(VD->getLocation(), 3009 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 3010 << VD; 3011 continue; 3012 } 3013 3014 // Check if this is a TLS variable. If TLS is not being supported, produce 3015 // the corresponding diagnostic. 3016 if ((VD->getTLSKind() != VarDecl::TLS_None && 3017 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() && 3018 getLangOpts().OpenMPUseTLS && 3019 getASTContext().getTargetInfo().isTLSSupported())) || 3020 (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() && 3021 !VD->isLocalVarDecl())) { 3022 Diag(ILoc, diag::err_omp_var_thread_local) 3023 << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1); 3024 bool IsDecl = 3025 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 3026 Diag(VD->getLocation(), 3027 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 3028 << VD; 3029 continue; 3030 } 3031 3032 // Check if initial value of threadprivate variable reference variable with 3033 // local storage (it is not supported by runtime). 3034 if (const Expr *Init = VD->getAnyInitializer()) { 3035 LocalVarRefChecker Checker(*this); 3036 if (Checker.Visit(Init)) 3037 continue; 3038 } 3039 3040 Vars.push_back(RefExpr); 3041 DSAStack->addDSA(VD, DE, OMPC_threadprivate); 3042 VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit( 3043 Context, SourceRange(Loc, Loc))); 3044 if (ASTMutationListener *ML = Context.getASTMutationListener()) 3045 ML->DeclarationMarkedOpenMPThreadPrivate(VD); 3046 } 3047 OMPThreadPrivateDecl *D = nullptr; 3048 if (!Vars.empty()) { 3049 D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc, 3050 Vars); 3051 D->setAccess(AS_public); 3052 } 3053 return D; 3054 } 3055 3056 static OMPAllocateDeclAttr::AllocatorTypeTy 3057 getAllocatorKind(Sema &S, DSAStackTy *Stack, Expr *Allocator) { 3058 if (!Allocator) 3059 return OMPAllocateDeclAttr::OMPNullMemAlloc; 3060 if (Allocator->isTypeDependent() || Allocator->isValueDependent() || 3061 Allocator->isInstantiationDependent() || 3062 Allocator->containsUnexpandedParameterPack()) 3063 return OMPAllocateDeclAttr::OMPUserDefinedMemAlloc; 3064 auto AllocatorKindRes = OMPAllocateDeclAttr::OMPUserDefinedMemAlloc; 3065 const Expr *AE = Allocator->IgnoreParenImpCasts(); 3066 for (int I = 0; I < OMPAllocateDeclAttr::OMPUserDefinedMemAlloc; ++I) { 3067 auto AllocatorKind = static_cast<OMPAllocateDeclAttr::AllocatorTypeTy>(I); 3068 const Expr *DefAllocator = Stack->getAllocator(AllocatorKind); 3069 llvm::FoldingSetNodeID AEId, DAEId; 3070 AE->Profile(AEId, S.getASTContext(), /*Canonical=*/true); 3071 DefAllocator->Profile(DAEId, S.getASTContext(), /*Canonical=*/true); 3072 if (AEId == DAEId) { 3073 AllocatorKindRes = AllocatorKind; 3074 break; 3075 } 3076 } 3077 return AllocatorKindRes; 3078 } 3079 3080 static bool checkPreviousOMPAllocateAttribute( 3081 Sema &S, DSAStackTy *Stack, Expr *RefExpr, VarDecl *VD, 3082 OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind, Expr *Allocator) { 3083 if (!VD->hasAttr<OMPAllocateDeclAttr>()) 3084 return false; 3085 const auto *A = VD->getAttr<OMPAllocateDeclAttr>(); 3086 Expr *PrevAllocator = A->getAllocator(); 3087 OMPAllocateDeclAttr::AllocatorTypeTy PrevAllocatorKind = 3088 getAllocatorKind(S, Stack, PrevAllocator); 3089 bool AllocatorsMatch = AllocatorKind == PrevAllocatorKind; 3090 if (AllocatorsMatch && 3091 AllocatorKind == OMPAllocateDeclAttr::OMPUserDefinedMemAlloc && 3092 Allocator && PrevAllocator) { 3093 const Expr *AE = Allocator->IgnoreParenImpCasts(); 3094 const Expr *PAE = PrevAllocator->IgnoreParenImpCasts(); 3095 llvm::FoldingSetNodeID AEId, PAEId; 3096 AE->Profile(AEId, S.Context, /*Canonical=*/true); 3097 PAE->Profile(PAEId, S.Context, /*Canonical=*/true); 3098 AllocatorsMatch = AEId == PAEId; 3099 } 3100 if (!AllocatorsMatch) { 3101 SmallString<256> AllocatorBuffer; 3102 llvm::raw_svector_ostream AllocatorStream(AllocatorBuffer); 3103 if (Allocator) 3104 Allocator->printPretty(AllocatorStream, nullptr, S.getPrintingPolicy()); 3105 SmallString<256> PrevAllocatorBuffer; 3106 llvm::raw_svector_ostream PrevAllocatorStream(PrevAllocatorBuffer); 3107 if (PrevAllocator) 3108 PrevAllocator->printPretty(PrevAllocatorStream, nullptr, 3109 S.getPrintingPolicy()); 3110 3111 SourceLocation AllocatorLoc = 3112 Allocator ? Allocator->getExprLoc() : RefExpr->getExprLoc(); 3113 SourceRange AllocatorRange = 3114 Allocator ? Allocator->getSourceRange() : RefExpr->getSourceRange(); 3115 SourceLocation PrevAllocatorLoc = 3116 PrevAllocator ? PrevAllocator->getExprLoc() : A->getLocation(); 3117 SourceRange PrevAllocatorRange = 3118 PrevAllocator ? PrevAllocator->getSourceRange() : A->getRange(); 3119 S.Diag(AllocatorLoc, diag::warn_omp_used_different_allocator) 3120 << (Allocator ? 1 : 0) << AllocatorStream.str() 3121 << (PrevAllocator ? 1 : 0) << PrevAllocatorStream.str() 3122 << AllocatorRange; 3123 S.Diag(PrevAllocatorLoc, diag::note_omp_previous_allocator) 3124 << PrevAllocatorRange; 3125 return true; 3126 } 3127 return false; 3128 } 3129 3130 static void 3131 applyOMPAllocateAttribute(Sema &S, VarDecl *VD, 3132 OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind, 3133 Expr *Allocator, SourceRange SR) { 3134 if (VD->hasAttr<OMPAllocateDeclAttr>()) 3135 return; 3136 if (Allocator && 3137 (Allocator->isTypeDependent() || Allocator->isValueDependent() || 3138 Allocator->isInstantiationDependent() || 3139 Allocator->containsUnexpandedParameterPack())) 3140 return; 3141 auto *A = OMPAllocateDeclAttr::CreateImplicit(S.Context, AllocatorKind, 3142 Allocator, SR); 3143 VD->addAttr(A); 3144 if (ASTMutationListener *ML = S.Context.getASTMutationListener()) 3145 ML->DeclarationMarkedOpenMPAllocate(VD, A); 3146 } 3147 3148 Sema::DeclGroupPtrTy Sema::ActOnOpenMPAllocateDirective( 3149 SourceLocation Loc, ArrayRef<Expr *> VarList, 3150 ArrayRef<OMPClause *> Clauses, DeclContext *Owner) { 3151 assert(Clauses.size() <= 1 && "Expected at most one clause."); 3152 Expr *Allocator = nullptr; 3153 if (Clauses.empty()) { 3154 // OpenMP 5.0, 2.11.3 allocate Directive, Restrictions. 3155 // allocate directives that appear in a target region must specify an 3156 // allocator clause unless a requires directive with the dynamic_allocators 3157 // clause is present in the same compilation unit. 3158 if (LangOpts.OpenMPIsDevice && 3159 !DSAStack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>()) 3160 targetDiag(Loc, diag::err_expected_allocator_clause); 3161 } else { 3162 Allocator = cast<OMPAllocatorClause>(Clauses.back())->getAllocator(); 3163 } 3164 OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind = 3165 getAllocatorKind(*this, DSAStack, Allocator); 3166 SmallVector<Expr *, 8> Vars; 3167 for (Expr *RefExpr : VarList) { 3168 auto *DE = cast<DeclRefExpr>(RefExpr); 3169 auto *VD = cast<VarDecl>(DE->getDecl()); 3170 3171 // Check if this is a TLS variable or global register. 3172 if (VD->getTLSKind() != VarDecl::TLS_None || 3173 VD->hasAttr<OMPThreadPrivateDeclAttr>() || 3174 (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() && 3175 !VD->isLocalVarDecl())) 3176 continue; 3177 3178 // If the used several times in the allocate directive, the same allocator 3179 // must be used. 3180 if (checkPreviousOMPAllocateAttribute(*this, DSAStack, RefExpr, VD, 3181 AllocatorKind, Allocator)) 3182 continue; 3183 3184 // OpenMP, 2.11.3 allocate Directive, Restrictions, C / C++ 3185 // If a list item has a static storage type, the allocator expression in the 3186 // allocator clause must be a constant expression that evaluates to one of 3187 // the predefined memory allocator values. 3188 if (Allocator && VD->hasGlobalStorage()) { 3189 if (AllocatorKind == OMPAllocateDeclAttr::OMPUserDefinedMemAlloc) { 3190 Diag(Allocator->getExprLoc(), 3191 diag::err_omp_expected_predefined_allocator) 3192 << Allocator->getSourceRange(); 3193 bool IsDecl = VD->isThisDeclarationADefinition(Context) == 3194 VarDecl::DeclarationOnly; 3195 Diag(VD->getLocation(), 3196 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 3197 << VD; 3198 continue; 3199 } 3200 } 3201 3202 Vars.push_back(RefExpr); 3203 applyOMPAllocateAttribute(*this, VD, AllocatorKind, Allocator, 3204 DE->getSourceRange()); 3205 } 3206 if (Vars.empty()) 3207 return nullptr; 3208 if (!Owner) 3209 Owner = getCurLexicalContext(); 3210 auto *D = OMPAllocateDecl::Create(Context, Owner, Loc, Vars, Clauses); 3211 D->setAccess(AS_public); 3212 Owner->addDecl(D); 3213 return DeclGroupPtrTy::make(DeclGroupRef(D)); 3214 } 3215 3216 Sema::DeclGroupPtrTy 3217 Sema::ActOnOpenMPRequiresDirective(SourceLocation Loc, 3218 ArrayRef<OMPClause *> ClauseList) { 3219 OMPRequiresDecl *D = nullptr; 3220 if (!CurContext->isFileContext()) { 3221 Diag(Loc, diag::err_omp_invalid_scope) << "requires"; 3222 } else { 3223 D = CheckOMPRequiresDecl(Loc, ClauseList); 3224 if (D) { 3225 CurContext->addDecl(D); 3226 DSAStack->addRequiresDecl(D); 3227 } 3228 } 3229 return DeclGroupPtrTy::make(DeclGroupRef(D)); 3230 } 3231 3232 void Sema::ActOnOpenMPAssumesDirective(SourceLocation Loc, 3233 OpenMPDirectiveKind DKind, 3234 ArrayRef<std::string> Assumptions, 3235 bool SkippedClauses) { 3236 if (!SkippedClauses && Assumptions.empty()) 3237 Diag(Loc, diag::err_omp_no_clause_for_directive) 3238 << llvm::omp::getAllAssumeClauseOptions() 3239 << llvm::omp::getOpenMPDirectiveName(DKind); 3240 3241 auto *AA = AssumptionAttr::Create(Context, llvm::join(Assumptions, ","), Loc); 3242 if (DKind == llvm::omp::Directive::OMPD_begin_assumes) { 3243 OMPAssumeScoped.push_back(AA); 3244 return; 3245 } 3246 3247 // Global assumes without assumption clauses are ignored. 3248 if (Assumptions.empty()) 3249 return; 3250 3251 assert(DKind == llvm::omp::Directive::OMPD_assumes && 3252 "Unexpected omp assumption directive!"); 3253 OMPAssumeGlobal.push_back(AA); 3254 3255 // The OMPAssumeGlobal scope above will take care of new declarations but 3256 // we also want to apply the assumption to existing ones, e.g., to 3257 // declarations in included headers. To this end, we traverse all existing 3258 // declaration contexts and annotate function declarations here. 3259 SmallVector<DeclContext *, 8> DeclContexts; 3260 auto *Ctx = CurContext; 3261 while (Ctx->getLexicalParent()) 3262 Ctx = Ctx->getLexicalParent(); 3263 DeclContexts.push_back(Ctx); 3264 while (!DeclContexts.empty()) { 3265 DeclContext *DC = DeclContexts.pop_back_val(); 3266 for (auto *SubDC : DC->decls()) { 3267 if (SubDC->isInvalidDecl()) 3268 continue; 3269 if (auto *CTD = dyn_cast<ClassTemplateDecl>(SubDC)) { 3270 DeclContexts.push_back(CTD->getTemplatedDecl()); 3271 for (auto *S : CTD->specializations()) 3272 DeclContexts.push_back(S); 3273 continue; 3274 } 3275 if (auto *DC = dyn_cast<DeclContext>(SubDC)) 3276 DeclContexts.push_back(DC); 3277 if (auto *F = dyn_cast<FunctionDecl>(SubDC)) { 3278 F->addAttr(AA); 3279 continue; 3280 } 3281 } 3282 } 3283 } 3284 3285 void Sema::ActOnOpenMPEndAssumesDirective() { 3286 assert(isInOpenMPAssumeScope() && "Not in OpenMP assumes scope!"); 3287 OMPAssumeScoped.pop_back(); 3288 } 3289 3290 OMPRequiresDecl *Sema::CheckOMPRequiresDecl(SourceLocation Loc, 3291 ArrayRef<OMPClause *> ClauseList) { 3292 /// For target specific clauses, the requires directive cannot be 3293 /// specified after the handling of any of the target regions in the 3294 /// current compilation unit. 3295 ArrayRef<SourceLocation> TargetLocations = 3296 DSAStack->getEncounteredTargetLocs(); 3297 SourceLocation AtomicLoc = DSAStack->getAtomicDirectiveLoc(); 3298 if (!TargetLocations.empty() || !AtomicLoc.isInvalid()) { 3299 for (const OMPClause *CNew : ClauseList) { 3300 // Check if any of the requires clauses affect target regions. 3301 if (isa<OMPUnifiedSharedMemoryClause>(CNew) || 3302 isa<OMPUnifiedAddressClause>(CNew) || 3303 isa<OMPReverseOffloadClause>(CNew) || 3304 isa<OMPDynamicAllocatorsClause>(CNew)) { 3305 Diag(Loc, diag::err_omp_directive_before_requires) 3306 << "target" << getOpenMPClauseName(CNew->getClauseKind()); 3307 for (SourceLocation TargetLoc : TargetLocations) { 3308 Diag(TargetLoc, diag::note_omp_requires_encountered_directive) 3309 << "target"; 3310 } 3311 } else if (!AtomicLoc.isInvalid() && 3312 isa<OMPAtomicDefaultMemOrderClause>(CNew)) { 3313 Diag(Loc, diag::err_omp_directive_before_requires) 3314 << "atomic" << getOpenMPClauseName(CNew->getClauseKind()); 3315 Diag(AtomicLoc, diag::note_omp_requires_encountered_directive) 3316 << "atomic"; 3317 } 3318 } 3319 } 3320 3321 if (!DSAStack->hasDuplicateRequiresClause(ClauseList)) 3322 return OMPRequiresDecl::Create(Context, getCurLexicalContext(), Loc, 3323 ClauseList); 3324 return nullptr; 3325 } 3326 3327 static void reportOriginalDsa(Sema &SemaRef, const DSAStackTy *Stack, 3328 const ValueDecl *D, 3329 const DSAStackTy::DSAVarData &DVar, 3330 bool IsLoopIterVar) { 3331 if (DVar.RefExpr) { 3332 SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa) 3333 << getOpenMPClauseName(DVar.CKind); 3334 return; 3335 } 3336 enum { 3337 PDSA_StaticMemberShared, 3338 PDSA_StaticLocalVarShared, 3339 PDSA_LoopIterVarPrivate, 3340 PDSA_LoopIterVarLinear, 3341 PDSA_LoopIterVarLastprivate, 3342 PDSA_ConstVarShared, 3343 PDSA_GlobalVarShared, 3344 PDSA_TaskVarFirstprivate, 3345 PDSA_LocalVarPrivate, 3346 PDSA_Implicit 3347 } Reason = PDSA_Implicit; 3348 bool ReportHint = false; 3349 auto ReportLoc = D->getLocation(); 3350 auto *VD = dyn_cast<VarDecl>(D); 3351 if (IsLoopIterVar) { 3352 if (DVar.CKind == OMPC_private) 3353 Reason = PDSA_LoopIterVarPrivate; 3354 else if (DVar.CKind == OMPC_lastprivate) 3355 Reason = PDSA_LoopIterVarLastprivate; 3356 else 3357 Reason = PDSA_LoopIterVarLinear; 3358 } else if (isOpenMPTaskingDirective(DVar.DKind) && 3359 DVar.CKind == OMPC_firstprivate) { 3360 Reason = PDSA_TaskVarFirstprivate; 3361 ReportLoc = DVar.ImplicitDSALoc; 3362 } else if (VD && VD->isStaticLocal()) 3363 Reason = PDSA_StaticLocalVarShared; 3364 else if (VD && VD->isStaticDataMember()) 3365 Reason = PDSA_StaticMemberShared; 3366 else if (VD && VD->isFileVarDecl()) 3367 Reason = PDSA_GlobalVarShared; 3368 else if (D->getType().isConstant(SemaRef.getASTContext())) 3369 Reason = PDSA_ConstVarShared; 3370 else if (VD && VD->isLocalVarDecl() && DVar.CKind == OMPC_private) { 3371 ReportHint = true; 3372 Reason = PDSA_LocalVarPrivate; 3373 } 3374 if (Reason != PDSA_Implicit) { 3375 SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa) 3376 << Reason << ReportHint 3377 << getOpenMPDirectiveName(Stack->getCurrentDirective()); 3378 } else if (DVar.ImplicitDSALoc.isValid()) { 3379 SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa) 3380 << getOpenMPClauseName(DVar.CKind); 3381 } 3382 } 3383 3384 static OpenMPMapClauseKind 3385 getMapClauseKindFromModifier(OpenMPDefaultmapClauseModifier M, 3386 bool IsAggregateOrDeclareTarget) { 3387 OpenMPMapClauseKind Kind = OMPC_MAP_unknown; 3388 switch (M) { 3389 case OMPC_DEFAULTMAP_MODIFIER_alloc: 3390 Kind = OMPC_MAP_alloc; 3391 break; 3392 case OMPC_DEFAULTMAP_MODIFIER_to: 3393 Kind = OMPC_MAP_to; 3394 break; 3395 case OMPC_DEFAULTMAP_MODIFIER_from: 3396 Kind = OMPC_MAP_from; 3397 break; 3398 case OMPC_DEFAULTMAP_MODIFIER_tofrom: 3399 Kind = OMPC_MAP_tofrom; 3400 break; 3401 case OMPC_DEFAULTMAP_MODIFIER_present: 3402 // OpenMP 5.1 [2.21.7.3] defaultmap clause, Description] 3403 // If implicit-behavior is present, each variable referenced in the 3404 // construct in the category specified by variable-category is treated as if 3405 // it had been listed in a map clause with the map-type of alloc and 3406 // map-type-modifier of present. 3407 Kind = OMPC_MAP_alloc; 3408 break; 3409 case OMPC_DEFAULTMAP_MODIFIER_firstprivate: 3410 case OMPC_DEFAULTMAP_MODIFIER_last: 3411 llvm_unreachable("Unexpected defaultmap implicit behavior"); 3412 case OMPC_DEFAULTMAP_MODIFIER_none: 3413 case OMPC_DEFAULTMAP_MODIFIER_default: 3414 case OMPC_DEFAULTMAP_MODIFIER_unknown: 3415 // IsAggregateOrDeclareTarget could be true if: 3416 // 1. the implicit behavior for aggregate is tofrom 3417 // 2. it's a declare target link 3418 if (IsAggregateOrDeclareTarget) { 3419 Kind = OMPC_MAP_tofrom; 3420 break; 3421 } 3422 llvm_unreachable("Unexpected defaultmap implicit behavior"); 3423 } 3424 assert(Kind != OMPC_MAP_unknown && "Expect map kind to be known"); 3425 return Kind; 3426 } 3427 3428 namespace { 3429 class DSAAttrChecker final : public StmtVisitor<DSAAttrChecker, void> { 3430 DSAStackTy *Stack; 3431 Sema &SemaRef; 3432 bool ErrorFound = false; 3433 bool TryCaptureCXXThisMembers = false; 3434 CapturedStmt *CS = nullptr; 3435 const static unsigned DefaultmapKindNum = OMPC_DEFAULTMAP_pointer + 1; 3436 llvm::SmallVector<Expr *, 4> ImplicitFirstprivate; 3437 llvm::SmallVector<Expr *, 4> ImplicitMap[DefaultmapKindNum][OMPC_MAP_delete]; 3438 llvm::SmallVector<OpenMPMapModifierKind, NumberOfOMPMapClauseModifiers> 3439 ImplicitMapModifier[DefaultmapKindNum]; 3440 Sema::VarsWithInheritedDSAType VarsWithInheritedDSA; 3441 llvm::SmallDenseSet<const ValueDecl *, 4> ImplicitDeclarations; 3442 3443 void VisitSubCaptures(OMPExecutableDirective *S) { 3444 // Check implicitly captured variables. 3445 if (!S->hasAssociatedStmt() || !S->getAssociatedStmt()) 3446 return; 3447 if (S->getDirectiveKind() == OMPD_atomic || 3448 S->getDirectiveKind() == OMPD_critical || 3449 S->getDirectiveKind() == OMPD_section || 3450 S->getDirectiveKind() == OMPD_master || 3451 S->getDirectiveKind() == OMPD_masked || 3452 isOpenMPLoopTransformationDirective(S->getDirectiveKind())) { 3453 Visit(S->getAssociatedStmt()); 3454 return; 3455 } 3456 visitSubCaptures(S->getInnermostCapturedStmt()); 3457 // Try to capture inner this->member references to generate correct mappings 3458 // and diagnostics. 3459 if (TryCaptureCXXThisMembers || 3460 (isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()) && 3461 llvm::any_of(S->getInnermostCapturedStmt()->captures(), 3462 [](const CapturedStmt::Capture &C) { 3463 return C.capturesThis(); 3464 }))) { 3465 bool SavedTryCaptureCXXThisMembers = TryCaptureCXXThisMembers; 3466 TryCaptureCXXThisMembers = true; 3467 Visit(S->getInnermostCapturedStmt()->getCapturedStmt()); 3468 TryCaptureCXXThisMembers = SavedTryCaptureCXXThisMembers; 3469 } 3470 // In tasks firstprivates are not captured anymore, need to analyze them 3471 // explicitly. 3472 if (isOpenMPTaskingDirective(S->getDirectiveKind()) && 3473 !isOpenMPTaskLoopDirective(S->getDirectiveKind())) { 3474 for (OMPClause *C : S->clauses()) 3475 if (auto *FC = dyn_cast<OMPFirstprivateClause>(C)) { 3476 for (Expr *Ref : FC->varlists()) 3477 Visit(Ref); 3478 } 3479 } 3480 } 3481 3482 public: 3483 void VisitDeclRefExpr(DeclRefExpr *E) { 3484 if (TryCaptureCXXThisMembers || E->isTypeDependent() || 3485 E->isValueDependent() || E->containsUnexpandedParameterPack() || 3486 E->isInstantiationDependent()) 3487 return; 3488 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) { 3489 // Check the datasharing rules for the expressions in the clauses. 3490 if (!CS) { 3491 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(VD)) 3492 if (!CED->hasAttr<OMPCaptureNoInitAttr>()) { 3493 Visit(CED->getInit()); 3494 return; 3495 } 3496 } else if (VD->isImplicit() || isa<OMPCapturedExprDecl>(VD)) 3497 // Do not analyze internal variables and do not enclose them into 3498 // implicit clauses. 3499 return; 3500 VD = VD->getCanonicalDecl(); 3501 // Skip internally declared variables. 3502 if (VD->hasLocalStorage() && CS && !CS->capturesVariable(VD) && 3503 !Stack->isImplicitTaskFirstprivate(VD)) 3504 return; 3505 // Skip allocators in uses_allocators clauses. 3506 if (Stack->isUsesAllocatorsDecl(VD).hasValue()) 3507 return; 3508 3509 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, /*FromParent=*/false); 3510 // Check if the variable has explicit DSA set and stop analysis if it so. 3511 if (DVar.RefExpr || !ImplicitDeclarations.insert(VD).second) 3512 return; 3513 3514 // Skip internally declared static variables. 3515 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res = 3516 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD); 3517 if (VD->hasGlobalStorage() && CS && !CS->capturesVariable(VD) && 3518 (Stack->hasRequiresDeclWithClause<OMPUnifiedSharedMemoryClause>() || 3519 !Res || *Res != OMPDeclareTargetDeclAttr::MT_Link) && 3520 !Stack->isImplicitTaskFirstprivate(VD)) 3521 return; 3522 3523 SourceLocation ELoc = E->getExprLoc(); 3524 OpenMPDirectiveKind DKind = Stack->getCurrentDirective(); 3525 // The default(none) clause requires that each variable that is referenced 3526 // in the construct, and does not have a predetermined data-sharing 3527 // attribute, must have its data-sharing attribute explicitly determined 3528 // by being listed in a data-sharing attribute clause. 3529 if (DVar.CKind == OMPC_unknown && 3530 (Stack->getDefaultDSA() == DSA_none || 3531 Stack->getDefaultDSA() == DSA_firstprivate) && 3532 isImplicitOrExplicitTaskingRegion(DKind) && 3533 VarsWithInheritedDSA.count(VD) == 0) { 3534 bool InheritedDSA = Stack->getDefaultDSA() == DSA_none; 3535 if (!InheritedDSA && Stack->getDefaultDSA() == DSA_firstprivate) { 3536 DSAStackTy::DSAVarData DVar = 3537 Stack->getImplicitDSA(VD, /*FromParent=*/false); 3538 InheritedDSA = DVar.CKind == OMPC_unknown; 3539 } 3540 if (InheritedDSA) 3541 VarsWithInheritedDSA[VD] = E; 3542 return; 3543 } 3544 3545 // OpenMP 5.0 [2.19.7.2, defaultmap clause, Description] 3546 // If implicit-behavior is none, each variable referenced in the 3547 // construct that does not have a predetermined data-sharing attribute 3548 // and does not appear in a to or link clause on a declare target 3549 // directive must be listed in a data-mapping attribute clause, a 3550 // data-haring attribute clause (including a data-sharing attribute 3551 // clause on a combined construct where target. is one of the 3552 // constituent constructs), or an is_device_ptr clause. 3553 OpenMPDefaultmapClauseKind ClauseKind = 3554 getVariableCategoryFromDecl(SemaRef.getLangOpts(), VD); 3555 if (SemaRef.getLangOpts().OpenMP >= 50) { 3556 bool IsModifierNone = Stack->getDefaultmapModifier(ClauseKind) == 3557 OMPC_DEFAULTMAP_MODIFIER_none; 3558 if (DVar.CKind == OMPC_unknown && IsModifierNone && 3559 VarsWithInheritedDSA.count(VD) == 0 && !Res) { 3560 // Only check for data-mapping attribute and is_device_ptr here 3561 // since we have already make sure that the declaration does not 3562 // have a data-sharing attribute above 3563 if (!Stack->checkMappableExprComponentListsForDecl( 3564 VD, /*CurrentRegionOnly=*/true, 3565 [VD](OMPClauseMappableExprCommon::MappableExprComponentListRef 3566 MapExprComponents, 3567 OpenMPClauseKind) { 3568 auto MI = MapExprComponents.rbegin(); 3569 auto ME = MapExprComponents.rend(); 3570 return MI != ME && MI->getAssociatedDeclaration() == VD; 3571 })) { 3572 VarsWithInheritedDSA[VD] = E; 3573 return; 3574 } 3575 } 3576 } 3577 if (SemaRef.getLangOpts().OpenMP > 50) { 3578 bool IsModifierPresent = Stack->getDefaultmapModifier(ClauseKind) == 3579 OMPC_DEFAULTMAP_MODIFIER_present; 3580 if (IsModifierPresent) { 3581 if (llvm::find(ImplicitMapModifier[ClauseKind], 3582 OMPC_MAP_MODIFIER_present) == 3583 std::end(ImplicitMapModifier[ClauseKind])) { 3584 ImplicitMapModifier[ClauseKind].push_back( 3585 OMPC_MAP_MODIFIER_present); 3586 } 3587 } 3588 } 3589 3590 if (isOpenMPTargetExecutionDirective(DKind) && 3591 !Stack->isLoopControlVariable(VD).first) { 3592 if (!Stack->checkMappableExprComponentListsForDecl( 3593 VD, /*CurrentRegionOnly=*/true, 3594 [this](OMPClauseMappableExprCommon::MappableExprComponentListRef 3595 StackComponents, 3596 OpenMPClauseKind) { 3597 if (SemaRef.LangOpts.OpenMP >= 50) 3598 return !StackComponents.empty(); 3599 // Variable is used if it has been marked as an array, array 3600 // section, array shaping or the variable iself. 3601 return StackComponents.size() == 1 || 3602 std::all_of( 3603 std::next(StackComponents.rbegin()), 3604 StackComponents.rend(), 3605 [](const OMPClauseMappableExprCommon:: 3606 MappableComponent &MC) { 3607 return MC.getAssociatedDeclaration() == 3608 nullptr && 3609 (isa<OMPArraySectionExpr>( 3610 MC.getAssociatedExpression()) || 3611 isa<OMPArrayShapingExpr>( 3612 MC.getAssociatedExpression()) || 3613 isa<ArraySubscriptExpr>( 3614 MC.getAssociatedExpression())); 3615 }); 3616 })) { 3617 bool IsFirstprivate = false; 3618 // By default lambdas are captured as firstprivates. 3619 if (const auto *RD = 3620 VD->getType().getNonReferenceType()->getAsCXXRecordDecl()) 3621 IsFirstprivate = RD->isLambda(); 3622 IsFirstprivate = 3623 IsFirstprivate || (Stack->mustBeFirstprivate(ClauseKind) && !Res); 3624 if (IsFirstprivate) { 3625 ImplicitFirstprivate.emplace_back(E); 3626 } else { 3627 OpenMPDefaultmapClauseModifier M = 3628 Stack->getDefaultmapModifier(ClauseKind); 3629 OpenMPMapClauseKind Kind = getMapClauseKindFromModifier( 3630 M, ClauseKind == OMPC_DEFAULTMAP_aggregate || Res); 3631 ImplicitMap[ClauseKind][Kind].emplace_back(E); 3632 } 3633 return; 3634 } 3635 } 3636 3637 // OpenMP [2.9.3.6, Restrictions, p.2] 3638 // A list item that appears in a reduction clause of the innermost 3639 // enclosing worksharing or parallel construct may not be accessed in an 3640 // explicit task. 3641 DVar = Stack->hasInnermostDSA( 3642 VD, 3643 [](OpenMPClauseKind C, bool AppliedToPointee) { 3644 return C == OMPC_reduction && !AppliedToPointee; 3645 }, 3646 [](OpenMPDirectiveKind K) { 3647 return isOpenMPParallelDirective(K) || 3648 isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K); 3649 }, 3650 /*FromParent=*/true); 3651 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) { 3652 ErrorFound = true; 3653 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task); 3654 reportOriginalDsa(SemaRef, Stack, VD, DVar); 3655 return; 3656 } 3657 3658 // Define implicit data-sharing attributes for task. 3659 DVar = Stack->getImplicitDSA(VD, /*FromParent=*/false); 3660 if (((isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared) || 3661 (Stack->getDefaultDSA() == DSA_firstprivate && 3662 DVar.CKind == OMPC_firstprivate && !DVar.RefExpr)) && 3663 !Stack->isLoopControlVariable(VD).first) { 3664 ImplicitFirstprivate.push_back(E); 3665 return; 3666 } 3667 3668 // Store implicitly used globals with declare target link for parent 3669 // target. 3670 if (!isOpenMPTargetExecutionDirective(DKind) && Res && 3671 *Res == OMPDeclareTargetDeclAttr::MT_Link) { 3672 Stack->addToParentTargetRegionLinkGlobals(E); 3673 return; 3674 } 3675 } 3676 } 3677 void VisitMemberExpr(MemberExpr *E) { 3678 if (E->isTypeDependent() || E->isValueDependent() || 3679 E->containsUnexpandedParameterPack() || E->isInstantiationDependent()) 3680 return; 3681 auto *FD = dyn_cast<FieldDecl>(E->getMemberDecl()); 3682 OpenMPDirectiveKind DKind = Stack->getCurrentDirective(); 3683 if (auto *TE = dyn_cast<CXXThisExpr>(E->getBase()->IgnoreParenCasts())) { 3684 if (!FD) 3685 return; 3686 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(FD, /*FromParent=*/false); 3687 // Check if the variable has explicit DSA set and stop analysis if it 3688 // so. 3689 if (DVar.RefExpr || !ImplicitDeclarations.insert(FD).second) 3690 return; 3691 3692 if (isOpenMPTargetExecutionDirective(DKind) && 3693 !Stack->isLoopControlVariable(FD).first && 3694 !Stack->checkMappableExprComponentListsForDecl( 3695 FD, /*CurrentRegionOnly=*/true, 3696 [](OMPClauseMappableExprCommon::MappableExprComponentListRef 3697 StackComponents, 3698 OpenMPClauseKind) { 3699 return isa<CXXThisExpr>( 3700 cast<MemberExpr>( 3701 StackComponents.back().getAssociatedExpression()) 3702 ->getBase() 3703 ->IgnoreParens()); 3704 })) { 3705 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3] 3706 // A bit-field cannot appear in a map clause. 3707 // 3708 if (FD->isBitField()) 3709 return; 3710 3711 // Check to see if the member expression is referencing a class that 3712 // has already been explicitly mapped 3713 if (Stack->isClassPreviouslyMapped(TE->getType())) 3714 return; 3715 3716 OpenMPDefaultmapClauseModifier Modifier = 3717 Stack->getDefaultmapModifier(OMPC_DEFAULTMAP_aggregate); 3718 OpenMPDefaultmapClauseKind ClauseKind = 3719 getVariableCategoryFromDecl(SemaRef.getLangOpts(), FD); 3720 OpenMPMapClauseKind Kind = getMapClauseKindFromModifier( 3721 Modifier, /*IsAggregateOrDeclareTarget*/ true); 3722 ImplicitMap[ClauseKind][Kind].emplace_back(E); 3723 return; 3724 } 3725 3726 SourceLocation ELoc = E->getExprLoc(); 3727 // OpenMP [2.9.3.6, Restrictions, p.2] 3728 // A list item that appears in a reduction clause of the innermost 3729 // enclosing worksharing or parallel construct may not be accessed in 3730 // an explicit task. 3731 DVar = Stack->hasInnermostDSA( 3732 FD, 3733 [](OpenMPClauseKind C, bool AppliedToPointee) { 3734 return C == OMPC_reduction && !AppliedToPointee; 3735 }, 3736 [](OpenMPDirectiveKind K) { 3737 return isOpenMPParallelDirective(K) || 3738 isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K); 3739 }, 3740 /*FromParent=*/true); 3741 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) { 3742 ErrorFound = true; 3743 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task); 3744 reportOriginalDsa(SemaRef, Stack, FD, DVar); 3745 return; 3746 } 3747 3748 // Define implicit data-sharing attributes for task. 3749 DVar = Stack->getImplicitDSA(FD, /*FromParent=*/false); 3750 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared && 3751 !Stack->isLoopControlVariable(FD).first) { 3752 // Check if there is a captured expression for the current field in the 3753 // region. Do not mark it as firstprivate unless there is no captured 3754 // expression. 3755 // TODO: try to make it firstprivate. 3756 if (DVar.CKind != OMPC_unknown) 3757 ImplicitFirstprivate.push_back(E); 3758 } 3759 return; 3760 } 3761 if (isOpenMPTargetExecutionDirective(DKind)) { 3762 OMPClauseMappableExprCommon::MappableExprComponentList CurComponents; 3763 if (!checkMapClauseExpressionBase(SemaRef, E, CurComponents, OMPC_map, 3764 Stack->getCurrentDirective(), 3765 /*NoDiagnose=*/true)) 3766 return; 3767 const auto *VD = cast<ValueDecl>( 3768 CurComponents.back().getAssociatedDeclaration()->getCanonicalDecl()); 3769 if (!Stack->checkMappableExprComponentListsForDecl( 3770 VD, /*CurrentRegionOnly=*/true, 3771 [&CurComponents]( 3772 OMPClauseMappableExprCommon::MappableExprComponentListRef 3773 StackComponents, 3774 OpenMPClauseKind) { 3775 auto CCI = CurComponents.rbegin(); 3776 auto CCE = CurComponents.rend(); 3777 for (const auto &SC : llvm::reverse(StackComponents)) { 3778 // Do both expressions have the same kind? 3779 if (CCI->getAssociatedExpression()->getStmtClass() != 3780 SC.getAssociatedExpression()->getStmtClass()) 3781 if (!((isa<OMPArraySectionExpr>( 3782 SC.getAssociatedExpression()) || 3783 isa<OMPArrayShapingExpr>( 3784 SC.getAssociatedExpression())) && 3785 isa<ArraySubscriptExpr>( 3786 CCI->getAssociatedExpression()))) 3787 return false; 3788 3789 const Decl *CCD = CCI->getAssociatedDeclaration(); 3790 const Decl *SCD = SC.getAssociatedDeclaration(); 3791 CCD = CCD ? CCD->getCanonicalDecl() : nullptr; 3792 SCD = SCD ? SCD->getCanonicalDecl() : nullptr; 3793 if (SCD != CCD) 3794 return false; 3795 std::advance(CCI, 1); 3796 if (CCI == CCE) 3797 break; 3798 } 3799 return true; 3800 })) { 3801 Visit(E->getBase()); 3802 } 3803 } else if (!TryCaptureCXXThisMembers) { 3804 Visit(E->getBase()); 3805 } 3806 } 3807 void VisitOMPExecutableDirective(OMPExecutableDirective *S) { 3808 for (OMPClause *C : S->clauses()) { 3809 // Skip analysis of arguments of implicitly defined firstprivate clause 3810 // for task|target directives. 3811 // Skip analysis of arguments of implicitly defined map clause for target 3812 // directives. 3813 if (C && !((isa<OMPFirstprivateClause>(C) || isa<OMPMapClause>(C)) && 3814 C->isImplicit() && 3815 !isOpenMPTaskingDirective(Stack->getCurrentDirective()))) { 3816 for (Stmt *CC : C->children()) { 3817 if (CC) 3818 Visit(CC); 3819 } 3820 } 3821 } 3822 // Check implicitly captured variables. 3823 VisitSubCaptures(S); 3824 } 3825 3826 void VisitOMPLoopTransformationDirective(OMPLoopTransformationDirective *S) { 3827 // Loop transformation directives do not introduce data sharing 3828 VisitStmt(S); 3829 } 3830 3831 void VisitStmt(Stmt *S) { 3832 for (Stmt *C : S->children()) { 3833 if (C) { 3834 // Check implicitly captured variables in the task-based directives to 3835 // check if they must be firstprivatized. 3836 Visit(C); 3837 } 3838 } 3839 } 3840 3841 void visitSubCaptures(CapturedStmt *S) { 3842 for (const CapturedStmt::Capture &Cap : S->captures()) { 3843 if (!Cap.capturesVariable() && !Cap.capturesVariableByCopy()) 3844 continue; 3845 VarDecl *VD = Cap.getCapturedVar(); 3846 // Do not try to map the variable if it or its sub-component was mapped 3847 // already. 3848 if (isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()) && 3849 Stack->checkMappableExprComponentListsForDecl( 3850 VD, /*CurrentRegionOnly=*/true, 3851 [](OMPClauseMappableExprCommon::MappableExprComponentListRef, 3852 OpenMPClauseKind) { return true; })) 3853 continue; 3854 DeclRefExpr *DRE = buildDeclRefExpr( 3855 SemaRef, VD, VD->getType().getNonLValueExprType(SemaRef.Context), 3856 Cap.getLocation(), /*RefersToCapture=*/true); 3857 Visit(DRE); 3858 } 3859 } 3860 bool isErrorFound() const { return ErrorFound; } 3861 ArrayRef<Expr *> getImplicitFirstprivate() const { 3862 return ImplicitFirstprivate; 3863 } 3864 ArrayRef<Expr *> getImplicitMap(OpenMPDefaultmapClauseKind DK, 3865 OpenMPMapClauseKind MK) const { 3866 return ImplicitMap[DK][MK]; 3867 } 3868 ArrayRef<OpenMPMapModifierKind> 3869 getImplicitMapModifier(OpenMPDefaultmapClauseKind Kind) const { 3870 return ImplicitMapModifier[Kind]; 3871 } 3872 const Sema::VarsWithInheritedDSAType &getVarsWithInheritedDSA() const { 3873 return VarsWithInheritedDSA; 3874 } 3875 3876 DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS) 3877 : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) { 3878 // Process declare target link variables for the target directives. 3879 if (isOpenMPTargetExecutionDirective(S->getCurrentDirective())) { 3880 for (DeclRefExpr *E : Stack->getLinkGlobals()) 3881 Visit(E); 3882 } 3883 } 3884 }; 3885 } // namespace 3886 3887 static void handleDeclareVariantConstructTrait(DSAStackTy *Stack, 3888 OpenMPDirectiveKind DKind, 3889 bool ScopeEntry) { 3890 SmallVector<llvm::omp::TraitProperty, 8> Traits; 3891 if (isOpenMPTargetExecutionDirective(DKind)) 3892 Traits.emplace_back(llvm::omp::TraitProperty::construct_target_target); 3893 if (isOpenMPTeamsDirective(DKind)) 3894 Traits.emplace_back(llvm::omp::TraitProperty::construct_teams_teams); 3895 if (isOpenMPParallelDirective(DKind)) 3896 Traits.emplace_back(llvm::omp::TraitProperty::construct_parallel_parallel); 3897 if (isOpenMPWorksharingDirective(DKind)) 3898 Traits.emplace_back(llvm::omp::TraitProperty::construct_for_for); 3899 if (isOpenMPSimdDirective(DKind)) 3900 Traits.emplace_back(llvm::omp::TraitProperty::construct_simd_simd); 3901 Stack->handleConstructTrait(Traits, ScopeEntry); 3902 } 3903 3904 void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) { 3905 switch (DKind) { 3906 case OMPD_parallel: 3907 case OMPD_parallel_for: 3908 case OMPD_parallel_for_simd: 3909 case OMPD_parallel_sections: 3910 case OMPD_parallel_master: 3911 case OMPD_teams: 3912 case OMPD_teams_distribute: 3913 case OMPD_teams_distribute_simd: { 3914 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst(); 3915 QualType KmpInt32PtrTy = 3916 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 3917 Sema::CapturedParamNameType Params[] = { 3918 std::make_pair(".global_tid.", KmpInt32PtrTy), 3919 std::make_pair(".bound_tid.", KmpInt32PtrTy), 3920 std::make_pair(StringRef(), QualType()) // __context with shared vars 3921 }; 3922 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 3923 Params); 3924 break; 3925 } 3926 case OMPD_target_teams: 3927 case OMPD_target_parallel: 3928 case OMPD_target_parallel_for: 3929 case OMPD_target_parallel_for_simd: 3930 case OMPD_target_teams_distribute: 3931 case OMPD_target_teams_distribute_simd: { 3932 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst(); 3933 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict(); 3934 QualType KmpInt32PtrTy = 3935 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 3936 QualType Args[] = {VoidPtrTy}; 3937 FunctionProtoType::ExtProtoInfo EPI; 3938 EPI.Variadic = true; 3939 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI); 3940 Sema::CapturedParamNameType Params[] = { 3941 std::make_pair(".global_tid.", KmpInt32Ty), 3942 std::make_pair(".part_id.", KmpInt32PtrTy), 3943 std::make_pair(".privates.", VoidPtrTy), 3944 std::make_pair( 3945 ".copy_fn.", 3946 Context.getPointerType(CopyFnType).withConst().withRestrict()), 3947 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()), 3948 std::make_pair(StringRef(), QualType()) // __context with shared vars 3949 }; 3950 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 3951 Params, /*OpenMPCaptureLevel=*/0); 3952 // Mark this captured region as inlined, because we don't use outlined 3953 // function directly. 3954 getCurCapturedRegion()->TheCapturedDecl->addAttr( 3955 AlwaysInlineAttr::CreateImplicit( 3956 Context, {}, AttributeCommonInfo::AS_Keyword, 3957 AlwaysInlineAttr::Keyword_forceinline)); 3958 Sema::CapturedParamNameType ParamsTarget[] = { 3959 std::make_pair(StringRef(), QualType()) // __context with shared vars 3960 }; 3961 // Start a captured region for 'target' with no implicit parameters. 3962 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 3963 ParamsTarget, /*OpenMPCaptureLevel=*/1); 3964 Sema::CapturedParamNameType ParamsTeamsOrParallel[] = { 3965 std::make_pair(".global_tid.", KmpInt32PtrTy), 3966 std::make_pair(".bound_tid.", KmpInt32PtrTy), 3967 std::make_pair(StringRef(), QualType()) // __context with shared vars 3968 }; 3969 // Start a captured region for 'teams' or 'parallel'. Both regions have 3970 // the same implicit parameters. 3971 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 3972 ParamsTeamsOrParallel, /*OpenMPCaptureLevel=*/2); 3973 break; 3974 } 3975 case OMPD_target: 3976 case OMPD_target_simd: { 3977 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst(); 3978 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict(); 3979 QualType KmpInt32PtrTy = 3980 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 3981 QualType Args[] = {VoidPtrTy}; 3982 FunctionProtoType::ExtProtoInfo EPI; 3983 EPI.Variadic = true; 3984 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI); 3985 Sema::CapturedParamNameType Params[] = { 3986 std::make_pair(".global_tid.", KmpInt32Ty), 3987 std::make_pair(".part_id.", KmpInt32PtrTy), 3988 std::make_pair(".privates.", VoidPtrTy), 3989 std::make_pair( 3990 ".copy_fn.", 3991 Context.getPointerType(CopyFnType).withConst().withRestrict()), 3992 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()), 3993 std::make_pair(StringRef(), QualType()) // __context with shared vars 3994 }; 3995 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 3996 Params, /*OpenMPCaptureLevel=*/0); 3997 // Mark this captured region as inlined, because we don't use outlined 3998 // function directly. 3999 getCurCapturedRegion()->TheCapturedDecl->addAttr( 4000 AlwaysInlineAttr::CreateImplicit( 4001 Context, {}, AttributeCommonInfo::AS_Keyword, 4002 AlwaysInlineAttr::Keyword_forceinline)); 4003 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 4004 std::make_pair(StringRef(), QualType()), 4005 /*OpenMPCaptureLevel=*/1); 4006 break; 4007 } 4008 case OMPD_atomic: 4009 case OMPD_critical: 4010 case OMPD_section: 4011 case OMPD_master: 4012 case OMPD_masked: 4013 case OMPD_tile: 4014 case OMPD_unroll: 4015 break; 4016 case OMPD_simd: 4017 case OMPD_for: 4018 case OMPD_for_simd: 4019 case OMPD_sections: 4020 case OMPD_single: 4021 case OMPD_taskgroup: 4022 case OMPD_distribute: 4023 case OMPD_distribute_simd: 4024 case OMPD_ordered: 4025 case OMPD_target_data: 4026 case OMPD_dispatch: { 4027 Sema::CapturedParamNameType Params[] = { 4028 std::make_pair(StringRef(), QualType()) // __context with shared vars 4029 }; 4030 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 4031 Params); 4032 break; 4033 } 4034 case OMPD_task: { 4035 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst(); 4036 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict(); 4037 QualType KmpInt32PtrTy = 4038 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 4039 QualType Args[] = {VoidPtrTy}; 4040 FunctionProtoType::ExtProtoInfo EPI; 4041 EPI.Variadic = true; 4042 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI); 4043 Sema::CapturedParamNameType Params[] = { 4044 std::make_pair(".global_tid.", KmpInt32Ty), 4045 std::make_pair(".part_id.", KmpInt32PtrTy), 4046 std::make_pair(".privates.", VoidPtrTy), 4047 std::make_pair( 4048 ".copy_fn.", 4049 Context.getPointerType(CopyFnType).withConst().withRestrict()), 4050 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()), 4051 std::make_pair(StringRef(), QualType()) // __context with shared vars 4052 }; 4053 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 4054 Params); 4055 // Mark this captured region as inlined, because we don't use outlined 4056 // function directly. 4057 getCurCapturedRegion()->TheCapturedDecl->addAttr( 4058 AlwaysInlineAttr::CreateImplicit( 4059 Context, {}, AttributeCommonInfo::AS_Keyword, 4060 AlwaysInlineAttr::Keyword_forceinline)); 4061 break; 4062 } 4063 case OMPD_taskloop: 4064 case OMPD_taskloop_simd: 4065 case OMPD_master_taskloop: 4066 case OMPD_master_taskloop_simd: { 4067 QualType KmpInt32Ty = 4068 Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1) 4069 .withConst(); 4070 QualType KmpUInt64Ty = 4071 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0) 4072 .withConst(); 4073 QualType KmpInt64Ty = 4074 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1) 4075 .withConst(); 4076 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict(); 4077 QualType KmpInt32PtrTy = 4078 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 4079 QualType Args[] = {VoidPtrTy}; 4080 FunctionProtoType::ExtProtoInfo EPI; 4081 EPI.Variadic = true; 4082 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI); 4083 Sema::CapturedParamNameType Params[] = { 4084 std::make_pair(".global_tid.", KmpInt32Ty), 4085 std::make_pair(".part_id.", KmpInt32PtrTy), 4086 std::make_pair(".privates.", VoidPtrTy), 4087 std::make_pair( 4088 ".copy_fn.", 4089 Context.getPointerType(CopyFnType).withConst().withRestrict()), 4090 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()), 4091 std::make_pair(".lb.", KmpUInt64Ty), 4092 std::make_pair(".ub.", KmpUInt64Ty), 4093 std::make_pair(".st.", KmpInt64Ty), 4094 std::make_pair(".liter.", KmpInt32Ty), 4095 std::make_pair(".reductions.", VoidPtrTy), 4096 std::make_pair(StringRef(), QualType()) // __context with shared vars 4097 }; 4098 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 4099 Params); 4100 // Mark this captured region as inlined, because we don't use outlined 4101 // function directly. 4102 getCurCapturedRegion()->TheCapturedDecl->addAttr( 4103 AlwaysInlineAttr::CreateImplicit( 4104 Context, {}, AttributeCommonInfo::AS_Keyword, 4105 AlwaysInlineAttr::Keyword_forceinline)); 4106 break; 4107 } 4108 case OMPD_parallel_master_taskloop: 4109 case OMPD_parallel_master_taskloop_simd: { 4110 QualType KmpInt32Ty = 4111 Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1) 4112 .withConst(); 4113 QualType KmpUInt64Ty = 4114 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0) 4115 .withConst(); 4116 QualType KmpInt64Ty = 4117 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1) 4118 .withConst(); 4119 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict(); 4120 QualType KmpInt32PtrTy = 4121 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 4122 Sema::CapturedParamNameType ParamsParallel[] = { 4123 std::make_pair(".global_tid.", KmpInt32PtrTy), 4124 std::make_pair(".bound_tid.", KmpInt32PtrTy), 4125 std::make_pair(StringRef(), QualType()) // __context with shared vars 4126 }; 4127 // Start a captured region for 'parallel'. 4128 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 4129 ParamsParallel, /*OpenMPCaptureLevel=*/0); 4130 QualType Args[] = {VoidPtrTy}; 4131 FunctionProtoType::ExtProtoInfo EPI; 4132 EPI.Variadic = true; 4133 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI); 4134 Sema::CapturedParamNameType Params[] = { 4135 std::make_pair(".global_tid.", KmpInt32Ty), 4136 std::make_pair(".part_id.", KmpInt32PtrTy), 4137 std::make_pair(".privates.", VoidPtrTy), 4138 std::make_pair( 4139 ".copy_fn.", 4140 Context.getPointerType(CopyFnType).withConst().withRestrict()), 4141 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()), 4142 std::make_pair(".lb.", KmpUInt64Ty), 4143 std::make_pair(".ub.", KmpUInt64Ty), 4144 std::make_pair(".st.", KmpInt64Ty), 4145 std::make_pair(".liter.", KmpInt32Ty), 4146 std::make_pair(".reductions.", VoidPtrTy), 4147 std::make_pair(StringRef(), QualType()) // __context with shared vars 4148 }; 4149 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 4150 Params, /*OpenMPCaptureLevel=*/1); 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 break; 4158 } 4159 case OMPD_distribute_parallel_for_simd: 4160 case OMPD_distribute_parallel_for: { 4161 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst(); 4162 QualType KmpInt32PtrTy = 4163 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 4164 Sema::CapturedParamNameType Params[] = { 4165 std::make_pair(".global_tid.", KmpInt32PtrTy), 4166 std::make_pair(".bound_tid.", KmpInt32PtrTy), 4167 std::make_pair(".previous.lb.", Context.getSizeType().withConst()), 4168 std::make_pair(".previous.ub.", Context.getSizeType().withConst()), 4169 std::make_pair(StringRef(), QualType()) // __context with shared vars 4170 }; 4171 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 4172 Params); 4173 break; 4174 } 4175 case OMPD_target_teams_distribute_parallel_for: 4176 case OMPD_target_teams_distribute_parallel_for_simd: { 4177 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst(); 4178 QualType KmpInt32PtrTy = 4179 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 4180 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict(); 4181 4182 QualType Args[] = {VoidPtrTy}; 4183 FunctionProtoType::ExtProtoInfo EPI; 4184 EPI.Variadic = true; 4185 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI); 4186 Sema::CapturedParamNameType Params[] = { 4187 std::make_pair(".global_tid.", KmpInt32Ty), 4188 std::make_pair(".part_id.", KmpInt32PtrTy), 4189 std::make_pair(".privates.", VoidPtrTy), 4190 std::make_pair( 4191 ".copy_fn.", 4192 Context.getPointerType(CopyFnType).withConst().withRestrict()), 4193 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()), 4194 std::make_pair(StringRef(), QualType()) // __context with shared vars 4195 }; 4196 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 4197 Params, /*OpenMPCaptureLevel=*/0); 4198 // Mark this captured region as inlined, because we don't use outlined 4199 // function directly. 4200 getCurCapturedRegion()->TheCapturedDecl->addAttr( 4201 AlwaysInlineAttr::CreateImplicit( 4202 Context, {}, AttributeCommonInfo::AS_Keyword, 4203 AlwaysInlineAttr::Keyword_forceinline)); 4204 Sema::CapturedParamNameType ParamsTarget[] = { 4205 std::make_pair(StringRef(), QualType()) // __context with shared vars 4206 }; 4207 // Start a captured region for 'target' with no implicit parameters. 4208 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 4209 ParamsTarget, /*OpenMPCaptureLevel=*/1); 4210 4211 Sema::CapturedParamNameType ParamsTeams[] = { 4212 std::make_pair(".global_tid.", KmpInt32PtrTy), 4213 std::make_pair(".bound_tid.", KmpInt32PtrTy), 4214 std::make_pair(StringRef(), QualType()) // __context with shared vars 4215 }; 4216 // Start a captured region for 'target' with no implicit parameters. 4217 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 4218 ParamsTeams, /*OpenMPCaptureLevel=*/2); 4219 4220 Sema::CapturedParamNameType ParamsParallel[] = { 4221 std::make_pair(".global_tid.", KmpInt32PtrTy), 4222 std::make_pair(".bound_tid.", KmpInt32PtrTy), 4223 std::make_pair(".previous.lb.", Context.getSizeType().withConst()), 4224 std::make_pair(".previous.ub.", Context.getSizeType().withConst()), 4225 std::make_pair(StringRef(), QualType()) // __context with shared vars 4226 }; 4227 // Start a captured region for 'teams' or 'parallel'. Both regions have 4228 // the same implicit parameters. 4229 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 4230 ParamsParallel, /*OpenMPCaptureLevel=*/3); 4231 break; 4232 } 4233 4234 case OMPD_teams_distribute_parallel_for: 4235 case OMPD_teams_distribute_parallel_for_simd: { 4236 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst(); 4237 QualType KmpInt32PtrTy = 4238 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 4239 4240 Sema::CapturedParamNameType ParamsTeams[] = { 4241 std::make_pair(".global_tid.", KmpInt32PtrTy), 4242 std::make_pair(".bound_tid.", KmpInt32PtrTy), 4243 std::make_pair(StringRef(), QualType()) // __context with shared vars 4244 }; 4245 // Start a captured region for 'target' with no implicit parameters. 4246 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 4247 ParamsTeams, /*OpenMPCaptureLevel=*/0); 4248 4249 Sema::CapturedParamNameType ParamsParallel[] = { 4250 std::make_pair(".global_tid.", KmpInt32PtrTy), 4251 std::make_pair(".bound_tid.", KmpInt32PtrTy), 4252 std::make_pair(".previous.lb.", Context.getSizeType().withConst()), 4253 std::make_pair(".previous.ub.", Context.getSizeType().withConst()), 4254 std::make_pair(StringRef(), QualType()) // __context with shared vars 4255 }; 4256 // Start a captured region for 'teams' or 'parallel'. Both regions have 4257 // the same implicit parameters. 4258 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 4259 ParamsParallel, /*OpenMPCaptureLevel=*/1); 4260 break; 4261 } 4262 case OMPD_target_update: 4263 case OMPD_target_enter_data: 4264 case OMPD_target_exit_data: { 4265 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst(); 4266 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict(); 4267 QualType KmpInt32PtrTy = 4268 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 4269 QualType Args[] = {VoidPtrTy}; 4270 FunctionProtoType::ExtProtoInfo EPI; 4271 EPI.Variadic = true; 4272 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI); 4273 Sema::CapturedParamNameType Params[] = { 4274 std::make_pair(".global_tid.", KmpInt32Ty), 4275 std::make_pair(".part_id.", KmpInt32PtrTy), 4276 std::make_pair(".privates.", VoidPtrTy), 4277 std::make_pair( 4278 ".copy_fn.", 4279 Context.getPointerType(CopyFnType).withConst().withRestrict()), 4280 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()), 4281 std::make_pair(StringRef(), QualType()) // __context with shared vars 4282 }; 4283 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 4284 Params); 4285 // Mark this captured region as inlined, because we don't use outlined 4286 // function directly. 4287 getCurCapturedRegion()->TheCapturedDecl->addAttr( 4288 AlwaysInlineAttr::CreateImplicit( 4289 Context, {}, AttributeCommonInfo::AS_Keyword, 4290 AlwaysInlineAttr::Keyword_forceinline)); 4291 break; 4292 } 4293 case OMPD_threadprivate: 4294 case OMPD_allocate: 4295 case OMPD_taskyield: 4296 case OMPD_barrier: 4297 case OMPD_taskwait: 4298 case OMPD_cancellation_point: 4299 case OMPD_cancel: 4300 case OMPD_flush: 4301 case OMPD_depobj: 4302 case OMPD_scan: 4303 case OMPD_declare_reduction: 4304 case OMPD_declare_mapper: 4305 case OMPD_declare_simd: 4306 case OMPD_declare_target: 4307 case OMPD_end_declare_target: 4308 case OMPD_requires: 4309 case OMPD_declare_variant: 4310 case OMPD_begin_declare_variant: 4311 case OMPD_end_declare_variant: 4312 case OMPD_metadirective: 4313 llvm_unreachable("OpenMP Directive is not allowed"); 4314 case OMPD_unknown: 4315 default: 4316 llvm_unreachable("Unknown OpenMP directive"); 4317 } 4318 DSAStack->setContext(CurContext); 4319 handleDeclareVariantConstructTrait(DSAStack, DKind, /* ScopeEntry */ true); 4320 } 4321 4322 int Sema::getNumberOfConstructScopes(unsigned Level) const { 4323 return getOpenMPCaptureLevels(DSAStack->getDirective(Level)); 4324 } 4325 4326 int Sema::getOpenMPCaptureLevels(OpenMPDirectiveKind DKind) { 4327 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions; 4328 getOpenMPCaptureRegions(CaptureRegions, DKind); 4329 return CaptureRegions.size(); 4330 } 4331 4332 static OMPCapturedExprDecl *buildCaptureDecl(Sema &S, IdentifierInfo *Id, 4333 Expr *CaptureExpr, bool WithInit, 4334 bool AsExpression) { 4335 assert(CaptureExpr); 4336 ASTContext &C = S.getASTContext(); 4337 Expr *Init = AsExpression ? CaptureExpr : CaptureExpr->IgnoreImpCasts(); 4338 QualType Ty = Init->getType(); 4339 if (CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue()) { 4340 if (S.getLangOpts().CPlusPlus) { 4341 Ty = C.getLValueReferenceType(Ty); 4342 } else { 4343 Ty = C.getPointerType(Ty); 4344 ExprResult Res = 4345 S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_AddrOf, Init); 4346 if (!Res.isUsable()) 4347 return nullptr; 4348 Init = Res.get(); 4349 } 4350 WithInit = true; 4351 } 4352 auto *CED = OMPCapturedExprDecl::Create(C, S.CurContext, Id, Ty, 4353 CaptureExpr->getBeginLoc()); 4354 if (!WithInit) 4355 CED->addAttr(OMPCaptureNoInitAttr::CreateImplicit(C)); 4356 S.CurContext->addHiddenDecl(CED); 4357 Sema::TentativeAnalysisScope Trap(S); 4358 S.AddInitializerToDecl(CED, Init, /*DirectInit=*/false); 4359 return CED; 4360 } 4361 4362 static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr, 4363 bool WithInit) { 4364 OMPCapturedExprDecl *CD; 4365 if (VarDecl *VD = S.isOpenMPCapturedDecl(D)) 4366 CD = cast<OMPCapturedExprDecl>(VD); 4367 else 4368 CD = buildCaptureDecl(S, D->getIdentifier(), CaptureExpr, WithInit, 4369 /*AsExpression=*/false); 4370 return buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(), 4371 CaptureExpr->getExprLoc()); 4372 } 4373 4374 static ExprResult buildCapture(Sema &S, Expr *CaptureExpr, DeclRefExpr *&Ref) { 4375 CaptureExpr = S.DefaultLvalueConversion(CaptureExpr).get(); 4376 if (!Ref) { 4377 OMPCapturedExprDecl *CD = buildCaptureDecl( 4378 S, &S.getASTContext().Idents.get(".capture_expr."), CaptureExpr, 4379 /*WithInit=*/true, /*AsExpression=*/true); 4380 Ref = buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(), 4381 CaptureExpr->getExprLoc()); 4382 } 4383 ExprResult Res = Ref; 4384 if (!S.getLangOpts().CPlusPlus && 4385 CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue() && 4386 Ref->getType()->isPointerType()) { 4387 Res = S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_Deref, Ref); 4388 if (!Res.isUsable()) 4389 return ExprError(); 4390 } 4391 return S.DefaultLvalueConversion(Res.get()); 4392 } 4393 4394 namespace { 4395 // OpenMP directives parsed in this section are represented as a 4396 // CapturedStatement with an associated statement. If a syntax error 4397 // is detected during the parsing of the associated statement, the 4398 // compiler must abort processing and close the CapturedStatement. 4399 // 4400 // Combined directives such as 'target parallel' have more than one 4401 // nested CapturedStatements. This RAII ensures that we unwind out 4402 // of all the nested CapturedStatements when an error is found. 4403 class CaptureRegionUnwinderRAII { 4404 private: 4405 Sema &S; 4406 bool &ErrorFound; 4407 OpenMPDirectiveKind DKind = OMPD_unknown; 4408 4409 public: 4410 CaptureRegionUnwinderRAII(Sema &S, bool &ErrorFound, 4411 OpenMPDirectiveKind DKind) 4412 : S(S), ErrorFound(ErrorFound), DKind(DKind) {} 4413 ~CaptureRegionUnwinderRAII() { 4414 if (ErrorFound) { 4415 int ThisCaptureLevel = S.getOpenMPCaptureLevels(DKind); 4416 while (--ThisCaptureLevel >= 0) 4417 S.ActOnCapturedRegionError(); 4418 } 4419 } 4420 }; 4421 } // namespace 4422 4423 void Sema::tryCaptureOpenMPLambdas(ValueDecl *V) { 4424 // Capture variables captured by reference in lambdas for target-based 4425 // directives. 4426 if (!CurContext->isDependentContext() && 4427 (isOpenMPTargetExecutionDirective(DSAStack->getCurrentDirective()) || 4428 isOpenMPTargetDataManagementDirective( 4429 DSAStack->getCurrentDirective()))) { 4430 QualType Type = V->getType(); 4431 if (const auto *RD = Type.getCanonicalType() 4432 .getNonReferenceType() 4433 ->getAsCXXRecordDecl()) { 4434 bool SavedForceCaptureByReferenceInTargetExecutable = 4435 DSAStack->isForceCaptureByReferenceInTargetExecutable(); 4436 DSAStack->setForceCaptureByReferenceInTargetExecutable( 4437 /*V=*/true); 4438 if (RD->isLambda()) { 4439 llvm::DenseMap<const VarDecl *, FieldDecl *> Captures; 4440 FieldDecl *ThisCapture; 4441 RD->getCaptureFields(Captures, ThisCapture); 4442 for (const LambdaCapture &LC : RD->captures()) { 4443 if (LC.getCaptureKind() == LCK_ByRef) { 4444 VarDecl *VD = LC.getCapturedVar(); 4445 DeclContext *VDC = VD->getDeclContext(); 4446 if (!VDC->Encloses(CurContext)) 4447 continue; 4448 MarkVariableReferenced(LC.getLocation(), VD); 4449 } else if (LC.getCaptureKind() == LCK_This) { 4450 QualType ThisTy = getCurrentThisType(); 4451 if (!ThisTy.isNull() && 4452 Context.typesAreCompatible(ThisTy, ThisCapture->getType())) 4453 CheckCXXThisCapture(LC.getLocation()); 4454 } 4455 } 4456 } 4457 DSAStack->setForceCaptureByReferenceInTargetExecutable( 4458 SavedForceCaptureByReferenceInTargetExecutable); 4459 } 4460 } 4461 } 4462 4463 static bool checkOrderedOrderSpecified(Sema &S, 4464 const ArrayRef<OMPClause *> Clauses) { 4465 const OMPOrderedClause *Ordered = nullptr; 4466 const OMPOrderClause *Order = nullptr; 4467 4468 for (const OMPClause *Clause : Clauses) { 4469 if (Clause->getClauseKind() == OMPC_ordered) 4470 Ordered = cast<OMPOrderedClause>(Clause); 4471 else if (Clause->getClauseKind() == OMPC_order) { 4472 Order = cast<OMPOrderClause>(Clause); 4473 if (Order->getKind() != OMPC_ORDER_concurrent) 4474 Order = nullptr; 4475 } 4476 if (Ordered && Order) 4477 break; 4478 } 4479 4480 if (Ordered && Order) { 4481 S.Diag(Order->getKindKwLoc(), 4482 diag::err_omp_simple_clause_incompatible_with_ordered) 4483 << getOpenMPClauseName(OMPC_order) 4484 << getOpenMPSimpleClauseTypeName(OMPC_order, OMPC_ORDER_concurrent) 4485 << SourceRange(Order->getBeginLoc(), Order->getEndLoc()); 4486 S.Diag(Ordered->getBeginLoc(), diag::note_omp_ordered_param) 4487 << 0 << SourceRange(Ordered->getBeginLoc(), Ordered->getEndLoc()); 4488 return true; 4489 } 4490 return false; 4491 } 4492 4493 StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S, 4494 ArrayRef<OMPClause *> Clauses) { 4495 handleDeclareVariantConstructTrait(DSAStack, DSAStack->getCurrentDirective(), 4496 /* ScopeEntry */ false); 4497 if (DSAStack->getCurrentDirective() == OMPD_atomic || 4498 DSAStack->getCurrentDirective() == OMPD_critical || 4499 DSAStack->getCurrentDirective() == OMPD_section || 4500 DSAStack->getCurrentDirective() == OMPD_master || 4501 DSAStack->getCurrentDirective() == OMPD_masked) 4502 return S; 4503 4504 bool ErrorFound = false; 4505 CaptureRegionUnwinderRAII CaptureRegionUnwinder( 4506 *this, ErrorFound, DSAStack->getCurrentDirective()); 4507 if (!S.isUsable()) { 4508 ErrorFound = true; 4509 return StmtError(); 4510 } 4511 4512 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions; 4513 getOpenMPCaptureRegions(CaptureRegions, DSAStack->getCurrentDirective()); 4514 OMPOrderedClause *OC = nullptr; 4515 OMPScheduleClause *SC = nullptr; 4516 SmallVector<const OMPLinearClause *, 4> LCs; 4517 SmallVector<const OMPClauseWithPreInit *, 4> PICs; 4518 // This is required for proper codegen. 4519 for (OMPClause *Clause : Clauses) { 4520 if (!LangOpts.OpenMPSimd && 4521 isOpenMPTaskingDirective(DSAStack->getCurrentDirective()) && 4522 Clause->getClauseKind() == OMPC_in_reduction) { 4523 // Capture taskgroup task_reduction descriptors inside the tasking regions 4524 // with the corresponding in_reduction items. 4525 auto *IRC = cast<OMPInReductionClause>(Clause); 4526 for (Expr *E : IRC->taskgroup_descriptors()) 4527 if (E) 4528 MarkDeclarationsReferencedInExpr(E); 4529 } 4530 if (isOpenMPPrivate(Clause->getClauseKind()) || 4531 Clause->getClauseKind() == OMPC_copyprivate || 4532 (getLangOpts().OpenMPUseTLS && 4533 getASTContext().getTargetInfo().isTLSSupported() && 4534 Clause->getClauseKind() == OMPC_copyin)) { 4535 DSAStack->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin); 4536 // Mark all variables in private list clauses as used in inner region. 4537 for (Stmt *VarRef : Clause->children()) { 4538 if (auto *E = cast_or_null<Expr>(VarRef)) { 4539 MarkDeclarationsReferencedInExpr(E); 4540 } 4541 } 4542 DSAStack->setForceVarCapturing(/*V=*/false); 4543 } else if (isOpenMPLoopTransformationDirective( 4544 DSAStack->getCurrentDirective())) { 4545 assert(CaptureRegions.empty() && 4546 "No captured regions in loop transformation directives."); 4547 } else if (CaptureRegions.size() > 1 || 4548 CaptureRegions.back() != OMPD_unknown) { 4549 if (auto *C = OMPClauseWithPreInit::get(Clause)) 4550 PICs.push_back(C); 4551 if (auto *C = OMPClauseWithPostUpdate::get(Clause)) { 4552 if (Expr *E = C->getPostUpdateExpr()) 4553 MarkDeclarationsReferencedInExpr(E); 4554 } 4555 } 4556 if (Clause->getClauseKind() == OMPC_schedule) 4557 SC = cast<OMPScheduleClause>(Clause); 4558 else if (Clause->getClauseKind() == OMPC_ordered) 4559 OC = cast<OMPOrderedClause>(Clause); 4560 else if (Clause->getClauseKind() == OMPC_linear) 4561 LCs.push_back(cast<OMPLinearClause>(Clause)); 4562 } 4563 // Capture allocator expressions if used. 4564 for (Expr *E : DSAStack->getInnerAllocators()) 4565 MarkDeclarationsReferencedInExpr(E); 4566 // OpenMP, 2.7.1 Loop Construct, Restrictions 4567 // The nonmonotonic modifier cannot be specified if an ordered clause is 4568 // specified. 4569 if (SC && 4570 (SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic || 4571 SC->getSecondScheduleModifier() == 4572 OMPC_SCHEDULE_MODIFIER_nonmonotonic) && 4573 OC) { 4574 Diag(SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic 4575 ? SC->getFirstScheduleModifierLoc() 4576 : SC->getSecondScheduleModifierLoc(), 4577 diag::err_omp_simple_clause_incompatible_with_ordered) 4578 << getOpenMPClauseName(OMPC_schedule) 4579 << getOpenMPSimpleClauseTypeName(OMPC_schedule, 4580 OMPC_SCHEDULE_MODIFIER_nonmonotonic) 4581 << SourceRange(OC->getBeginLoc(), OC->getEndLoc()); 4582 ErrorFound = true; 4583 } 4584 // OpenMP 5.0, 2.9.2 Worksharing-Loop Construct, Restrictions. 4585 // If an order(concurrent) clause is present, an ordered clause may not appear 4586 // on the same directive. 4587 if (checkOrderedOrderSpecified(*this, Clauses)) 4588 ErrorFound = true; 4589 if (!LCs.empty() && OC && OC->getNumForLoops()) { 4590 for (const OMPLinearClause *C : LCs) { 4591 Diag(C->getBeginLoc(), diag::err_omp_linear_ordered) 4592 << SourceRange(OC->getBeginLoc(), OC->getEndLoc()); 4593 } 4594 ErrorFound = true; 4595 } 4596 if (isOpenMPWorksharingDirective(DSAStack->getCurrentDirective()) && 4597 isOpenMPSimdDirective(DSAStack->getCurrentDirective()) && OC && 4598 OC->getNumForLoops()) { 4599 Diag(OC->getBeginLoc(), diag::err_omp_ordered_simd) 4600 << getOpenMPDirectiveName(DSAStack->getCurrentDirective()); 4601 ErrorFound = true; 4602 } 4603 if (ErrorFound) { 4604 return StmtError(); 4605 } 4606 StmtResult SR = S; 4607 unsigned CompletedRegions = 0; 4608 for (OpenMPDirectiveKind ThisCaptureRegion : llvm::reverse(CaptureRegions)) { 4609 // Mark all variables in private list clauses as used in inner region. 4610 // Required for proper codegen of combined directives. 4611 // TODO: add processing for other clauses. 4612 if (ThisCaptureRegion != OMPD_unknown) { 4613 for (const clang::OMPClauseWithPreInit *C : PICs) { 4614 OpenMPDirectiveKind CaptureRegion = C->getCaptureRegion(); 4615 // Find the particular capture region for the clause if the 4616 // directive is a combined one with multiple capture regions. 4617 // If the directive is not a combined one, the capture region 4618 // associated with the clause is OMPD_unknown and is generated 4619 // only once. 4620 if (CaptureRegion == ThisCaptureRegion || 4621 CaptureRegion == OMPD_unknown) { 4622 if (auto *DS = cast_or_null<DeclStmt>(C->getPreInitStmt())) { 4623 for (Decl *D : DS->decls()) 4624 MarkVariableReferenced(D->getLocation(), cast<VarDecl>(D)); 4625 } 4626 } 4627 } 4628 } 4629 if (ThisCaptureRegion == OMPD_target) { 4630 // Capture allocator traits in the target region. They are used implicitly 4631 // and, thus, are not captured by default. 4632 for (OMPClause *C : Clauses) { 4633 if (const auto *UAC = dyn_cast<OMPUsesAllocatorsClause>(C)) { 4634 for (unsigned I = 0, End = UAC->getNumberOfAllocators(); I < End; 4635 ++I) { 4636 OMPUsesAllocatorsClause::Data D = UAC->getAllocatorData(I); 4637 if (Expr *E = D.AllocatorTraits) 4638 MarkDeclarationsReferencedInExpr(E); 4639 } 4640 continue; 4641 } 4642 } 4643 } 4644 if (ThisCaptureRegion == OMPD_parallel) { 4645 // Capture temp arrays for inscan reductions and locals in aligned 4646 // clauses. 4647 for (OMPClause *C : Clauses) { 4648 if (auto *RC = dyn_cast<OMPReductionClause>(C)) { 4649 if (RC->getModifier() != OMPC_REDUCTION_inscan) 4650 continue; 4651 for (Expr *E : RC->copy_array_temps()) 4652 MarkDeclarationsReferencedInExpr(E); 4653 } 4654 if (auto *AC = dyn_cast<OMPAlignedClause>(C)) { 4655 for (Expr *E : AC->varlists()) 4656 MarkDeclarationsReferencedInExpr(E); 4657 } 4658 } 4659 } 4660 if (++CompletedRegions == CaptureRegions.size()) 4661 DSAStack->setBodyComplete(); 4662 SR = ActOnCapturedRegionEnd(SR.get()); 4663 } 4664 return SR; 4665 } 4666 4667 static bool checkCancelRegion(Sema &SemaRef, OpenMPDirectiveKind CurrentRegion, 4668 OpenMPDirectiveKind CancelRegion, 4669 SourceLocation StartLoc) { 4670 // CancelRegion is only needed for cancel and cancellation_point. 4671 if (CurrentRegion != OMPD_cancel && CurrentRegion != OMPD_cancellation_point) 4672 return false; 4673 4674 if (CancelRegion == OMPD_parallel || CancelRegion == OMPD_for || 4675 CancelRegion == OMPD_sections || CancelRegion == OMPD_taskgroup) 4676 return false; 4677 4678 SemaRef.Diag(StartLoc, diag::err_omp_wrong_cancel_region) 4679 << getOpenMPDirectiveName(CancelRegion); 4680 return true; 4681 } 4682 4683 static bool checkNestingOfRegions(Sema &SemaRef, const DSAStackTy *Stack, 4684 OpenMPDirectiveKind CurrentRegion, 4685 const DeclarationNameInfo &CurrentName, 4686 OpenMPDirectiveKind CancelRegion, 4687 SourceLocation StartLoc) { 4688 if (Stack->getCurScope()) { 4689 OpenMPDirectiveKind ParentRegion = Stack->getParentDirective(); 4690 OpenMPDirectiveKind OffendingRegion = ParentRegion; 4691 bool NestingProhibited = false; 4692 bool CloseNesting = true; 4693 bool OrphanSeen = false; 4694 enum { 4695 NoRecommend, 4696 ShouldBeInParallelRegion, 4697 ShouldBeInOrderedRegion, 4698 ShouldBeInTargetRegion, 4699 ShouldBeInTeamsRegion, 4700 ShouldBeInLoopSimdRegion, 4701 } Recommend = NoRecommend; 4702 if (isOpenMPSimdDirective(ParentRegion) && 4703 ((SemaRef.LangOpts.OpenMP <= 45 && CurrentRegion != OMPD_ordered) || 4704 (SemaRef.LangOpts.OpenMP >= 50 && CurrentRegion != OMPD_ordered && 4705 CurrentRegion != OMPD_simd && CurrentRegion != OMPD_atomic && 4706 CurrentRegion != OMPD_scan))) { 4707 // OpenMP [2.16, Nesting of Regions] 4708 // OpenMP constructs may not be nested inside a simd region. 4709 // OpenMP [2.8.1,simd Construct, Restrictions] 4710 // An ordered construct with the simd clause is the only OpenMP 4711 // construct that can appear in the simd region. 4712 // Allowing a SIMD construct nested in another SIMD construct is an 4713 // extension. The OpenMP 4.5 spec does not allow it. Issue a warning 4714 // message. 4715 // OpenMP 5.0 [2.9.3.1, simd Construct, Restrictions] 4716 // The only OpenMP constructs that can be encountered during execution of 4717 // a simd region are the atomic construct, the loop construct, the simd 4718 // construct and the ordered construct with the simd clause. 4719 SemaRef.Diag(StartLoc, (CurrentRegion != OMPD_simd) 4720 ? diag::err_omp_prohibited_region_simd 4721 : diag::warn_omp_nesting_simd) 4722 << (SemaRef.LangOpts.OpenMP >= 50 ? 1 : 0); 4723 return CurrentRegion != OMPD_simd; 4724 } 4725 if (ParentRegion == OMPD_atomic) { 4726 // OpenMP [2.16, Nesting of Regions] 4727 // OpenMP constructs may not be nested inside an atomic region. 4728 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic); 4729 return true; 4730 } 4731 if (CurrentRegion == OMPD_section) { 4732 // OpenMP [2.7.2, sections Construct, Restrictions] 4733 // Orphaned section directives are prohibited. That is, the section 4734 // directives must appear within the sections construct and must not be 4735 // encountered elsewhere in the sections region. 4736 if (ParentRegion != OMPD_sections && 4737 ParentRegion != OMPD_parallel_sections) { 4738 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive) 4739 << (ParentRegion != OMPD_unknown) 4740 << getOpenMPDirectiveName(ParentRegion); 4741 return true; 4742 } 4743 return false; 4744 } 4745 // Allow some constructs (except teams and cancellation constructs) to be 4746 // orphaned (they could be used in functions, called from OpenMP regions 4747 // with the required preconditions). 4748 if (ParentRegion == OMPD_unknown && 4749 !isOpenMPNestingTeamsDirective(CurrentRegion) && 4750 CurrentRegion != OMPD_cancellation_point && 4751 CurrentRegion != OMPD_cancel && CurrentRegion != OMPD_scan) 4752 return false; 4753 if (CurrentRegion == OMPD_cancellation_point || 4754 CurrentRegion == OMPD_cancel) { 4755 // OpenMP [2.16, Nesting of Regions] 4756 // A cancellation point construct for which construct-type-clause is 4757 // taskgroup must be nested inside a task construct. A cancellation 4758 // point construct for which construct-type-clause is not taskgroup must 4759 // be closely nested inside an OpenMP construct that matches the type 4760 // specified in construct-type-clause. 4761 // A cancel construct for which construct-type-clause is taskgroup must be 4762 // nested inside a task construct. A cancel construct for which 4763 // construct-type-clause is not taskgroup must be closely nested inside an 4764 // OpenMP construct that matches the type specified in 4765 // construct-type-clause. 4766 NestingProhibited = 4767 !((CancelRegion == OMPD_parallel && 4768 (ParentRegion == OMPD_parallel || 4769 ParentRegion == OMPD_target_parallel)) || 4770 (CancelRegion == OMPD_for && 4771 (ParentRegion == OMPD_for || ParentRegion == OMPD_parallel_for || 4772 ParentRegion == OMPD_target_parallel_for || 4773 ParentRegion == OMPD_distribute_parallel_for || 4774 ParentRegion == OMPD_teams_distribute_parallel_for || 4775 ParentRegion == OMPD_target_teams_distribute_parallel_for)) || 4776 (CancelRegion == OMPD_taskgroup && 4777 (ParentRegion == OMPD_task || 4778 (SemaRef.getLangOpts().OpenMP >= 50 && 4779 (ParentRegion == OMPD_taskloop || 4780 ParentRegion == OMPD_master_taskloop || 4781 ParentRegion == OMPD_parallel_master_taskloop)))) || 4782 (CancelRegion == OMPD_sections && 4783 (ParentRegion == OMPD_section || ParentRegion == OMPD_sections || 4784 ParentRegion == OMPD_parallel_sections))); 4785 OrphanSeen = ParentRegion == OMPD_unknown; 4786 } else if (CurrentRegion == OMPD_master || CurrentRegion == OMPD_masked) { 4787 // OpenMP 5.1 [2.22, Nesting of Regions] 4788 // A masked region may not be closely nested inside a worksharing, loop, 4789 // atomic, task, or taskloop region. 4790 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) || 4791 isOpenMPTaskingDirective(ParentRegion); 4792 } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) { 4793 // OpenMP [2.16, Nesting of Regions] 4794 // A critical region may not be nested (closely or otherwise) inside a 4795 // critical region with the same name. Note that this restriction is not 4796 // sufficient to prevent deadlock. 4797 SourceLocation PreviousCriticalLoc; 4798 bool DeadLock = Stack->hasDirective( 4799 [CurrentName, &PreviousCriticalLoc](OpenMPDirectiveKind K, 4800 const DeclarationNameInfo &DNI, 4801 SourceLocation Loc) { 4802 if (K == OMPD_critical && DNI.getName() == CurrentName.getName()) { 4803 PreviousCriticalLoc = Loc; 4804 return true; 4805 } 4806 return false; 4807 }, 4808 false /* skip top directive */); 4809 if (DeadLock) { 4810 SemaRef.Diag(StartLoc, 4811 diag::err_omp_prohibited_region_critical_same_name) 4812 << CurrentName.getName(); 4813 if (PreviousCriticalLoc.isValid()) 4814 SemaRef.Diag(PreviousCriticalLoc, 4815 diag::note_omp_previous_critical_region); 4816 return true; 4817 } 4818 } else if (CurrentRegion == OMPD_barrier) { 4819 // OpenMP 5.1 [2.22, Nesting of Regions] 4820 // A barrier region may not be closely nested inside a worksharing, loop, 4821 // task, taskloop, critical, ordered, atomic, or masked region. 4822 NestingProhibited = 4823 isOpenMPWorksharingDirective(ParentRegion) || 4824 isOpenMPTaskingDirective(ParentRegion) || 4825 ParentRegion == OMPD_master || ParentRegion == OMPD_masked || 4826 ParentRegion == OMPD_parallel_master || 4827 ParentRegion == OMPD_critical || ParentRegion == OMPD_ordered; 4828 } else if (isOpenMPWorksharingDirective(CurrentRegion) && 4829 !isOpenMPParallelDirective(CurrentRegion) && 4830 !isOpenMPTeamsDirective(CurrentRegion)) { 4831 // OpenMP 5.1 [2.22, Nesting of Regions] 4832 // A loop region that binds to a parallel region or a worksharing region 4833 // may not be closely nested inside a worksharing, loop, task, taskloop, 4834 // critical, ordered, atomic, or masked region. 4835 NestingProhibited = 4836 isOpenMPWorksharingDirective(ParentRegion) || 4837 isOpenMPTaskingDirective(ParentRegion) || 4838 ParentRegion == OMPD_master || ParentRegion == OMPD_masked || 4839 ParentRegion == OMPD_parallel_master || 4840 ParentRegion == OMPD_critical || ParentRegion == OMPD_ordered; 4841 Recommend = ShouldBeInParallelRegion; 4842 } else if (CurrentRegion == OMPD_ordered) { 4843 // OpenMP [2.16, Nesting of Regions] 4844 // An ordered region may not be closely nested inside a critical, 4845 // atomic, or explicit task region. 4846 // An ordered region must be closely nested inside a loop region (or 4847 // parallel loop region) with an ordered clause. 4848 // OpenMP [2.8.1,simd Construct, Restrictions] 4849 // An ordered construct with the simd clause is the only OpenMP construct 4850 // that can appear in the simd region. 4851 NestingProhibited = ParentRegion == OMPD_critical || 4852 isOpenMPTaskingDirective(ParentRegion) || 4853 !(isOpenMPSimdDirective(ParentRegion) || 4854 Stack->isParentOrderedRegion()); 4855 Recommend = ShouldBeInOrderedRegion; 4856 } else if (isOpenMPNestingTeamsDirective(CurrentRegion)) { 4857 // OpenMP [2.16, Nesting of Regions] 4858 // If specified, a teams construct must be contained within a target 4859 // construct. 4860 NestingProhibited = 4861 (SemaRef.LangOpts.OpenMP <= 45 && ParentRegion != OMPD_target) || 4862 (SemaRef.LangOpts.OpenMP >= 50 && ParentRegion != OMPD_unknown && 4863 ParentRegion != OMPD_target); 4864 OrphanSeen = ParentRegion == OMPD_unknown; 4865 Recommend = ShouldBeInTargetRegion; 4866 } else if (CurrentRegion == OMPD_scan) { 4867 // OpenMP [2.16, Nesting of Regions] 4868 // If specified, a teams construct must be contained within a target 4869 // construct. 4870 NestingProhibited = 4871 SemaRef.LangOpts.OpenMP < 50 || 4872 (ParentRegion != OMPD_simd && ParentRegion != OMPD_for && 4873 ParentRegion != OMPD_for_simd && ParentRegion != OMPD_parallel_for && 4874 ParentRegion != OMPD_parallel_for_simd); 4875 OrphanSeen = ParentRegion == OMPD_unknown; 4876 Recommend = ShouldBeInLoopSimdRegion; 4877 } 4878 if (!NestingProhibited && 4879 !isOpenMPTargetExecutionDirective(CurrentRegion) && 4880 !isOpenMPTargetDataManagementDirective(CurrentRegion) && 4881 (ParentRegion == OMPD_teams || ParentRegion == OMPD_target_teams)) { 4882 // OpenMP [2.16, Nesting of Regions] 4883 // distribute, parallel, parallel sections, parallel workshare, and the 4884 // parallel loop and parallel loop SIMD constructs are the only OpenMP 4885 // constructs that can be closely nested in the teams region. 4886 NestingProhibited = !isOpenMPParallelDirective(CurrentRegion) && 4887 !isOpenMPDistributeDirective(CurrentRegion); 4888 Recommend = ShouldBeInParallelRegion; 4889 } 4890 if (!NestingProhibited && 4891 isOpenMPNestingDistributeDirective(CurrentRegion)) { 4892 // OpenMP 4.5 [2.17 Nesting of Regions] 4893 // The region associated with the distribute construct must be strictly 4894 // nested inside a teams region 4895 NestingProhibited = 4896 (ParentRegion != OMPD_teams && ParentRegion != OMPD_target_teams); 4897 Recommend = ShouldBeInTeamsRegion; 4898 } 4899 if (!NestingProhibited && 4900 (isOpenMPTargetExecutionDirective(CurrentRegion) || 4901 isOpenMPTargetDataManagementDirective(CurrentRegion))) { 4902 // OpenMP 4.5 [2.17 Nesting of Regions] 4903 // If a target, target update, target data, target enter data, or 4904 // target exit data construct is encountered during execution of a 4905 // target region, the behavior is unspecified. 4906 NestingProhibited = Stack->hasDirective( 4907 [&OffendingRegion](OpenMPDirectiveKind K, const DeclarationNameInfo &, 4908 SourceLocation) { 4909 if (isOpenMPTargetExecutionDirective(K)) { 4910 OffendingRegion = K; 4911 return true; 4912 } 4913 return false; 4914 }, 4915 false /* don't skip top directive */); 4916 CloseNesting = false; 4917 } 4918 if (NestingProhibited) { 4919 if (OrphanSeen) { 4920 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_device_directive) 4921 << getOpenMPDirectiveName(CurrentRegion) << Recommend; 4922 } else { 4923 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region) 4924 << CloseNesting << getOpenMPDirectiveName(OffendingRegion) 4925 << Recommend << getOpenMPDirectiveName(CurrentRegion); 4926 } 4927 return true; 4928 } 4929 } 4930 return false; 4931 } 4932 4933 struct Kind2Unsigned { 4934 using argument_type = OpenMPDirectiveKind; 4935 unsigned operator()(argument_type DK) { return unsigned(DK); } 4936 }; 4937 static bool checkIfClauses(Sema &S, OpenMPDirectiveKind Kind, 4938 ArrayRef<OMPClause *> Clauses, 4939 ArrayRef<OpenMPDirectiveKind> AllowedNameModifiers) { 4940 bool ErrorFound = false; 4941 unsigned NamedModifiersNumber = 0; 4942 llvm::IndexedMap<const OMPIfClause *, Kind2Unsigned> FoundNameModifiers; 4943 FoundNameModifiers.resize(llvm::omp::Directive_enumSize + 1); 4944 SmallVector<SourceLocation, 4> NameModifierLoc; 4945 for (const OMPClause *C : Clauses) { 4946 if (const auto *IC = dyn_cast_or_null<OMPIfClause>(C)) { 4947 // At most one if clause without a directive-name-modifier can appear on 4948 // the directive. 4949 OpenMPDirectiveKind CurNM = IC->getNameModifier(); 4950 if (FoundNameModifiers[CurNM]) { 4951 S.Diag(C->getBeginLoc(), diag::err_omp_more_one_clause) 4952 << getOpenMPDirectiveName(Kind) << getOpenMPClauseName(OMPC_if) 4953 << (CurNM != OMPD_unknown) << getOpenMPDirectiveName(CurNM); 4954 ErrorFound = true; 4955 } else if (CurNM != OMPD_unknown) { 4956 NameModifierLoc.push_back(IC->getNameModifierLoc()); 4957 ++NamedModifiersNumber; 4958 } 4959 FoundNameModifiers[CurNM] = IC; 4960 if (CurNM == OMPD_unknown) 4961 continue; 4962 // Check if the specified name modifier is allowed for the current 4963 // directive. 4964 // At most one if clause with the particular directive-name-modifier can 4965 // appear on the directive. 4966 if (!llvm::is_contained(AllowedNameModifiers, CurNM)) { 4967 S.Diag(IC->getNameModifierLoc(), 4968 diag::err_omp_wrong_if_directive_name_modifier) 4969 << getOpenMPDirectiveName(CurNM) << getOpenMPDirectiveName(Kind); 4970 ErrorFound = true; 4971 } 4972 } 4973 } 4974 // If any if clause on the directive includes a directive-name-modifier then 4975 // all if clauses on the directive must include a directive-name-modifier. 4976 if (FoundNameModifiers[OMPD_unknown] && NamedModifiersNumber > 0) { 4977 if (NamedModifiersNumber == AllowedNameModifiers.size()) { 4978 S.Diag(FoundNameModifiers[OMPD_unknown]->getBeginLoc(), 4979 diag::err_omp_no_more_if_clause); 4980 } else { 4981 std::string Values; 4982 std::string Sep(", "); 4983 unsigned AllowedCnt = 0; 4984 unsigned TotalAllowedNum = 4985 AllowedNameModifiers.size() - NamedModifiersNumber; 4986 for (unsigned Cnt = 0, End = AllowedNameModifiers.size(); Cnt < End; 4987 ++Cnt) { 4988 OpenMPDirectiveKind NM = AllowedNameModifiers[Cnt]; 4989 if (!FoundNameModifiers[NM]) { 4990 Values += "'"; 4991 Values += getOpenMPDirectiveName(NM); 4992 Values += "'"; 4993 if (AllowedCnt + 2 == TotalAllowedNum) 4994 Values += " or "; 4995 else if (AllowedCnt + 1 != TotalAllowedNum) 4996 Values += Sep; 4997 ++AllowedCnt; 4998 } 4999 } 5000 S.Diag(FoundNameModifiers[OMPD_unknown]->getCondition()->getBeginLoc(), 5001 diag::err_omp_unnamed_if_clause) 5002 << (TotalAllowedNum > 1) << Values; 5003 } 5004 for (SourceLocation Loc : NameModifierLoc) { 5005 S.Diag(Loc, diag::note_omp_previous_named_if_clause); 5006 } 5007 ErrorFound = true; 5008 } 5009 return ErrorFound; 5010 } 5011 5012 static std::pair<ValueDecl *, bool> getPrivateItem(Sema &S, Expr *&RefExpr, 5013 SourceLocation &ELoc, 5014 SourceRange &ERange, 5015 bool AllowArraySection) { 5016 if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() || 5017 RefExpr->containsUnexpandedParameterPack()) 5018 return std::make_pair(nullptr, true); 5019 5020 // OpenMP [3.1, C/C++] 5021 // A list item is a variable name. 5022 // OpenMP [2.9.3.3, Restrictions, p.1] 5023 // A variable that is part of another variable (as an array or 5024 // structure element) cannot appear in a private clause. 5025 RefExpr = RefExpr->IgnoreParens(); 5026 enum { 5027 NoArrayExpr = -1, 5028 ArraySubscript = 0, 5029 OMPArraySection = 1 5030 } IsArrayExpr = NoArrayExpr; 5031 if (AllowArraySection) { 5032 if (auto *ASE = dyn_cast_or_null<ArraySubscriptExpr>(RefExpr)) { 5033 Expr *Base = ASE->getBase()->IgnoreParenImpCasts(); 5034 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) 5035 Base = TempASE->getBase()->IgnoreParenImpCasts(); 5036 RefExpr = Base; 5037 IsArrayExpr = ArraySubscript; 5038 } else if (auto *OASE = dyn_cast_or_null<OMPArraySectionExpr>(RefExpr)) { 5039 Expr *Base = OASE->getBase()->IgnoreParenImpCasts(); 5040 while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base)) 5041 Base = TempOASE->getBase()->IgnoreParenImpCasts(); 5042 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) 5043 Base = TempASE->getBase()->IgnoreParenImpCasts(); 5044 RefExpr = Base; 5045 IsArrayExpr = OMPArraySection; 5046 } 5047 } 5048 ELoc = RefExpr->getExprLoc(); 5049 ERange = RefExpr->getSourceRange(); 5050 RefExpr = RefExpr->IgnoreParenImpCasts(); 5051 auto *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr); 5052 auto *ME = dyn_cast_or_null<MemberExpr>(RefExpr); 5053 if ((!DE || !isa<VarDecl>(DE->getDecl())) && 5054 (S.getCurrentThisType().isNull() || !ME || 5055 !isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()) || 5056 !isa<FieldDecl>(ME->getMemberDecl()))) { 5057 if (IsArrayExpr != NoArrayExpr) { 5058 S.Diag(ELoc, diag::err_omp_expected_base_var_name) << IsArrayExpr 5059 << ERange; 5060 } else { 5061 S.Diag(ELoc, 5062 AllowArraySection 5063 ? diag::err_omp_expected_var_name_member_expr_or_array_item 5064 : diag::err_omp_expected_var_name_member_expr) 5065 << (S.getCurrentThisType().isNull() ? 0 : 1) << ERange; 5066 } 5067 return std::make_pair(nullptr, false); 5068 } 5069 return std::make_pair( 5070 getCanonicalDecl(DE ? DE->getDecl() : ME->getMemberDecl()), false); 5071 } 5072 5073 namespace { 5074 /// Checks if the allocator is used in uses_allocators clause to be allowed in 5075 /// target regions. 5076 class AllocatorChecker final : public ConstStmtVisitor<AllocatorChecker, bool> { 5077 DSAStackTy *S = nullptr; 5078 5079 public: 5080 bool VisitDeclRefExpr(const DeclRefExpr *E) { 5081 return S->isUsesAllocatorsDecl(E->getDecl()) 5082 .getValueOr( 5083 DSAStackTy::UsesAllocatorsDeclKind::AllocatorTrait) == 5084 DSAStackTy::UsesAllocatorsDeclKind::AllocatorTrait; 5085 } 5086 bool VisitStmt(const Stmt *S) { 5087 for (const Stmt *Child : S->children()) { 5088 if (Child && Visit(Child)) 5089 return true; 5090 } 5091 return false; 5092 } 5093 explicit AllocatorChecker(DSAStackTy *S) : S(S) {} 5094 }; 5095 } // namespace 5096 5097 static void checkAllocateClauses(Sema &S, DSAStackTy *Stack, 5098 ArrayRef<OMPClause *> Clauses) { 5099 assert(!S.CurContext->isDependentContext() && 5100 "Expected non-dependent context."); 5101 auto AllocateRange = 5102 llvm::make_filter_range(Clauses, OMPAllocateClause::classof); 5103 llvm::DenseMap<CanonicalDeclPtr<Decl>, CanonicalDeclPtr<VarDecl>> 5104 DeclToCopy; 5105 auto PrivateRange = llvm::make_filter_range(Clauses, [](const OMPClause *C) { 5106 return isOpenMPPrivate(C->getClauseKind()); 5107 }); 5108 for (OMPClause *Cl : PrivateRange) { 5109 MutableArrayRef<Expr *>::iterator I, It, Et; 5110 if (Cl->getClauseKind() == OMPC_private) { 5111 auto *PC = cast<OMPPrivateClause>(Cl); 5112 I = PC->private_copies().begin(); 5113 It = PC->varlist_begin(); 5114 Et = PC->varlist_end(); 5115 } else if (Cl->getClauseKind() == OMPC_firstprivate) { 5116 auto *PC = cast<OMPFirstprivateClause>(Cl); 5117 I = PC->private_copies().begin(); 5118 It = PC->varlist_begin(); 5119 Et = PC->varlist_end(); 5120 } else if (Cl->getClauseKind() == OMPC_lastprivate) { 5121 auto *PC = cast<OMPLastprivateClause>(Cl); 5122 I = PC->private_copies().begin(); 5123 It = PC->varlist_begin(); 5124 Et = PC->varlist_end(); 5125 } else if (Cl->getClauseKind() == OMPC_linear) { 5126 auto *PC = cast<OMPLinearClause>(Cl); 5127 I = PC->privates().begin(); 5128 It = PC->varlist_begin(); 5129 Et = PC->varlist_end(); 5130 } else if (Cl->getClauseKind() == OMPC_reduction) { 5131 auto *PC = cast<OMPReductionClause>(Cl); 5132 I = PC->privates().begin(); 5133 It = PC->varlist_begin(); 5134 Et = PC->varlist_end(); 5135 } else if (Cl->getClauseKind() == OMPC_task_reduction) { 5136 auto *PC = cast<OMPTaskReductionClause>(Cl); 5137 I = PC->privates().begin(); 5138 It = PC->varlist_begin(); 5139 Et = PC->varlist_end(); 5140 } else if (Cl->getClauseKind() == OMPC_in_reduction) { 5141 auto *PC = cast<OMPInReductionClause>(Cl); 5142 I = PC->privates().begin(); 5143 It = PC->varlist_begin(); 5144 Et = PC->varlist_end(); 5145 } else { 5146 llvm_unreachable("Expected private clause."); 5147 } 5148 for (Expr *E : llvm::make_range(It, Et)) { 5149 if (!*I) { 5150 ++I; 5151 continue; 5152 } 5153 SourceLocation ELoc; 5154 SourceRange ERange; 5155 Expr *SimpleRefExpr = E; 5156 auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange, 5157 /*AllowArraySection=*/true); 5158 DeclToCopy.try_emplace(Res.first, 5159 cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl())); 5160 ++I; 5161 } 5162 } 5163 for (OMPClause *C : AllocateRange) { 5164 auto *AC = cast<OMPAllocateClause>(C); 5165 if (S.getLangOpts().OpenMP >= 50 && 5166 !Stack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>() && 5167 isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()) && 5168 AC->getAllocator()) { 5169 Expr *Allocator = AC->getAllocator(); 5170 // OpenMP, 2.12.5 target Construct 5171 // Memory allocators that do not appear in a uses_allocators clause cannot 5172 // appear as an allocator in an allocate clause or be used in the target 5173 // region unless a requires directive with the dynamic_allocators clause 5174 // is present in the same compilation unit. 5175 AllocatorChecker Checker(Stack); 5176 if (Checker.Visit(Allocator)) 5177 S.Diag(Allocator->getExprLoc(), 5178 diag::err_omp_allocator_not_in_uses_allocators) 5179 << Allocator->getSourceRange(); 5180 } 5181 OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind = 5182 getAllocatorKind(S, Stack, AC->getAllocator()); 5183 // OpenMP, 2.11.4 allocate Clause, Restrictions. 5184 // For task, taskloop or target directives, allocation requests to memory 5185 // allocators with the trait access set to thread result in unspecified 5186 // behavior. 5187 if (AllocatorKind == OMPAllocateDeclAttr::OMPThreadMemAlloc && 5188 (isOpenMPTaskingDirective(Stack->getCurrentDirective()) || 5189 isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()))) { 5190 S.Diag(AC->getAllocator()->getExprLoc(), 5191 diag::warn_omp_allocate_thread_on_task_target_directive) 5192 << getOpenMPDirectiveName(Stack->getCurrentDirective()); 5193 } 5194 for (Expr *E : AC->varlists()) { 5195 SourceLocation ELoc; 5196 SourceRange ERange; 5197 Expr *SimpleRefExpr = E; 5198 auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange); 5199 ValueDecl *VD = Res.first; 5200 DSAStackTy::DSAVarData Data = Stack->getTopDSA(VD, /*FromParent=*/false); 5201 if (!isOpenMPPrivate(Data.CKind)) { 5202 S.Diag(E->getExprLoc(), 5203 diag::err_omp_expected_private_copy_for_allocate); 5204 continue; 5205 } 5206 VarDecl *PrivateVD = DeclToCopy[VD]; 5207 if (checkPreviousOMPAllocateAttribute(S, Stack, E, PrivateVD, 5208 AllocatorKind, AC->getAllocator())) 5209 continue; 5210 applyOMPAllocateAttribute(S, PrivateVD, AllocatorKind, AC->getAllocator(), 5211 E->getSourceRange()); 5212 } 5213 } 5214 } 5215 5216 namespace { 5217 /// Rewrite statements and expressions for Sema \p Actions CurContext. 5218 /// 5219 /// Used to wrap already parsed statements/expressions into a new CapturedStmt 5220 /// context. DeclRefExpr used inside the new context are changed to refer to the 5221 /// captured variable instead. 5222 class CaptureVars : public TreeTransform<CaptureVars> { 5223 using BaseTransform = TreeTransform<CaptureVars>; 5224 5225 public: 5226 CaptureVars(Sema &Actions) : BaseTransform(Actions) {} 5227 5228 bool AlwaysRebuild() { return true; } 5229 }; 5230 } // namespace 5231 5232 static VarDecl *precomputeExpr(Sema &Actions, 5233 SmallVectorImpl<Stmt *> &BodyStmts, Expr *E, 5234 StringRef Name) { 5235 Expr *NewE = AssertSuccess(CaptureVars(Actions).TransformExpr(E)); 5236 VarDecl *NewVar = buildVarDecl(Actions, {}, NewE->getType(), Name, nullptr, 5237 dyn_cast<DeclRefExpr>(E->IgnoreImplicit())); 5238 auto *NewDeclStmt = cast<DeclStmt>(AssertSuccess( 5239 Actions.ActOnDeclStmt(Actions.ConvertDeclToDeclGroup(NewVar), {}, {}))); 5240 Actions.AddInitializerToDecl(NewDeclStmt->getSingleDecl(), NewE, false); 5241 BodyStmts.push_back(NewDeclStmt); 5242 return NewVar; 5243 } 5244 5245 /// Create a closure that computes the number of iterations of a loop. 5246 /// 5247 /// \param Actions The Sema object. 5248 /// \param LogicalTy Type for the logical iteration number. 5249 /// \param Rel Comparison operator of the loop condition. 5250 /// \param StartExpr Value of the loop counter at the first iteration. 5251 /// \param StopExpr Expression the loop counter is compared against in the loop 5252 /// condition. \param StepExpr Amount of increment after each iteration. 5253 /// 5254 /// \return Closure (CapturedStmt) of the distance calculation. 5255 static CapturedStmt *buildDistanceFunc(Sema &Actions, QualType LogicalTy, 5256 BinaryOperator::Opcode Rel, 5257 Expr *StartExpr, Expr *StopExpr, 5258 Expr *StepExpr) { 5259 ASTContext &Ctx = Actions.getASTContext(); 5260 TypeSourceInfo *LogicalTSI = Ctx.getTrivialTypeSourceInfo(LogicalTy); 5261 5262 // Captured regions currently don't support return values, we use an 5263 // out-parameter instead. All inputs are implicit captures. 5264 // TODO: Instead of capturing each DeclRefExpr occurring in 5265 // StartExpr/StopExpr/Step, these could also be passed as a value capture. 5266 QualType ResultTy = Ctx.getLValueReferenceType(LogicalTy); 5267 Sema::CapturedParamNameType Params[] = {{"Distance", ResultTy}, 5268 {StringRef(), QualType()}}; 5269 Actions.ActOnCapturedRegionStart({}, nullptr, CR_Default, Params); 5270 5271 Stmt *Body; 5272 { 5273 Sema::CompoundScopeRAII CompoundScope(Actions); 5274 CapturedDecl *CS = cast<CapturedDecl>(Actions.CurContext); 5275 5276 // Get the LValue expression for the result. 5277 ImplicitParamDecl *DistParam = CS->getParam(0); 5278 DeclRefExpr *DistRef = Actions.BuildDeclRefExpr( 5279 DistParam, LogicalTy, VK_LValue, {}, nullptr, nullptr, {}, nullptr); 5280 5281 SmallVector<Stmt *, 4> BodyStmts; 5282 5283 // Capture all referenced variable references. 5284 // TODO: Instead of computing NewStart/NewStop/NewStep inside the 5285 // CapturedStmt, we could compute them before and capture the result, to be 5286 // used jointly with the LoopVar function. 5287 VarDecl *NewStart = precomputeExpr(Actions, BodyStmts, StartExpr, ".start"); 5288 VarDecl *NewStop = precomputeExpr(Actions, BodyStmts, StopExpr, ".stop"); 5289 VarDecl *NewStep = precomputeExpr(Actions, BodyStmts, StepExpr, ".step"); 5290 auto BuildVarRef = [&](VarDecl *VD) { 5291 return buildDeclRefExpr(Actions, VD, VD->getType(), {}); 5292 }; 5293 5294 IntegerLiteral *Zero = IntegerLiteral::Create( 5295 Ctx, llvm::APInt(Ctx.getIntWidth(LogicalTy), 0), LogicalTy, {}); 5296 Expr *Dist; 5297 if (Rel == BO_NE) { 5298 // When using a != comparison, the increment can be +1 or -1. This can be 5299 // dynamic at runtime, so we need to check for the direction. 5300 Expr *IsNegStep = AssertSuccess( 5301 Actions.BuildBinOp(nullptr, {}, BO_LT, BuildVarRef(NewStep), Zero)); 5302 5303 // Positive increment. 5304 Expr *ForwardRange = AssertSuccess(Actions.BuildBinOp( 5305 nullptr, {}, BO_Sub, BuildVarRef(NewStop), BuildVarRef(NewStart))); 5306 ForwardRange = AssertSuccess( 5307 Actions.BuildCStyleCastExpr({}, LogicalTSI, {}, ForwardRange)); 5308 Expr *ForwardDist = AssertSuccess(Actions.BuildBinOp( 5309 nullptr, {}, BO_Div, ForwardRange, BuildVarRef(NewStep))); 5310 5311 // Negative increment. 5312 Expr *BackwardRange = AssertSuccess(Actions.BuildBinOp( 5313 nullptr, {}, BO_Sub, BuildVarRef(NewStart), BuildVarRef(NewStop))); 5314 BackwardRange = AssertSuccess( 5315 Actions.BuildCStyleCastExpr({}, LogicalTSI, {}, BackwardRange)); 5316 Expr *NegIncAmount = AssertSuccess( 5317 Actions.BuildUnaryOp(nullptr, {}, UO_Minus, BuildVarRef(NewStep))); 5318 Expr *BackwardDist = AssertSuccess( 5319 Actions.BuildBinOp(nullptr, {}, BO_Div, BackwardRange, NegIncAmount)); 5320 5321 // Use the appropriate case. 5322 Dist = AssertSuccess(Actions.ActOnConditionalOp( 5323 {}, {}, IsNegStep, BackwardDist, ForwardDist)); 5324 } else { 5325 assert((Rel == BO_LT || Rel == BO_LE || Rel == BO_GE || Rel == BO_GT) && 5326 "Expected one of these relational operators"); 5327 5328 // We can derive the direction from any other comparison operator. It is 5329 // non well-formed OpenMP if Step increments/decrements in the other 5330 // directions. Whether at least the first iteration passes the loop 5331 // condition. 5332 Expr *HasAnyIteration = AssertSuccess(Actions.BuildBinOp( 5333 nullptr, {}, Rel, BuildVarRef(NewStart), BuildVarRef(NewStop))); 5334 5335 // Compute the range between first and last counter value. 5336 Expr *Range; 5337 if (Rel == BO_GE || Rel == BO_GT) 5338 Range = AssertSuccess(Actions.BuildBinOp( 5339 nullptr, {}, BO_Sub, BuildVarRef(NewStart), BuildVarRef(NewStop))); 5340 else 5341 Range = AssertSuccess(Actions.BuildBinOp( 5342 nullptr, {}, BO_Sub, BuildVarRef(NewStop), BuildVarRef(NewStart))); 5343 5344 // Ensure unsigned range space. 5345 Range = 5346 AssertSuccess(Actions.BuildCStyleCastExpr({}, LogicalTSI, {}, Range)); 5347 5348 if (Rel == BO_LE || Rel == BO_GE) { 5349 // Add one to the range if the relational operator is inclusive. 5350 Range = AssertSuccess(Actions.BuildBinOp( 5351 nullptr, {}, BO_Add, Range, 5352 Actions.ActOnIntegerConstant(SourceLocation(), 1).get())); 5353 } 5354 5355 // Divide by the absolute step amount. 5356 Expr *Divisor = BuildVarRef(NewStep); 5357 if (Rel == BO_GE || Rel == BO_GT) 5358 Divisor = 5359 AssertSuccess(Actions.BuildUnaryOp(nullptr, {}, UO_Minus, Divisor)); 5360 Dist = AssertSuccess( 5361 Actions.BuildBinOp(nullptr, {}, BO_Div, Range, Divisor)); 5362 5363 // If there is not at least one iteration, the range contains garbage. Fix 5364 // to zero in this case. 5365 Dist = AssertSuccess( 5366 Actions.ActOnConditionalOp({}, {}, HasAnyIteration, Dist, Zero)); 5367 } 5368 5369 // Assign the result to the out-parameter. 5370 Stmt *ResultAssign = AssertSuccess(Actions.BuildBinOp( 5371 Actions.getCurScope(), {}, BO_Assign, DistRef, Dist)); 5372 BodyStmts.push_back(ResultAssign); 5373 5374 Body = AssertSuccess(Actions.ActOnCompoundStmt({}, {}, BodyStmts, false)); 5375 } 5376 5377 return cast<CapturedStmt>( 5378 AssertSuccess(Actions.ActOnCapturedRegionEnd(Body))); 5379 } 5380 5381 /// Create a closure that computes the loop variable from the logical iteration 5382 /// number. 5383 /// 5384 /// \param Actions The Sema object. 5385 /// \param LoopVarTy Type for the loop variable used for result value. 5386 /// \param LogicalTy Type for the logical iteration number. 5387 /// \param StartExpr Value of the loop counter at the first iteration. 5388 /// \param Step Amount of increment after each iteration. 5389 /// \param Deref Whether the loop variable is a dereference of the loop 5390 /// counter variable. 5391 /// 5392 /// \return Closure (CapturedStmt) of the loop value calculation. 5393 static CapturedStmt *buildLoopVarFunc(Sema &Actions, QualType LoopVarTy, 5394 QualType LogicalTy, 5395 DeclRefExpr *StartExpr, Expr *Step, 5396 bool Deref) { 5397 ASTContext &Ctx = Actions.getASTContext(); 5398 5399 // Pass the result as an out-parameter. Passing as return value would require 5400 // the OpenMPIRBuilder to know additional C/C++ semantics, such as how to 5401 // invoke a copy constructor. 5402 QualType TargetParamTy = Ctx.getLValueReferenceType(LoopVarTy); 5403 Sema::CapturedParamNameType Params[] = {{"LoopVar", TargetParamTy}, 5404 {"Logical", LogicalTy}, 5405 {StringRef(), QualType()}}; 5406 Actions.ActOnCapturedRegionStart({}, nullptr, CR_Default, Params); 5407 5408 // Capture the initial iterator which represents the LoopVar value at the 5409 // zero's logical iteration. Since the original ForStmt/CXXForRangeStmt update 5410 // it in every iteration, capture it by value before it is modified. 5411 VarDecl *StartVar = cast<VarDecl>(StartExpr->getDecl()); 5412 bool Invalid = Actions.tryCaptureVariable(StartVar, {}, 5413 Sema::TryCapture_ExplicitByVal, {}); 5414 (void)Invalid; 5415 assert(!Invalid && "Expecting capture-by-value to work."); 5416 5417 Expr *Body; 5418 { 5419 Sema::CompoundScopeRAII CompoundScope(Actions); 5420 auto *CS = cast<CapturedDecl>(Actions.CurContext); 5421 5422 ImplicitParamDecl *TargetParam = CS->getParam(0); 5423 DeclRefExpr *TargetRef = Actions.BuildDeclRefExpr( 5424 TargetParam, LoopVarTy, VK_LValue, {}, nullptr, nullptr, {}, nullptr); 5425 ImplicitParamDecl *IndvarParam = CS->getParam(1); 5426 DeclRefExpr *LogicalRef = Actions.BuildDeclRefExpr( 5427 IndvarParam, LogicalTy, VK_LValue, {}, nullptr, nullptr, {}, nullptr); 5428 5429 // Capture the Start expression. 5430 CaptureVars Recap(Actions); 5431 Expr *NewStart = AssertSuccess(Recap.TransformExpr(StartExpr)); 5432 Expr *NewStep = AssertSuccess(Recap.TransformExpr(Step)); 5433 5434 Expr *Skip = AssertSuccess( 5435 Actions.BuildBinOp(nullptr, {}, BO_Mul, NewStep, LogicalRef)); 5436 // TODO: Explicitly cast to the iterator's difference_type instead of 5437 // relying on implicit conversion. 5438 Expr *Advanced = 5439 AssertSuccess(Actions.BuildBinOp(nullptr, {}, BO_Add, NewStart, Skip)); 5440 5441 if (Deref) { 5442 // For range-based for-loops convert the loop counter value to a concrete 5443 // loop variable value by dereferencing the iterator. 5444 Advanced = 5445 AssertSuccess(Actions.BuildUnaryOp(nullptr, {}, UO_Deref, Advanced)); 5446 } 5447 5448 // Assign the result to the output parameter. 5449 Body = AssertSuccess(Actions.BuildBinOp(Actions.getCurScope(), {}, 5450 BO_Assign, TargetRef, Advanced)); 5451 } 5452 return cast<CapturedStmt>( 5453 AssertSuccess(Actions.ActOnCapturedRegionEnd(Body))); 5454 } 5455 5456 StmtResult Sema::ActOnOpenMPCanonicalLoop(Stmt *AStmt) { 5457 ASTContext &Ctx = getASTContext(); 5458 5459 // Extract the common elements of ForStmt and CXXForRangeStmt: 5460 // Loop variable, repeat condition, increment 5461 Expr *Cond, *Inc; 5462 VarDecl *LIVDecl, *LUVDecl; 5463 if (auto *For = dyn_cast<ForStmt>(AStmt)) { 5464 Stmt *Init = For->getInit(); 5465 if (auto *LCVarDeclStmt = dyn_cast<DeclStmt>(Init)) { 5466 // For statement declares loop variable. 5467 LIVDecl = cast<VarDecl>(LCVarDeclStmt->getSingleDecl()); 5468 } else if (auto *LCAssign = dyn_cast<BinaryOperator>(Init)) { 5469 // For statement reuses variable. 5470 assert(LCAssign->getOpcode() == BO_Assign && 5471 "init part must be a loop variable assignment"); 5472 auto *CounterRef = cast<DeclRefExpr>(LCAssign->getLHS()); 5473 LIVDecl = cast<VarDecl>(CounterRef->getDecl()); 5474 } else 5475 llvm_unreachable("Cannot determine loop variable"); 5476 LUVDecl = LIVDecl; 5477 5478 Cond = For->getCond(); 5479 Inc = For->getInc(); 5480 } else if (auto *RangeFor = dyn_cast<CXXForRangeStmt>(AStmt)) { 5481 DeclStmt *BeginStmt = RangeFor->getBeginStmt(); 5482 LIVDecl = cast<VarDecl>(BeginStmt->getSingleDecl()); 5483 LUVDecl = RangeFor->getLoopVariable(); 5484 5485 Cond = RangeFor->getCond(); 5486 Inc = RangeFor->getInc(); 5487 } else 5488 llvm_unreachable("unhandled kind of loop"); 5489 5490 QualType CounterTy = LIVDecl->getType(); 5491 QualType LVTy = LUVDecl->getType(); 5492 5493 // Analyze the loop condition. 5494 Expr *LHS, *RHS; 5495 BinaryOperator::Opcode CondRel; 5496 Cond = Cond->IgnoreImplicit(); 5497 if (auto *CondBinExpr = dyn_cast<BinaryOperator>(Cond)) { 5498 LHS = CondBinExpr->getLHS(); 5499 RHS = CondBinExpr->getRHS(); 5500 CondRel = CondBinExpr->getOpcode(); 5501 } else if (auto *CondCXXOp = dyn_cast<CXXOperatorCallExpr>(Cond)) { 5502 assert(CondCXXOp->getNumArgs() == 2 && "Comparison should have 2 operands"); 5503 LHS = CondCXXOp->getArg(0); 5504 RHS = CondCXXOp->getArg(1); 5505 switch (CondCXXOp->getOperator()) { 5506 case OO_ExclaimEqual: 5507 CondRel = BO_NE; 5508 break; 5509 case OO_Less: 5510 CondRel = BO_LT; 5511 break; 5512 case OO_LessEqual: 5513 CondRel = BO_LE; 5514 break; 5515 case OO_Greater: 5516 CondRel = BO_GT; 5517 break; 5518 case OO_GreaterEqual: 5519 CondRel = BO_GE; 5520 break; 5521 default: 5522 llvm_unreachable("unexpected iterator operator"); 5523 } 5524 } else 5525 llvm_unreachable("unexpected loop condition"); 5526 5527 // Normalize such that the loop counter is on the LHS. 5528 if (!isa<DeclRefExpr>(LHS->IgnoreImplicit()) || 5529 cast<DeclRefExpr>(LHS->IgnoreImplicit())->getDecl() != LIVDecl) { 5530 std::swap(LHS, RHS); 5531 CondRel = BinaryOperator::reverseComparisonOp(CondRel); 5532 } 5533 auto *CounterRef = cast<DeclRefExpr>(LHS->IgnoreImplicit()); 5534 5535 // Decide the bit width for the logical iteration counter. By default use the 5536 // unsigned ptrdiff_t integer size (for iterators and pointers). 5537 // TODO: For iterators, use iterator::difference_type, 5538 // std::iterator_traits<>::difference_type or decltype(it - end). 5539 QualType LogicalTy = Ctx.getUnsignedPointerDiffType(); 5540 if (CounterTy->isIntegerType()) { 5541 unsigned BitWidth = Ctx.getIntWidth(CounterTy); 5542 LogicalTy = Ctx.getIntTypeForBitwidth(BitWidth, false); 5543 } 5544 5545 // Analyze the loop increment. 5546 Expr *Step; 5547 if (auto *IncUn = dyn_cast<UnaryOperator>(Inc)) { 5548 int Direction; 5549 switch (IncUn->getOpcode()) { 5550 case UO_PreInc: 5551 case UO_PostInc: 5552 Direction = 1; 5553 break; 5554 case UO_PreDec: 5555 case UO_PostDec: 5556 Direction = -1; 5557 break; 5558 default: 5559 llvm_unreachable("unhandled unary increment operator"); 5560 } 5561 Step = IntegerLiteral::Create( 5562 Ctx, llvm::APInt(Ctx.getIntWidth(LogicalTy), Direction), LogicalTy, {}); 5563 } else if (auto *IncBin = dyn_cast<BinaryOperator>(Inc)) { 5564 if (IncBin->getOpcode() == BO_AddAssign) { 5565 Step = IncBin->getRHS(); 5566 } else if (IncBin->getOpcode() == BO_SubAssign) { 5567 Step = 5568 AssertSuccess(BuildUnaryOp(nullptr, {}, UO_Minus, IncBin->getRHS())); 5569 } else 5570 llvm_unreachable("unhandled binary increment operator"); 5571 } else if (auto *CondCXXOp = dyn_cast<CXXOperatorCallExpr>(Inc)) { 5572 switch (CondCXXOp->getOperator()) { 5573 case OO_PlusPlus: 5574 Step = IntegerLiteral::Create( 5575 Ctx, llvm::APInt(Ctx.getIntWidth(LogicalTy), 1), LogicalTy, {}); 5576 break; 5577 case OO_MinusMinus: 5578 Step = IntegerLiteral::Create( 5579 Ctx, llvm::APInt(Ctx.getIntWidth(LogicalTy), -1), LogicalTy, {}); 5580 break; 5581 case OO_PlusEqual: 5582 Step = CondCXXOp->getArg(1); 5583 break; 5584 case OO_MinusEqual: 5585 Step = AssertSuccess( 5586 BuildUnaryOp(nullptr, {}, UO_Minus, CondCXXOp->getArg(1))); 5587 break; 5588 default: 5589 llvm_unreachable("unhandled overloaded increment operator"); 5590 } 5591 } else 5592 llvm_unreachable("unknown increment expression"); 5593 5594 CapturedStmt *DistanceFunc = 5595 buildDistanceFunc(*this, LogicalTy, CondRel, LHS, RHS, Step); 5596 CapturedStmt *LoopVarFunc = buildLoopVarFunc( 5597 *this, LVTy, LogicalTy, CounterRef, Step, isa<CXXForRangeStmt>(AStmt)); 5598 DeclRefExpr *LVRef = BuildDeclRefExpr(LUVDecl, LUVDecl->getType(), VK_LValue, 5599 {}, nullptr, nullptr, {}, nullptr); 5600 return OMPCanonicalLoop::create(getASTContext(), AStmt, DistanceFunc, 5601 LoopVarFunc, LVRef); 5602 } 5603 5604 StmtResult Sema::ActOnOpenMPLoopnest(Stmt *AStmt) { 5605 // Handle a literal loop. 5606 if (isa<ForStmt>(AStmt) || isa<CXXForRangeStmt>(AStmt)) 5607 return ActOnOpenMPCanonicalLoop(AStmt); 5608 5609 // If not a literal loop, it must be the result of a loop transformation. 5610 OMPExecutableDirective *LoopTransform = cast<OMPExecutableDirective>(AStmt); 5611 assert( 5612 isOpenMPLoopTransformationDirective(LoopTransform->getDirectiveKind()) && 5613 "Loop transformation directive expected"); 5614 return LoopTransform; 5615 } 5616 5617 static ExprResult buildUserDefinedMapperRef(Sema &SemaRef, Scope *S, 5618 CXXScopeSpec &MapperIdScopeSpec, 5619 const DeclarationNameInfo &MapperId, 5620 QualType Type, 5621 Expr *UnresolvedMapper); 5622 5623 /// Perform DFS through the structure/class data members trying to find 5624 /// member(s) with user-defined 'default' mapper and generate implicit map 5625 /// clauses for such members with the found 'default' mapper. 5626 static void 5627 processImplicitMapsWithDefaultMappers(Sema &S, DSAStackTy *Stack, 5628 SmallVectorImpl<OMPClause *> &Clauses) { 5629 // Check for the deault mapper for data members. 5630 if (S.getLangOpts().OpenMP < 50) 5631 return; 5632 SmallVector<OMPClause *, 4> ImplicitMaps; 5633 for (int Cnt = 0, EndCnt = Clauses.size(); Cnt < EndCnt; ++Cnt) { 5634 auto *C = dyn_cast<OMPMapClause>(Clauses[Cnt]); 5635 if (!C) 5636 continue; 5637 SmallVector<Expr *, 4> SubExprs; 5638 auto *MI = C->mapperlist_begin(); 5639 for (auto I = C->varlist_begin(), End = C->varlist_end(); I != End; 5640 ++I, ++MI) { 5641 // Expression is mapped using mapper - skip it. 5642 if (*MI) 5643 continue; 5644 Expr *E = *I; 5645 // Expression is dependent - skip it, build the mapper when it gets 5646 // instantiated. 5647 if (E->isTypeDependent() || E->isValueDependent() || 5648 E->containsUnexpandedParameterPack()) 5649 continue; 5650 // Array section - need to check for the mapping of the array section 5651 // element. 5652 QualType CanonType = E->getType().getCanonicalType(); 5653 if (CanonType->isSpecificBuiltinType(BuiltinType::OMPArraySection)) { 5654 const auto *OASE = cast<OMPArraySectionExpr>(E->IgnoreParenImpCasts()); 5655 QualType BaseType = 5656 OMPArraySectionExpr::getBaseOriginalType(OASE->getBase()); 5657 QualType ElemType; 5658 if (const auto *ATy = BaseType->getAsArrayTypeUnsafe()) 5659 ElemType = ATy->getElementType(); 5660 else 5661 ElemType = BaseType->getPointeeType(); 5662 CanonType = ElemType; 5663 } 5664 5665 // DFS over data members in structures/classes. 5666 SmallVector<std::pair<QualType, FieldDecl *>, 4> Types( 5667 1, {CanonType, nullptr}); 5668 llvm::DenseMap<const Type *, Expr *> Visited; 5669 SmallVector<std::pair<FieldDecl *, unsigned>, 4> ParentChain( 5670 1, {nullptr, 1}); 5671 while (!Types.empty()) { 5672 QualType BaseType; 5673 FieldDecl *CurFD; 5674 std::tie(BaseType, CurFD) = Types.pop_back_val(); 5675 while (ParentChain.back().second == 0) 5676 ParentChain.pop_back(); 5677 --ParentChain.back().second; 5678 if (BaseType.isNull()) 5679 continue; 5680 // Only structs/classes are allowed to have mappers. 5681 const RecordDecl *RD = BaseType.getCanonicalType()->getAsRecordDecl(); 5682 if (!RD) 5683 continue; 5684 auto It = Visited.find(BaseType.getTypePtr()); 5685 if (It == Visited.end()) { 5686 // Try to find the associated user-defined mapper. 5687 CXXScopeSpec MapperIdScopeSpec; 5688 DeclarationNameInfo DefaultMapperId; 5689 DefaultMapperId.setName(S.Context.DeclarationNames.getIdentifier( 5690 &S.Context.Idents.get("default"))); 5691 DefaultMapperId.setLoc(E->getExprLoc()); 5692 ExprResult ER = buildUserDefinedMapperRef( 5693 S, Stack->getCurScope(), MapperIdScopeSpec, DefaultMapperId, 5694 BaseType, /*UnresolvedMapper=*/nullptr); 5695 if (ER.isInvalid()) 5696 continue; 5697 It = Visited.try_emplace(BaseType.getTypePtr(), ER.get()).first; 5698 } 5699 // Found default mapper. 5700 if (It->second) { 5701 auto *OE = new (S.Context) OpaqueValueExpr(E->getExprLoc(), CanonType, 5702 VK_LValue, OK_Ordinary, E); 5703 OE->setIsUnique(/*V=*/true); 5704 Expr *BaseExpr = OE; 5705 for (const auto &P : ParentChain) { 5706 if (P.first) { 5707 BaseExpr = S.BuildMemberExpr( 5708 BaseExpr, /*IsArrow=*/false, E->getExprLoc(), 5709 NestedNameSpecifierLoc(), SourceLocation(), P.first, 5710 DeclAccessPair::make(P.first, P.first->getAccess()), 5711 /*HadMultipleCandidates=*/false, DeclarationNameInfo(), 5712 P.first->getType(), VK_LValue, OK_Ordinary); 5713 BaseExpr = S.DefaultLvalueConversion(BaseExpr).get(); 5714 } 5715 } 5716 if (CurFD) 5717 BaseExpr = S.BuildMemberExpr( 5718 BaseExpr, /*IsArrow=*/false, E->getExprLoc(), 5719 NestedNameSpecifierLoc(), SourceLocation(), CurFD, 5720 DeclAccessPair::make(CurFD, CurFD->getAccess()), 5721 /*HadMultipleCandidates=*/false, DeclarationNameInfo(), 5722 CurFD->getType(), VK_LValue, OK_Ordinary); 5723 SubExprs.push_back(BaseExpr); 5724 continue; 5725 } 5726 // Check for the "default" mapper for data members. 5727 bool FirstIter = true; 5728 for (FieldDecl *FD : RD->fields()) { 5729 if (!FD) 5730 continue; 5731 QualType FieldTy = FD->getType(); 5732 if (FieldTy.isNull() || 5733 !(FieldTy->isStructureOrClassType() || FieldTy->isUnionType())) 5734 continue; 5735 if (FirstIter) { 5736 FirstIter = false; 5737 ParentChain.emplace_back(CurFD, 1); 5738 } else { 5739 ++ParentChain.back().second; 5740 } 5741 Types.emplace_back(FieldTy, FD); 5742 } 5743 } 5744 } 5745 if (SubExprs.empty()) 5746 continue; 5747 CXXScopeSpec MapperIdScopeSpec; 5748 DeclarationNameInfo MapperId; 5749 if (OMPClause *NewClause = S.ActOnOpenMPMapClause( 5750 C->getMapTypeModifiers(), C->getMapTypeModifiersLoc(), 5751 MapperIdScopeSpec, MapperId, C->getMapType(), 5752 /*IsMapTypeImplicit=*/true, SourceLocation(), SourceLocation(), 5753 SubExprs, OMPVarListLocTy())) 5754 Clauses.push_back(NewClause); 5755 } 5756 } 5757 5758 StmtResult Sema::ActOnOpenMPExecutableDirective( 5759 OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName, 5760 OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses, 5761 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) { 5762 StmtResult Res = StmtError(); 5763 // First check CancelRegion which is then used in checkNestingOfRegions. 5764 if (checkCancelRegion(*this, Kind, CancelRegion, StartLoc) || 5765 checkNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion, 5766 StartLoc)) 5767 return StmtError(); 5768 5769 llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit; 5770 VarsWithInheritedDSAType VarsWithInheritedDSA; 5771 bool ErrorFound = false; 5772 ClausesWithImplicit.append(Clauses.begin(), Clauses.end()); 5773 if (AStmt && !CurContext->isDependentContext() && Kind != OMPD_atomic && 5774 Kind != OMPD_critical && Kind != OMPD_section && Kind != OMPD_master && 5775 Kind != OMPD_masked && !isOpenMPLoopTransformationDirective(Kind)) { 5776 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 5777 5778 // Check default data sharing attributes for referenced variables. 5779 DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt)); 5780 int ThisCaptureLevel = getOpenMPCaptureLevels(Kind); 5781 Stmt *S = AStmt; 5782 while (--ThisCaptureLevel >= 0) 5783 S = cast<CapturedStmt>(S)->getCapturedStmt(); 5784 DSAChecker.Visit(S); 5785 if (!isOpenMPTargetDataManagementDirective(Kind) && 5786 !isOpenMPTaskingDirective(Kind)) { 5787 // Visit subcaptures to generate implicit clauses for captured vars. 5788 auto *CS = cast<CapturedStmt>(AStmt); 5789 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions; 5790 getOpenMPCaptureRegions(CaptureRegions, Kind); 5791 // Ignore outer tasking regions for target directives. 5792 if (CaptureRegions.size() > 1 && CaptureRegions.front() == OMPD_task) 5793 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 5794 DSAChecker.visitSubCaptures(CS); 5795 } 5796 if (DSAChecker.isErrorFound()) 5797 return StmtError(); 5798 // Generate list of implicitly defined firstprivate variables. 5799 VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA(); 5800 5801 SmallVector<Expr *, 4> ImplicitFirstprivates( 5802 DSAChecker.getImplicitFirstprivate().begin(), 5803 DSAChecker.getImplicitFirstprivate().end()); 5804 const unsigned DefaultmapKindNum = OMPC_DEFAULTMAP_pointer + 1; 5805 SmallVector<Expr *, 4> ImplicitMaps[DefaultmapKindNum][OMPC_MAP_delete]; 5806 SmallVector<OpenMPMapModifierKind, NumberOfOMPMapClauseModifiers> 5807 ImplicitMapModifiers[DefaultmapKindNum]; 5808 SmallVector<SourceLocation, NumberOfOMPMapClauseModifiers> 5809 ImplicitMapModifiersLoc[DefaultmapKindNum]; 5810 // Get the original location of present modifier from Defaultmap clause. 5811 SourceLocation PresentModifierLocs[DefaultmapKindNum]; 5812 for (OMPClause *C : Clauses) { 5813 if (auto *DMC = dyn_cast<OMPDefaultmapClause>(C)) 5814 if (DMC->getDefaultmapModifier() == OMPC_DEFAULTMAP_MODIFIER_present) 5815 PresentModifierLocs[DMC->getDefaultmapKind()] = 5816 DMC->getDefaultmapModifierLoc(); 5817 } 5818 for (unsigned VC = 0; VC < DefaultmapKindNum; ++VC) { 5819 auto Kind = static_cast<OpenMPDefaultmapClauseKind>(VC); 5820 for (unsigned I = 0; I < OMPC_MAP_delete; ++I) { 5821 ArrayRef<Expr *> ImplicitMap = DSAChecker.getImplicitMap( 5822 Kind, static_cast<OpenMPMapClauseKind>(I)); 5823 ImplicitMaps[VC][I].append(ImplicitMap.begin(), ImplicitMap.end()); 5824 } 5825 ArrayRef<OpenMPMapModifierKind> ImplicitModifier = 5826 DSAChecker.getImplicitMapModifier(Kind); 5827 ImplicitMapModifiers[VC].append(ImplicitModifier.begin(), 5828 ImplicitModifier.end()); 5829 std::fill_n(std::back_inserter(ImplicitMapModifiersLoc[VC]), 5830 ImplicitModifier.size(), PresentModifierLocs[VC]); 5831 } 5832 // Mark taskgroup task_reduction descriptors as implicitly firstprivate. 5833 for (OMPClause *C : Clauses) { 5834 if (auto *IRC = dyn_cast<OMPInReductionClause>(C)) { 5835 for (Expr *E : IRC->taskgroup_descriptors()) 5836 if (E) 5837 ImplicitFirstprivates.emplace_back(E); 5838 } 5839 // OpenMP 5.0, 2.10.1 task Construct 5840 // [detach clause]... The event-handle will be considered as if it was 5841 // specified on a firstprivate clause. 5842 if (auto *DC = dyn_cast<OMPDetachClause>(C)) 5843 ImplicitFirstprivates.push_back(DC->getEventHandler()); 5844 } 5845 if (!ImplicitFirstprivates.empty()) { 5846 if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause( 5847 ImplicitFirstprivates, SourceLocation(), SourceLocation(), 5848 SourceLocation())) { 5849 ClausesWithImplicit.push_back(Implicit); 5850 ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() != 5851 ImplicitFirstprivates.size(); 5852 } else { 5853 ErrorFound = true; 5854 } 5855 } 5856 // OpenMP 5.0 [2.19.7] 5857 // If a list item appears in a reduction, lastprivate or linear 5858 // clause on a combined target construct then it is treated as 5859 // if it also appears in a map clause with a map-type of tofrom 5860 if (getLangOpts().OpenMP >= 50 && Kind != OMPD_target && 5861 isOpenMPTargetExecutionDirective(Kind)) { 5862 SmallVector<Expr *, 4> ImplicitExprs; 5863 for (OMPClause *C : Clauses) { 5864 if (auto *RC = dyn_cast<OMPReductionClause>(C)) 5865 for (Expr *E : RC->varlists()) 5866 if (!isa<DeclRefExpr>(E->IgnoreParenImpCasts())) 5867 ImplicitExprs.emplace_back(E); 5868 } 5869 if (!ImplicitExprs.empty()) { 5870 ArrayRef<Expr *> Exprs = ImplicitExprs; 5871 CXXScopeSpec MapperIdScopeSpec; 5872 DeclarationNameInfo MapperId; 5873 if (OMPClause *Implicit = ActOnOpenMPMapClause( 5874 OMPC_MAP_MODIFIER_unknown, SourceLocation(), MapperIdScopeSpec, 5875 MapperId, OMPC_MAP_tofrom, 5876 /*IsMapTypeImplicit=*/true, SourceLocation(), SourceLocation(), 5877 Exprs, OMPVarListLocTy(), /*NoDiagnose=*/true)) 5878 ClausesWithImplicit.emplace_back(Implicit); 5879 } 5880 } 5881 for (unsigned I = 0, E = DefaultmapKindNum; I < E; ++I) { 5882 int ClauseKindCnt = -1; 5883 for (ArrayRef<Expr *> ImplicitMap : ImplicitMaps[I]) { 5884 ++ClauseKindCnt; 5885 if (ImplicitMap.empty()) 5886 continue; 5887 CXXScopeSpec MapperIdScopeSpec; 5888 DeclarationNameInfo MapperId; 5889 auto Kind = static_cast<OpenMPMapClauseKind>(ClauseKindCnt); 5890 if (OMPClause *Implicit = ActOnOpenMPMapClause( 5891 ImplicitMapModifiers[I], ImplicitMapModifiersLoc[I], 5892 MapperIdScopeSpec, MapperId, Kind, /*IsMapTypeImplicit=*/true, 5893 SourceLocation(), SourceLocation(), ImplicitMap, 5894 OMPVarListLocTy())) { 5895 ClausesWithImplicit.emplace_back(Implicit); 5896 ErrorFound |= cast<OMPMapClause>(Implicit)->varlist_size() != 5897 ImplicitMap.size(); 5898 } else { 5899 ErrorFound = true; 5900 } 5901 } 5902 } 5903 // Build expressions for implicit maps of data members with 'default' 5904 // mappers. 5905 if (LangOpts.OpenMP >= 50) 5906 processImplicitMapsWithDefaultMappers(*this, DSAStack, 5907 ClausesWithImplicit); 5908 } 5909 5910 llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers; 5911 switch (Kind) { 5912 case OMPD_parallel: 5913 Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc, 5914 EndLoc); 5915 AllowedNameModifiers.push_back(OMPD_parallel); 5916 break; 5917 case OMPD_simd: 5918 Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc, 5919 VarsWithInheritedDSA); 5920 if (LangOpts.OpenMP >= 50) 5921 AllowedNameModifiers.push_back(OMPD_simd); 5922 break; 5923 case OMPD_tile: 5924 Res = 5925 ActOnOpenMPTileDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc); 5926 break; 5927 case OMPD_unroll: 5928 Res = ActOnOpenMPUnrollDirective(ClausesWithImplicit, AStmt, StartLoc, 5929 EndLoc); 5930 break; 5931 case OMPD_for: 5932 Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc, 5933 VarsWithInheritedDSA); 5934 break; 5935 case OMPD_for_simd: 5936 Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc, 5937 EndLoc, VarsWithInheritedDSA); 5938 if (LangOpts.OpenMP >= 50) 5939 AllowedNameModifiers.push_back(OMPD_simd); 5940 break; 5941 case OMPD_sections: 5942 Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc, 5943 EndLoc); 5944 break; 5945 case OMPD_section: 5946 assert(ClausesWithImplicit.empty() && 5947 "No clauses are allowed for 'omp section' directive"); 5948 Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc); 5949 break; 5950 case OMPD_single: 5951 Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc, 5952 EndLoc); 5953 break; 5954 case OMPD_master: 5955 assert(ClausesWithImplicit.empty() && 5956 "No clauses are allowed for 'omp master' directive"); 5957 Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc); 5958 break; 5959 case OMPD_masked: 5960 Res = ActOnOpenMPMaskedDirective(ClausesWithImplicit, AStmt, StartLoc, 5961 EndLoc); 5962 break; 5963 case OMPD_critical: 5964 Res = ActOnOpenMPCriticalDirective(DirName, ClausesWithImplicit, AStmt, 5965 StartLoc, EndLoc); 5966 break; 5967 case OMPD_parallel_for: 5968 Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc, 5969 EndLoc, VarsWithInheritedDSA); 5970 AllowedNameModifiers.push_back(OMPD_parallel); 5971 break; 5972 case OMPD_parallel_for_simd: 5973 Res = ActOnOpenMPParallelForSimdDirective( 5974 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 5975 AllowedNameModifiers.push_back(OMPD_parallel); 5976 if (LangOpts.OpenMP >= 50) 5977 AllowedNameModifiers.push_back(OMPD_simd); 5978 break; 5979 case OMPD_parallel_master: 5980 Res = ActOnOpenMPParallelMasterDirective(ClausesWithImplicit, AStmt, 5981 StartLoc, EndLoc); 5982 AllowedNameModifiers.push_back(OMPD_parallel); 5983 break; 5984 case OMPD_parallel_sections: 5985 Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt, 5986 StartLoc, EndLoc); 5987 AllowedNameModifiers.push_back(OMPD_parallel); 5988 break; 5989 case OMPD_task: 5990 Res = 5991 ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc); 5992 AllowedNameModifiers.push_back(OMPD_task); 5993 break; 5994 case OMPD_taskyield: 5995 assert(ClausesWithImplicit.empty() && 5996 "No clauses are allowed for 'omp taskyield' directive"); 5997 assert(AStmt == nullptr && 5998 "No associated statement allowed for 'omp taskyield' directive"); 5999 Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc); 6000 break; 6001 case OMPD_barrier: 6002 assert(ClausesWithImplicit.empty() && 6003 "No clauses are allowed for 'omp barrier' directive"); 6004 assert(AStmt == nullptr && 6005 "No associated statement allowed for 'omp barrier' directive"); 6006 Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc); 6007 break; 6008 case OMPD_taskwait: 6009 assert(ClausesWithImplicit.empty() && 6010 "No clauses are allowed for 'omp taskwait' directive"); 6011 assert(AStmt == nullptr && 6012 "No associated statement allowed for 'omp taskwait' directive"); 6013 Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc); 6014 break; 6015 case OMPD_taskgroup: 6016 Res = ActOnOpenMPTaskgroupDirective(ClausesWithImplicit, AStmt, StartLoc, 6017 EndLoc); 6018 break; 6019 case OMPD_flush: 6020 assert(AStmt == nullptr && 6021 "No associated statement allowed for 'omp flush' directive"); 6022 Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc); 6023 break; 6024 case OMPD_depobj: 6025 assert(AStmt == nullptr && 6026 "No associated statement allowed for 'omp depobj' directive"); 6027 Res = ActOnOpenMPDepobjDirective(ClausesWithImplicit, StartLoc, EndLoc); 6028 break; 6029 case OMPD_scan: 6030 assert(AStmt == nullptr && 6031 "No associated statement allowed for 'omp scan' directive"); 6032 Res = ActOnOpenMPScanDirective(ClausesWithImplicit, StartLoc, EndLoc); 6033 break; 6034 case OMPD_ordered: 6035 Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc, 6036 EndLoc); 6037 break; 6038 case OMPD_atomic: 6039 Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc, 6040 EndLoc); 6041 break; 6042 case OMPD_teams: 6043 Res = 6044 ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc); 6045 break; 6046 case OMPD_target: 6047 Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc, 6048 EndLoc); 6049 AllowedNameModifiers.push_back(OMPD_target); 6050 break; 6051 case OMPD_target_parallel: 6052 Res = ActOnOpenMPTargetParallelDirective(ClausesWithImplicit, AStmt, 6053 StartLoc, EndLoc); 6054 AllowedNameModifiers.push_back(OMPD_target); 6055 AllowedNameModifiers.push_back(OMPD_parallel); 6056 break; 6057 case OMPD_target_parallel_for: 6058 Res = ActOnOpenMPTargetParallelForDirective( 6059 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 6060 AllowedNameModifiers.push_back(OMPD_target); 6061 AllowedNameModifiers.push_back(OMPD_parallel); 6062 break; 6063 case OMPD_cancellation_point: 6064 assert(ClausesWithImplicit.empty() && 6065 "No clauses are allowed for 'omp cancellation point' directive"); 6066 assert(AStmt == nullptr && "No associated statement allowed for 'omp " 6067 "cancellation point' directive"); 6068 Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion); 6069 break; 6070 case OMPD_cancel: 6071 assert(AStmt == nullptr && 6072 "No associated statement allowed for 'omp cancel' directive"); 6073 Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc, 6074 CancelRegion); 6075 AllowedNameModifiers.push_back(OMPD_cancel); 6076 break; 6077 case OMPD_target_data: 6078 Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc, 6079 EndLoc); 6080 AllowedNameModifiers.push_back(OMPD_target_data); 6081 break; 6082 case OMPD_target_enter_data: 6083 Res = ActOnOpenMPTargetEnterDataDirective(ClausesWithImplicit, StartLoc, 6084 EndLoc, AStmt); 6085 AllowedNameModifiers.push_back(OMPD_target_enter_data); 6086 break; 6087 case OMPD_target_exit_data: 6088 Res = ActOnOpenMPTargetExitDataDirective(ClausesWithImplicit, StartLoc, 6089 EndLoc, AStmt); 6090 AllowedNameModifiers.push_back(OMPD_target_exit_data); 6091 break; 6092 case OMPD_taskloop: 6093 Res = ActOnOpenMPTaskLoopDirective(ClausesWithImplicit, AStmt, StartLoc, 6094 EndLoc, VarsWithInheritedDSA); 6095 AllowedNameModifiers.push_back(OMPD_taskloop); 6096 break; 6097 case OMPD_taskloop_simd: 6098 Res = ActOnOpenMPTaskLoopSimdDirective(ClausesWithImplicit, AStmt, StartLoc, 6099 EndLoc, VarsWithInheritedDSA); 6100 AllowedNameModifiers.push_back(OMPD_taskloop); 6101 if (LangOpts.OpenMP >= 50) 6102 AllowedNameModifiers.push_back(OMPD_simd); 6103 break; 6104 case OMPD_master_taskloop: 6105 Res = ActOnOpenMPMasterTaskLoopDirective( 6106 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 6107 AllowedNameModifiers.push_back(OMPD_taskloop); 6108 break; 6109 case OMPD_master_taskloop_simd: 6110 Res = ActOnOpenMPMasterTaskLoopSimdDirective( 6111 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 6112 AllowedNameModifiers.push_back(OMPD_taskloop); 6113 if (LangOpts.OpenMP >= 50) 6114 AllowedNameModifiers.push_back(OMPD_simd); 6115 break; 6116 case OMPD_parallel_master_taskloop: 6117 Res = ActOnOpenMPParallelMasterTaskLoopDirective( 6118 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 6119 AllowedNameModifiers.push_back(OMPD_taskloop); 6120 AllowedNameModifiers.push_back(OMPD_parallel); 6121 break; 6122 case OMPD_parallel_master_taskloop_simd: 6123 Res = ActOnOpenMPParallelMasterTaskLoopSimdDirective( 6124 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 6125 AllowedNameModifiers.push_back(OMPD_taskloop); 6126 AllowedNameModifiers.push_back(OMPD_parallel); 6127 if (LangOpts.OpenMP >= 50) 6128 AllowedNameModifiers.push_back(OMPD_simd); 6129 break; 6130 case OMPD_distribute: 6131 Res = ActOnOpenMPDistributeDirective(ClausesWithImplicit, AStmt, StartLoc, 6132 EndLoc, VarsWithInheritedDSA); 6133 break; 6134 case OMPD_target_update: 6135 Res = ActOnOpenMPTargetUpdateDirective(ClausesWithImplicit, StartLoc, 6136 EndLoc, AStmt); 6137 AllowedNameModifiers.push_back(OMPD_target_update); 6138 break; 6139 case OMPD_distribute_parallel_for: 6140 Res = ActOnOpenMPDistributeParallelForDirective( 6141 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 6142 AllowedNameModifiers.push_back(OMPD_parallel); 6143 break; 6144 case OMPD_distribute_parallel_for_simd: 6145 Res = ActOnOpenMPDistributeParallelForSimdDirective( 6146 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 6147 AllowedNameModifiers.push_back(OMPD_parallel); 6148 if (LangOpts.OpenMP >= 50) 6149 AllowedNameModifiers.push_back(OMPD_simd); 6150 break; 6151 case OMPD_distribute_simd: 6152 Res = ActOnOpenMPDistributeSimdDirective( 6153 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 6154 if (LangOpts.OpenMP >= 50) 6155 AllowedNameModifiers.push_back(OMPD_simd); 6156 break; 6157 case OMPD_target_parallel_for_simd: 6158 Res = ActOnOpenMPTargetParallelForSimdDirective( 6159 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 6160 AllowedNameModifiers.push_back(OMPD_target); 6161 AllowedNameModifiers.push_back(OMPD_parallel); 6162 if (LangOpts.OpenMP >= 50) 6163 AllowedNameModifiers.push_back(OMPD_simd); 6164 break; 6165 case OMPD_target_simd: 6166 Res = ActOnOpenMPTargetSimdDirective(ClausesWithImplicit, AStmt, StartLoc, 6167 EndLoc, VarsWithInheritedDSA); 6168 AllowedNameModifiers.push_back(OMPD_target); 6169 if (LangOpts.OpenMP >= 50) 6170 AllowedNameModifiers.push_back(OMPD_simd); 6171 break; 6172 case OMPD_teams_distribute: 6173 Res = ActOnOpenMPTeamsDistributeDirective( 6174 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 6175 break; 6176 case OMPD_teams_distribute_simd: 6177 Res = ActOnOpenMPTeamsDistributeSimdDirective( 6178 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 6179 if (LangOpts.OpenMP >= 50) 6180 AllowedNameModifiers.push_back(OMPD_simd); 6181 break; 6182 case OMPD_teams_distribute_parallel_for_simd: 6183 Res = ActOnOpenMPTeamsDistributeParallelForSimdDirective( 6184 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 6185 AllowedNameModifiers.push_back(OMPD_parallel); 6186 if (LangOpts.OpenMP >= 50) 6187 AllowedNameModifiers.push_back(OMPD_simd); 6188 break; 6189 case OMPD_teams_distribute_parallel_for: 6190 Res = ActOnOpenMPTeamsDistributeParallelForDirective( 6191 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 6192 AllowedNameModifiers.push_back(OMPD_parallel); 6193 break; 6194 case OMPD_target_teams: 6195 Res = ActOnOpenMPTargetTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, 6196 EndLoc); 6197 AllowedNameModifiers.push_back(OMPD_target); 6198 break; 6199 case OMPD_target_teams_distribute: 6200 Res = ActOnOpenMPTargetTeamsDistributeDirective( 6201 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 6202 AllowedNameModifiers.push_back(OMPD_target); 6203 break; 6204 case OMPD_target_teams_distribute_parallel_for: 6205 Res = ActOnOpenMPTargetTeamsDistributeParallelForDirective( 6206 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 6207 AllowedNameModifiers.push_back(OMPD_target); 6208 AllowedNameModifiers.push_back(OMPD_parallel); 6209 break; 6210 case OMPD_target_teams_distribute_parallel_for_simd: 6211 Res = ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective( 6212 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 6213 AllowedNameModifiers.push_back(OMPD_target); 6214 AllowedNameModifiers.push_back(OMPD_parallel); 6215 if (LangOpts.OpenMP >= 50) 6216 AllowedNameModifiers.push_back(OMPD_simd); 6217 break; 6218 case OMPD_target_teams_distribute_simd: 6219 Res = ActOnOpenMPTargetTeamsDistributeSimdDirective( 6220 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 6221 AllowedNameModifiers.push_back(OMPD_target); 6222 if (LangOpts.OpenMP >= 50) 6223 AllowedNameModifiers.push_back(OMPD_simd); 6224 break; 6225 case OMPD_interop: 6226 assert(AStmt == nullptr && 6227 "No associated statement allowed for 'omp interop' directive"); 6228 Res = ActOnOpenMPInteropDirective(ClausesWithImplicit, StartLoc, EndLoc); 6229 break; 6230 case OMPD_dispatch: 6231 Res = ActOnOpenMPDispatchDirective(ClausesWithImplicit, AStmt, StartLoc, 6232 EndLoc); 6233 break; 6234 case OMPD_declare_target: 6235 case OMPD_end_declare_target: 6236 case OMPD_threadprivate: 6237 case OMPD_allocate: 6238 case OMPD_declare_reduction: 6239 case OMPD_declare_mapper: 6240 case OMPD_declare_simd: 6241 case OMPD_requires: 6242 case OMPD_declare_variant: 6243 case OMPD_begin_declare_variant: 6244 case OMPD_end_declare_variant: 6245 llvm_unreachable("OpenMP Directive is not allowed"); 6246 case OMPD_unknown: 6247 default: 6248 llvm_unreachable("Unknown OpenMP directive"); 6249 } 6250 6251 ErrorFound = Res.isInvalid() || ErrorFound; 6252 6253 // Check variables in the clauses if default(none) or 6254 // default(firstprivate) was specified. 6255 if (DSAStack->getDefaultDSA() == DSA_none || 6256 DSAStack->getDefaultDSA() == DSA_firstprivate) { 6257 DSAAttrChecker DSAChecker(DSAStack, *this, nullptr); 6258 for (OMPClause *C : Clauses) { 6259 switch (C->getClauseKind()) { 6260 case OMPC_num_threads: 6261 case OMPC_dist_schedule: 6262 // Do not analyse if no parent teams directive. 6263 if (isOpenMPTeamsDirective(Kind)) 6264 break; 6265 continue; 6266 case OMPC_if: 6267 if (isOpenMPTeamsDirective(Kind) && 6268 cast<OMPIfClause>(C)->getNameModifier() != OMPD_target) 6269 break; 6270 if (isOpenMPParallelDirective(Kind) && 6271 isOpenMPTaskLoopDirective(Kind) && 6272 cast<OMPIfClause>(C)->getNameModifier() != OMPD_parallel) 6273 break; 6274 continue; 6275 case OMPC_schedule: 6276 case OMPC_detach: 6277 break; 6278 case OMPC_grainsize: 6279 case OMPC_num_tasks: 6280 case OMPC_final: 6281 case OMPC_priority: 6282 case OMPC_novariants: 6283 case OMPC_nocontext: 6284 // Do not analyze if no parent parallel directive. 6285 if (isOpenMPParallelDirective(Kind)) 6286 break; 6287 continue; 6288 case OMPC_ordered: 6289 case OMPC_device: 6290 case OMPC_num_teams: 6291 case OMPC_thread_limit: 6292 case OMPC_hint: 6293 case OMPC_collapse: 6294 case OMPC_safelen: 6295 case OMPC_simdlen: 6296 case OMPC_sizes: 6297 case OMPC_default: 6298 case OMPC_proc_bind: 6299 case OMPC_private: 6300 case OMPC_firstprivate: 6301 case OMPC_lastprivate: 6302 case OMPC_shared: 6303 case OMPC_reduction: 6304 case OMPC_task_reduction: 6305 case OMPC_in_reduction: 6306 case OMPC_linear: 6307 case OMPC_aligned: 6308 case OMPC_copyin: 6309 case OMPC_copyprivate: 6310 case OMPC_nowait: 6311 case OMPC_untied: 6312 case OMPC_mergeable: 6313 case OMPC_allocate: 6314 case OMPC_read: 6315 case OMPC_write: 6316 case OMPC_update: 6317 case OMPC_capture: 6318 case OMPC_seq_cst: 6319 case OMPC_acq_rel: 6320 case OMPC_acquire: 6321 case OMPC_release: 6322 case OMPC_relaxed: 6323 case OMPC_depend: 6324 case OMPC_threads: 6325 case OMPC_simd: 6326 case OMPC_map: 6327 case OMPC_nogroup: 6328 case OMPC_defaultmap: 6329 case OMPC_to: 6330 case OMPC_from: 6331 case OMPC_use_device_ptr: 6332 case OMPC_use_device_addr: 6333 case OMPC_is_device_ptr: 6334 case OMPC_nontemporal: 6335 case OMPC_order: 6336 case OMPC_destroy: 6337 case OMPC_inclusive: 6338 case OMPC_exclusive: 6339 case OMPC_uses_allocators: 6340 case OMPC_affinity: 6341 continue; 6342 case OMPC_allocator: 6343 case OMPC_flush: 6344 case OMPC_depobj: 6345 case OMPC_threadprivate: 6346 case OMPC_uniform: 6347 case OMPC_unknown: 6348 case OMPC_unified_address: 6349 case OMPC_unified_shared_memory: 6350 case OMPC_reverse_offload: 6351 case OMPC_dynamic_allocators: 6352 case OMPC_atomic_default_mem_order: 6353 case OMPC_device_type: 6354 case OMPC_match: 6355 case OMPC_when: 6356 default: 6357 llvm_unreachable("Unexpected clause"); 6358 } 6359 for (Stmt *CC : C->children()) { 6360 if (CC) 6361 DSAChecker.Visit(CC); 6362 } 6363 } 6364 for (const auto &P : DSAChecker.getVarsWithInheritedDSA()) 6365 VarsWithInheritedDSA[P.getFirst()] = P.getSecond(); 6366 } 6367 for (const auto &P : VarsWithInheritedDSA) { 6368 if (P.getFirst()->isImplicit() || isa<OMPCapturedExprDecl>(P.getFirst())) 6369 continue; 6370 ErrorFound = true; 6371 if (DSAStack->getDefaultDSA() == DSA_none || 6372 DSAStack->getDefaultDSA() == DSA_firstprivate) { 6373 Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable) 6374 << P.first << P.second->getSourceRange(); 6375 Diag(DSAStack->getDefaultDSALocation(), diag::note_omp_default_dsa_none); 6376 } else if (getLangOpts().OpenMP >= 50) { 6377 Diag(P.second->getExprLoc(), 6378 diag::err_omp_defaultmap_no_attr_for_variable) 6379 << P.first << P.second->getSourceRange(); 6380 Diag(DSAStack->getDefaultDSALocation(), 6381 diag::note_omp_defaultmap_attr_none); 6382 } 6383 } 6384 6385 if (!AllowedNameModifiers.empty()) 6386 ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) || 6387 ErrorFound; 6388 6389 if (ErrorFound) 6390 return StmtError(); 6391 6392 if (!CurContext->isDependentContext() && 6393 isOpenMPTargetExecutionDirective(Kind) && 6394 !(DSAStack->hasRequiresDeclWithClause<OMPUnifiedSharedMemoryClause>() || 6395 DSAStack->hasRequiresDeclWithClause<OMPUnifiedAddressClause>() || 6396 DSAStack->hasRequiresDeclWithClause<OMPReverseOffloadClause>() || 6397 DSAStack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>())) { 6398 // Register target to DSA Stack. 6399 DSAStack->addTargetDirLocation(StartLoc); 6400 } 6401 6402 return Res; 6403 } 6404 6405 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareSimdDirective( 6406 DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen, 6407 ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds, 6408 ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears, 6409 ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR) { 6410 assert(Aligneds.size() == Alignments.size()); 6411 assert(Linears.size() == LinModifiers.size()); 6412 assert(Linears.size() == Steps.size()); 6413 if (!DG || DG.get().isNull()) 6414 return DeclGroupPtrTy(); 6415 6416 const int SimdId = 0; 6417 if (!DG.get().isSingleDecl()) { 6418 Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd_variant) 6419 << SimdId; 6420 return DG; 6421 } 6422 Decl *ADecl = DG.get().getSingleDecl(); 6423 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl)) 6424 ADecl = FTD->getTemplatedDecl(); 6425 6426 auto *FD = dyn_cast<FunctionDecl>(ADecl); 6427 if (!FD) { 6428 Diag(ADecl->getLocation(), diag::err_omp_function_expected) << SimdId; 6429 return DeclGroupPtrTy(); 6430 } 6431 6432 // OpenMP [2.8.2, declare simd construct, Description] 6433 // The parameter of the simdlen clause must be a constant positive integer 6434 // expression. 6435 ExprResult SL; 6436 if (Simdlen) 6437 SL = VerifyPositiveIntegerConstantInClause(Simdlen, OMPC_simdlen); 6438 // OpenMP [2.8.2, declare simd construct, Description] 6439 // The special this pointer can be used as if was one of the arguments to the 6440 // function in any of the linear, aligned, or uniform clauses. 6441 // The uniform clause declares one or more arguments to have an invariant 6442 // value for all concurrent invocations of the function in the execution of a 6443 // single SIMD loop. 6444 llvm::DenseMap<const Decl *, const Expr *> UniformedArgs; 6445 const Expr *UniformedLinearThis = nullptr; 6446 for (const Expr *E : Uniforms) { 6447 E = E->IgnoreParenImpCasts(); 6448 if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) 6449 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) 6450 if (FD->getNumParams() > PVD->getFunctionScopeIndex() && 6451 FD->getParamDecl(PVD->getFunctionScopeIndex()) 6452 ->getCanonicalDecl() == PVD->getCanonicalDecl()) { 6453 UniformedArgs.try_emplace(PVD->getCanonicalDecl(), E); 6454 continue; 6455 } 6456 if (isa<CXXThisExpr>(E)) { 6457 UniformedLinearThis = E; 6458 continue; 6459 } 6460 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause) 6461 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0); 6462 } 6463 // OpenMP [2.8.2, declare simd construct, Description] 6464 // The aligned clause declares that the object to which each list item points 6465 // is aligned to the number of bytes expressed in the optional parameter of 6466 // the aligned clause. 6467 // The special this pointer can be used as if was one of the arguments to the 6468 // function in any of the linear, aligned, or uniform clauses. 6469 // The type of list items appearing in the aligned clause must be array, 6470 // pointer, reference to array, or reference to pointer. 6471 llvm::DenseMap<const Decl *, const Expr *> AlignedArgs; 6472 const Expr *AlignedThis = nullptr; 6473 for (const Expr *E : Aligneds) { 6474 E = E->IgnoreParenImpCasts(); 6475 if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) 6476 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) { 6477 const VarDecl *CanonPVD = PVD->getCanonicalDecl(); 6478 if (FD->getNumParams() > PVD->getFunctionScopeIndex() && 6479 FD->getParamDecl(PVD->getFunctionScopeIndex()) 6480 ->getCanonicalDecl() == CanonPVD) { 6481 // OpenMP [2.8.1, simd construct, Restrictions] 6482 // A list-item cannot appear in more than one aligned clause. 6483 if (AlignedArgs.count(CanonPVD) > 0) { 6484 Diag(E->getExprLoc(), diag::err_omp_used_in_clause_twice) 6485 << 1 << getOpenMPClauseName(OMPC_aligned) 6486 << E->getSourceRange(); 6487 Diag(AlignedArgs[CanonPVD]->getExprLoc(), 6488 diag::note_omp_explicit_dsa) 6489 << getOpenMPClauseName(OMPC_aligned); 6490 continue; 6491 } 6492 AlignedArgs[CanonPVD] = E; 6493 QualType QTy = PVD->getType() 6494 .getNonReferenceType() 6495 .getUnqualifiedType() 6496 .getCanonicalType(); 6497 const Type *Ty = QTy.getTypePtrOrNull(); 6498 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) { 6499 Diag(E->getExprLoc(), diag::err_omp_aligned_expected_array_or_ptr) 6500 << QTy << getLangOpts().CPlusPlus << E->getSourceRange(); 6501 Diag(PVD->getLocation(), diag::note_previous_decl) << PVD; 6502 } 6503 continue; 6504 } 6505 } 6506 if (isa<CXXThisExpr>(E)) { 6507 if (AlignedThis) { 6508 Diag(E->getExprLoc(), diag::err_omp_used_in_clause_twice) 6509 << 2 << getOpenMPClauseName(OMPC_aligned) << E->getSourceRange(); 6510 Diag(AlignedThis->getExprLoc(), diag::note_omp_explicit_dsa) 6511 << getOpenMPClauseName(OMPC_aligned); 6512 } 6513 AlignedThis = E; 6514 continue; 6515 } 6516 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause) 6517 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0); 6518 } 6519 // The optional parameter of the aligned clause, alignment, must be a constant 6520 // positive integer expression. If no optional parameter is specified, 6521 // implementation-defined default alignments for SIMD instructions on the 6522 // target platforms are assumed. 6523 SmallVector<const Expr *, 4> NewAligns; 6524 for (Expr *E : Alignments) { 6525 ExprResult Align; 6526 if (E) 6527 Align = VerifyPositiveIntegerConstantInClause(E, OMPC_aligned); 6528 NewAligns.push_back(Align.get()); 6529 } 6530 // OpenMP [2.8.2, declare simd construct, Description] 6531 // The linear clause declares one or more list items to be private to a SIMD 6532 // lane and to have a linear relationship with respect to the iteration space 6533 // of a loop. 6534 // The special this pointer can be used as if was one of the arguments to the 6535 // function in any of the linear, aligned, or uniform clauses. 6536 // When a linear-step expression is specified in a linear clause it must be 6537 // either a constant integer expression or an integer-typed parameter that is 6538 // specified in a uniform clause on the directive. 6539 llvm::DenseMap<const Decl *, const Expr *> LinearArgs; 6540 const bool IsUniformedThis = UniformedLinearThis != nullptr; 6541 auto MI = LinModifiers.begin(); 6542 for (const Expr *E : Linears) { 6543 auto LinKind = static_cast<OpenMPLinearClauseKind>(*MI); 6544 ++MI; 6545 E = E->IgnoreParenImpCasts(); 6546 if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) 6547 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) { 6548 const VarDecl *CanonPVD = PVD->getCanonicalDecl(); 6549 if (FD->getNumParams() > PVD->getFunctionScopeIndex() && 6550 FD->getParamDecl(PVD->getFunctionScopeIndex()) 6551 ->getCanonicalDecl() == CanonPVD) { 6552 // OpenMP [2.15.3.7, linear Clause, Restrictions] 6553 // A list-item cannot appear in more than one linear clause. 6554 if (LinearArgs.count(CanonPVD) > 0) { 6555 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa) 6556 << getOpenMPClauseName(OMPC_linear) 6557 << getOpenMPClauseName(OMPC_linear) << E->getSourceRange(); 6558 Diag(LinearArgs[CanonPVD]->getExprLoc(), 6559 diag::note_omp_explicit_dsa) 6560 << getOpenMPClauseName(OMPC_linear); 6561 continue; 6562 } 6563 // Each argument can appear in at most one uniform or linear clause. 6564 if (UniformedArgs.count(CanonPVD) > 0) { 6565 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa) 6566 << getOpenMPClauseName(OMPC_linear) 6567 << getOpenMPClauseName(OMPC_uniform) << E->getSourceRange(); 6568 Diag(UniformedArgs[CanonPVD]->getExprLoc(), 6569 diag::note_omp_explicit_dsa) 6570 << getOpenMPClauseName(OMPC_uniform); 6571 continue; 6572 } 6573 LinearArgs[CanonPVD] = E; 6574 if (E->isValueDependent() || E->isTypeDependent() || 6575 E->isInstantiationDependent() || 6576 E->containsUnexpandedParameterPack()) 6577 continue; 6578 (void)CheckOpenMPLinearDecl(CanonPVD, E->getExprLoc(), LinKind, 6579 PVD->getOriginalType(), 6580 /*IsDeclareSimd=*/true); 6581 continue; 6582 } 6583 } 6584 if (isa<CXXThisExpr>(E)) { 6585 if (UniformedLinearThis) { 6586 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa) 6587 << getOpenMPClauseName(OMPC_linear) 6588 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform : OMPC_linear) 6589 << E->getSourceRange(); 6590 Diag(UniformedLinearThis->getExprLoc(), diag::note_omp_explicit_dsa) 6591 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform 6592 : OMPC_linear); 6593 continue; 6594 } 6595 UniformedLinearThis = E; 6596 if (E->isValueDependent() || E->isTypeDependent() || 6597 E->isInstantiationDependent() || E->containsUnexpandedParameterPack()) 6598 continue; 6599 (void)CheckOpenMPLinearDecl(/*D=*/nullptr, E->getExprLoc(), LinKind, 6600 E->getType(), /*IsDeclareSimd=*/true); 6601 continue; 6602 } 6603 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause) 6604 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0); 6605 } 6606 Expr *Step = nullptr; 6607 Expr *NewStep = nullptr; 6608 SmallVector<Expr *, 4> NewSteps; 6609 for (Expr *E : Steps) { 6610 // Skip the same step expression, it was checked already. 6611 if (Step == E || !E) { 6612 NewSteps.push_back(E ? NewStep : nullptr); 6613 continue; 6614 } 6615 Step = E; 6616 if (const auto *DRE = dyn_cast<DeclRefExpr>(Step)) 6617 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) { 6618 const VarDecl *CanonPVD = PVD->getCanonicalDecl(); 6619 if (UniformedArgs.count(CanonPVD) == 0) { 6620 Diag(Step->getExprLoc(), diag::err_omp_expected_uniform_param) 6621 << Step->getSourceRange(); 6622 } else if (E->isValueDependent() || E->isTypeDependent() || 6623 E->isInstantiationDependent() || 6624 E->containsUnexpandedParameterPack() || 6625 CanonPVD->getType()->hasIntegerRepresentation()) { 6626 NewSteps.push_back(Step); 6627 } else { 6628 Diag(Step->getExprLoc(), diag::err_omp_expected_int_param) 6629 << Step->getSourceRange(); 6630 } 6631 continue; 6632 } 6633 NewStep = Step; 6634 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() && 6635 !Step->isInstantiationDependent() && 6636 !Step->containsUnexpandedParameterPack()) { 6637 NewStep = PerformOpenMPImplicitIntegerConversion(Step->getExprLoc(), Step) 6638 .get(); 6639 if (NewStep) 6640 NewStep = 6641 VerifyIntegerConstantExpression(NewStep, /*FIXME*/ AllowFold).get(); 6642 } 6643 NewSteps.push_back(NewStep); 6644 } 6645 auto *NewAttr = OMPDeclareSimdDeclAttr::CreateImplicit( 6646 Context, BS, SL.get(), const_cast<Expr **>(Uniforms.data()), 6647 Uniforms.size(), const_cast<Expr **>(Aligneds.data()), Aligneds.size(), 6648 const_cast<Expr **>(NewAligns.data()), NewAligns.size(), 6649 const_cast<Expr **>(Linears.data()), Linears.size(), 6650 const_cast<unsigned *>(LinModifiers.data()), LinModifiers.size(), 6651 NewSteps.data(), NewSteps.size(), SR); 6652 ADecl->addAttr(NewAttr); 6653 return DG; 6654 } 6655 6656 static void setPrototype(Sema &S, FunctionDecl *FD, FunctionDecl *FDWithProto, 6657 QualType NewType) { 6658 assert(NewType->isFunctionProtoType() && 6659 "Expected function type with prototype."); 6660 assert(FD->getType()->isFunctionNoProtoType() && 6661 "Expected function with type with no prototype."); 6662 assert(FDWithProto->getType()->isFunctionProtoType() && 6663 "Expected function with prototype."); 6664 // Synthesize parameters with the same types. 6665 FD->setType(NewType); 6666 SmallVector<ParmVarDecl *, 16> Params; 6667 for (const ParmVarDecl *P : FDWithProto->parameters()) { 6668 auto *Param = ParmVarDecl::Create(S.getASTContext(), FD, SourceLocation(), 6669 SourceLocation(), nullptr, P->getType(), 6670 /*TInfo=*/nullptr, SC_None, nullptr); 6671 Param->setScopeInfo(0, Params.size()); 6672 Param->setImplicit(); 6673 Params.push_back(Param); 6674 } 6675 6676 FD->setParams(Params); 6677 } 6678 6679 void Sema::ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(Decl *D) { 6680 if (D->isInvalidDecl()) 6681 return; 6682 FunctionDecl *FD = nullptr; 6683 if (auto *UTemplDecl = dyn_cast<FunctionTemplateDecl>(D)) 6684 FD = UTemplDecl->getTemplatedDecl(); 6685 else 6686 FD = cast<FunctionDecl>(D); 6687 assert(FD && "Expected a function declaration!"); 6688 6689 // If we are instantiating templates we do *not* apply scoped assumptions but 6690 // only global ones. We apply scoped assumption to the template definition 6691 // though. 6692 if (!inTemplateInstantiation()) { 6693 for (AssumptionAttr *AA : OMPAssumeScoped) 6694 FD->addAttr(AA); 6695 } 6696 for (AssumptionAttr *AA : OMPAssumeGlobal) 6697 FD->addAttr(AA); 6698 } 6699 6700 Sema::OMPDeclareVariantScope::OMPDeclareVariantScope(OMPTraitInfo &TI) 6701 : TI(&TI), NameSuffix(TI.getMangledName()) {} 6702 6703 void Sema::ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope( 6704 Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParamLists, 6705 SmallVectorImpl<FunctionDecl *> &Bases) { 6706 if (!D.getIdentifier()) 6707 return; 6708 6709 OMPDeclareVariantScope &DVScope = OMPDeclareVariantScopes.back(); 6710 6711 // Template specialization is an extension, check if we do it. 6712 bool IsTemplated = !TemplateParamLists.empty(); 6713 if (IsTemplated & 6714 !DVScope.TI->isExtensionActive( 6715 llvm::omp::TraitProperty::implementation_extension_allow_templates)) 6716 return; 6717 6718 IdentifierInfo *BaseII = D.getIdentifier(); 6719 LookupResult Lookup(*this, DeclarationName(BaseII), D.getIdentifierLoc(), 6720 LookupOrdinaryName); 6721 LookupParsedName(Lookup, S, &D.getCXXScopeSpec()); 6722 6723 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 6724 QualType FType = TInfo->getType(); 6725 6726 bool IsConstexpr = 6727 D.getDeclSpec().getConstexprSpecifier() == ConstexprSpecKind::Constexpr; 6728 bool IsConsteval = 6729 D.getDeclSpec().getConstexprSpecifier() == ConstexprSpecKind::Consteval; 6730 6731 for (auto *Candidate : Lookup) { 6732 auto *CandidateDecl = Candidate->getUnderlyingDecl(); 6733 FunctionDecl *UDecl = nullptr; 6734 if (IsTemplated && isa<FunctionTemplateDecl>(CandidateDecl)) 6735 UDecl = cast<FunctionTemplateDecl>(CandidateDecl)->getTemplatedDecl(); 6736 else if (!IsTemplated) 6737 UDecl = dyn_cast<FunctionDecl>(CandidateDecl); 6738 if (!UDecl) 6739 continue; 6740 6741 // Don't specialize constexpr/consteval functions with 6742 // non-constexpr/consteval functions. 6743 if (UDecl->isConstexpr() && !IsConstexpr) 6744 continue; 6745 if (UDecl->isConsteval() && !IsConsteval) 6746 continue; 6747 6748 QualType UDeclTy = UDecl->getType(); 6749 if (!UDeclTy->isDependentType()) { 6750 QualType NewType = Context.mergeFunctionTypes( 6751 FType, UDeclTy, /* OfBlockPointer */ false, 6752 /* Unqualified */ false, /* AllowCXX */ true); 6753 if (NewType.isNull()) 6754 continue; 6755 } 6756 6757 // Found a base! 6758 Bases.push_back(UDecl); 6759 } 6760 6761 bool UseImplicitBase = !DVScope.TI->isExtensionActive( 6762 llvm::omp::TraitProperty::implementation_extension_disable_implicit_base); 6763 // If no base was found we create a declaration that we use as base. 6764 if (Bases.empty() && UseImplicitBase) { 6765 D.setFunctionDefinitionKind(FunctionDefinitionKind::Declaration); 6766 Decl *BaseD = HandleDeclarator(S, D, TemplateParamLists); 6767 BaseD->setImplicit(true); 6768 if (auto *BaseTemplD = dyn_cast<FunctionTemplateDecl>(BaseD)) 6769 Bases.push_back(BaseTemplD->getTemplatedDecl()); 6770 else 6771 Bases.push_back(cast<FunctionDecl>(BaseD)); 6772 } 6773 6774 std::string MangledName; 6775 MangledName += D.getIdentifier()->getName(); 6776 MangledName += getOpenMPVariantManglingSeparatorStr(); 6777 MangledName += DVScope.NameSuffix; 6778 IdentifierInfo &VariantII = Context.Idents.get(MangledName); 6779 6780 VariantII.setMangledOpenMPVariantName(true); 6781 D.SetIdentifier(&VariantII, D.getBeginLoc()); 6782 } 6783 6784 void Sema::ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope( 6785 Decl *D, SmallVectorImpl<FunctionDecl *> &Bases) { 6786 // Do not mark function as is used to prevent its emission if this is the 6787 // only place where it is used. 6788 EnterExpressionEvaluationContext Unevaluated( 6789 *this, Sema::ExpressionEvaluationContext::Unevaluated); 6790 6791 FunctionDecl *FD = nullptr; 6792 if (auto *UTemplDecl = dyn_cast<FunctionTemplateDecl>(D)) 6793 FD = UTemplDecl->getTemplatedDecl(); 6794 else 6795 FD = cast<FunctionDecl>(D); 6796 auto *VariantFuncRef = DeclRefExpr::Create( 6797 Context, NestedNameSpecifierLoc(), SourceLocation(), FD, 6798 /* RefersToEnclosingVariableOrCapture */ false, 6799 /* NameLoc */ FD->getLocation(), FD->getType(), 6800 ExprValueKind::VK_PRValue); 6801 6802 OMPDeclareVariantScope &DVScope = OMPDeclareVariantScopes.back(); 6803 auto *OMPDeclareVariantA = OMPDeclareVariantAttr::CreateImplicit( 6804 Context, VariantFuncRef, DVScope.TI, 6805 /*NothingArgs=*/nullptr, /*NothingArgsSize=*/0, 6806 /*NeedDevicePtrArgs=*/nullptr, /*NeedDevicePtrArgsSize=*/0, 6807 /*AppendArgs=*/nullptr, /*AppendArgsSize=*/0); 6808 for (FunctionDecl *BaseFD : Bases) 6809 BaseFD->addAttr(OMPDeclareVariantA); 6810 } 6811 6812 ExprResult Sema::ActOnOpenMPCall(ExprResult Call, Scope *Scope, 6813 SourceLocation LParenLoc, 6814 MultiExprArg ArgExprs, 6815 SourceLocation RParenLoc, Expr *ExecConfig) { 6816 // The common case is a regular call we do not want to specialize at all. Try 6817 // to make that case fast by bailing early. 6818 CallExpr *CE = dyn_cast<CallExpr>(Call.get()); 6819 if (!CE) 6820 return Call; 6821 6822 FunctionDecl *CalleeFnDecl = CE->getDirectCallee(); 6823 if (!CalleeFnDecl) 6824 return Call; 6825 6826 if (!CalleeFnDecl->hasAttr<OMPDeclareVariantAttr>()) 6827 return Call; 6828 6829 ASTContext &Context = getASTContext(); 6830 std::function<void(StringRef)> DiagUnknownTrait = [this, 6831 CE](StringRef ISATrait) { 6832 // TODO Track the selector locations in a way that is accessible here to 6833 // improve the diagnostic location. 6834 Diag(CE->getBeginLoc(), diag::warn_unknown_declare_variant_isa_trait) 6835 << ISATrait; 6836 }; 6837 TargetOMPContext OMPCtx(Context, std::move(DiagUnknownTrait), 6838 getCurFunctionDecl(), DSAStack->getConstructTraits()); 6839 6840 QualType CalleeFnType = CalleeFnDecl->getType(); 6841 6842 SmallVector<Expr *, 4> Exprs; 6843 SmallVector<VariantMatchInfo, 4> VMIs; 6844 while (CalleeFnDecl) { 6845 for (OMPDeclareVariantAttr *A : 6846 CalleeFnDecl->specific_attrs<OMPDeclareVariantAttr>()) { 6847 Expr *VariantRef = A->getVariantFuncRef(); 6848 6849 VariantMatchInfo VMI; 6850 OMPTraitInfo &TI = A->getTraitInfo(); 6851 TI.getAsVariantMatchInfo(Context, VMI); 6852 if (!isVariantApplicableInContext(VMI, OMPCtx, 6853 /* DeviceSetOnly */ false)) 6854 continue; 6855 6856 VMIs.push_back(VMI); 6857 Exprs.push_back(VariantRef); 6858 } 6859 6860 CalleeFnDecl = CalleeFnDecl->getPreviousDecl(); 6861 } 6862 6863 ExprResult NewCall; 6864 do { 6865 int BestIdx = getBestVariantMatchForContext(VMIs, OMPCtx); 6866 if (BestIdx < 0) 6867 return Call; 6868 Expr *BestExpr = cast<DeclRefExpr>(Exprs[BestIdx]); 6869 Decl *BestDecl = cast<DeclRefExpr>(BestExpr)->getDecl(); 6870 6871 { 6872 // Try to build a (member) call expression for the current best applicable 6873 // variant expression. We allow this to fail in which case we continue 6874 // with the next best variant expression. The fail case is part of the 6875 // implementation defined behavior in the OpenMP standard when it talks 6876 // about what differences in the function prototypes: "Any differences 6877 // that the specific OpenMP context requires in the prototype of the 6878 // variant from the base function prototype are implementation defined." 6879 // This wording is there to allow the specialized variant to have a 6880 // different type than the base function. This is intended and OK but if 6881 // we cannot create a call the difference is not in the "implementation 6882 // defined range" we allow. 6883 Sema::TentativeAnalysisScope Trap(*this); 6884 6885 if (auto *SpecializedMethod = dyn_cast<CXXMethodDecl>(BestDecl)) { 6886 auto *MemberCall = dyn_cast<CXXMemberCallExpr>(CE); 6887 BestExpr = MemberExpr::CreateImplicit( 6888 Context, MemberCall->getImplicitObjectArgument(), 6889 /* IsArrow */ false, SpecializedMethod, Context.BoundMemberTy, 6890 MemberCall->getValueKind(), MemberCall->getObjectKind()); 6891 } 6892 NewCall = BuildCallExpr(Scope, BestExpr, LParenLoc, ArgExprs, RParenLoc, 6893 ExecConfig); 6894 if (NewCall.isUsable()) { 6895 if (CallExpr *NCE = dyn_cast<CallExpr>(NewCall.get())) { 6896 FunctionDecl *NewCalleeFnDecl = NCE->getDirectCallee(); 6897 QualType NewType = Context.mergeFunctionTypes( 6898 CalleeFnType, NewCalleeFnDecl->getType(), 6899 /* OfBlockPointer */ false, 6900 /* Unqualified */ false, /* AllowCXX */ true); 6901 if (!NewType.isNull()) 6902 break; 6903 // Don't use the call if the function type was not compatible. 6904 NewCall = nullptr; 6905 } 6906 } 6907 } 6908 6909 VMIs.erase(VMIs.begin() + BestIdx); 6910 Exprs.erase(Exprs.begin() + BestIdx); 6911 } while (!VMIs.empty()); 6912 6913 if (!NewCall.isUsable()) 6914 return Call; 6915 return PseudoObjectExpr::Create(Context, CE, {NewCall.get()}, 0); 6916 } 6917 6918 Optional<std::pair<FunctionDecl *, Expr *>> 6919 Sema::checkOpenMPDeclareVariantFunction(Sema::DeclGroupPtrTy DG, 6920 Expr *VariantRef, OMPTraitInfo &TI, 6921 unsigned NumAppendArgs, 6922 SourceRange SR) { 6923 if (!DG || DG.get().isNull()) 6924 return None; 6925 6926 const int VariantId = 1; 6927 // Must be applied only to single decl. 6928 if (!DG.get().isSingleDecl()) { 6929 Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd_variant) 6930 << VariantId << SR; 6931 return None; 6932 } 6933 Decl *ADecl = DG.get().getSingleDecl(); 6934 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl)) 6935 ADecl = FTD->getTemplatedDecl(); 6936 6937 // Decl must be a function. 6938 auto *FD = dyn_cast<FunctionDecl>(ADecl); 6939 if (!FD) { 6940 Diag(ADecl->getLocation(), diag::err_omp_function_expected) 6941 << VariantId << SR; 6942 return None; 6943 } 6944 6945 auto &&HasMultiVersionAttributes = [](const FunctionDecl *FD) { 6946 return FD->hasAttrs() && 6947 (FD->hasAttr<CPUDispatchAttr>() || FD->hasAttr<CPUSpecificAttr>() || 6948 FD->hasAttr<TargetAttr>()); 6949 }; 6950 // OpenMP is not compatible with CPU-specific attributes. 6951 if (HasMultiVersionAttributes(FD)) { 6952 Diag(FD->getLocation(), diag::err_omp_declare_variant_incompat_attributes) 6953 << SR; 6954 return None; 6955 } 6956 6957 // Allow #pragma omp declare variant only if the function is not used. 6958 if (FD->isUsed(false)) 6959 Diag(SR.getBegin(), diag::warn_omp_declare_variant_after_used) 6960 << FD->getLocation(); 6961 6962 // Check if the function was emitted already. 6963 const FunctionDecl *Definition; 6964 if (!FD->isThisDeclarationADefinition() && FD->isDefined(Definition) && 6965 (LangOpts.EmitAllDecls || Context.DeclMustBeEmitted(Definition))) 6966 Diag(SR.getBegin(), diag::warn_omp_declare_variant_after_emitted) 6967 << FD->getLocation(); 6968 6969 // The VariantRef must point to function. 6970 if (!VariantRef) { 6971 Diag(SR.getBegin(), diag::err_omp_function_expected) << VariantId; 6972 return None; 6973 } 6974 6975 auto ShouldDelayChecks = [](Expr *&E, bool) { 6976 return E && (E->isTypeDependent() || E->isValueDependent() || 6977 E->containsUnexpandedParameterPack() || 6978 E->isInstantiationDependent()); 6979 }; 6980 // Do not check templates, wait until instantiation. 6981 if (FD->isDependentContext() || ShouldDelayChecks(VariantRef, false) || 6982 TI.anyScoreOrCondition(ShouldDelayChecks)) 6983 return std::make_pair(FD, VariantRef); 6984 6985 // Deal with non-constant score and user condition expressions. 6986 auto HandleNonConstantScoresAndConditions = [this](Expr *&E, 6987 bool IsScore) -> bool { 6988 if (!E || E->isIntegerConstantExpr(Context)) 6989 return false; 6990 6991 if (IsScore) { 6992 // We warn on non-constant scores and pretend they were not present. 6993 Diag(E->getExprLoc(), diag::warn_omp_declare_variant_score_not_constant) 6994 << E; 6995 E = nullptr; 6996 } else { 6997 // We could replace a non-constant user condition with "false" but we 6998 // will soon need to handle these anyway for the dynamic version of 6999 // OpenMP context selectors. 7000 Diag(E->getExprLoc(), 7001 diag::err_omp_declare_variant_user_condition_not_constant) 7002 << E; 7003 } 7004 return true; 7005 }; 7006 if (TI.anyScoreOrCondition(HandleNonConstantScoresAndConditions)) 7007 return None; 7008 7009 QualType AdjustedFnType = FD->getType(); 7010 if (NumAppendArgs) { 7011 if (isa<FunctionNoProtoType>(FD->getType())) { 7012 Diag(FD->getLocation(), diag::err_omp_declare_variant_prototype_required) 7013 << SR; 7014 return None; 7015 } 7016 // Adjust the function type to account for an extra omp_interop_t for each 7017 // specified in the append_args clause. 7018 const TypeDecl *TD = nullptr; 7019 LookupResult Result(*this, &Context.Idents.get("omp_interop_t"), 7020 SR.getBegin(), Sema::LookupOrdinaryName); 7021 if (LookupName(Result, getCurScope())) { 7022 NamedDecl *ND = Result.getFoundDecl(); 7023 TD = dyn_cast_or_null<TypeDecl>(ND); 7024 } 7025 if (!TD) { 7026 Diag(SR.getBegin(), diag::err_omp_interop_type_not_found) << SR; 7027 return None; 7028 } 7029 QualType InteropType = QualType(TD->getTypeForDecl(), 0); 7030 auto *PTy = cast<FunctionProtoType>(FD->getType()); 7031 if (PTy->isVariadic()) { 7032 Diag(FD->getLocation(), diag::err_omp_append_args_with_varargs) << SR; 7033 return None; 7034 } 7035 llvm::SmallVector<QualType, 8> Params; 7036 Params.append(PTy->param_type_begin(), PTy->param_type_end()); 7037 Params.insert(Params.end(), NumAppendArgs, InteropType); 7038 AdjustedFnType = Context.getFunctionType(PTy->getReturnType(), Params, 7039 PTy->getExtProtoInfo()); 7040 } 7041 7042 // Convert VariantRef expression to the type of the original function to 7043 // resolve possible conflicts. 7044 ExprResult VariantRefCast = VariantRef; 7045 if (LangOpts.CPlusPlus) { 7046 QualType FnPtrType; 7047 auto *Method = dyn_cast<CXXMethodDecl>(FD); 7048 if (Method && !Method->isStatic()) { 7049 const Type *ClassType = 7050 Context.getTypeDeclType(Method->getParent()).getTypePtr(); 7051 FnPtrType = Context.getMemberPointerType(AdjustedFnType, ClassType); 7052 ExprResult ER; 7053 { 7054 // Build adrr_of unary op to correctly handle type checks for member 7055 // functions. 7056 Sema::TentativeAnalysisScope Trap(*this); 7057 ER = CreateBuiltinUnaryOp(VariantRef->getBeginLoc(), UO_AddrOf, 7058 VariantRef); 7059 } 7060 if (!ER.isUsable()) { 7061 Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected) 7062 << VariantId << VariantRef->getSourceRange(); 7063 return None; 7064 } 7065 VariantRef = ER.get(); 7066 } else { 7067 FnPtrType = Context.getPointerType(AdjustedFnType); 7068 } 7069 QualType VarianPtrType = Context.getPointerType(VariantRef->getType()); 7070 if (VarianPtrType.getUnqualifiedType() != FnPtrType.getUnqualifiedType()) { 7071 ImplicitConversionSequence ICS = TryImplicitConversion( 7072 VariantRef, FnPtrType.getUnqualifiedType(), 7073 /*SuppressUserConversions=*/false, AllowedExplicit::None, 7074 /*InOverloadResolution=*/false, 7075 /*CStyle=*/false, 7076 /*AllowObjCWritebackConversion=*/false); 7077 if (ICS.isFailure()) { 7078 Diag(VariantRef->getExprLoc(), 7079 diag::err_omp_declare_variant_incompat_types) 7080 << VariantRef->getType() 7081 << ((Method && !Method->isStatic()) ? FnPtrType : FD->getType()) 7082 << (NumAppendArgs ? 1 : 0) << VariantRef->getSourceRange(); 7083 return None; 7084 } 7085 VariantRefCast = PerformImplicitConversion( 7086 VariantRef, FnPtrType.getUnqualifiedType(), AA_Converting); 7087 if (!VariantRefCast.isUsable()) 7088 return None; 7089 } 7090 // Drop previously built artificial addr_of unary op for member functions. 7091 if (Method && !Method->isStatic()) { 7092 Expr *PossibleAddrOfVariantRef = VariantRefCast.get(); 7093 if (auto *UO = dyn_cast<UnaryOperator>( 7094 PossibleAddrOfVariantRef->IgnoreImplicit())) 7095 VariantRefCast = UO->getSubExpr(); 7096 } 7097 } 7098 7099 ExprResult ER = CheckPlaceholderExpr(VariantRefCast.get()); 7100 if (!ER.isUsable() || 7101 !ER.get()->IgnoreParenImpCasts()->getType()->isFunctionType()) { 7102 Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected) 7103 << VariantId << VariantRef->getSourceRange(); 7104 return None; 7105 } 7106 7107 // The VariantRef must point to function. 7108 auto *DRE = dyn_cast<DeclRefExpr>(ER.get()->IgnoreParenImpCasts()); 7109 if (!DRE) { 7110 Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected) 7111 << VariantId << VariantRef->getSourceRange(); 7112 return None; 7113 } 7114 auto *NewFD = dyn_cast_or_null<FunctionDecl>(DRE->getDecl()); 7115 if (!NewFD) { 7116 Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected) 7117 << VariantId << VariantRef->getSourceRange(); 7118 return None; 7119 } 7120 7121 // Check if function types are compatible in C. 7122 if (!LangOpts.CPlusPlus) { 7123 QualType NewType = 7124 Context.mergeFunctionTypes(AdjustedFnType, NewFD->getType()); 7125 if (NewType.isNull()) { 7126 Diag(VariantRef->getExprLoc(), 7127 diag::err_omp_declare_variant_incompat_types) 7128 << NewFD->getType() << FD->getType() << (NumAppendArgs ? 1 : 0) 7129 << VariantRef->getSourceRange(); 7130 return None; 7131 } 7132 if (NewType->isFunctionProtoType()) { 7133 if (FD->getType()->isFunctionNoProtoType()) 7134 setPrototype(*this, FD, NewFD, NewType); 7135 else if (NewFD->getType()->isFunctionNoProtoType()) 7136 setPrototype(*this, NewFD, FD, NewType); 7137 } 7138 } 7139 7140 // Check if variant function is not marked with declare variant directive. 7141 if (NewFD->hasAttrs() && NewFD->hasAttr<OMPDeclareVariantAttr>()) { 7142 Diag(VariantRef->getExprLoc(), 7143 diag::warn_omp_declare_variant_marked_as_declare_variant) 7144 << VariantRef->getSourceRange(); 7145 SourceRange SR = 7146 NewFD->specific_attr_begin<OMPDeclareVariantAttr>()->getRange(); 7147 Diag(SR.getBegin(), diag::note_omp_marked_declare_variant_here) << SR; 7148 return None; 7149 } 7150 7151 enum DoesntSupport { 7152 VirtFuncs = 1, 7153 Constructors = 3, 7154 Destructors = 4, 7155 DeletedFuncs = 5, 7156 DefaultedFuncs = 6, 7157 ConstexprFuncs = 7, 7158 ConstevalFuncs = 8, 7159 }; 7160 if (const auto *CXXFD = dyn_cast<CXXMethodDecl>(FD)) { 7161 if (CXXFD->isVirtual()) { 7162 Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support) 7163 << VirtFuncs; 7164 return None; 7165 } 7166 7167 if (isa<CXXConstructorDecl>(FD)) { 7168 Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support) 7169 << Constructors; 7170 return None; 7171 } 7172 7173 if (isa<CXXDestructorDecl>(FD)) { 7174 Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support) 7175 << Destructors; 7176 return None; 7177 } 7178 } 7179 7180 if (FD->isDeleted()) { 7181 Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support) 7182 << DeletedFuncs; 7183 return None; 7184 } 7185 7186 if (FD->isDefaulted()) { 7187 Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support) 7188 << DefaultedFuncs; 7189 return None; 7190 } 7191 7192 if (FD->isConstexpr()) { 7193 Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support) 7194 << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs); 7195 return None; 7196 } 7197 7198 // Check general compatibility. 7199 if (areMultiversionVariantFunctionsCompatible( 7200 FD, NewFD, PartialDiagnostic::NullDiagnostic(), 7201 PartialDiagnosticAt(SourceLocation(), 7202 PartialDiagnostic::NullDiagnostic()), 7203 PartialDiagnosticAt( 7204 VariantRef->getExprLoc(), 7205 PDiag(diag::err_omp_declare_variant_doesnt_support)), 7206 PartialDiagnosticAt(VariantRef->getExprLoc(), 7207 PDiag(diag::err_omp_declare_variant_diff) 7208 << FD->getLocation()), 7209 /*TemplatesSupported=*/true, /*ConstexprSupported=*/false, 7210 /*CLinkageMayDiffer=*/true)) 7211 return None; 7212 return std::make_pair(FD, cast<Expr>(DRE)); 7213 } 7214 7215 void Sema::ActOnOpenMPDeclareVariantDirective( 7216 FunctionDecl *FD, Expr *VariantRef, OMPTraitInfo &TI, 7217 ArrayRef<Expr *> AdjustArgsNothing, 7218 ArrayRef<Expr *> AdjustArgsNeedDevicePtr, 7219 ArrayRef<OMPDeclareVariantAttr::InteropType> AppendArgs, 7220 SourceLocation AdjustArgsLoc, SourceLocation AppendArgsLoc, 7221 SourceRange SR) { 7222 7223 // OpenMP 5.1 [2.3.5, declare variant directive, Restrictions] 7224 // An adjust_args clause or append_args clause can only be specified if the 7225 // dispatch selector of the construct selector set appears in the match 7226 // clause. 7227 7228 SmallVector<Expr *, 8> AllAdjustArgs; 7229 llvm::append_range(AllAdjustArgs, AdjustArgsNothing); 7230 llvm::append_range(AllAdjustArgs, AdjustArgsNeedDevicePtr); 7231 7232 if (!AllAdjustArgs.empty() || !AppendArgs.empty()) { 7233 VariantMatchInfo VMI; 7234 TI.getAsVariantMatchInfo(Context, VMI); 7235 if (!llvm::is_contained( 7236 VMI.ConstructTraits, 7237 llvm::omp::TraitProperty::construct_dispatch_dispatch)) { 7238 if (!AllAdjustArgs.empty()) 7239 Diag(AdjustArgsLoc, diag::err_omp_clause_requires_dispatch_construct) 7240 << getOpenMPClauseName(OMPC_adjust_args); 7241 if (!AppendArgs.empty()) 7242 Diag(AppendArgsLoc, diag::err_omp_clause_requires_dispatch_construct) 7243 << getOpenMPClauseName(OMPC_append_args); 7244 return; 7245 } 7246 } 7247 7248 // OpenMP 5.1 [2.3.5, declare variant directive, Restrictions] 7249 // Each argument can only appear in a single adjust_args clause for each 7250 // declare variant directive. 7251 llvm::SmallPtrSet<const VarDecl *, 4> AdjustVars; 7252 7253 for (Expr *E : AllAdjustArgs) { 7254 E = E->IgnoreParenImpCasts(); 7255 if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) { 7256 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) { 7257 const VarDecl *CanonPVD = PVD->getCanonicalDecl(); 7258 if (FD->getNumParams() > PVD->getFunctionScopeIndex() && 7259 FD->getParamDecl(PVD->getFunctionScopeIndex()) 7260 ->getCanonicalDecl() == CanonPVD) { 7261 // It's a parameter of the function, check duplicates. 7262 if (!AdjustVars.insert(CanonPVD).second) { 7263 Diag(DRE->getLocation(), diag::err_omp_adjust_arg_multiple_clauses) 7264 << PVD; 7265 return; 7266 } 7267 continue; 7268 } 7269 } 7270 } 7271 // Anything that is not a function parameter is an error. 7272 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause) << FD << 0; 7273 return; 7274 } 7275 7276 auto *NewAttr = OMPDeclareVariantAttr::CreateImplicit( 7277 Context, VariantRef, &TI, const_cast<Expr **>(AdjustArgsNothing.data()), 7278 AdjustArgsNothing.size(), 7279 const_cast<Expr **>(AdjustArgsNeedDevicePtr.data()), 7280 AdjustArgsNeedDevicePtr.size(), 7281 const_cast<OMPDeclareVariantAttr::InteropType *>(AppendArgs.data()), 7282 AppendArgs.size(), SR); 7283 FD->addAttr(NewAttr); 7284 } 7285 7286 StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses, 7287 Stmt *AStmt, 7288 SourceLocation StartLoc, 7289 SourceLocation EndLoc) { 7290 if (!AStmt) 7291 return StmtError(); 7292 7293 auto *CS = cast<CapturedStmt>(AStmt); 7294 // 1.2.2 OpenMP Language Terminology 7295 // Structured block - An executable statement with a single entry at the 7296 // top and a single exit at the bottom. 7297 // The point of exit cannot be a branch out of the structured block. 7298 // longjmp() and throw() must not violate the entry/exit criteria. 7299 CS->getCapturedDecl()->setNothrow(); 7300 7301 setFunctionHasBranchProtectedScope(); 7302 7303 return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt, 7304 DSAStack->getTaskgroupReductionRef(), 7305 DSAStack->isCancelRegion()); 7306 } 7307 7308 namespace { 7309 /// Iteration space of a single for loop. 7310 struct LoopIterationSpace final { 7311 /// True if the condition operator is the strict compare operator (<, > or 7312 /// !=). 7313 bool IsStrictCompare = false; 7314 /// Condition of the loop. 7315 Expr *PreCond = nullptr; 7316 /// This expression calculates the number of iterations in the loop. 7317 /// It is always possible to calculate it before starting the loop. 7318 Expr *NumIterations = nullptr; 7319 /// The loop counter variable. 7320 Expr *CounterVar = nullptr; 7321 /// Private loop counter variable. 7322 Expr *PrivateCounterVar = nullptr; 7323 /// This is initializer for the initial value of #CounterVar. 7324 Expr *CounterInit = nullptr; 7325 /// This is step for the #CounterVar used to generate its update: 7326 /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration. 7327 Expr *CounterStep = nullptr; 7328 /// Should step be subtracted? 7329 bool Subtract = false; 7330 /// Source range of the loop init. 7331 SourceRange InitSrcRange; 7332 /// Source range of the loop condition. 7333 SourceRange CondSrcRange; 7334 /// Source range of the loop increment. 7335 SourceRange IncSrcRange; 7336 /// Minimum value that can have the loop control variable. Used to support 7337 /// non-rectangular loops. Applied only for LCV with the non-iterator types, 7338 /// since only such variables can be used in non-loop invariant expressions. 7339 Expr *MinValue = nullptr; 7340 /// Maximum value that can have the loop control variable. Used to support 7341 /// non-rectangular loops. Applied only for LCV with the non-iterator type, 7342 /// since only such variables can be used in non-loop invariant expressions. 7343 Expr *MaxValue = nullptr; 7344 /// true, if the lower bound depends on the outer loop control var. 7345 bool IsNonRectangularLB = false; 7346 /// true, if the upper bound depends on the outer loop control var. 7347 bool IsNonRectangularUB = false; 7348 /// Index of the loop this loop depends on and forms non-rectangular loop 7349 /// nest. 7350 unsigned LoopDependentIdx = 0; 7351 /// Final condition for the non-rectangular loop nest support. It is used to 7352 /// check that the number of iterations for this particular counter must be 7353 /// finished. 7354 Expr *FinalCondition = nullptr; 7355 }; 7356 7357 /// Helper class for checking canonical form of the OpenMP loops and 7358 /// extracting iteration space of each loop in the loop nest, that will be used 7359 /// for IR generation. 7360 class OpenMPIterationSpaceChecker { 7361 /// Reference to Sema. 7362 Sema &SemaRef; 7363 /// Does the loop associated directive support non-rectangular loops? 7364 bool SupportsNonRectangular; 7365 /// Data-sharing stack. 7366 DSAStackTy &Stack; 7367 /// A location for diagnostics (when there is no some better location). 7368 SourceLocation DefaultLoc; 7369 /// A location for diagnostics (when increment is not compatible). 7370 SourceLocation ConditionLoc; 7371 /// A source location for referring to loop init later. 7372 SourceRange InitSrcRange; 7373 /// A source location for referring to condition later. 7374 SourceRange ConditionSrcRange; 7375 /// A source location for referring to increment later. 7376 SourceRange IncrementSrcRange; 7377 /// Loop variable. 7378 ValueDecl *LCDecl = nullptr; 7379 /// Reference to loop variable. 7380 Expr *LCRef = nullptr; 7381 /// Lower bound (initializer for the var). 7382 Expr *LB = nullptr; 7383 /// Upper bound. 7384 Expr *UB = nullptr; 7385 /// Loop step (increment). 7386 Expr *Step = nullptr; 7387 /// This flag is true when condition is one of: 7388 /// Var < UB 7389 /// Var <= UB 7390 /// UB > Var 7391 /// UB >= Var 7392 /// This will have no value when the condition is != 7393 llvm::Optional<bool> TestIsLessOp; 7394 /// This flag is true when condition is strict ( < or > ). 7395 bool TestIsStrictOp = false; 7396 /// This flag is true when step is subtracted on each iteration. 7397 bool SubtractStep = false; 7398 /// The outer loop counter this loop depends on (if any). 7399 const ValueDecl *DepDecl = nullptr; 7400 /// Contains number of loop (starts from 1) on which loop counter init 7401 /// expression of this loop depends on. 7402 Optional<unsigned> InitDependOnLC; 7403 /// Contains number of loop (starts from 1) on which loop counter condition 7404 /// expression of this loop depends on. 7405 Optional<unsigned> CondDependOnLC; 7406 /// Checks if the provide statement depends on the loop counter. 7407 Optional<unsigned> doesDependOnLoopCounter(const Stmt *S, bool IsInitializer); 7408 /// Original condition required for checking of the exit condition for 7409 /// non-rectangular loop. 7410 Expr *Condition = nullptr; 7411 7412 public: 7413 OpenMPIterationSpaceChecker(Sema &SemaRef, bool SupportsNonRectangular, 7414 DSAStackTy &Stack, SourceLocation DefaultLoc) 7415 : SemaRef(SemaRef), SupportsNonRectangular(SupportsNonRectangular), 7416 Stack(Stack), DefaultLoc(DefaultLoc), ConditionLoc(DefaultLoc) {} 7417 /// Check init-expr for canonical loop form and save loop counter 7418 /// variable - #Var and its initialization value - #LB. 7419 bool checkAndSetInit(Stmt *S, bool EmitDiags = true); 7420 /// Check test-expr for canonical form, save upper-bound (#UB), flags 7421 /// for less/greater and for strict/non-strict comparison. 7422 bool checkAndSetCond(Expr *S); 7423 /// Check incr-expr for canonical loop form and return true if it 7424 /// does not conform, otherwise save loop step (#Step). 7425 bool checkAndSetInc(Expr *S); 7426 /// Return the loop counter variable. 7427 ValueDecl *getLoopDecl() const { return LCDecl; } 7428 /// Return the reference expression to loop counter variable. 7429 Expr *getLoopDeclRefExpr() const { return LCRef; } 7430 /// Source range of the loop init. 7431 SourceRange getInitSrcRange() const { return InitSrcRange; } 7432 /// Source range of the loop condition. 7433 SourceRange getConditionSrcRange() const { return ConditionSrcRange; } 7434 /// Source range of the loop increment. 7435 SourceRange getIncrementSrcRange() const { return IncrementSrcRange; } 7436 /// True if the step should be subtracted. 7437 bool shouldSubtractStep() const { return SubtractStep; } 7438 /// True, if the compare operator is strict (<, > or !=). 7439 bool isStrictTestOp() const { return TestIsStrictOp; } 7440 /// Build the expression to calculate the number of iterations. 7441 Expr *buildNumIterations( 7442 Scope *S, ArrayRef<LoopIterationSpace> ResultIterSpaces, bool LimitedType, 7443 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const; 7444 /// Build the precondition expression for the loops. 7445 Expr * 7446 buildPreCond(Scope *S, Expr *Cond, 7447 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const; 7448 /// Build reference expression to the counter be used for codegen. 7449 DeclRefExpr * 7450 buildCounterVar(llvm::MapVector<const Expr *, DeclRefExpr *> &Captures, 7451 DSAStackTy &DSA) const; 7452 /// Build reference expression to the private counter be used for 7453 /// codegen. 7454 Expr *buildPrivateCounterVar() const; 7455 /// Build initialization of the counter be used for codegen. 7456 Expr *buildCounterInit() const; 7457 /// Build step of the counter be used for codegen. 7458 Expr *buildCounterStep() const; 7459 /// Build loop data with counter value for depend clauses in ordered 7460 /// directives. 7461 Expr * 7462 buildOrderedLoopData(Scope *S, Expr *Counter, 7463 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures, 7464 SourceLocation Loc, Expr *Inc = nullptr, 7465 OverloadedOperatorKind OOK = OO_Amp); 7466 /// Builds the minimum value for the loop counter. 7467 std::pair<Expr *, Expr *> buildMinMaxValues( 7468 Scope *S, llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const; 7469 /// Builds final condition for the non-rectangular loops. 7470 Expr *buildFinalCondition(Scope *S) const; 7471 /// Return true if any expression is dependent. 7472 bool dependent() const; 7473 /// Returns true if the initializer forms non-rectangular loop. 7474 bool doesInitDependOnLC() const { return InitDependOnLC.hasValue(); } 7475 /// Returns true if the condition forms non-rectangular loop. 7476 bool doesCondDependOnLC() const { return CondDependOnLC.hasValue(); } 7477 /// Returns index of the loop we depend on (starting from 1), or 0 otherwise. 7478 unsigned getLoopDependentIdx() const { 7479 return InitDependOnLC.getValueOr(CondDependOnLC.getValueOr(0)); 7480 } 7481 7482 private: 7483 /// Check the right-hand side of an assignment in the increment 7484 /// expression. 7485 bool checkAndSetIncRHS(Expr *RHS); 7486 /// Helper to set loop counter variable and its initializer. 7487 bool setLCDeclAndLB(ValueDecl *NewLCDecl, Expr *NewDeclRefExpr, Expr *NewLB, 7488 bool EmitDiags); 7489 /// Helper to set upper bound. 7490 bool setUB(Expr *NewUB, llvm::Optional<bool> LessOp, bool StrictOp, 7491 SourceRange SR, SourceLocation SL); 7492 /// Helper to set loop increment. 7493 bool setStep(Expr *NewStep, bool Subtract); 7494 }; 7495 7496 bool OpenMPIterationSpaceChecker::dependent() const { 7497 if (!LCDecl) { 7498 assert(!LB && !UB && !Step); 7499 return false; 7500 } 7501 return LCDecl->getType()->isDependentType() || 7502 (LB && LB->isValueDependent()) || (UB && UB->isValueDependent()) || 7503 (Step && Step->isValueDependent()); 7504 } 7505 7506 bool OpenMPIterationSpaceChecker::setLCDeclAndLB(ValueDecl *NewLCDecl, 7507 Expr *NewLCRefExpr, 7508 Expr *NewLB, bool EmitDiags) { 7509 // State consistency checking to ensure correct usage. 7510 assert(LCDecl == nullptr && LB == nullptr && LCRef == nullptr && 7511 UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp); 7512 if (!NewLCDecl || !NewLB || NewLB->containsErrors()) 7513 return true; 7514 LCDecl = getCanonicalDecl(NewLCDecl); 7515 LCRef = NewLCRefExpr; 7516 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB)) 7517 if (const CXXConstructorDecl *Ctor = CE->getConstructor()) 7518 if ((Ctor->isCopyOrMoveConstructor() || 7519 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) && 7520 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr) 7521 NewLB = CE->getArg(0)->IgnoreParenImpCasts(); 7522 LB = NewLB; 7523 if (EmitDiags) 7524 InitDependOnLC = doesDependOnLoopCounter(LB, /*IsInitializer=*/true); 7525 return false; 7526 } 7527 7528 bool OpenMPIterationSpaceChecker::setUB(Expr *NewUB, 7529 llvm::Optional<bool> LessOp, 7530 bool StrictOp, SourceRange SR, 7531 SourceLocation SL) { 7532 // State consistency checking to ensure correct usage. 7533 assert(LCDecl != nullptr && LB != nullptr && UB == nullptr && 7534 Step == nullptr && !TestIsLessOp && !TestIsStrictOp); 7535 if (!NewUB || NewUB->containsErrors()) 7536 return true; 7537 UB = NewUB; 7538 if (LessOp) 7539 TestIsLessOp = LessOp; 7540 TestIsStrictOp = StrictOp; 7541 ConditionSrcRange = SR; 7542 ConditionLoc = SL; 7543 CondDependOnLC = doesDependOnLoopCounter(UB, /*IsInitializer=*/false); 7544 return false; 7545 } 7546 7547 bool OpenMPIterationSpaceChecker::setStep(Expr *NewStep, bool Subtract) { 7548 // State consistency checking to ensure correct usage. 7549 assert(LCDecl != nullptr && LB != nullptr && Step == nullptr); 7550 if (!NewStep || NewStep->containsErrors()) 7551 return true; 7552 if (!NewStep->isValueDependent()) { 7553 // Check that the step is integer expression. 7554 SourceLocation StepLoc = NewStep->getBeginLoc(); 7555 ExprResult Val = SemaRef.PerformOpenMPImplicitIntegerConversion( 7556 StepLoc, getExprAsWritten(NewStep)); 7557 if (Val.isInvalid()) 7558 return true; 7559 NewStep = Val.get(); 7560 7561 // OpenMP [2.6, Canonical Loop Form, Restrictions] 7562 // If test-expr is of form var relational-op b and relational-op is < or 7563 // <= then incr-expr must cause var to increase on each iteration of the 7564 // loop. If test-expr is of form var relational-op b and relational-op is 7565 // > or >= then incr-expr must cause var to decrease on each iteration of 7566 // the loop. 7567 // If test-expr is of form b relational-op var and relational-op is < or 7568 // <= then incr-expr must cause var to decrease on each iteration of the 7569 // loop. If test-expr is of form b relational-op var and relational-op is 7570 // > or >= then incr-expr must cause var to increase on each iteration of 7571 // the loop. 7572 Optional<llvm::APSInt> Result = 7573 NewStep->getIntegerConstantExpr(SemaRef.Context); 7574 bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation(); 7575 bool IsConstNeg = 7576 Result && Result->isSigned() && (Subtract != Result->isNegative()); 7577 bool IsConstPos = 7578 Result && Result->isSigned() && (Subtract == Result->isNegative()); 7579 bool IsConstZero = Result && !Result->getBoolValue(); 7580 7581 // != with increment is treated as <; != with decrement is treated as > 7582 if (!TestIsLessOp.hasValue()) 7583 TestIsLessOp = IsConstPos || (IsUnsigned && !Subtract); 7584 if (UB && (IsConstZero || 7585 (TestIsLessOp.getValue() ? 7586 (IsConstNeg || (IsUnsigned && Subtract)) : 7587 (IsConstPos || (IsUnsigned && !Subtract))))) { 7588 SemaRef.Diag(NewStep->getExprLoc(), 7589 diag::err_omp_loop_incr_not_compatible) 7590 << LCDecl << TestIsLessOp.getValue() << NewStep->getSourceRange(); 7591 SemaRef.Diag(ConditionLoc, 7592 diag::note_omp_loop_cond_requres_compatible_incr) 7593 << TestIsLessOp.getValue() << ConditionSrcRange; 7594 return true; 7595 } 7596 if (TestIsLessOp.getValue() == Subtract) { 7597 NewStep = 7598 SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus, NewStep) 7599 .get(); 7600 Subtract = !Subtract; 7601 } 7602 } 7603 7604 Step = NewStep; 7605 SubtractStep = Subtract; 7606 return false; 7607 } 7608 7609 namespace { 7610 /// Checker for the non-rectangular loops. Checks if the initializer or 7611 /// condition expression references loop counter variable. 7612 class LoopCounterRefChecker final 7613 : public ConstStmtVisitor<LoopCounterRefChecker, bool> { 7614 Sema &SemaRef; 7615 DSAStackTy &Stack; 7616 const ValueDecl *CurLCDecl = nullptr; 7617 const ValueDecl *DepDecl = nullptr; 7618 const ValueDecl *PrevDepDecl = nullptr; 7619 bool IsInitializer = true; 7620 bool SupportsNonRectangular; 7621 unsigned BaseLoopId = 0; 7622 bool checkDecl(const Expr *E, const ValueDecl *VD) { 7623 if (getCanonicalDecl(VD) == getCanonicalDecl(CurLCDecl)) { 7624 SemaRef.Diag(E->getExprLoc(), diag::err_omp_stmt_depends_on_loop_counter) 7625 << (IsInitializer ? 0 : 1); 7626 return false; 7627 } 7628 const auto &&Data = Stack.isLoopControlVariable(VD); 7629 // OpenMP, 2.9.1 Canonical Loop Form, Restrictions. 7630 // The type of the loop iterator on which we depend may not have a random 7631 // access iterator type. 7632 if (Data.first && VD->getType()->isRecordType()) { 7633 SmallString<128> Name; 7634 llvm::raw_svector_ostream OS(Name); 7635 VD->getNameForDiagnostic(OS, SemaRef.getPrintingPolicy(), 7636 /*Qualified=*/true); 7637 SemaRef.Diag(E->getExprLoc(), 7638 diag::err_omp_wrong_dependency_iterator_type) 7639 << OS.str(); 7640 SemaRef.Diag(VD->getLocation(), diag::note_previous_decl) << VD; 7641 return false; 7642 } 7643 if (Data.first && !SupportsNonRectangular) { 7644 SemaRef.Diag(E->getExprLoc(), diag::err_omp_invariant_dependency); 7645 return false; 7646 } 7647 if (Data.first && 7648 (DepDecl || (PrevDepDecl && 7649 getCanonicalDecl(VD) != getCanonicalDecl(PrevDepDecl)))) { 7650 if (!DepDecl && PrevDepDecl) 7651 DepDecl = PrevDepDecl; 7652 SmallString<128> Name; 7653 llvm::raw_svector_ostream OS(Name); 7654 DepDecl->getNameForDiagnostic(OS, SemaRef.getPrintingPolicy(), 7655 /*Qualified=*/true); 7656 SemaRef.Diag(E->getExprLoc(), 7657 diag::err_omp_invariant_or_linear_dependency) 7658 << OS.str(); 7659 return false; 7660 } 7661 if (Data.first) { 7662 DepDecl = VD; 7663 BaseLoopId = Data.first; 7664 } 7665 return Data.first; 7666 } 7667 7668 public: 7669 bool VisitDeclRefExpr(const DeclRefExpr *E) { 7670 const ValueDecl *VD = E->getDecl(); 7671 if (isa<VarDecl>(VD)) 7672 return checkDecl(E, VD); 7673 return false; 7674 } 7675 bool VisitMemberExpr(const MemberExpr *E) { 7676 if (isa<CXXThisExpr>(E->getBase()->IgnoreParens())) { 7677 const ValueDecl *VD = E->getMemberDecl(); 7678 if (isa<VarDecl>(VD) || isa<FieldDecl>(VD)) 7679 return checkDecl(E, VD); 7680 } 7681 return false; 7682 } 7683 bool VisitStmt(const Stmt *S) { 7684 bool Res = false; 7685 for (const Stmt *Child : S->children()) 7686 Res = (Child && Visit(Child)) || Res; 7687 return Res; 7688 } 7689 explicit LoopCounterRefChecker(Sema &SemaRef, DSAStackTy &Stack, 7690 const ValueDecl *CurLCDecl, bool IsInitializer, 7691 const ValueDecl *PrevDepDecl = nullptr, 7692 bool SupportsNonRectangular = true) 7693 : SemaRef(SemaRef), Stack(Stack), CurLCDecl(CurLCDecl), 7694 PrevDepDecl(PrevDepDecl), IsInitializer(IsInitializer), 7695 SupportsNonRectangular(SupportsNonRectangular) {} 7696 unsigned getBaseLoopId() const { 7697 assert(CurLCDecl && "Expected loop dependency."); 7698 return BaseLoopId; 7699 } 7700 const ValueDecl *getDepDecl() const { 7701 assert(CurLCDecl && "Expected loop dependency."); 7702 return DepDecl; 7703 } 7704 }; 7705 } // namespace 7706 7707 Optional<unsigned> 7708 OpenMPIterationSpaceChecker::doesDependOnLoopCounter(const Stmt *S, 7709 bool IsInitializer) { 7710 // Check for the non-rectangular loops. 7711 LoopCounterRefChecker LoopStmtChecker(SemaRef, Stack, LCDecl, IsInitializer, 7712 DepDecl, SupportsNonRectangular); 7713 if (LoopStmtChecker.Visit(S)) { 7714 DepDecl = LoopStmtChecker.getDepDecl(); 7715 return LoopStmtChecker.getBaseLoopId(); 7716 } 7717 return llvm::None; 7718 } 7719 7720 bool OpenMPIterationSpaceChecker::checkAndSetInit(Stmt *S, bool EmitDiags) { 7721 // Check init-expr for canonical loop form and save loop counter 7722 // variable - #Var and its initialization value - #LB. 7723 // OpenMP [2.6] Canonical loop form. init-expr may be one of the following: 7724 // var = lb 7725 // integer-type var = lb 7726 // random-access-iterator-type var = lb 7727 // pointer-type var = lb 7728 // 7729 if (!S) { 7730 if (EmitDiags) { 7731 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init); 7732 } 7733 return true; 7734 } 7735 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S)) 7736 if (!ExprTemp->cleanupsHaveSideEffects()) 7737 S = ExprTemp->getSubExpr(); 7738 7739 InitSrcRange = S->getSourceRange(); 7740 if (Expr *E = dyn_cast<Expr>(S)) 7741 S = E->IgnoreParens(); 7742 if (auto *BO = dyn_cast<BinaryOperator>(S)) { 7743 if (BO->getOpcode() == BO_Assign) { 7744 Expr *LHS = BO->getLHS()->IgnoreParens(); 7745 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) { 7746 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl())) 7747 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit()))) 7748 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(), 7749 EmitDiags); 7750 return setLCDeclAndLB(DRE->getDecl(), DRE, BO->getRHS(), EmitDiags); 7751 } 7752 if (auto *ME = dyn_cast<MemberExpr>(LHS)) { 7753 if (ME->isArrow() && 7754 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts())) 7755 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(), 7756 EmitDiags); 7757 } 7758 } 7759 } else if (auto *DS = dyn_cast<DeclStmt>(S)) { 7760 if (DS->isSingleDecl()) { 7761 if (auto *Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) { 7762 if (Var->hasInit() && !Var->getType()->isReferenceType()) { 7763 // Accept non-canonical init form here but emit ext. warning. 7764 if (Var->getInitStyle() != VarDecl::CInit && EmitDiags) 7765 SemaRef.Diag(S->getBeginLoc(), 7766 diag::ext_omp_loop_not_canonical_init) 7767 << S->getSourceRange(); 7768 return setLCDeclAndLB( 7769 Var, 7770 buildDeclRefExpr(SemaRef, Var, 7771 Var->getType().getNonReferenceType(), 7772 DS->getBeginLoc()), 7773 Var->getInit(), EmitDiags); 7774 } 7775 } 7776 } 7777 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) { 7778 if (CE->getOperator() == OO_Equal) { 7779 Expr *LHS = CE->getArg(0); 7780 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) { 7781 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl())) 7782 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit()))) 7783 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(), 7784 EmitDiags); 7785 return setLCDeclAndLB(DRE->getDecl(), DRE, CE->getArg(1), EmitDiags); 7786 } 7787 if (auto *ME = dyn_cast<MemberExpr>(LHS)) { 7788 if (ME->isArrow() && 7789 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts())) 7790 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(), 7791 EmitDiags); 7792 } 7793 } 7794 } 7795 7796 if (dependent() || SemaRef.CurContext->isDependentContext()) 7797 return false; 7798 if (EmitDiags) { 7799 SemaRef.Diag(S->getBeginLoc(), diag::err_omp_loop_not_canonical_init) 7800 << S->getSourceRange(); 7801 } 7802 return true; 7803 } 7804 7805 /// Ignore parenthesizes, implicit casts, copy constructor and return the 7806 /// variable (which may be the loop variable) if possible. 7807 static const ValueDecl *getInitLCDecl(const Expr *E) { 7808 if (!E) 7809 return nullptr; 7810 E = getExprAsWritten(E); 7811 if (const auto *CE = dyn_cast_or_null<CXXConstructExpr>(E)) 7812 if (const CXXConstructorDecl *Ctor = CE->getConstructor()) 7813 if ((Ctor->isCopyOrMoveConstructor() || 7814 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) && 7815 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr) 7816 E = CE->getArg(0)->IgnoreParenImpCasts(); 7817 if (const auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) { 7818 if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) 7819 return getCanonicalDecl(VD); 7820 } 7821 if (const auto *ME = dyn_cast_or_null<MemberExpr>(E)) 7822 if (ME->isArrow() && isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts())) 7823 return getCanonicalDecl(ME->getMemberDecl()); 7824 return nullptr; 7825 } 7826 7827 bool OpenMPIterationSpaceChecker::checkAndSetCond(Expr *S) { 7828 // Check test-expr for canonical form, save upper-bound UB, flags for 7829 // less/greater and for strict/non-strict comparison. 7830 // OpenMP [2.9] Canonical loop form. Test-expr may be one of the following: 7831 // var relational-op b 7832 // b relational-op var 7833 // 7834 bool IneqCondIsCanonical = SemaRef.getLangOpts().OpenMP >= 50; 7835 if (!S) { 7836 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond) 7837 << (IneqCondIsCanonical ? 1 : 0) << LCDecl; 7838 return true; 7839 } 7840 Condition = S; 7841 S = getExprAsWritten(S); 7842 SourceLocation CondLoc = S->getBeginLoc(); 7843 auto &&CheckAndSetCond = [this, IneqCondIsCanonical]( 7844 BinaryOperatorKind Opcode, const Expr *LHS, 7845 const Expr *RHS, SourceRange SR, 7846 SourceLocation OpLoc) -> llvm::Optional<bool> { 7847 if (BinaryOperator::isRelationalOp(Opcode)) { 7848 if (getInitLCDecl(LHS) == LCDecl) 7849 return setUB(const_cast<Expr *>(RHS), 7850 (Opcode == BO_LT || Opcode == BO_LE), 7851 (Opcode == BO_LT || Opcode == BO_GT), SR, OpLoc); 7852 if (getInitLCDecl(RHS) == LCDecl) 7853 return setUB(const_cast<Expr *>(LHS), 7854 (Opcode == BO_GT || Opcode == BO_GE), 7855 (Opcode == BO_LT || Opcode == BO_GT), SR, OpLoc); 7856 } else if (IneqCondIsCanonical && Opcode == BO_NE) { 7857 return setUB(const_cast<Expr *>(getInitLCDecl(LHS) == LCDecl ? RHS : LHS), 7858 /*LessOp=*/llvm::None, 7859 /*StrictOp=*/true, SR, OpLoc); 7860 } 7861 return llvm::None; 7862 }; 7863 llvm::Optional<bool> Res; 7864 if (auto *RBO = dyn_cast<CXXRewrittenBinaryOperator>(S)) { 7865 CXXRewrittenBinaryOperator::DecomposedForm DF = RBO->getDecomposedForm(); 7866 Res = CheckAndSetCond(DF.Opcode, DF.LHS, DF.RHS, RBO->getSourceRange(), 7867 RBO->getOperatorLoc()); 7868 } else if (auto *BO = dyn_cast<BinaryOperator>(S)) { 7869 Res = CheckAndSetCond(BO->getOpcode(), BO->getLHS(), BO->getRHS(), 7870 BO->getSourceRange(), BO->getOperatorLoc()); 7871 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) { 7872 if (CE->getNumArgs() == 2) { 7873 Res = CheckAndSetCond( 7874 BinaryOperator::getOverloadedOpcode(CE->getOperator()), CE->getArg(0), 7875 CE->getArg(1), CE->getSourceRange(), CE->getOperatorLoc()); 7876 } 7877 } 7878 if (Res.hasValue()) 7879 return *Res; 7880 if (dependent() || SemaRef.CurContext->isDependentContext()) 7881 return false; 7882 SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond) 7883 << (IneqCondIsCanonical ? 1 : 0) << S->getSourceRange() << LCDecl; 7884 return true; 7885 } 7886 7887 bool OpenMPIterationSpaceChecker::checkAndSetIncRHS(Expr *RHS) { 7888 // RHS of canonical loop form increment can be: 7889 // var + incr 7890 // incr + var 7891 // var - incr 7892 // 7893 RHS = RHS->IgnoreParenImpCasts(); 7894 if (auto *BO = dyn_cast<BinaryOperator>(RHS)) { 7895 if (BO->isAdditiveOp()) { 7896 bool IsAdd = BO->getOpcode() == BO_Add; 7897 if (getInitLCDecl(BO->getLHS()) == LCDecl) 7898 return setStep(BO->getRHS(), !IsAdd); 7899 if (IsAdd && getInitLCDecl(BO->getRHS()) == LCDecl) 7900 return setStep(BO->getLHS(), /*Subtract=*/false); 7901 } 7902 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(RHS)) { 7903 bool IsAdd = CE->getOperator() == OO_Plus; 7904 if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) { 7905 if (getInitLCDecl(CE->getArg(0)) == LCDecl) 7906 return setStep(CE->getArg(1), !IsAdd); 7907 if (IsAdd && getInitLCDecl(CE->getArg(1)) == LCDecl) 7908 return setStep(CE->getArg(0), /*Subtract=*/false); 7909 } 7910 } 7911 if (dependent() || SemaRef.CurContext->isDependentContext()) 7912 return false; 7913 SemaRef.Diag(RHS->getBeginLoc(), diag::err_omp_loop_not_canonical_incr) 7914 << RHS->getSourceRange() << LCDecl; 7915 return true; 7916 } 7917 7918 bool OpenMPIterationSpaceChecker::checkAndSetInc(Expr *S) { 7919 // Check incr-expr for canonical loop form and return true if it 7920 // does not conform. 7921 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following: 7922 // ++var 7923 // var++ 7924 // --var 7925 // var-- 7926 // var += incr 7927 // var -= incr 7928 // var = var + incr 7929 // var = incr + var 7930 // var = var - incr 7931 // 7932 if (!S) { 7933 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << LCDecl; 7934 return true; 7935 } 7936 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S)) 7937 if (!ExprTemp->cleanupsHaveSideEffects()) 7938 S = ExprTemp->getSubExpr(); 7939 7940 IncrementSrcRange = S->getSourceRange(); 7941 S = S->IgnoreParens(); 7942 if (auto *UO = dyn_cast<UnaryOperator>(S)) { 7943 if (UO->isIncrementDecrementOp() && 7944 getInitLCDecl(UO->getSubExpr()) == LCDecl) 7945 return setStep(SemaRef 7946 .ActOnIntegerConstant(UO->getBeginLoc(), 7947 (UO->isDecrementOp() ? -1 : 1)) 7948 .get(), 7949 /*Subtract=*/false); 7950 } else if (auto *BO = dyn_cast<BinaryOperator>(S)) { 7951 switch (BO->getOpcode()) { 7952 case BO_AddAssign: 7953 case BO_SubAssign: 7954 if (getInitLCDecl(BO->getLHS()) == LCDecl) 7955 return setStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign); 7956 break; 7957 case BO_Assign: 7958 if (getInitLCDecl(BO->getLHS()) == LCDecl) 7959 return checkAndSetIncRHS(BO->getRHS()); 7960 break; 7961 default: 7962 break; 7963 } 7964 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) { 7965 switch (CE->getOperator()) { 7966 case OO_PlusPlus: 7967 case OO_MinusMinus: 7968 if (getInitLCDecl(CE->getArg(0)) == LCDecl) 7969 return setStep(SemaRef 7970 .ActOnIntegerConstant( 7971 CE->getBeginLoc(), 7972 ((CE->getOperator() == OO_MinusMinus) ? -1 : 1)) 7973 .get(), 7974 /*Subtract=*/false); 7975 break; 7976 case OO_PlusEqual: 7977 case OO_MinusEqual: 7978 if (getInitLCDecl(CE->getArg(0)) == LCDecl) 7979 return setStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual); 7980 break; 7981 case OO_Equal: 7982 if (getInitLCDecl(CE->getArg(0)) == LCDecl) 7983 return checkAndSetIncRHS(CE->getArg(1)); 7984 break; 7985 default: 7986 break; 7987 } 7988 } 7989 if (dependent() || SemaRef.CurContext->isDependentContext()) 7990 return false; 7991 SemaRef.Diag(S->getBeginLoc(), diag::err_omp_loop_not_canonical_incr) 7992 << S->getSourceRange() << LCDecl; 7993 return true; 7994 } 7995 7996 static ExprResult 7997 tryBuildCapture(Sema &SemaRef, Expr *Capture, 7998 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) { 7999 if (SemaRef.CurContext->isDependentContext() || Capture->containsErrors()) 8000 return Capture; 8001 if (Capture->isEvaluatable(SemaRef.Context, Expr::SE_AllowSideEffects)) 8002 return SemaRef.PerformImplicitConversion( 8003 Capture->IgnoreImpCasts(), Capture->getType(), Sema::AA_Converting, 8004 /*AllowExplicit=*/true); 8005 auto I = Captures.find(Capture); 8006 if (I != Captures.end()) 8007 return buildCapture(SemaRef, Capture, I->second); 8008 DeclRefExpr *Ref = nullptr; 8009 ExprResult Res = buildCapture(SemaRef, Capture, Ref); 8010 Captures[Capture] = Ref; 8011 return Res; 8012 } 8013 8014 /// Calculate number of iterations, transforming to unsigned, if number of 8015 /// iterations may be larger than the original type. 8016 static Expr * 8017 calculateNumIters(Sema &SemaRef, Scope *S, SourceLocation DefaultLoc, 8018 Expr *Lower, Expr *Upper, Expr *Step, QualType LCTy, 8019 bool TestIsStrictOp, bool RoundToStep, 8020 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) { 8021 ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures); 8022 if (!NewStep.isUsable()) 8023 return nullptr; 8024 llvm::APSInt LRes, SRes; 8025 bool IsLowerConst = false, IsStepConst = false; 8026 if (Optional<llvm::APSInt> Res = Lower->getIntegerConstantExpr(SemaRef.Context)) { 8027 LRes = *Res; 8028 IsLowerConst = true; 8029 } 8030 if (Optional<llvm::APSInt> Res = Step->getIntegerConstantExpr(SemaRef.Context)) { 8031 SRes = *Res; 8032 IsStepConst = true; 8033 } 8034 bool NoNeedToConvert = IsLowerConst && !RoundToStep && 8035 ((!TestIsStrictOp && LRes.isNonNegative()) || 8036 (TestIsStrictOp && LRes.isStrictlyPositive())); 8037 bool NeedToReorganize = false; 8038 // Check if any subexpressions in Lower -Step [+ 1] lead to overflow. 8039 if (!NoNeedToConvert && IsLowerConst && 8040 (TestIsStrictOp || (RoundToStep && IsStepConst))) { 8041 NoNeedToConvert = true; 8042 if (RoundToStep) { 8043 unsigned BW = LRes.getBitWidth() > SRes.getBitWidth() 8044 ? LRes.getBitWidth() 8045 : SRes.getBitWidth(); 8046 LRes = LRes.extend(BW + 1); 8047 LRes.setIsSigned(true); 8048 SRes = SRes.extend(BW + 1); 8049 SRes.setIsSigned(true); 8050 LRes -= SRes; 8051 NoNeedToConvert = LRes.trunc(BW).extend(BW + 1) == LRes; 8052 LRes = LRes.trunc(BW); 8053 } 8054 if (TestIsStrictOp) { 8055 unsigned BW = LRes.getBitWidth(); 8056 LRes = LRes.extend(BW + 1); 8057 LRes.setIsSigned(true); 8058 ++LRes; 8059 NoNeedToConvert = 8060 NoNeedToConvert && LRes.trunc(BW).extend(BW + 1) == LRes; 8061 // truncate to the original bitwidth. 8062 LRes = LRes.trunc(BW); 8063 } 8064 NeedToReorganize = NoNeedToConvert; 8065 } 8066 llvm::APSInt URes; 8067 bool IsUpperConst = false; 8068 if (Optional<llvm::APSInt> Res = Upper->getIntegerConstantExpr(SemaRef.Context)) { 8069 URes = *Res; 8070 IsUpperConst = true; 8071 } 8072 if (NoNeedToConvert && IsLowerConst && IsUpperConst && 8073 (!RoundToStep || IsStepConst)) { 8074 unsigned BW = LRes.getBitWidth() > URes.getBitWidth() ? LRes.getBitWidth() 8075 : URes.getBitWidth(); 8076 LRes = LRes.extend(BW + 1); 8077 LRes.setIsSigned(true); 8078 URes = URes.extend(BW + 1); 8079 URes.setIsSigned(true); 8080 URes -= LRes; 8081 NoNeedToConvert = URes.trunc(BW).extend(BW + 1) == URes; 8082 NeedToReorganize = NoNeedToConvert; 8083 } 8084 // If the boundaries are not constant or (Lower - Step [+ 1]) is not constant 8085 // or less than zero (Upper - (Lower - Step [+ 1]) may overflow) - promote to 8086 // unsigned. 8087 if ((!NoNeedToConvert || (LRes.isNegative() && !IsUpperConst)) && 8088 !LCTy->isDependentType() && LCTy->isIntegerType()) { 8089 QualType LowerTy = Lower->getType(); 8090 QualType UpperTy = Upper->getType(); 8091 uint64_t LowerSize = SemaRef.Context.getTypeSize(LowerTy); 8092 uint64_t UpperSize = SemaRef.Context.getTypeSize(UpperTy); 8093 if ((LowerSize <= UpperSize && UpperTy->hasSignedIntegerRepresentation()) || 8094 (LowerSize > UpperSize && LowerTy->hasSignedIntegerRepresentation())) { 8095 QualType CastType = SemaRef.Context.getIntTypeForBitwidth( 8096 LowerSize > UpperSize ? LowerSize : UpperSize, /*Signed=*/0); 8097 Upper = 8098 SemaRef 8099 .PerformImplicitConversion( 8100 SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Upper).get(), 8101 CastType, Sema::AA_Converting) 8102 .get(); 8103 Lower = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Lower).get(); 8104 NewStep = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, NewStep.get()); 8105 } 8106 } 8107 if (!Lower || !Upper || NewStep.isInvalid()) 8108 return nullptr; 8109 8110 ExprResult Diff; 8111 // If need to reorganize, then calculate the form as Upper - (Lower - Step [+ 8112 // 1]). 8113 if (NeedToReorganize) { 8114 Diff = Lower; 8115 8116 if (RoundToStep) { 8117 // Lower - Step 8118 Diff = 8119 SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Diff.get(), NewStep.get()); 8120 if (!Diff.isUsable()) 8121 return nullptr; 8122 } 8123 8124 // Lower - Step [+ 1] 8125 if (TestIsStrictOp) 8126 Diff = SemaRef.BuildBinOp( 8127 S, DefaultLoc, BO_Add, Diff.get(), 8128 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get()); 8129 if (!Diff.isUsable()) 8130 return nullptr; 8131 8132 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get()); 8133 if (!Diff.isUsable()) 8134 return nullptr; 8135 8136 // Upper - (Lower - Step [+ 1]). 8137 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Diff.get()); 8138 if (!Diff.isUsable()) 8139 return nullptr; 8140 } else { 8141 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower); 8142 8143 if (!Diff.isUsable() && LCTy->getAsCXXRecordDecl()) { 8144 // BuildBinOp already emitted error, this one is to point user to upper 8145 // and lower bound, and to tell what is passed to 'operator-'. 8146 SemaRef.Diag(Upper->getBeginLoc(), diag::err_omp_loop_diff_cxx) 8147 << Upper->getSourceRange() << Lower->getSourceRange(); 8148 return nullptr; 8149 } 8150 8151 if (!Diff.isUsable()) 8152 return nullptr; 8153 8154 // Upper - Lower [- 1] 8155 if (TestIsStrictOp) 8156 Diff = SemaRef.BuildBinOp( 8157 S, DefaultLoc, BO_Sub, Diff.get(), 8158 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get()); 8159 if (!Diff.isUsable()) 8160 return nullptr; 8161 8162 if (RoundToStep) { 8163 // Upper - Lower [- 1] + Step 8164 Diff = 8165 SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get()); 8166 if (!Diff.isUsable()) 8167 return nullptr; 8168 } 8169 } 8170 8171 // Parentheses (for dumping/debugging purposes only). 8172 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get()); 8173 if (!Diff.isUsable()) 8174 return nullptr; 8175 8176 // (Upper - Lower [- 1] + Step) / Step or (Upper - Lower) / Step 8177 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get()); 8178 if (!Diff.isUsable()) 8179 return nullptr; 8180 8181 return Diff.get(); 8182 } 8183 8184 /// Build the expression to calculate the number of iterations. 8185 Expr *OpenMPIterationSpaceChecker::buildNumIterations( 8186 Scope *S, ArrayRef<LoopIterationSpace> ResultIterSpaces, bool LimitedType, 8187 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const { 8188 QualType VarType = LCDecl->getType().getNonReferenceType(); 8189 if (!VarType->isIntegerType() && !VarType->isPointerType() && 8190 !SemaRef.getLangOpts().CPlusPlus) 8191 return nullptr; 8192 Expr *LBVal = LB; 8193 Expr *UBVal = UB; 8194 // LB = TestIsLessOp.getValue() ? min(LB(MinVal), LB(MaxVal)) : 8195 // max(LB(MinVal), LB(MaxVal)) 8196 if (InitDependOnLC) { 8197 const LoopIterationSpace &IS = ResultIterSpaces[*InitDependOnLC - 1]; 8198 if (!IS.MinValue || !IS.MaxValue) 8199 return nullptr; 8200 // OuterVar = Min 8201 ExprResult MinValue = 8202 SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MinValue); 8203 if (!MinValue.isUsable()) 8204 return nullptr; 8205 8206 ExprResult LBMinVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign, 8207 IS.CounterVar, MinValue.get()); 8208 if (!LBMinVal.isUsable()) 8209 return nullptr; 8210 // OuterVar = Min, LBVal 8211 LBMinVal = 8212 SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, LBMinVal.get(), LBVal); 8213 if (!LBMinVal.isUsable()) 8214 return nullptr; 8215 // (OuterVar = Min, LBVal) 8216 LBMinVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, LBMinVal.get()); 8217 if (!LBMinVal.isUsable()) 8218 return nullptr; 8219 8220 // OuterVar = Max 8221 ExprResult MaxValue = 8222 SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MaxValue); 8223 if (!MaxValue.isUsable()) 8224 return nullptr; 8225 8226 ExprResult LBMaxVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign, 8227 IS.CounterVar, MaxValue.get()); 8228 if (!LBMaxVal.isUsable()) 8229 return nullptr; 8230 // OuterVar = Max, LBVal 8231 LBMaxVal = 8232 SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, LBMaxVal.get(), LBVal); 8233 if (!LBMaxVal.isUsable()) 8234 return nullptr; 8235 // (OuterVar = Max, LBVal) 8236 LBMaxVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, LBMaxVal.get()); 8237 if (!LBMaxVal.isUsable()) 8238 return nullptr; 8239 8240 Expr *LBMin = tryBuildCapture(SemaRef, LBMinVal.get(), Captures).get(); 8241 Expr *LBMax = tryBuildCapture(SemaRef, LBMaxVal.get(), Captures).get(); 8242 if (!LBMin || !LBMax) 8243 return nullptr; 8244 // LB(MinVal) < LB(MaxVal) 8245 ExprResult MinLessMaxRes = 8246 SemaRef.BuildBinOp(S, DefaultLoc, BO_LT, LBMin, LBMax); 8247 if (!MinLessMaxRes.isUsable()) 8248 return nullptr; 8249 Expr *MinLessMax = 8250 tryBuildCapture(SemaRef, MinLessMaxRes.get(), Captures).get(); 8251 if (!MinLessMax) 8252 return nullptr; 8253 if (TestIsLessOp.getValue()) { 8254 // LB(MinVal) < LB(MaxVal) ? LB(MinVal) : LB(MaxVal) - min(LB(MinVal), 8255 // LB(MaxVal)) 8256 ExprResult MinLB = SemaRef.ActOnConditionalOp(DefaultLoc, DefaultLoc, 8257 MinLessMax, LBMin, LBMax); 8258 if (!MinLB.isUsable()) 8259 return nullptr; 8260 LBVal = MinLB.get(); 8261 } else { 8262 // LB(MinVal) < LB(MaxVal) ? LB(MaxVal) : LB(MinVal) - max(LB(MinVal), 8263 // LB(MaxVal)) 8264 ExprResult MaxLB = SemaRef.ActOnConditionalOp(DefaultLoc, DefaultLoc, 8265 MinLessMax, LBMax, LBMin); 8266 if (!MaxLB.isUsable()) 8267 return nullptr; 8268 LBVal = MaxLB.get(); 8269 } 8270 } 8271 // UB = TestIsLessOp.getValue() ? max(UB(MinVal), UB(MaxVal)) : 8272 // min(UB(MinVal), UB(MaxVal)) 8273 if (CondDependOnLC) { 8274 const LoopIterationSpace &IS = ResultIterSpaces[*CondDependOnLC - 1]; 8275 if (!IS.MinValue || !IS.MaxValue) 8276 return nullptr; 8277 // OuterVar = Min 8278 ExprResult MinValue = 8279 SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MinValue); 8280 if (!MinValue.isUsable()) 8281 return nullptr; 8282 8283 ExprResult UBMinVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign, 8284 IS.CounterVar, MinValue.get()); 8285 if (!UBMinVal.isUsable()) 8286 return nullptr; 8287 // OuterVar = Min, UBVal 8288 UBMinVal = 8289 SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, UBMinVal.get(), UBVal); 8290 if (!UBMinVal.isUsable()) 8291 return nullptr; 8292 // (OuterVar = Min, UBVal) 8293 UBMinVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, UBMinVal.get()); 8294 if (!UBMinVal.isUsable()) 8295 return nullptr; 8296 8297 // OuterVar = Max 8298 ExprResult MaxValue = 8299 SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MaxValue); 8300 if (!MaxValue.isUsable()) 8301 return nullptr; 8302 8303 ExprResult UBMaxVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign, 8304 IS.CounterVar, MaxValue.get()); 8305 if (!UBMaxVal.isUsable()) 8306 return nullptr; 8307 // OuterVar = Max, UBVal 8308 UBMaxVal = 8309 SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, UBMaxVal.get(), UBVal); 8310 if (!UBMaxVal.isUsable()) 8311 return nullptr; 8312 // (OuterVar = Max, UBVal) 8313 UBMaxVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, UBMaxVal.get()); 8314 if (!UBMaxVal.isUsable()) 8315 return nullptr; 8316 8317 Expr *UBMin = tryBuildCapture(SemaRef, UBMinVal.get(), Captures).get(); 8318 Expr *UBMax = tryBuildCapture(SemaRef, UBMaxVal.get(), Captures).get(); 8319 if (!UBMin || !UBMax) 8320 return nullptr; 8321 // UB(MinVal) > UB(MaxVal) 8322 ExprResult MinGreaterMaxRes = 8323 SemaRef.BuildBinOp(S, DefaultLoc, BO_GT, UBMin, UBMax); 8324 if (!MinGreaterMaxRes.isUsable()) 8325 return nullptr; 8326 Expr *MinGreaterMax = 8327 tryBuildCapture(SemaRef, MinGreaterMaxRes.get(), Captures).get(); 8328 if (!MinGreaterMax) 8329 return nullptr; 8330 if (TestIsLessOp.getValue()) { 8331 // UB(MinVal) > UB(MaxVal) ? UB(MinVal) : UB(MaxVal) - max(UB(MinVal), 8332 // UB(MaxVal)) 8333 ExprResult MaxUB = SemaRef.ActOnConditionalOp( 8334 DefaultLoc, DefaultLoc, MinGreaterMax, UBMin, UBMax); 8335 if (!MaxUB.isUsable()) 8336 return nullptr; 8337 UBVal = MaxUB.get(); 8338 } else { 8339 // UB(MinVal) > UB(MaxVal) ? UB(MaxVal) : UB(MinVal) - min(UB(MinVal), 8340 // UB(MaxVal)) 8341 ExprResult MinUB = SemaRef.ActOnConditionalOp( 8342 DefaultLoc, DefaultLoc, MinGreaterMax, UBMax, UBMin); 8343 if (!MinUB.isUsable()) 8344 return nullptr; 8345 UBVal = MinUB.get(); 8346 } 8347 } 8348 Expr *UBExpr = TestIsLessOp.getValue() ? UBVal : LBVal; 8349 Expr *LBExpr = TestIsLessOp.getValue() ? LBVal : UBVal; 8350 Expr *Upper = tryBuildCapture(SemaRef, UBExpr, Captures).get(); 8351 Expr *Lower = tryBuildCapture(SemaRef, LBExpr, Captures).get(); 8352 if (!Upper || !Lower) 8353 return nullptr; 8354 8355 ExprResult Diff = calculateNumIters(SemaRef, S, DefaultLoc, Lower, Upper, 8356 Step, VarType, TestIsStrictOp, 8357 /*RoundToStep=*/true, Captures); 8358 if (!Diff.isUsable()) 8359 return nullptr; 8360 8361 // OpenMP runtime requires 32-bit or 64-bit loop variables. 8362 QualType Type = Diff.get()->getType(); 8363 ASTContext &C = SemaRef.Context; 8364 bool UseVarType = VarType->hasIntegerRepresentation() && 8365 C.getTypeSize(Type) > C.getTypeSize(VarType); 8366 if (!Type->isIntegerType() || UseVarType) { 8367 unsigned NewSize = 8368 UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type); 8369 bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation() 8370 : Type->hasSignedIntegerRepresentation(); 8371 Type = C.getIntTypeForBitwidth(NewSize, IsSigned); 8372 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), Type)) { 8373 Diff = SemaRef.PerformImplicitConversion( 8374 Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true); 8375 if (!Diff.isUsable()) 8376 return nullptr; 8377 } 8378 } 8379 if (LimitedType) { 8380 unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32; 8381 if (NewSize != C.getTypeSize(Type)) { 8382 if (NewSize < C.getTypeSize(Type)) { 8383 assert(NewSize == 64 && "incorrect loop var size"); 8384 SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var) 8385 << InitSrcRange << ConditionSrcRange; 8386 } 8387 QualType NewType = C.getIntTypeForBitwidth( 8388 NewSize, Type->hasSignedIntegerRepresentation() || 8389 C.getTypeSize(Type) < NewSize); 8390 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), NewType)) { 8391 Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType, 8392 Sema::AA_Converting, true); 8393 if (!Diff.isUsable()) 8394 return nullptr; 8395 } 8396 } 8397 } 8398 8399 return Diff.get(); 8400 } 8401 8402 std::pair<Expr *, Expr *> OpenMPIterationSpaceChecker::buildMinMaxValues( 8403 Scope *S, llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const { 8404 // Do not build for iterators, they cannot be used in non-rectangular loop 8405 // nests. 8406 if (LCDecl->getType()->isRecordType()) 8407 return std::make_pair(nullptr, nullptr); 8408 // If we subtract, the min is in the condition, otherwise the min is in the 8409 // init value. 8410 Expr *MinExpr = nullptr; 8411 Expr *MaxExpr = nullptr; 8412 Expr *LBExpr = TestIsLessOp.getValue() ? LB : UB; 8413 Expr *UBExpr = TestIsLessOp.getValue() ? UB : LB; 8414 bool LBNonRect = TestIsLessOp.getValue() ? InitDependOnLC.hasValue() 8415 : CondDependOnLC.hasValue(); 8416 bool UBNonRect = TestIsLessOp.getValue() ? CondDependOnLC.hasValue() 8417 : InitDependOnLC.hasValue(); 8418 Expr *Lower = 8419 LBNonRect ? LBExpr : tryBuildCapture(SemaRef, LBExpr, Captures).get(); 8420 Expr *Upper = 8421 UBNonRect ? UBExpr : tryBuildCapture(SemaRef, UBExpr, Captures).get(); 8422 if (!Upper || !Lower) 8423 return std::make_pair(nullptr, nullptr); 8424 8425 if (TestIsLessOp.getValue()) 8426 MinExpr = Lower; 8427 else 8428 MaxExpr = Upper; 8429 8430 // Build minimum/maximum value based on number of iterations. 8431 QualType VarType = LCDecl->getType().getNonReferenceType(); 8432 8433 ExprResult Diff = calculateNumIters(SemaRef, S, DefaultLoc, Lower, Upper, 8434 Step, VarType, TestIsStrictOp, 8435 /*RoundToStep=*/false, Captures); 8436 if (!Diff.isUsable()) 8437 return std::make_pair(nullptr, nullptr); 8438 8439 // ((Upper - Lower [- 1]) / Step) * Step 8440 // Parentheses (for dumping/debugging purposes only). 8441 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get()); 8442 if (!Diff.isUsable()) 8443 return std::make_pair(nullptr, nullptr); 8444 8445 ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures); 8446 if (!NewStep.isUsable()) 8447 return std::make_pair(nullptr, nullptr); 8448 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Mul, Diff.get(), NewStep.get()); 8449 if (!Diff.isUsable()) 8450 return std::make_pair(nullptr, nullptr); 8451 8452 // Parentheses (for dumping/debugging purposes only). 8453 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get()); 8454 if (!Diff.isUsable()) 8455 return std::make_pair(nullptr, nullptr); 8456 8457 // Convert to the ptrdiff_t, if original type is pointer. 8458 if (VarType->isAnyPointerType() && 8459 !SemaRef.Context.hasSameType( 8460 Diff.get()->getType(), 8461 SemaRef.Context.getUnsignedPointerDiffType())) { 8462 Diff = SemaRef.PerformImplicitConversion( 8463 Diff.get(), SemaRef.Context.getUnsignedPointerDiffType(), 8464 Sema::AA_Converting, /*AllowExplicit=*/true); 8465 } 8466 if (!Diff.isUsable()) 8467 return std::make_pair(nullptr, nullptr); 8468 8469 if (TestIsLessOp.getValue()) { 8470 // MinExpr = Lower; 8471 // MaxExpr = Lower + (((Upper - Lower [- 1]) / Step) * Step) 8472 Diff = SemaRef.BuildBinOp( 8473 S, DefaultLoc, BO_Add, 8474 SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Lower).get(), 8475 Diff.get()); 8476 if (!Diff.isUsable()) 8477 return std::make_pair(nullptr, nullptr); 8478 } else { 8479 // MaxExpr = Upper; 8480 // MinExpr = Upper - (((Upper - Lower [- 1]) / Step) * Step) 8481 Diff = SemaRef.BuildBinOp( 8482 S, DefaultLoc, BO_Sub, 8483 SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Upper).get(), 8484 Diff.get()); 8485 if (!Diff.isUsable()) 8486 return std::make_pair(nullptr, nullptr); 8487 } 8488 8489 // Convert to the original type. 8490 if (SemaRef.Context.hasSameType(Diff.get()->getType(), VarType)) 8491 Diff = SemaRef.PerformImplicitConversion(Diff.get(), VarType, 8492 Sema::AA_Converting, 8493 /*AllowExplicit=*/true); 8494 if (!Diff.isUsable()) 8495 return std::make_pair(nullptr, nullptr); 8496 8497 Sema::TentativeAnalysisScope Trap(SemaRef); 8498 Diff = SemaRef.ActOnFinishFullExpr(Diff.get(), /*DiscardedValue=*/false); 8499 if (!Diff.isUsable()) 8500 return std::make_pair(nullptr, nullptr); 8501 8502 if (TestIsLessOp.getValue()) 8503 MaxExpr = Diff.get(); 8504 else 8505 MinExpr = Diff.get(); 8506 8507 return std::make_pair(MinExpr, MaxExpr); 8508 } 8509 8510 Expr *OpenMPIterationSpaceChecker::buildFinalCondition(Scope *S) const { 8511 if (InitDependOnLC || CondDependOnLC) 8512 return Condition; 8513 return nullptr; 8514 } 8515 8516 Expr *OpenMPIterationSpaceChecker::buildPreCond( 8517 Scope *S, Expr *Cond, 8518 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const { 8519 // Do not build a precondition when the condition/initialization is dependent 8520 // to prevent pessimistic early loop exit. 8521 // TODO: this can be improved by calculating min/max values but not sure that 8522 // it will be very effective. 8523 if (CondDependOnLC || InitDependOnLC) 8524 return SemaRef.PerformImplicitConversion( 8525 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get(), 8526 SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting, 8527 /*AllowExplicit=*/true).get(); 8528 8529 // Try to build LB <op> UB, where <op> is <, >, <=, or >=. 8530 Sema::TentativeAnalysisScope Trap(SemaRef); 8531 8532 ExprResult NewLB = tryBuildCapture(SemaRef, LB, Captures); 8533 ExprResult NewUB = tryBuildCapture(SemaRef, UB, Captures); 8534 if (!NewLB.isUsable() || !NewUB.isUsable()) 8535 return nullptr; 8536 8537 ExprResult CondExpr = 8538 SemaRef.BuildBinOp(S, DefaultLoc, 8539 TestIsLessOp.getValue() ? 8540 (TestIsStrictOp ? BO_LT : BO_LE) : 8541 (TestIsStrictOp ? BO_GT : BO_GE), 8542 NewLB.get(), NewUB.get()); 8543 if (CondExpr.isUsable()) { 8544 if (!SemaRef.Context.hasSameUnqualifiedType(CondExpr.get()->getType(), 8545 SemaRef.Context.BoolTy)) 8546 CondExpr = SemaRef.PerformImplicitConversion( 8547 CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting, 8548 /*AllowExplicit=*/true); 8549 } 8550 8551 // Otherwise use original loop condition and evaluate it in runtime. 8552 return CondExpr.isUsable() ? CondExpr.get() : Cond; 8553 } 8554 8555 /// Build reference expression to the counter be used for codegen. 8556 DeclRefExpr *OpenMPIterationSpaceChecker::buildCounterVar( 8557 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures, 8558 DSAStackTy &DSA) const { 8559 auto *VD = dyn_cast<VarDecl>(LCDecl); 8560 if (!VD) { 8561 VD = SemaRef.isOpenMPCapturedDecl(LCDecl); 8562 DeclRefExpr *Ref = buildDeclRefExpr( 8563 SemaRef, VD, VD->getType().getNonReferenceType(), DefaultLoc); 8564 const DSAStackTy::DSAVarData Data = 8565 DSA.getTopDSA(LCDecl, /*FromParent=*/false); 8566 // If the loop control decl is explicitly marked as private, do not mark it 8567 // as captured again. 8568 if (!isOpenMPPrivate(Data.CKind) || !Data.RefExpr) 8569 Captures.insert(std::make_pair(LCRef, Ref)); 8570 return Ref; 8571 } 8572 return cast<DeclRefExpr>(LCRef); 8573 } 8574 8575 Expr *OpenMPIterationSpaceChecker::buildPrivateCounterVar() const { 8576 if (LCDecl && !LCDecl->isInvalidDecl()) { 8577 QualType Type = LCDecl->getType().getNonReferenceType(); 8578 VarDecl *PrivateVar = buildVarDecl( 8579 SemaRef, DefaultLoc, Type, LCDecl->getName(), 8580 LCDecl->hasAttrs() ? &LCDecl->getAttrs() : nullptr, 8581 isa<VarDecl>(LCDecl) 8582 ? buildDeclRefExpr(SemaRef, cast<VarDecl>(LCDecl), Type, DefaultLoc) 8583 : nullptr); 8584 if (PrivateVar->isInvalidDecl()) 8585 return nullptr; 8586 return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc); 8587 } 8588 return nullptr; 8589 } 8590 8591 /// Build initialization of the counter to be used for codegen. 8592 Expr *OpenMPIterationSpaceChecker::buildCounterInit() const { return LB; } 8593 8594 /// Build step of the counter be used for codegen. 8595 Expr *OpenMPIterationSpaceChecker::buildCounterStep() const { return Step; } 8596 8597 Expr *OpenMPIterationSpaceChecker::buildOrderedLoopData( 8598 Scope *S, Expr *Counter, 8599 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures, SourceLocation Loc, 8600 Expr *Inc, OverloadedOperatorKind OOK) { 8601 Expr *Cnt = SemaRef.DefaultLvalueConversion(Counter).get(); 8602 if (!Cnt) 8603 return nullptr; 8604 if (Inc) { 8605 assert((OOK == OO_Plus || OOK == OO_Minus) && 8606 "Expected only + or - operations for depend clauses."); 8607 BinaryOperatorKind BOK = (OOK == OO_Plus) ? BO_Add : BO_Sub; 8608 Cnt = SemaRef.BuildBinOp(S, Loc, BOK, Cnt, Inc).get(); 8609 if (!Cnt) 8610 return nullptr; 8611 } 8612 QualType VarType = LCDecl->getType().getNonReferenceType(); 8613 if (!VarType->isIntegerType() && !VarType->isPointerType() && 8614 !SemaRef.getLangOpts().CPlusPlus) 8615 return nullptr; 8616 // Upper - Lower 8617 Expr *Upper = TestIsLessOp.getValue() 8618 ? Cnt 8619 : tryBuildCapture(SemaRef, LB, Captures).get(); 8620 Expr *Lower = TestIsLessOp.getValue() 8621 ? tryBuildCapture(SemaRef, LB, Captures).get() 8622 : Cnt; 8623 if (!Upper || !Lower) 8624 return nullptr; 8625 8626 ExprResult Diff = calculateNumIters( 8627 SemaRef, S, DefaultLoc, Lower, Upper, Step, VarType, 8628 /*TestIsStrictOp=*/false, /*RoundToStep=*/false, Captures); 8629 if (!Diff.isUsable()) 8630 return nullptr; 8631 8632 return Diff.get(); 8633 } 8634 } // namespace 8635 8636 void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) { 8637 assert(getLangOpts().OpenMP && "OpenMP is not active."); 8638 assert(Init && "Expected loop in canonical form."); 8639 unsigned AssociatedLoops = DSAStack->getAssociatedLoops(); 8640 if (AssociatedLoops > 0 && 8641 isOpenMPLoopDirective(DSAStack->getCurrentDirective())) { 8642 DSAStack->loopStart(); 8643 OpenMPIterationSpaceChecker ISC(*this, /*SupportsNonRectangular=*/true, 8644 *DSAStack, ForLoc); 8645 if (!ISC.checkAndSetInit(Init, /*EmitDiags=*/false)) { 8646 if (ValueDecl *D = ISC.getLoopDecl()) { 8647 auto *VD = dyn_cast<VarDecl>(D); 8648 DeclRefExpr *PrivateRef = nullptr; 8649 if (!VD) { 8650 if (VarDecl *Private = isOpenMPCapturedDecl(D)) { 8651 VD = Private; 8652 } else { 8653 PrivateRef = buildCapture(*this, D, ISC.getLoopDeclRefExpr(), 8654 /*WithInit=*/false); 8655 VD = cast<VarDecl>(PrivateRef->getDecl()); 8656 } 8657 } 8658 DSAStack->addLoopControlVariable(D, VD); 8659 const Decl *LD = DSAStack->getPossiblyLoopCunter(); 8660 if (LD != D->getCanonicalDecl()) { 8661 DSAStack->resetPossibleLoopCounter(); 8662 if (auto *Var = dyn_cast_or_null<VarDecl>(LD)) 8663 MarkDeclarationsReferencedInExpr( 8664 buildDeclRefExpr(*this, const_cast<VarDecl *>(Var), 8665 Var->getType().getNonLValueExprType(Context), 8666 ForLoc, /*RefersToCapture=*/true)); 8667 } 8668 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective(); 8669 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables 8670 // Referenced in a Construct, C/C++]. The loop iteration variable in the 8671 // associated for-loop of a simd construct with just one associated 8672 // for-loop may be listed in a linear clause with a constant-linear-step 8673 // that is the increment of the associated for-loop. The loop iteration 8674 // variable(s) in the associated for-loop(s) of a for or parallel for 8675 // construct may be listed in a private or lastprivate clause. 8676 DSAStackTy::DSAVarData DVar = 8677 DSAStack->getTopDSA(D, /*FromParent=*/false); 8678 // If LoopVarRefExpr is nullptr it means the corresponding loop variable 8679 // is declared in the loop and it is predetermined as a private. 8680 Expr *LoopDeclRefExpr = ISC.getLoopDeclRefExpr(); 8681 OpenMPClauseKind PredeterminedCKind = 8682 isOpenMPSimdDirective(DKind) 8683 ? (DSAStack->hasMutipleLoops() ? OMPC_lastprivate : OMPC_linear) 8684 : OMPC_private; 8685 if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown && 8686 DVar.CKind != PredeterminedCKind && DVar.RefExpr && 8687 (LangOpts.OpenMP <= 45 || (DVar.CKind != OMPC_lastprivate && 8688 DVar.CKind != OMPC_private))) || 8689 ((isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop || 8690 DKind == OMPD_master_taskloop || 8691 DKind == OMPD_parallel_master_taskloop || 8692 isOpenMPDistributeDirective(DKind)) && 8693 !isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown && 8694 DVar.CKind != OMPC_private && DVar.CKind != OMPC_lastprivate)) && 8695 (DVar.CKind != OMPC_private || DVar.RefExpr)) { 8696 Diag(Init->getBeginLoc(), diag::err_omp_loop_var_dsa) 8697 << getOpenMPClauseName(DVar.CKind) 8698 << getOpenMPDirectiveName(DKind) 8699 << getOpenMPClauseName(PredeterminedCKind); 8700 if (DVar.RefExpr == nullptr) 8701 DVar.CKind = PredeterminedCKind; 8702 reportOriginalDsa(*this, DSAStack, D, DVar, 8703 /*IsLoopIterVar=*/true); 8704 } else if (LoopDeclRefExpr) { 8705 // Make the loop iteration variable private (for worksharing 8706 // constructs), linear (for simd directives with the only one 8707 // associated loop) or lastprivate (for simd directives with several 8708 // collapsed or ordered loops). 8709 if (DVar.CKind == OMPC_unknown) 8710 DSAStack->addDSA(D, LoopDeclRefExpr, PredeterminedCKind, 8711 PrivateRef); 8712 } 8713 } 8714 } 8715 DSAStack->setAssociatedLoops(AssociatedLoops - 1); 8716 } 8717 } 8718 8719 /// Called on a for stmt to check and extract its iteration space 8720 /// for further processing (such as collapsing). 8721 static bool checkOpenMPIterationSpace( 8722 OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA, 8723 unsigned CurrentNestedLoopCount, unsigned NestedLoopCount, 8724 unsigned TotalNestedLoopCount, Expr *CollapseLoopCountExpr, 8725 Expr *OrderedLoopCountExpr, 8726 Sema::VarsWithInheritedDSAType &VarsWithImplicitDSA, 8727 llvm::MutableArrayRef<LoopIterationSpace> ResultIterSpaces, 8728 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) { 8729 bool SupportsNonRectangular = !isOpenMPLoopTransformationDirective(DKind); 8730 // OpenMP [2.9.1, Canonical Loop Form] 8731 // for (init-expr; test-expr; incr-expr) structured-block 8732 // for (range-decl: range-expr) structured-block 8733 if (auto *CanonLoop = dyn_cast_or_null<OMPCanonicalLoop>(S)) 8734 S = CanonLoop->getLoopStmt(); 8735 auto *For = dyn_cast_or_null<ForStmt>(S); 8736 auto *CXXFor = dyn_cast_or_null<CXXForRangeStmt>(S); 8737 // Ranged for is supported only in OpenMP 5.0. 8738 if (!For && (SemaRef.LangOpts.OpenMP <= 45 || !CXXFor)) { 8739 SemaRef.Diag(S->getBeginLoc(), diag::err_omp_not_for) 8740 << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr) 8741 << getOpenMPDirectiveName(DKind) << TotalNestedLoopCount 8742 << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount; 8743 if (TotalNestedLoopCount > 1) { 8744 if (CollapseLoopCountExpr && OrderedLoopCountExpr) 8745 SemaRef.Diag(DSA.getConstructLoc(), 8746 diag::note_omp_collapse_ordered_expr) 8747 << 2 << CollapseLoopCountExpr->getSourceRange() 8748 << OrderedLoopCountExpr->getSourceRange(); 8749 else if (CollapseLoopCountExpr) 8750 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(), 8751 diag::note_omp_collapse_ordered_expr) 8752 << 0 << CollapseLoopCountExpr->getSourceRange(); 8753 else 8754 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(), 8755 diag::note_omp_collapse_ordered_expr) 8756 << 1 << OrderedLoopCountExpr->getSourceRange(); 8757 } 8758 return true; 8759 } 8760 assert(((For && For->getBody()) || (CXXFor && CXXFor->getBody())) && 8761 "No loop body."); 8762 8763 OpenMPIterationSpaceChecker ISC(SemaRef, SupportsNonRectangular, DSA, 8764 For ? For->getForLoc() : CXXFor->getForLoc()); 8765 8766 // Check init. 8767 Stmt *Init = For ? For->getInit() : CXXFor->getBeginStmt(); 8768 if (ISC.checkAndSetInit(Init)) 8769 return true; 8770 8771 bool HasErrors = false; 8772 8773 // Check loop variable's type. 8774 if (ValueDecl *LCDecl = ISC.getLoopDecl()) { 8775 // OpenMP [2.6, Canonical Loop Form] 8776 // Var is one of the following: 8777 // A variable of signed or unsigned integer type. 8778 // For C++, a variable of a random access iterator type. 8779 // For C, a variable of a pointer type. 8780 QualType VarType = LCDecl->getType().getNonReferenceType(); 8781 if (!VarType->isDependentType() && !VarType->isIntegerType() && 8782 !VarType->isPointerType() && 8783 !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) { 8784 SemaRef.Diag(Init->getBeginLoc(), diag::err_omp_loop_variable_type) 8785 << SemaRef.getLangOpts().CPlusPlus; 8786 HasErrors = true; 8787 } 8788 8789 // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in 8790 // a Construct 8791 // The loop iteration variable(s) in the associated for-loop(s) of a for or 8792 // parallel for construct is (are) private. 8793 // The loop iteration variable in the associated for-loop of a simd 8794 // construct with just one associated for-loop is linear with a 8795 // constant-linear-step that is the increment of the associated for-loop. 8796 // Exclude loop var from the list of variables with implicitly defined data 8797 // sharing attributes. 8798 VarsWithImplicitDSA.erase(LCDecl); 8799 8800 assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars"); 8801 8802 // Check test-expr. 8803 HasErrors |= ISC.checkAndSetCond(For ? For->getCond() : CXXFor->getCond()); 8804 8805 // Check incr-expr. 8806 HasErrors |= ISC.checkAndSetInc(For ? For->getInc() : CXXFor->getInc()); 8807 } 8808 8809 if (ISC.dependent() || SemaRef.CurContext->isDependentContext() || HasErrors) 8810 return HasErrors; 8811 8812 // Build the loop's iteration space representation. 8813 ResultIterSpaces[CurrentNestedLoopCount].PreCond = ISC.buildPreCond( 8814 DSA.getCurScope(), For ? For->getCond() : CXXFor->getCond(), Captures); 8815 ResultIterSpaces[CurrentNestedLoopCount].NumIterations = 8816 ISC.buildNumIterations(DSA.getCurScope(), ResultIterSpaces, 8817 (isOpenMPWorksharingDirective(DKind) || 8818 isOpenMPTaskLoopDirective(DKind) || 8819 isOpenMPDistributeDirective(DKind) || 8820 isOpenMPLoopTransformationDirective(DKind)), 8821 Captures); 8822 ResultIterSpaces[CurrentNestedLoopCount].CounterVar = 8823 ISC.buildCounterVar(Captures, DSA); 8824 ResultIterSpaces[CurrentNestedLoopCount].PrivateCounterVar = 8825 ISC.buildPrivateCounterVar(); 8826 ResultIterSpaces[CurrentNestedLoopCount].CounterInit = ISC.buildCounterInit(); 8827 ResultIterSpaces[CurrentNestedLoopCount].CounterStep = ISC.buildCounterStep(); 8828 ResultIterSpaces[CurrentNestedLoopCount].InitSrcRange = ISC.getInitSrcRange(); 8829 ResultIterSpaces[CurrentNestedLoopCount].CondSrcRange = 8830 ISC.getConditionSrcRange(); 8831 ResultIterSpaces[CurrentNestedLoopCount].IncSrcRange = 8832 ISC.getIncrementSrcRange(); 8833 ResultIterSpaces[CurrentNestedLoopCount].Subtract = ISC.shouldSubtractStep(); 8834 ResultIterSpaces[CurrentNestedLoopCount].IsStrictCompare = 8835 ISC.isStrictTestOp(); 8836 std::tie(ResultIterSpaces[CurrentNestedLoopCount].MinValue, 8837 ResultIterSpaces[CurrentNestedLoopCount].MaxValue) = 8838 ISC.buildMinMaxValues(DSA.getCurScope(), Captures); 8839 ResultIterSpaces[CurrentNestedLoopCount].FinalCondition = 8840 ISC.buildFinalCondition(DSA.getCurScope()); 8841 ResultIterSpaces[CurrentNestedLoopCount].IsNonRectangularLB = 8842 ISC.doesInitDependOnLC(); 8843 ResultIterSpaces[CurrentNestedLoopCount].IsNonRectangularUB = 8844 ISC.doesCondDependOnLC(); 8845 ResultIterSpaces[CurrentNestedLoopCount].LoopDependentIdx = 8846 ISC.getLoopDependentIdx(); 8847 8848 HasErrors |= 8849 (ResultIterSpaces[CurrentNestedLoopCount].PreCond == nullptr || 8850 ResultIterSpaces[CurrentNestedLoopCount].NumIterations == nullptr || 8851 ResultIterSpaces[CurrentNestedLoopCount].CounterVar == nullptr || 8852 ResultIterSpaces[CurrentNestedLoopCount].PrivateCounterVar == nullptr || 8853 ResultIterSpaces[CurrentNestedLoopCount].CounterInit == nullptr || 8854 ResultIterSpaces[CurrentNestedLoopCount].CounterStep == nullptr); 8855 if (!HasErrors && DSA.isOrderedRegion()) { 8856 if (DSA.getOrderedRegionParam().second->getNumForLoops()) { 8857 if (CurrentNestedLoopCount < 8858 DSA.getOrderedRegionParam().second->getLoopNumIterations().size()) { 8859 DSA.getOrderedRegionParam().second->setLoopNumIterations( 8860 CurrentNestedLoopCount, 8861 ResultIterSpaces[CurrentNestedLoopCount].NumIterations); 8862 DSA.getOrderedRegionParam().second->setLoopCounter( 8863 CurrentNestedLoopCount, 8864 ResultIterSpaces[CurrentNestedLoopCount].CounterVar); 8865 } 8866 } 8867 for (auto &Pair : DSA.getDoacrossDependClauses()) { 8868 if (CurrentNestedLoopCount >= Pair.first->getNumLoops()) { 8869 // Erroneous case - clause has some problems. 8870 continue; 8871 } 8872 if (Pair.first->getDependencyKind() == OMPC_DEPEND_sink && 8873 Pair.second.size() <= CurrentNestedLoopCount) { 8874 // Erroneous case - clause has some problems. 8875 Pair.first->setLoopData(CurrentNestedLoopCount, nullptr); 8876 continue; 8877 } 8878 Expr *CntValue; 8879 if (Pair.first->getDependencyKind() == OMPC_DEPEND_source) 8880 CntValue = ISC.buildOrderedLoopData( 8881 DSA.getCurScope(), 8882 ResultIterSpaces[CurrentNestedLoopCount].CounterVar, Captures, 8883 Pair.first->getDependencyLoc()); 8884 else 8885 CntValue = ISC.buildOrderedLoopData( 8886 DSA.getCurScope(), 8887 ResultIterSpaces[CurrentNestedLoopCount].CounterVar, Captures, 8888 Pair.first->getDependencyLoc(), 8889 Pair.second[CurrentNestedLoopCount].first, 8890 Pair.second[CurrentNestedLoopCount].second); 8891 Pair.first->setLoopData(CurrentNestedLoopCount, CntValue); 8892 } 8893 } 8894 8895 return HasErrors; 8896 } 8897 8898 /// Build 'VarRef = Start. 8899 static ExprResult 8900 buildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef, 8901 ExprResult Start, bool IsNonRectangularLB, 8902 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) { 8903 // Build 'VarRef = Start. 8904 ExprResult NewStart = IsNonRectangularLB 8905 ? Start.get() 8906 : tryBuildCapture(SemaRef, Start.get(), Captures); 8907 if (!NewStart.isUsable()) 8908 return ExprError(); 8909 if (!SemaRef.Context.hasSameType(NewStart.get()->getType(), 8910 VarRef.get()->getType())) { 8911 NewStart = SemaRef.PerformImplicitConversion( 8912 NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting, 8913 /*AllowExplicit=*/true); 8914 if (!NewStart.isUsable()) 8915 return ExprError(); 8916 } 8917 8918 ExprResult Init = 8919 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get()); 8920 return Init; 8921 } 8922 8923 /// Build 'VarRef = Start + Iter * Step'. 8924 static ExprResult buildCounterUpdate( 8925 Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef, 8926 ExprResult Start, ExprResult Iter, ExprResult Step, bool Subtract, 8927 bool IsNonRectangularLB, 8928 llvm::MapVector<const Expr *, DeclRefExpr *> *Captures = nullptr) { 8929 // Add parentheses (for debugging purposes only). 8930 Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get()); 8931 if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() || 8932 !Step.isUsable()) 8933 return ExprError(); 8934 8935 ExprResult NewStep = Step; 8936 if (Captures) 8937 NewStep = tryBuildCapture(SemaRef, Step.get(), *Captures); 8938 if (NewStep.isInvalid()) 8939 return ExprError(); 8940 ExprResult Update = 8941 SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get()); 8942 if (!Update.isUsable()) 8943 return ExprError(); 8944 8945 // Try to build 'VarRef = Start, VarRef (+|-)= Iter * Step' or 8946 // 'VarRef = Start (+|-) Iter * Step'. 8947 if (!Start.isUsable()) 8948 return ExprError(); 8949 ExprResult NewStart = SemaRef.ActOnParenExpr(Loc, Loc, Start.get()); 8950 if (!NewStart.isUsable()) 8951 return ExprError(); 8952 if (Captures && !IsNonRectangularLB) 8953 NewStart = tryBuildCapture(SemaRef, Start.get(), *Captures); 8954 if (NewStart.isInvalid()) 8955 return ExprError(); 8956 8957 // First attempt: try to build 'VarRef = Start, VarRef += Iter * Step'. 8958 ExprResult SavedUpdate = Update; 8959 ExprResult UpdateVal; 8960 if (VarRef.get()->getType()->isOverloadableType() || 8961 NewStart.get()->getType()->isOverloadableType() || 8962 Update.get()->getType()->isOverloadableType()) { 8963 Sema::TentativeAnalysisScope Trap(SemaRef); 8964 8965 Update = 8966 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get()); 8967 if (Update.isUsable()) { 8968 UpdateVal = 8969 SemaRef.BuildBinOp(S, Loc, Subtract ? BO_SubAssign : BO_AddAssign, 8970 VarRef.get(), SavedUpdate.get()); 8971 if (UpdateVal.isUsable()) { 8972 Update = SemaRef.CreateBuiltinBinOp(Loc, BO_Comma, Update.get(), 8973 UpdateVal.get()); 8974 } 8975 } 8976 } 8977 8978 // Second attempt: try to build 'VarRef = Start (+|-) Iter * Step'. 8979 if (!Update.isUsable() || !UpdateVal.isUsable()) { 8980 Update = SemaRef.BuildBinOp(S, Loc, Subtract ? BO_Sub : BO_Add, 8981 NewStart.get(), SavedUpdate.get()); 8982 if (!Update.isUsable()) 8983 return ExprError(); 8984 8985 if (!SemaRef.Context.hasSameType(Update.get()->getType(), 8986 VarRef.get()->getType())) { 8987 Update = SemaRef.PerformImplicitConversion( 8988 Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true); 8989 if (!Update.isUsable()) 8990 return ExprError(); 8991 } 8992 8993 Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get()); 8994 } 8995 return Update; 8996 } 8997 8998 /// Convert integer expression \a E to make it have at least \a Bits 8999 /// bits. 9000 static ExprResult widenIterationCount(unsigned Bits, Expr *E, Sema &SemaRef) { 9001 if (E == nullptr) 9002 return ExprError(); 9003 ASTContext &C = SemaRef.Context; 9004 QualType OldType = E->getType(); 9005 unsigned HasBits = C.getTypeSize(OldType); 9006 if (HasBits >= Bits) 9007 return ExprResult(E); 9008 // OK to convert to signed, because new type has more bits than old. 9009 QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true); 9010 return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting, 9011 true); 9012 } 9013 9014 /// Check if the given expression \a E is a constant integer that fits 9015 /// into \a Bits bits. 9016 static bool fitsInto(unsigned Bits, bool Signed, const Expr *E, Sema &SemaRef) { 9017 if (E == nullptr) 9018 return false; 9019 if (Optional<llvm::APSInt> Result = 9020 E->getIntegerConstantExpr(SemaRef.Context)) 9021 return Signed ? Result->isSignedIntN(Bits) : Result->isIntN(Bits); 9022 return false; 9023 } 9024 9025 /// Build preinits statement for the given declarations. 9026 static Stmt *buildPreInits(ASTContext &Context, 9027 MutableArrayRef<Decl *> PreInits) { 9028 if (!PreInits.empty()) { 9029 return new (Context) DeclStmt( 9030 DeclGroupRef::Create(Context, PreInits.begin(), PreInits.size()), 9031 SourceLocation(), SourceLocation()); 9032 } 9033 return nullptr; 9034 } 9035 9036 /// Build preinits statement for the given declarations. 9037 static Stmt * 9038 buildPreInits(ASTContext &Context, 9039 const llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) { 9040 if (!Captures.empty()) { 9041 SmallVector<Decl *, 16> PreInits; 9042 for (const auto &Pair : Captures) 9043 PreInits.push_back(Pair.second->getDecl()); 9044 return buildPreInits(Context, PreInits); 9045 } 9046 return nullptr; 9047 } 9048 9049 /// Build postupdate expression for the given list of postupdates expressions. 9050 static Expr *buildPostUpdate(Sema &S, ArrayRef<Expr *> PostUpdates) { 9051 Expr *PostUpdate = nullptr; 9052 if (!PostUpdates.empty()) { 9053 for (Expr *E : PostUpdates) { 9054 Expr *ConvE = S.BuildCStyleCastExpr( 9055 E->getExprLoc(), 9056 S.Context.getTrivialTypeSourceInfo(S.Context.VoidTy), 9057 E->getExprLoc(), E) 9058 .get(); 9059 PostUpdate = PostUpdate 9060 ? S.CreateBuiltinBinOp(ConvE->getExprLoc(), BO_Comma, 9061 PostUpdate, ConvE) 9062 .get() 9063 : ConvE; 9064 } 9065 } 9066 return PostUpdate; 9067 } 9068 9069 /// Called on a for stmt to check itself and nested loops (if any). 9070 /// \return Returns 0 if one of the collapsed stmts is not canonical for loop, 9071 /// number of collapsed loops otherwise. 9072 static unsigned 9073 checkOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr, 9074 Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef, 9075 DSAStackTy &DSA, 9076 Sema::VarsWithInheritedDSAType &VarsWithImplicitDSA, 9077 OMPLoopBasedDirective::HelperExprs &Built) { 9078 unsigned NestedLoopCount = 1; 9079 bool SupportsNonPerfectlyNested = (SemaRef.LangOpts.OpenMP >= 50) && 9080 !isOpenMPLoopTransformationDirective(DKind); 9081 9082 if (CollapseLoopCountExpr) { 9083 // Found 'collapse' clause - calculate collapse number. 9084 Expr::EvalResult Result; 9085 if (!CollapseLoopCountExpr->isValueDependent() && 9086 CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext())) { 9087 NestedLoopCount = Result.Val.getInt().getLimitedValue(); 9088 } else { 9089 Built.clear(/*Size=*/1); 9090 return 1; 9091 } 9092 } 9093 unsigned OrderedLoopCount = 1; 9094 if (OrderedLoopCountExpr) { 9095 // Found 'ordered' clause - calculate collapse number. 9096 Expr::EvalResult EVResult; 9097 if (!OrderedLoopCountExpr->isValueDependent() && 9098 OrderedLoopCountExpr->EvaluateAsInt(EVResult, 9099 SemaRef.getASTContext())) { 9100 llvm::APSInt Result = EVResult.Val.getInt(); 9101 if (Result.getLimitedValue() < NestedLoopCount) { 9102 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(), 9103 diag::err_omp_wrong_ordered_loop_count) 9104 << OrderedLoopCountExpr->getSourceRange(); 9105 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(), 9106 diag::note_collapse_loop_count) 9107 << CollapseLoopCountExpr->getSourceRange(); 9108 } 9109 OrderedLoopCount = Result.getLimitedValue(); 9110 } else { 9111 Built.clear(/*Size=*/1); 9112 return 1; 9113 } 9114 } 9115 // This is helper routine for loop directives (e.g., 'for', 'simd', 9116 // 'for simd', etc.). 9117 llvm::MapVector<const Expr *, DeclRefExpr *> Captures; 9118 unsigned NumLoops = std::max(OrderedLoopCount, NestedLoopCount); 9119 SmallVector<LoopIterationSpace, 4> IterSpaces(NumLoops); 9120 if (!OMPLoopBasedDirective::doForAllLoops( 9121 AStmt->IgnoreContainers(!isOpenMPLoopTransformationDirective(DKind)), 9122 SupportsNonPerfectlyNested, NumLoops, 9123 [DKind, &SemaRef, &DSA, NumLoops, NestedLoopCount, 9124 CollapseLoopCountExpr, OrderedLoopCountExpr, &VarsWithImplicitDSA, 9125 &IterSpaces, &Captures](unsigned Cnt, Stmt *CurStmt) { 9126 if (checkOpenMPIterationSpace( 9127 DKind, CurStmt, SemaRef, DSA, Cnt, NestedLoopCount, 9128 NumLoops, CollapseLoopCountExpr, OrderedLoopCountExpr, 9129 VarsWithImplicitDSA, IterSpaces, Captures)) 9130 return true; 9131 if (Cnt > 0 && Cnt >= NestedLoopCount && 9132 IterSpaces[Cnt].CounterVar) { 9133 // Handle initialization of captured loop iterator variables. 9134 auto *DRE = cast<DeclRefExpr>(IterSpaces[Cnt].CounterVar); 9135 if (isa<OMPCapturedExprDecl>(DRE->getDecl())) { 9136 Captures[DRE] = DRE; 9137 } 9138 } 9139 return false; 9140 }, 9141 [&SemaRef, &Captures](OMPLoopTransformationDirective *Transform) { 9142 Stmt *DependentPreInits = Transform->getPreInits(); 9143 if (!DependentPreInits) 9144 return; 9145 for (Decl *C : cast<DeclStmt>(DependentPreInits)->getDeclGroup()) { 9146 auto *D = cast<VarDecl>(C); 9147 DeclRefExpr *Ref = buildDeclRefExpr(SemaRef, D, D->getType(), 9148 Transform->getBeginLoc()); 9149 Captures[Ref] = Ref; 9150 } 9151 })) 9152 return 0; 9153 9154 Built.clear(/* size */ NestedLoopCount); 9155 9156 if (SemaRef.CurContext->isDependentContext()) 9157 return NestedLoopCount; 9158 9159 // An example of what is generated for the following code: 9160 // 9161 // #pragma omp simd collapse(2) ordered(2) 9162 // for (i = 0; i < NI; ++i) 9163 // for (k = 0; k < NK; ++k) 9164 // for (j = J0; j < NJ; j+=2) { 9165 // <loop body> 9166 // } 9167 // 9168 // We generate the code below. 9169 // Note: the loop body may be outlined in CodeGen. 9170 // Note: some counters may be C++ classes, operator- is used to find number of 9171 // iterations and operator+= to calculate counter value. 9172 // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32 9173 // or i64 is currently supported). 9174 // 9175 // #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2)) 9176 // for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) { 9177 // .local.i = IV / ((NJ - J0 - 1 + 2) / 2); 9178 // .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2; 9179 // // similar updates for vars in clauses (e.g. 'linear') 9180 // <loop body (using local i and j)> 9181 // } 9182 // i = NI; // assign final values of counters 9183 // j = NJ; 9184 // 9185 9186 // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are 9187 // the iteration counts of the collapsed for loops. 9188 // Precondition tests if there is at least one iteration (all conditions are 9189 // true). 9190 auto PreCond = ExprResult(IterSpaces[0].PreCond); 9191 Expr *N0 = IterSpaces[0].NumIterations; 9192 ExprResult LastIteration32 = 9193 widenIterationCount(/*Bits=*/32, 9194 SemaRef 9195 .PerformImplicitConversion( 9196 N0->IgnoreImpCasts(), N0->getType(), 9197 Sema::AA_Converting, /*AllowExplicit=*/true) 9198 .get(), 9199 SemaRef); 9200 ExprResult LastIteration64 = widenIterationCount( 9201 /*Bits=*/64, 9202 SemaRef 9203 .PerformImplicitConversion(N0->IgnoreImpCasts(), N0->getType(), 9204 Sema::AA_Converting, 9205 /*AllowExplicit=*/true) 9206 .get(), 9207 SemaRef); 9208 9209 if (!LastIteration32.isUsable() || !LastIteration64.isUsable()) 9210 return NestedLoopCount; 9211 9212 ASTContext &C = SemaRef.Context; 9213 bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32; 9214 9215 Scope *CurScope = DSA.getCurScope(); 9216 for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) { 9217 if (PreCond.isUsable()) { 9218 PreCond = 9219 SemaRef.BuildBinOp(CurScope, PreCond.get()->getExprLoc(), BO_LAnd, 9220 PreCond.get(), IterSpaces[Cnt].PreCond); 9221 } 9222 Expr *N = IterSpaces[Cnt].NumIterations; 9223 SourceLocation Loc = N->getExprLoc(); 9224 AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32; 9225 if (LastIteration32.isUsable()) 9226 LastIteration32 = SemaRef.BuildBinOp( 9227 CurScope, Loc, BO_Mul, LastIteration32.get(), 9228 SemaRef 9229 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(), 9230 Sema::AA_Converting, 9231 /*AllowExplicit=*/true) 9232 .get()); 9233 if (LastIteration64.isUsable()) 9234 LastIteration64 = SemaRef.BuildBinOp( 9235 CurScope, Loc, BO_Mul, LastIteration64.get(), 9236 SemaRef 9237 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(), 9238 Sema::AA_Converting, 9239 /*AllowExplicit=*/true) 9240 .get()); 9241 } 9242 9243 // Choose either the 32-bit or 64-bit version. 9244 ExprResult LastIteration = LastIteration64; 9245 if (SemaRef.getLangOpts().OpenMPOptimisticCollapse || 9246 (LastIteration32.isUsable() && 9247 C.getTypeSize(LastIteration32.get()->getType()) == 32 && 9248 (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 || 9249 fitsInto( 9250 /*Bits=*/32, 9251 LastIteration32.get()->getType()->hasSignedIntegerRepresentation(), 9252 LastIteration64.get(), SemaRef)))) 9253 LastIteration = LastIteration32; 9254 QualType VType = LastIteration.get()->getType(); 9255 QualType RealVType = VType; 9256 QualType StrideVType = VType; 9257 if (isOpenMPTaskLoopDirective(DKind)) { 9258 VType = 9259 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0); 9260 StrideVType = 9261 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1); 9262 } 9263 9264 if (!LastIteration.isUsable()) 9265 return 0; 9266 9267 // Save the number of iterations. 9268 ExprResult NumIterations = LastIteration; 9269 { 9270 LastIteration = SemaRef.BuildBinOp( 9271 CurScope, LastIteration.get()->getExprLoc(), BO_Sub, 9272 LastIteration.get(), 9273 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get()); 9274 if (!LastIteration.isUsable()) 9275 return 0; 9276 } 9277 9278 // Calculate the last iteration number beforehand instead of doing this on 9279 // each iteration. Do not do this if the number of iterations may be kfold-ed. 9280 bool IsConstant = LastIteration.get()->isIntegerConstantExpr(SemaRef.Context); 9281 ExprResult CalcLastIteration; 9282 if (!IsConstant) { 9283 ExprResult SaveRef = 9284 tryBuildCapture(SemaRef, LastIteration.get(), Captures); 9285 LastIteration = SaveRef; 9286 9287 // Prepare SaveRef + 1. 9288 NumIterations = SemaRef.BuildBinOp( 9289 CurScope, SaveRef.get()->getExprLoc(), BO_Add, SaveRef.get(), 9290 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get()); 9291 if (!NumIterations.isUsable()) 9292 return 0; 9293 } 9294 9295 SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin(); 9296 9297 // Build variables passed into runtime, necessary for worksharing directives. 9298 ExprResult LB, UB, IL, ST, EUB, CombLB, CombUB, PrevLB, PrevUB, CombEUB; 9299 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) || 9300 isOpenMPDistributeDirective(DKind) || 9301 isOpenMPLoopTransformationDirective(DKind)) { 9302 // Lower bound variable, initialized with zero. 9303 VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb"); 9304 LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc); 9305 SemaRef.AddInitializerToDecl(LBDecl, 9306 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(), 9307 /*DirectInit*/ false); 9308 9309 // Upper bound variable, initialized with last iteration number. 9310 VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub"); 9311 UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc); 9312 SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(), 9313 /*DirectInit*/ false); 9314 9315 // A 32-bit variable-flag where runtime returns 1 for the last iteration. 9316 // This will be used to implement clause 'lastprivate'. 9317 QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true); 9318 VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last"); 9319 IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc); 9320 SemaRef.AddInitializerToDecl(ILDecl, 9321 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(), 9322 /*DirectInit*/ false); 9323 9324 // Stride variable returned by runtime (we initialize it to 1 by default). 9325 VarDecl *STDecl = 9326 buildVarDecl(SemaRef, InitLoc, StrideVType, ".omp.stride"); 9327 ST = buildDeclRefExpr(SemaRef, STDecl, StrideVType, InitLoc); 9328 SemaRef.AddInitializerToDecl(STDecl, 9329 SemaRef.ActOnIntegerConstant(InitLoc, 1).get(), 9330 /*DirectInit*/ false); 9331 9332 // Build expression: UB = min(UB, LastIteration) 9333 // It is necessary for CodeGen of directives with static scheduling. 9334 ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT, 9335 UB.get(), LastIteration.get()); 9336 ExprResult CondOp = SemaRef.ActOnConditionalOp( 9337 LastIteration.get()->getExprLoc(), InitLoc, IsUBGreater.get(), 9338 LastIteration.get(), UB.get()); 9339 EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(), 9340 CondOp.get()); 9341 EUB = SemaRef.ActOnFinishFullExpr(EUB.get(), /*DiscardedValue*/ false); 9342 9343 // If we have a combined directive that combines 'distribute', 'for' or 9344 // 'simd' we need to be able to access the bounds of the schedule of the 9345 // enclosing region. E.g. in 'distribute parallel for' the bounds obtained 9346 // by scheduling 'distribute' have to be passed to the schedule of 'for'. 9347 if (isOpenMPLoopBoundSharingDirective(DKind)) { 9348 // Lower bound variable, initialized with zero. 9349 VarDecl *CombLBDecl = 9350 buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.lb"); 9351 CombLB = buildDeclRefExpr(SemaRef, CombLBDecl, VType, InitLoc); 9352 SemaRef.AddInitializerToDecl( 9353 CombLBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(), 9354 /*DirectInit*/ false); 9355 9356 // Upper bound variable, initialized with last iteration number. 9357 VarDecl *CombUBDecl = 9358 buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.ub"); 9359 CombUB = buildDeclRefExpr(SemaRef, CombUBDecl, VType, InitLoc); 9360 SemaRef.AddInitializerToDecl(CombUBDecl, LastIteration.get(), 9361 /*DirectInit*/ false); 9362 9363 ExprResult CombIsUBGreater = SemaRef.BuildBinOp( 9364 CurScope, InitLoc, BO_GT, CombUB.get(), LastIteration.get()); 9365 ExprResult CombCondOp = 9366 SemaRef.ActOnConditionalOp(InitLoc, InitLoc, CombIsUBGreater.get(), 9367 LastIteration.get(), CombUB.get()); 9368 CombEUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, CombUB.get(), 9369 CombCondOp.get()); 9370 CombEUB = 9371 SemaRef.ActOnFinishFullExpr(CombEUB.get(), /*DiscardedValue*/ false); 9372 9373 const CapturedDecl *CD = cast<CapturedStmt>(AStmt)->getCapturedDecl(); 9374 // We expect to have at least 2 more parameters than the 'parallel' 9375 // directive does - the lower and upper bounds of the previous schedule. 9376 assert(CD->getNumParams() >= 4 && 9377 "Unexpected number of parameters in loop combined directive"); 9378 9379 // Set the proper type for the bounds given what we learned from the 9380 // enclosed loops. 9381 ImplicitParamDecl *PrevLBDecl = CD->getParam(/*PrevLB=*/2); 9382 ImplicitParamDecl *PrevUBDecl = CD->getParam(/*PrevUB=*/3); 9383 9384 // Previous lower and upper bounds are obtained from the region 9385 // parameters. 9386 PrevLB = 9387 buildDeclRefExpr(SemaRef, PrevLBDecl, PrevLBDecl->getType(), InitLoc); 9388 PrevUB = 9389 buildDeclRefExpr(SemaRef, PrevUBDecl, PrevUBDecl->getType(), InitLoc); 9390 } 9391 } 9392 9393 // Build the iteration variable and its initialization before loop. 9394 ExprResult IV; 9395 ExprResult Init, CombInit; 9396 { 9397 VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, RealVType, ".omp.iv"); 9398 IV = buildDeclRefExpr(SemaRef, IVDecl, RealVType, InitLoc); 9399 Expr *RHS = (isOpenMPWorksharingDirective(DKind) || 9400 isOpenMPTaskLoopDirective(DKind) || 9401 isOpenMPDistributeDirective(DKind) || 9402 isOpenMPLoopTransformationDirective(DKind)) 9403 ? LB.get() 9404 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get(); 9405 Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS); 9406 Init = SemaRef.ActOnFinishFullExpr(Init.get(), /*DiscardedValue*/ false); 9407 9408 if (isOpenMPLoopBoundSharingDirective(DKind)) { 9409 Expr *CombRHS = 9410 (isOpenMPWorksharingDirective(DKind) || 9411 isOpenMPTaskLoopDirective(DKind) || 9412 isOpenMPDistributeDirective(DKind)) 9413 ? CombLB.get() 9414 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get(); 9415 CombInit = 9416 SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), CombRHS); 9417 CombInit = 9418 SemaRef.ActOnFinishFullExpr(CombInit.get(), /*DiscardedValue*/ false); 9419 } 9420 } 9421 9422 bool UseStrictCompare = 9423 RealVType->hasUnsignedIntegerRepresentation() && 9424 llvm::all_of(IterSpaces, [](const LoopIterationSpace &LIS) { 9425 return LIS.IsStrictCompare; 9426 }); 9427 // Loop condition (IV < NumIterations) or (IV <= UB or IV < UB + 1 (for 9428 // unsigned IV)) for worksharing loops. 9429 SourceLocation CondLoc = AStmt->getBeginLoc(); 9430 Expr *BoundUB = UB.get(); 9431 if (UseStrictCompare) { 9432 BoundUB = 9433 SemaRef 9434 .BuildBinOp(CurScope, CondLoc, BO_Add, BoundUB, 9435 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get()) 9436 .get(); 9437 BoundUB = 9438 SemaRef.ActOnFinishFullExpr(BoundUB, /*DiscardedValue*/ false).get(); 9439 } 9440 ExprResult Cond = 9441 (isOpenMPWorksharingDirective(DKind) || 9442 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind) || 9443 isOpenMPLoopTransformationDirective(DKind)) 9444 ? SemaRef.BuildBinOp(CurScope, CondLoc, 9445 UseStrictCompare ? BO_LT : BO_LE, IV.get(), 9446 BoundUB) 9447 : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(), 9448 NumIterations.get()); 9449 ExprResult CombDistCond; 9450 if (isOpenMPLoopBoundSharingDirective(DKind)) { 9451 CombDistCond = SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(), 9452 NumIterations.get()); 9453 } 9454 9455 ExprResult CombCond; 9456 if (isOpenMPLoopBoundSharingDirective(DKind)) { 9457 Expr *BoundCombUB = CombUB.get(); 9458 if (UseStrictCompare) { 9459 BoundCombUB = 9460 SemaRef 9461 .BuildBinOp( 9462 CurScope, CondLoc, BO_Add, BoundCombUB, 9463 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get()) 9464 .get(); 9465 BoundCombUB = 9466 SemaRef.ActOnFinishFullExpr(BoundCombUB, /*DiscardedValue*/ false) 9467 .get(); 9468 } 9469 CombCond = 9470 SemaRef.BuildBinOp(CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE, 9471 IV.get(), BoundCombUB); 9472 } 9473 // Loop increment (IV = IV + 1) 9474 SourceLocation IncLoc = AStmt->getBeginLoc(); 9475 ExprResult Inc = 9476 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(), 9477 SemaRef.ActOnIntegerConstant(IncLoc, 1).get()); 9478 if (!Inc.isUsable()) 9479 return 0; 9480 Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get()); 9481 Inc = SemaRef.ActOnFinishFullExpr(Inc.get(), /*DiscardedValue*/ false); 9482 if (!Inc.isUsable()) 9483 return 0; 9484 9485 // Increments for worksharing loops (LB = LB + ST; UB = UB + ST). 9486 // Used for directives with static scheduling. 9487 // In combined construct, add combined version that use CombLB and CombUB 9488 // base variables for the update 9489 ExprResult NextLB, NextUB, CombNextLB, CombNextUB; 9490 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) || 9491 isOpenMPDistributeDirective(DKind) || 9492 isOpenMPLoopTransformationDirective(DKind)) { 9493 // LB + ST 9494 NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get()); 9495 if (!NextLB.isUsable()) 9496 return 0; 9497 // LB = LB + ST 9498 NextLB = 9499 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get()); 9500 NextLB = 9501 SemaRef.ActOnFinishFullExpr(NextLB.get(), /*DiscardedValue*/ false); 9502 if (!NextLB.isUsable()) 9503 return 0; 9504 // UB + ST 9505 NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get()); 9506 if (!NextUB.isUsable()) 9507 return 0; 9508 // UB = UB + ST 9509 NextUB = 9510 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get()); 9511 NextUB = 9512 SemaRef.ActOnFinishFullExpr(NextUB.get(), /*DiscardedValue*/ false); 9513 if (!NextUB.isUsable()) 9514 return 0; 9515 if (isOpenMPLoopBoundSharingDirective(DKind)) { 9516 CombNextLB = 9517 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombLB.get(), ST.get()); 9518 if (!NextLB.isUsable()) 9519 return 0; 9520 // LB = LB + ST 9521 CombNextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombLB.get(), 9522 CombNextLB.get()); 9523 CombNextLB = SemaRef.ActOnFinishFullExpr(CombNextLB.get(), 9524 /*DiscardedValue*/ false); 9525 if (!CombNextLB.isUsable()) 9526 return 0; 9527 // UB + ST 9528 CombNextUB = 9529 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombUB.get(), ST.get()); 9530 if (!CombNextUB.isUsable()) 9531 return 0; 9532 // UB = UB + ST 9533 CombNextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombUB.get(), 9534 CombNextUB.get()); 9535 CombNextUB = SemaRef.ActOnFinishFullExpr(CombNextUB.get(), 9536 /*DiscardedValue*/ false); 9537 if (!CombNextUB.isUsable()) 9538 return 0; 9539 } 9540 } 9541 9542 // Create increment expression for distribute loop when combined in a same 9543 // directive with for as IV = IV + ST; ensure upper bound expression based 9544 // on PrevUB instead of NumIterations - used to implement 'for' when found 9545 // in combination with 'distribute', like in 'distribute parallel for' 9546 SourceLocation DistIncLoc = AStmt->getBeginLoc(); 9547 ExprResult DistCond, DistInc, PrevEUB, ParForInDistCond; 9548 if (isOpenMPLoopBoundSharingDirective(DKind)) { 9549 DistCond = SemaRef.BuildBinOp( 9550 CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE, IV.get(), BoundUB); 9551 assert(DistCond.isUsable() && "distribute cond expr was not built"); 9552 9553 DistInc = 9554 SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Add, IV.get(), ST.get()); 9555 assert(DistInc.isUsable() && "distribute inc expr was not built"); 9556 DistInc = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, IV.get(), 9557 DistInc.get()); 9558 DistInc = 9559 SemaRef.ActOnFinishFullExpr(DistInc.get(), /*DiscardedValue*/ false); 9560 assert(DistInc.isUsable() && "distribute inc expr was not built"); 9561 9562 // Build expression: UB = min(UB, prevUB) for #for in composite or combined 9563 // construct 9564 ExprResult NewPrevUB = PrevUB; 9565 SourceLocation DistEUBLoc = AStmt->getBeginLoc(); 9566 if (!SemaRef.Context.hasSameType(UB.get()->getType(), 9567 PrevUB.get()->getType())) { 9568 NewPrevUB = SemaRef.BuildCStyleCastExpr( 9569 DistEUBLoc, 9570 SemaRef.Context.getTrivialTypeSourceInfo(UB.get()->getType()), 9571 DistEUBLoc, NewPrevUB.get()); 9572 if (!NewPrevUB.isUsable()) 9573 return 0; 9574 } 9575 ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, DistEUBLoc, BO_GT, 9576 UB.get(), NewPrevUB.get()); 9577 ExprResult CondOp = SemaRef.ActOnConditionalOp( 9578 DistEUBLoc, DistEUBLoc, IsUBGreater.get(), NewPrevUB.get(), UB.get()); 9579 PrevEUB = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, UB.get(), 9580 CondOp.get()); 9581 PrevEUB = 9582 SemaRef.ActOnFinishFullExpr(PrevEUB.get(), /*DiscardedValue*/ false); 9583 9584 // Build IV <= PrevUB or IV < PrevUB + 1 for unsigned IV to be used in 9585 // parallel for is in combination with a distribute directive with 9586 // schedule(static, 1) 9587 Expr *BoundPrevUB = PrevUB.get(); 9588 if (UseStrictCompare) { 9589 BoundPrevUB = 9590 SemaRef 9591 .BuildBinOp( 9592 CurScope, CondLoc, BO_Add, BoundPrevUB, 9593 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get()) 9594 .get(); 9595 BoundPrevUB = 9596 SemaRef.ActOnFinishFullExpr(BoundPrevUB, /*DiscardedValue*/ false) 9597 .get(); 9598 } 9599 ParForInDistCond = 9600 SemaRef.BuildBinOp(CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE, 9601 IV.get(), BoundPrevUB); 9602 } 9603 9604 // Build updates and final values of the loop counters. 9605 bool HasErrors = false; 9606 Built.Counters.resize(NestedLoopCount); 9607 Built.Inits.resize(NestedLoopCount); 9608 Built.Updates.resize(NestedLoopCount); 9609 Built.Finals.resize(NestedLoopCount); 9610 Built.DependentCounters.resize(NestedLoopCount); 9611 Built.DependentInits.resize(NestedLoopCount); 9612 Built.FinalsConditions.resize(NestedLoopCount); 9613 { 9614 // We implement the following algorithm for obtaining the 9615 // original loop iteration variable values based on the 9616 // value of the collapsed loop iteration variable IV. 9617 // 9618 // Let n+1 be the number of collapsed loops in the nest. 9619 // Iteration variables (I0, I1, .... In) 9620 // Iteration counts (N0, N1, ... Nn) 9621 // 9622 // Acc = IV; 9623 // 9624 // To compute Ik for loop k, 0 <= k <= n, generate: 9625 // Prod = N(k+1) * N(k+2) * ... * Nn; 9626 // Ik = Acc / Prod; 9627 // Acc -= Ik * Prod; 9628 // 9629 ExprResult Acc = IV; 9630 for (unsigned int Cnt = 0; Cnt < NestedLoopCount; ++Cnt) { 9631 LoopIterationSpace &IS = IterSpaces[Cnt]; 9632 SourceLocation UpdLoc = IS.IncSrcRange.getBegin(); 9633 ExprResult Iter; 9634 9635 // Compute prod 9636 ExprResult Prod = 9637 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get(); 9638 for (unsigned int K = Cnt+1; K < NestedLoopCount; ++K) 9639 Prod = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Prod.get(), 9640 IterSpaces[K].NumIterations); 9641 9642 // Iter = Acc / Prod 9643 // If there is at least one more inner loop to avoid 9644 // multiplication by 1. 9645 if (Cnt + 1 < NestedLoopCount) 9646 Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div, 9647 Acc.get(), Prod.get()); 9648 else 9649 Iter = Acc; 9650 if (!Iter.isUsable()) { 9651 HasErrors = true; 9652 break; 9653 } 9654 9655 // Update Acc: 9656 // Acc -= Iter * Prod 9657 // Check if there is at least one more inner loop to avoid 9658 // multiplication by 1. 9659 if (Cnt + 1 < NestedLoopCount) 9660 Prod = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, 9661 Iter.get(), Prod.get()); 9662 else 9663 Prod = Iter; 9664 Acc = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Sub, 9665 Acc.get(), Prod.get()); 9666 9667 // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step 9668 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl()); 9669 DeclRefExpr *CounterVar = buildDeclRefExpr( 9670 SemaRef, VD, IS.CounterVar->getType(), IS.CounterVar->getExprLoc(), 9671 /*RefersToCapture=*/true); 9672 ExprResult Init = 9673 buildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar, 9674 IS.CounterInit, IS.IsNonRectangularLB, Captures); 9675 if (!Init.isUsable()) { 9676 HasErrors = true; 9677 break; 9678 } 9679 ExprResult Update = buildCounterUpdate( 9680 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, Iter, 9681 IS.CounterStep, IS.Subtract, IS.IsNonRectangularLB, &Captures); 9682 if (!Update.isUsable()) { 9683 HasErrors = true; 9684 break; 9685 } 9686 9687 // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step 9688 ExprResult Final = 9689 buildCounterUpdate(SemaRef, CurScope, UpdLoc, CounterVar, 9690 IS.CounterInit, IS.NumIterations, IS.CounterStep, 9691 IS.Subtract, IS.IsNonRectangularLB, &Captures); 9692 if (!Final.isUsable()) { 9693 HasErrors = true; 9694 break; 9695 } 9696 9697 if (!Update.isUsable() || !Final.isUsable()) { 9698 HasErrors = true; 9699 break; 9700 } 9701 // Save results 9702 Built.Counters[Cnt] = IS.CounterVar; 9703 Built.PrivateCounters[Cnt] = IS.PrivateCounterVar; 9704 Built.Inits[Cnt] = Init.get(); 9705 Built.Updates[Cnt] = Update.get(); 9706 Built.Finals[Cnt] = Final.get(); 9707 Built.DependentCounters[Cnt] = nullptr; 9708 Built.DependentInits[Cnt] = nullptr; 9709 Built.FinalsConditions[Cnt] = nullptr; 9710 if (IS.IsNonRectangularLB || IS.IsNonRectangularUB) { 9711 Built.DependentCounters[Cnt] = 9712 Built.Counters[NestedLoopCount - 1 - IS.LoopDependentIdx]; 9713 Built.DependentInits[Cnt] = 9714 Built.Inits[NestedLoopCount - 1 - IS.LoopDependentIdx]; 9715 Built.FinalsConditions[Cnt] = IS.FinalCondition; 9716 } 9717 } 9718 } 9719 9720 if (HasErrors) 9721 return 0; 9722 9723 // Save results 9724 Built.IterationVarRef = IV.get(); 9725 Built.LastIteration = LastIteration.get(); 9726 Built.NumIterations = NumIterations.get(); 9727 Built.CalcLastIteration = SemaRef 9728 .ActOnFinishFullExpr(CalcLastIteration.get(), 9729 /*DiscardedValue=*/false) 9730 .get(); 9731 Built.PreCond = PreCond.get(); 9732 Built.PreInits = buildPreInits(C, Captures); 9733 Built.Cond = Cond.get(); 9734 Built.Init = Init.get(); 9735 Built.Inc = Inc.get(); 9736 Built.LB = LB.get(); 9737 Built.UB = UB.get(); 9738 Built.IL = IL.get(); 9739 Built.ST = ST.get(); 9740 Built.EUB = EUB.get(); 9741 Built.NLB = NextLB.get(); 9742 Built.NUB = NextUB.get(); 9743 Built.PrevLB = PrevLB.get(); 9744 Built.PrevUB = PrevUB.get(); 9745 Built.DistInc = DistInc.get(); 9746 Built.PrevEUB = PrevEUB.get(); 9747 Built.DistCombinedFields.LB = CombLB.get(); 9748 Built.DistCombinedFields.UB = CombUB.get(); 9749 Built.DistCombinedFields.EUB = CombEUB.get(); 9750 Built.DistCombinedFields.Init = CombInit.get(); 9751 Built.DistCombinedFields.Cond = CombCond.get(); 9752 Built.DistCombinedFields.NLB = CombNextLB.get(); 9753 Built.DistCombinedFields.NUB = CombNextUB.get(); 9754 Built.DistCombinedFields.DistCond = CombDistCond.get(); 9755 Built.DistCombinedFields.ParForInDistCond = ParForInDistCond.get(); 9756 9757 return NestedLoopCount; 9758 } 9759 9760 static Expr *getCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) { 9761 auto CollapseClauses = 9762 OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses); 9763 if (CollapseClauses.begin() != CollapseClauses.end()) 9764 return (*CollapseClauses.begin())->getNumForLoops(); 9765 return nullptr; 9766 } 9767 9768 static Expr *getOrderedNumberExpr(ArrayRef<OMPClause *> Clauses) { 9769 auto OrderedClauses = 9770 OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses); 9771 if (OrderedClauses.begin() != OrderedClauses.end()) 9772 return (*OrderedClauses.begin())->getNumForLoops(); 9773 return nullptr; 9774 } 9775 9776 static bool checkSimdlenSafelenSpecified(Sema &S, 9777 const ArrayRef<OMPClause *> Clauses) { 9778 const OMPSafelenClause *Safelen = nullptr; 9779 const OMPSimdlenClause *Simdlen = nullptr; 9780 9781 for (const OMPClause *Clause : Clauses) { 9782 if (Clause->getClauseKind() == OMPC_safelen) 9783 Safelen = cast<OMPSafelenClause>(Clause); 9784 else if (Clause->getClauseKind() == OMPC_simdlen) 9785 Simdlen = cast<OMPSimdlenClause>(Clause); 9786 if (Safelen && Simdlen) 9787 break; 9788 } 9789 9790 if (Simdlen && Safelen) { 9791 const Expr *SimdlenLength = Simdlen->getSimdlen(); 9792 const Expr *SafelenLength = Safelen->getSafelen(); 9793 if (SimdlenLength->isValueDependent() || SimdlenLength->isTypeDependent() || 9794 SimdlenLength->isInstantiationDependent() || 9795 SimdlenLength->containsUnexpandedParameterPack()) 9796 return false; 9797 if (SafelenLength->isValueDependent() || SafelenLength->isTypeDependent() || 9798 SafelenLength->isInstantiationDependent() || 9799 SafelenLength->containsUnexpandedParameterPack()) 9800 return false; 9801 Expr::EvalResult SimdlenResult, SafelenResult; 9802 SimdlenLength->EvaluateAsInt(SimdlenResult, S.Context); 9803 SafelenLength->EvaluateAsInt(SafelenResult, S.Context); 9804 llvm::APSInt SimdlenRes = SimdlenResult.Val.getInt(); 9805 llvm::APSInt SafelenRes = SafelenResult.Val.getInt(); 9806 // OpenMP 4.5 [2.8.1, simd Construct, Restrictions] 9807 // If both simdlen and safelen clauses are specified, the value of the 9808 // simdlen parameter must be less than or equal to the value of the safelen 9809 // parameter. 9810 if (SimdlenRes > SafelenRes) { 9811 S.Diag(SimdlenLength->getExprLoc(), 9812 diag::err_omp_wrong_simdlen_safelen_values) 9813 << SimdlenLength->getSourceRange() << SafelenLength->getSourceRange(); 9814 return true; 9815 } 9816 } 9817 return false; 9818 } 9819 9820 StmtResult 9821 Sema::ActOnOpenMPSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, 9822 SourceLocation StartLoc, SourceLocation EndLoc, 9823 VarsWithInheritedDSAType &VarsWithImplicitDSA) { 9824 if (!AStmt) 9825 return StmtError(); 9826 9827 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 9828 OMPLoopBasedDirective::HelperExprs B; 9829 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 9830 // define the nested loops number. 9831 unsigned NestedLoopCount = checkOpenMPLoop( 9832 OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses), 9833 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B); 9834 if (NestedLoopCount == 0) 9835 return StmtError(); 9836 9837 assert((CurContext->isDependentContext() || B.builtAll()) && 9838 "omp simd loop exprs were not built"); 9839 9840 if (!CurContext->isDependentContext()) { 9841 // Finalize the clauses that need pre-built expressions for CodeGen. 9842 for (OMPClause *C : Clauses) { 9843 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 9844 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 9845 B.NumIterations, *this, CurScope, 9846 DSAStack)) 9847 return StmtError(); 9848 } 9849 } 9850 9851 if (checkSimdlenSafelenSpecified(*this, Clauses)) 9852 return StmtError(); 9853 9854 setFunctionHasBranchProtectedScope(); 9855 return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount, 9856 Clauses, AStmt, B); 9857 } 9858 9859 StmtResult 9860 Sema::ActOnOpenMPForDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, 9861 SourceLocation StartLoc, SourceLocation EndLoc, 9862 VarsWithInheritedDSAType &VarsWithImplicitDSA) { 9863 if (!AStmt) 9864 return StmtError(); 9865 9866 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 9867 OMPLoopBasedDirective::HelperExprs B; 9868 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 9869 // define the nested loops number. 9870 unsigned NestedLoopCount = checkOpenMPLoop( 9871 OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses), 9872 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B); 9873 if (NestedLoopCount == 0) 9874 return StmtError(); 9875 9876 assert((CurContext->isDependentContext() || B.builtAll()) && 9877 "omp for loop exprs were not built"); 9878 9879 if (!CurContext->isDependentContext()) { 9880 // Finalize the clauses that need pre-built expressions for CodeGen. 9881 for (OMPClause *C : Clauses) { 9882 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 9883 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 9884 B.NumIterations, *this, CurScope, 9885 DSAStack)) 9886 return StmtError(); 9887 } 9888 } 9889 9890 setFunctionHasBranchProtectedScope(); 9891 return OMPForDirective::Create( 9892 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B, 9893 DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion()); 9894 } 9895 9896 StmtResult Sema::ActOnOpenMPForSimdDirective( 9897 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 9898 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 9899 if (!AStmt) 9900 return StmtError(); 9901 9902 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 9903 OMPLoopBasedDirective::HelperExprs B; 9904 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 9905 // define the nested loops number. 9906 unsigned NestedLoopCount = 9907 checkOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses), 9908 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack, 9909 VarsWithImplicitDSA, B); 9910 if (NestedLoopCount == 0) 9911 return StmtError(); 9912 9913 assert((CurContext->isDependentContext() || B.builtAll()) && 9914 "omp for simd loop exprs were not built"); 9915 9916 if (!CurContext->isDependentContext()) { 9917 // Finalize the clauses that need pre-built expressions for CodeGen. 9918 for (OMPClause *C : Clauses) { 9919 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 9920 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 9921 B.NumIterations, *this, CurScope, 9922 DSAStack)) 9923 return StmtError(); 9924 } 9925 } 9926 9927 if (checkSimdlenSafelenSpecified(*this, Clauses)) 9928 return StmtError(); 9929 9930 setFunctionHasBranchProtectedScope(); 9931 return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount, 9932 Clauses, AStmt, B); 9933 } 9934 9935 StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses, 9936 Stmt *AStmt, 9937 SourceLocation StartLoc, 9938 SourceLocation EndLoc) { 9939 if (!AStmt) 9940 return StmtError(); 9941 9942 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 9943 auto BaseStmt = AStmt; 9944 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt)) 9945 BaseStmt = CS->getCapturedStmt(); 9946 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) { 9947 auto S = C->children(); 9948 if (S.begin() == S.end()) 9949 return StmtError(); 9950 // All associated statements must be '#pragma omp section' except for 9951 // the first one. 9952 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) { 9953 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) { 9954 if (SectionStmt) 9955 Diag(SectionStmt->getBeginLoc(), 9956 diag::err_omp_sections_substmt_not_section); 9957 return StmtError(); 9958 } 9959 cast<OMPSectionDirective>(SectionStmt) 9960 ->setHasCancel(DSAStack->isCancelRegion()); 9961 } 9962 } else { 9963 Diag(AStmt->getBeginLoc(), diag::err_omp_sections_not_compound_stmt); 9964 return StmtError(); 9965 } 9966 9967 setFunctionHasBranchProtectedScope(); 9968 9969 return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt, 9970 DSAStack->getTaskgroupReductionRef(), 9971 DSAStack->isCancelRegion()); 9972 } 9973 9974 StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt, 9975 SourceLocation StartLoc, 9976 SourceLocation EndLoc) { 9977 if (!AStmt) 9978 return StmtError(); 9979 9980 setFunctionHasBranchProtectedScope(); 9981 DSAStack->setParentCancelRegion(DSAStack->isCancelRegion()); 9982 9983 return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt, 9984 DSAStack->isCancelRegion()); 9985 } 9986 9987 static Expr *getDirectCallExpr(Expr *E) { 9988 E = E->IgnoreParenCasts()->IgnoreImplicit(); 9989 if (auto *CE = dyn_cast<CallExpr>(E)) 9990 if (CE->getDirectCallee()) 9991 return E; 9992 return nullptr; 9993 } 9994 9995 StmtResult Sema::ActOnOpenMPDispatchDirective(ArrayRef<OMPClause *> Clauses, 9996 Stmt *AStmt, 9997 SourceLocation StartLoc, 9998 SourceLocation EndLoc) { 9999 if (!AStmt) 10000 return StmtError(); 10001 10002 Stmt *S = cast<CapturedStmt>(AStmt)->getCapturedStmt(); 10003 10004 // 5.1 OpenMP 10005 // expression-stmt : an expression statement with one of the following forms: 10006 // expression = target-call ( [expression-list] ); 10007 // target-call ( [expression-list] ); 10008 10009 SourceLocation TargetCallLoc; 10010 10011 if (!CurContext->isDependentContext()) { 10012 Expr *TargetCall = nullptr; 10013 10014 auto *E = dyn_cast<Expr>(S); 10015 if (!E) { 10016 Diag(S->getBeginLoc(), diag::err_omp_dispatch_statement_call); 10017 return StmtError(); 10018 } 10019 10020 E = E->IgnoreParenCasts()->IgnoreImplicit(); 10021 10022 if (auto *BO = dyn_cast<BinaryOperator>(E)) { 10023 if (BO->getOpcode() == BO_Assign) 10024 TargetCall = getDirectCallExpr(BO->getRHS()); 10025 } else { 10026 if (auto *COCE = dyn_cast<CXXOperatorCallExpr>(E)) 10027 if (COCE->getOperator() == OO_Equal) 10028 TargetCall = getDirectCallExpr(COCE->getArg(1)); 10029 if (!TargetCall) 10030 TargetCall = getDirectCallExpr(E); 10031 } 10032 if (!TargetCall) { 10033 Diag(E->getBeginLoc(), diag::err_omp_dispatch_statement_call); 10034 return StmtError(); 10035 } 10036 TargetCallLoc = TargetCall->getExprLoc(); 10037 } 10038 10039 setFunctionHasBranchProtectedScope(); 10040 10041 return OMPDispatchDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt, 10042 TargetCallLoc); 10043 } 10044 10045 StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses, 10046 Stmt *AStmt, 10047 SourceLocation StartLoc, 10048 SourceLocation EndLoc) { 10049 if (!AStmt) 10050 return StmtError(); 10051 10052 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 10053 10054 setFunctionHasBranchProtectedScope(); 10055 10056 // OpenMP [2.7.3, single Construct, Restrictions] 10057 // The copyprivate clause must not be used with the nowait clause. 10058 const OMPClause *Nowait = nullptr; 10059 const OMPClause *Copyprivate = nullptr; 10060 for (const OMPClause *Clause : Clauses) { 10061 if (Clause->getClauseKind() == OMPC_nowait) 10062 Nowait = Clause; 10063 else if (Clause->getClauseKind() == OMPC_copyprivate) 10064 Copyprivate = Clause; 10065 if (Copyprivate && Nowait) { 10066 Diag(Copyprivate->getBeginLoc(), 10067 diag::err_omp_single_copyprivate_with_nowait); 10068 Diag(Nowait->getBeginLoc(), diag::note_omp_nowait_clause_here); 10069 return StmtError(); 10070 } 10071 } 10072 10073 return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt); 10074 } 10075 10076 StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt, 10077 SourceLocation StartLoc, 10078 SourceLocation EndLoc) { 10079 if (!AStmt) 10080 return StmtError(); 10081 10082 setFunctionHasBranchProtectedScope(); 10083 10084 return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt); 10085 } 10086 10087 StmtResult Sema::ActOnOpenMPMaskedDirective(ArrayRef<OMPClause *> Clauses, 10088 Stmt *AStmt, 10089 SourceLocation StartLoc, 10090 SourceLocation EndLoc) { 10091 if (!AStmt) 10092 return StmtError(); 10093 10094 setFunctionHasBranchProtectedScope(); 10095 10096 return OMPMaskedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt); 10097 } 10098 10099 StmtResult Sema::ActOnOpenMPCriticalDirective( 10100 const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses, 10101 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) { 10102 if (!AStmt) 10103 return StmtError(); 10104 10105 bool ErrorFound = false; 10106 llvm::APSInt Hint; 10107 SourceLocation HintLoc; 10108 bool DependentHint = false; 10109 for (const OMPClause *C : Clauses) { 10110 if (C->getClauseKind() == OMPC_hint) { 10111 if (!DirName.getName()) { 10112 Diag(C->getBeginLoc(), diag::err_omp_hint_clause_no_name); 10113 ErrorFound = true; 10114 } 10115 Expr *E = cast<OMPHintClause>(C)->getHint(); 10116 if (E->isTypeDependent() || E->isValueDependent() || 10117 E->isInstantiationDependent()) { 10118 DependentHint = true; 10119 } else { 10120 Hint = E->EvaluateKnownConstInt(Context); 10121 HintLoc = C->getBeginLoc(); 10122 } 10123 } 10124 } 10125 if (ErrorFound) 10126 return StmtError(); 10127 const auto Pair = DSAStack->getCriticalWithHint(DirName); 10128 if (Pair.first && DirName.getName() && !DependentHint) { 10129 if (llvm::APSInt::compareValues(Hint, Pair.second) != 0) { 10130 Diag(StartLoc, diag::err_omp_critical_with_hint); 10131 if (HintLoc.isValid()) 10132 Diag(HintLoc, diag::note_omp_critical_hint_here) 10133 << 0 << toString(Hint, /*Radix=*/10, /*Signed=*/false); 10134 else 10135 Diag(StartLoc, diag::note_omp_critical_no_hint) << 0; 10136 if (const auto *C = Pair.first->getSingleClause<OMPHintClause>()) { 10137 Diag(C->getBeginLoc(), diag::note_omp_critical_hint_here) 10138 << 1 10139 << toString(C->getHint()->EvaluateKnownConstInt(Context), 10140 /*Radix=*/10, /*Signed=*/false); 10141 } else { 10142 Diag(Pair.first->getBeginLoc(), diag::note_omp_critical_no_hint) << 1; 10143 } 10144 } 10145 } 10146 10147 setFunctionHasBranchProtectedScope(); 10148 10149 auto *Dir = OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc, 10150 Clauses, AStmt); 10151 if (!Pair.first && DirName.getName() && !DependentHint) 10152 DSAStack->addCriticalWithHint(Dir, Hint); 10153 return Dir; 10154 } 10155 10156 StmtResult Sema::ActOnOpenMPParallelForDirective( 10157 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 10158 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 10159 if (!AStmt) 10160 return StmtError(); 10161 10162 auto *CS = cast<CapturedStmt>(AStmt); 10163 // 1.2.2 OpenMP Language Terminology 10164 // Structured block - An executable statement with a single entry at the 10165 // top and a single exit at the bottom. 10166 // The point of exit cannot be a branch out of the structured block. 10167 // longjmp() and throw() must not violate the entry/exit criteria. 10168 CS->getCapturedDecl()->setNothrow(); 10169 10170 OMPLoopBasedDirective::HelperExprs B; 10171 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 10172 // define the nested loops number. 10173 unsigned NestedLoopCount = 10174 checkOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses), 10175 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack, 10176 VarsWithImplicitDSA, B); 10177 if (NestedLoopCount == 0) 10178 return StmtError(); 10179 10180 assert((CurContext->isDependentContext() || B.builtAll()) && 10181 "omp parallel for loop exprs were not built"); 10182 10183 if (!CurContext->isDependentContext()) { 10184 // Finalize the clauses that need pre-built expressions for CodeGen. 10185 for (OMPClause *C : Clauses) { 10186 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 10187 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 10188 B.NumIterations, *this, CurScope, 10189 DSAStack)) 10190 return StmtError(); 10191 } 10192 } 10193 10194 setFunctionHasBranchProtectedScope(); 10195 return OMPParallelForDirective::Create( 10196 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B, 10197 DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion()); 10198 } 10199 10200 StmtResult Sema::ActOnOpenMPParallelForSimdDirective( 10201 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 10202 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 10203 if (!AStmt) 10204 return StmtError(); 10205 10206 auto *CS = cast<CapturedStmt>(AStmt); 10207 // 1.2.2 OpenMP Language Terminology 10208 // Structured block - An executable statement with a single entry at the 10209 // top and a single exit at the bottom. 10210 // The point of exit cannot be a branch out of the structured block. 10211 // longjmp() and throw() must not violate the entry/exit criteria. 10212 CS->getCapturedDecl()->setNothrow(); 10213 10214 OMPLoopBasedDirective::HelperExprs B; 10215 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 10216 // define the nested loops number. 10217 unsigned NestedLoopCount = 10218 checkOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses), 10219 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack, 10220 VarsWithImplicitDSA, B); 10221 if (NestedLoopCount == 0) 10222 return StmtError(); 10223 10224 if (!CurContext->isDependentContext()) { 10225 // Finalize the clauses that need pre-built expressions for CodeGen. 10226 for (OMPClause *C : Clauses) { 10227 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 10228 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 10229 B.NumIterations, *this, CurScope, 10230 DSAStack)) 10231 return StmtError(); 10232 } 10233 } 10234 10235 if (checkSimdlenSafelenSpecified(*this, Clauses)) 10236 return StmtError(); 10237 10238 setFunctionHasBranchProtectedScope(); 10239 return OMPParallelForSimdDirective::Create( 10240 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 10241 } 10242 10243 StmtResult 10244 Sema::ActOnOpenMPParallelMasterDirective(ArrayRef<OMPClause *> Clauses, 10245 Stmt *AStmt, SourceLocation StartLoc, 10246 SourceLocation EndLoc) { 10247 if (!AStmt) 10248 return StmtError(); 10249 10250 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 10251 auto *CS = cast<CapturedStmt>(AStmt); 10252 // 1.2.2 OpenMP Language Terminology 10253 // Structured block - An executable statement with a single entry at the 10254 // top and a single exit at the bottom. 10255 // The point of exit cannot be a branch out of the structured block. 10256 // longjmp() and throw() must not violate the entry/exit criteria. 10257 CS->getCapturedDecl()->setNothrow(); 10258 10259 setFunctionHasBranchProtectedScope(); 10260 10261 return OMPParallelMasterDirective::Create( 10262 Context, StartLoc, EndLoc, Clauses, AStmt, 10263 DSAStack->getTaskgroupReductionRef()); 10264 } 10265 10266 StmtResult 10267 Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses, 10268 Stmt *AStmt, SourceLocation StartLoc, 10269 SourceLocation EndLoc) { 10270 if (!AStmt) 10271 return StmtError(); 10272 10273 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 10274 auto BaseStmt = AStmt; 10275 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt)) 10276 BaseStmt = CS->getCapturedStmt(); 10277 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) { 10278 auto S = C->children(); 10279 if (S.begin() == S.end()) 10280 return StmtError(); 10281 // All associated statements must be '#pragma omp section' except for 10282 // the first one. 10283 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) { 10284 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) { 10285 if (SectionStmt) 10286 Diag(SectionStmt->getBeginLoc(), 10287 diag::err_omp_parallel_sections_substmt_not_section); 10288 return StmtError(); 10289 } 10290 cast<OMPSectionDirective>(SectionStmt) 10291 ->setHasCancel(DSAStack->isCancelRegion()); 10292 } 10293 } else { 10294 Diag(AStmt->getBeginLoc(), 10295 diag::err_omp_parallel_sections_not_compound_stmt); 10296 return StmtError(); 10297 } 10298 10299 setFunctionHasBranchProtectedScope(); 10300 10301 return OMPParallelSectionsDirective::Create( 10302 Context, StartLoc, EndLoc, Clauses, AStmt, 10303 DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion()); 10304 } 10305 10306 /// Find and diagnose mutually exclusive clause kinds. 10307 static bool checkMutuallyExclusiveClauses( 10308 Sema &S, ArrayRef<OMPClause *> Clauses, 10309 ArrayRef<OpenMPClauseKind> MutuallyExclusiveClauses) { 10310 const OMPClause *PrevClause = nullptr; 10311 bool ErrorFound = false; 10312 for (const OMPClause *C : Clauses) { 10313 if (llvm::is_contained(MutuallyExclusiveClauses, C->getClauseKind())) { 10314 if (!PrevClause) { 10315 PrevClause = C; 10316 } else if (PrevClause->getClauseKind() != C->getClauseKind()) { 10317 S.Diag(C->getBeginLoc(), diag::err_omp_clauses_mutually_exclusive) 10318 << getOpenMPClauseName(C->getClauseKind()) 10319 << getOpenMPClauseName(PrevClause->getClauseKind()); 10320 S.Diag(PrevClause->getBeginLoc(), diag::note_omp_previous_clause) 10321 << getOpenMPClauseName(PrevClause->getClauseKind()); 10322 ErrorFound = true; 10323 } 10324 } 10325 } 10326 return ErrorFound; 10327 } 10328 10329 StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses, 10330 Stmt *AStmt, SourceLocation StartLoc, 10331 SourceLocation EndLoc) { 10332 if (!AStmt) 10333 return StmtError(); 10334 10335 // OpenMP 5.0, 2.10.1 task Construct 10336 // If a detach clause appears on the directive, then a mergeable clause cannot 10337 // appear on the same directive. 10338 if (checkMutuallyExclusiveClauses(*this, Clauses, 10339 {OMPC_detach, OMPC_mergeable})) 10340 return StmtError(); 10341 10342 auto *CS = cast<CapturedStmt>(AStmt); 10343 // 1.2.2 OpenMP Language Terminology 10344 // Structured block - An executable statement with a single entry at the 10345 // top and a single exit at the bottom. 10346 // The point of exit cannot be a branch out of the structured block. 10347 // longjmp() and throw() must not violate the entry/exit criteria. 10348 CS->getCapturedDecl()->setNothrow(); 10349 10350 setFunctionHasBranchProtectedScope(); 10351 10352 return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt, 10353 DSAStack->isCancelRegion()); 10354 } 10355 10356 StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc, 10357 SourceLocation EndLoc) { 10358 return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc); 10359 } 10360 10361 StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc, 10362 SourceLocation EndLoc) { 10363 return OMPBarrierDirective::Create(Context, StartLoc, EndLoc); 10364 } 10365 10366 StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc, 10367 SourceLocation EndLoc) { 10368 return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc); 10369 } 10370 10371 StmtResult Sema::ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses, 10372 Stmt *AStmt, 10373 SourceLocation StartLoc, 10374 SourceLocation EndLoc) { 10375 if (!AStmt) 10376 return StmtError(); 10377 10378 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 10379 10380 setFunctionHasBranchProtectedScope(); 10381 10382 return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, Clauses, 10383 AStmt, 10384 DSAStack->getTaskgroupReductionRef()); 10385 } 10386 10387 StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses, 10388 SourceLocation StartLoc, 10389 SourceLocation EndLoc) { 10390 OMPFlushClause *FC = nullptr; 10391 OMPClause *OrderClause = nullptr; 10392 for (OMPClause *C : Clauses) { 10393 if (C->getClauseKind() == OMPC_flush) 10394 FC = cast<OMPFlushClause>(C); 10395 else 10396 OrderClause = C; 10397 } 10398 OpenMPClauseKind MemOrderKind = OMPC_unknown; 10399 SourceLocation MemOrderLoc; 10400 for (const OMPClause *C : Clauses) { 10401 if (C->getClauseKind() == OMPC_acq_rel || 10402 C->getClauseKind() == OMPC_acquire || 10403 C->getClauseKind() == OMPC_release) { 10404 if (MemOrderKind != OMPC_unknown) { 10405 Diag(C->getBeginLoc(), diag::err_omp_several_mem_order_clauses) 10406 << getOpenMPDirectiveName(OMPD_flush) << 1 10407 << SourceRange(C->getBeginLoc(), C->getEndLoc()); 10408 Diag(MemOrderLoc, diag::note_omp_previous_mem_order_clause) 10409 << getOpenMPClauseName(MemOrderKind); 10410 } else { 10411 MemOrderKind = C->getClauseKind(); 10412 MemOrderLoc = C->getBeginLoc(); 10413 } 10414 } 10415 } 10416 if (FC && OrderClause) { 10417 Diag(FC->getLParenLoc(), diag::err_omp_flush_order_clause_and_list) 10418 << getOpenMPClauseName(OrderClause->getClauseKind()); 10419 Diag(OrderClause->getBeginLoc(), diag::note_omp_flush_order_clause_here) 10420 << getOpenMPClauseName(OrderClause->getClauseKind()); 10421 return StmtError(); 10422 } 10423 return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses); 10424 } 10425 10426 StmtResult Sema::ActOnOpenMPDepobjDirective(ArrayRef<OMPClause *> Clauses, 10427 SourceLocation StartLoc, 10428 SourceLocation EndLoc) { 10429 if (Clauses.empty()) { 10430 Diag(StartLoc, diag::err_omp_depobj_expected); 10431 return StmtError(); 10432 } else if (Clauses[0]->getClauseKind() != OMPC_depobj) { 10433 Diag(Clauses[0]->getBeginLoc(), diag::err_omp_depobj_expected); 10434 return StmtError(); 10435 } 10436 // Only depobj expression and another single clause is allowed. 10437 if (Clauses.size() > 2) { 10438 Diag(Clauses[2]->getBeginLoc(), 10439 diag::err_omp_depobj_single_clause_expected); 10440 return StmtError(); 10441 } else if (Clauses.size() < 1) { 10442 Diag(Clauses[0]->getEndLoc(), diag::err_omp_depobj_single_clause_expected); 10443 return StmtError(); 10444 } 10445 return OMPDepobjDirective::Create(Context, StartLoc, EndLoc, Clauses); 10446 } 10447 10448 StmtResult Sema::ActOnOpenMPScanDirective(ArrayRef<OMPClause *> Clauses, 10449 SourceLocation StartLoc, 10450 SourceLocation EndLoc) { 10451 // Check that exactly one clause is specified. 10452 if (Clauses.size() != 1) { 10453 Diag(Clauses.empty() ? EndLoc : Clauses[1]->getBeginLoc(), 10454 diag::err_omp_scan_single_clause_expected); 10455 return StmtError(); 10456 } 10457 // Check that scan directive is used in the scopeof the OpenMP loop body. 10458 if (Scope *S = DSAStack->getCurScope()) { 10459 Scope *ParentS = S->getParent(); 10460 if (!ParentS || ParentS->getParent() != ParentS->getBreakParent() || 10461 !ParentS->getBreakParent()->isOpenMPLoopScope()) 10462 return StmtError(Diag(StartLoc, diag::err_omp_orphaned_device_directive) 10463 << getOpenMPDirectiveName(OMPD_scan) << 5); 10464 } 10465 // Check that only one instance of scan directives is used in the same outer 10466 // region. 10467 if (DSAStack->doesParentHasScanDirective()) { 10468 Diag(StartLoc, diag::err_omp_several_directives_in_region) << "scan"; 10469 Diag(DSAStack->getParentScanDirectiveLoc(), 10470 diag::note_omp_previous_directive) 10471 << "scan"; 10472 return StmtError(); 10473 } 10474 DSAStack->setParentHasScanDirective(StartLoc); 10475 return OMPScanDirective::Create(Context, StartLoc, EndLoc, Clauses); 10476 } 10477 10478 StmtResult Sema::ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses, 10479 Stmt *AStmt, 10480 SourceLocation StartLoc, 10481 SourceLocation EndLoc) { 10482 const OMPClause *DependFound = nullptr; 10483 const OMPClause *DependSourceClause = nullptr; 10484 const OMPClause *DependSinkClause = nullptr; 10485 bool ErrorFound = false; 10486 const OMPThreadsClause *TC = nullptr; 10487 const OMPSIMDClause *SC = nullptr; 10488 for (const OMPClause *C : Clauses) { 10489 if (auto *DC = dyn_cast<OMPDependClause>(C)) { 10490 DependFound = C; 10491 if (DC->getDependencyKind() == OMPC_DEPEND_source) { 10492 if (DependSourceClause) { 10493 Diag(C->getBeginLoc(), diag::err_omp_more_one_clause) 10494 << getOpenMPDirectiveName(OMPD_ordered) 10495 << getOpenMPClauseName(OMPC_depend) << 2; 10496 ErrorFound = true; 10497 } else { 10498 DependSourceClause = C; 10499 } 10500 if (DependSinkClause) { 10501 Diag(C->getBeginLoc(), diag::err_omp_depend_sink_source_not_allowed) 10502 << 0; 10503 ErrorFound = true; 10504 } 10505 } else if (DC->getDependencyKind() == OMPC_DEPEND_sink) { 10506 if (DependSourceClause) { 10507 Diag(C->getBeginLoc(), diag::err_omp_depend_sink_source_not_allowed) 10508 << 1; 10509 ErrorFound = true; 10510 } 10511 DependSinkClause = C; 10512 } 10513 } else if (C->getClauseKind() == OMPC_threads) { 10514 TC = cast<OMPThreadsClause>(C); 10515 } else if (C->getClauseKind() == OMPC_simd) { 10516 SC = cast<OMPSIMDClause>(C); 10517 } 10518 } 10519 if (!ErrorFound && !SC && 10520 isOpenMPSimdDirective(DSAStack->getParentDirective())) { 10521 // OpenMP [2.8.1,simd Construct, Restrictions] 10522 // An ordered construct with the simd clause is the only OpenMP construct 10523 // that can appear in the simd region. 10524 Diag(StartLoc, diag::err_omp_prohibited_region_simd) 10525 << (LangOpts.OpenMP >= 50 ? 1 : 0); 10526 ErrorFound = true; 10527 } else if (DependFound && (TC || SC)) { 10528 Diag(DependFound->getBeginLoc(), diag::err_omp_depend_clause_thread_simd) 10529 << getOpenMPClauseName(TC ? TC->getClauseKind() : SC->getClauseKind()); 10530 ErrorFound = true; 10531 } else if (DependFound && !DSAStack->getParentOrderedRegionParam().first) { 10532 Diag(DependFound->getBeginLoc(), 10533 diag::err_omp_ordered_directive_without_param); 10534 ErrorFound = true; 10535 } else if (TC || Clauses.empty()) { 10536 if (const Expr *Param = DSAStack->getParentOrderedRegionParam().first) { 10537 SourceLocation ErrLoc = TC ? TC->getBeginLoc() : StartLoc; 10538 Diag(ErrLoc, diag::err_omp_ordered_directive_with_param) 10539 << (TC != nullptr); 10540 Diag(Param->getBeginLoc(), diag::note_omp_ordered_param) << 1; 10541 ErrorFound = true; 10542 } 10543 } 10544 if ((!AStmt && !DependFound) || ErrorFound) 10545 return StmtError(); 10546 10547 // OpenMP 5.0, 2.17.9, ordered Construct, Restrictions. 10548 // During execution of an iteration of a worksharing-loop or a loop nest 10549 // within a worksharing-loop, simd, or worksharing-loop SIMD region, a thread 10550 // must not execute more than one ordered region corresponding to an ordered 10551 // construct without a depend clause. 10552 if (!DependFound) { 10553 if (DSAStack->doesParentHasOrderedDirective()) { 10554 Diag(StartLoc, diag::err_omp_several_directives_in_region) << "ordered"; 10555 Diag(DSAStack->getParentOrderedDirectiveLoc(), 10556 diag::note_omp_previous_directive) 10557 << "ordered"; 10558 return StmtError(); 10559 } 10560 DSAStack->setParentHasOrderedDirective(StartLoc); 10561 } 10562 10563 if (AStmt) { 10564 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 10565 10566 setFunctionHasBranchProtectedScope(); 10567 } 10568 10569 return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt); 10570 } 10571 10572 namespace { 10573 /// Helper class for checking expression in 'omp atomic [update]' 10574 /// construct. 10575 class OpenMPAtomicUpdateChecker { 10576 /// Error results for atomic update expressions. 10577 enum ExprAnalysisErrorCode { 10578 /// A statement is not an expression statement. 10579 NotAnExpression, 10580 /// Expression is not builtin binary or unary operation. 10581 NotABinaryOrUnaryExpression, 10582 /// Unary operation is not post-/pre- increment/decrement operation. 10583 NotAnUnaryIncDecExpression, 10584 /// An expression is not of scalar type. 10585 NotAScalarType, 10586 /// A binary operation is not an assignment operation. 10587 NotAnAssignmentOp, 10588 /// RHS part of the binary operation is not a binary expression. 10589 NotABinaryExpression, 10590 /// RHS part is not additive/multiplicative/shift/biwise binary 10591 /// expression. 10592 NotABinaryOperator, 10593 /// RHS binary operation does not have reference to the updated LHS 10594 /// part. 10595 NotAnUpdateExpression, 10596 /// No errors is found. 10597 NoError 10598 }; 10599 /// Reference to Sema. 10600 Sema &SemaRef; 10601 /// A location for note diagnostics (when error is found). 10602 SourceLocation NoteLoc; 10603 /// 'x' lvalue part of the source atomic expression. 10604 Expr *X; 10605 /// 'expr' rvalue part of the source atomic expression. 10606 Expr *E; 10607 /// Helper expression of the form 10608 /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or 10609 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'. 10610 Expr *UpdateExpr; 10611 /// Is 'x' a LHS in a RHS part of full update expression. It is 10612 /// important for non-associative operations. 10613 bool IsXLHSInRHSPart; 10614 BinaryOperatorKind Op; 10615 SourceLocation OpLoc; 10616 /// true if the source expression is a postfix unary operation, false 10617 /// if it is a prefix unary operation. 10618 bool IsPostfixUpdate; 10619 10620 public: 10621 OpenMPAtomicUpdateChecker(Sema &SemaRef) 10622 : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr), 10623 IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {} 10624 /// Check specified statement that it is suitable for 'atomic update' 10625 /// constructs and extract 'x', 'expr' and Operation from the original 10626 /// expression. If DiagId and NoteId == 0, then only check is performed 10627 /// without error notification. 10628 /// \param DiagId Diagnostic which should be emitted if error is found. 10629 /// \param NoteId Diagnostic note for the main error message. 10630 /// \return true if statement is not an update expression, false otherwise. 10631 bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0); 10632 /// Return the 'x' lvalue part of the source atomic expression. 10633 Expr *getX() const { return X; } 10634 /// Return the 'expr' rvalue part of the source atomic expression. 10635 Expr *getExpr() const { return E; } 10636 /// Return the update expression used in calculation of the updated 10637 /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or 10638 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'. 10639 Expr *getUpdateExpr() const { return UpdateExpr; } 10640 /// Return true if 'x' is LHS in RHS part of full update expression, 10641 /// false otherwise. 10642 bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; } 10643 10644 /// true if the source expression is a postfix unary operation, false 10645 /// if it is a prefix unary operation. 10646 bool isPostfixUpdate() const { return IsPostfixUpdate; } 10647 10648 private: 10649 bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0, 10650 unsigned NoteId = 0); 10651 }; 10652 } // namespace 10653 10654 bool OpenMPAtomicUpdateChecker::checkBinaryOperation( 10655 BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) { 10656 ExprAnalysisErrorCode ErrorFound = NoError; 10657 SourceLocation ErrorLoc, NoteLoc; 10658 SourceRange ErrorRange, NoteRange; 10659 // Allowed constructs are: 10660 // x = x binop expr; 10661 // x = expr binop x; 10662 if (AtomicBinOp->getOpcode() == BO_Assign) { 10663 X = AtomicBinOp->getLHS(); 10664 if (const auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>( 10665 AtomicBinOp->getRHS()->IgnoreParenImpCasts())) { 10666 if (AtomicInnerBinOp->isMultiplicativeOp() || 10667 AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() || 10668 AtomicInnerBinOp->isBitwiseOp()) { 10669 Op = AtomicInnerBinOp->getOpcode(); 10670 OpLoc = AtomicInnerBinOp->getOperatorLoc(); 10671 Expr *LHS = AtomicInnerBinOp->getLHS(); 10672 Expr *RHS = AtomicInnerBinOp->getRHS(); 10673 llvm::FoldingSetNodeID XId, LHSId, RHSId; 10674 X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(), 10675 /*Canonical=*/true); 10676 LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(), 10677 /*Canonical=*/true); 10678 RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(), 10679 /*Canonical=*/true); 10680 if (XId == LHSId) { 10681 E = RHS; 10682 IsXLHSInRHSPart = true; 10683 } else if (XId == RHSId) { 10684 E = LHS; 10685 IsXLHSInRHSPart = false; 10686 } else { 10687 ErrorLoc = AtomicInnerBinOp->getExprLoc(); 10688 ErrorRange = AtomicInnerBinOp->getSourceRange(); 10689 NoteLoc = X->getExprLoc(); 10690 NoteRange = X->getSourceRange(); 10691 ErrorFound = NotAnUpdateExpression; 10692 } 10693 } else { 10694 ErrorLoc = AtomicInnerBinOp->getExprLoc(); 10695 ErrorRange = AtomicInnerBinOp->getSourceRange(); 10696 NoteLoc = AtomicInnerBinOp->getOperatorLoc(); 10697 NoteRange = SourceRange(NoteLoc, NoteLoc); 10698 ErrorFound = NotABinaryOperator; 10699 } 10700 } else { 10701 NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc(); 10702 NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange(); 10703 ErrorFound = NotABinaryExpression; 10704 } 10705 } else { 10706 ErrorLoc = AtomicBinOp->getExprLoc(); 10707 ErrorRange = AtomicBinOp->getSourceRange(); 10708 NoteLoc = AtomicBinOp->getOperatorLoc(); 10709 NoteRange = SourceRange(NoteLoc, NoteLoc); 10710 ErrorFound = NotAnAssignmentOp; 10711 } 10712 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) { 10713 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange; 10714 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange; 10715 return true; 10716 } 10717 if (SemaRef.CurContext->isDependentContext()) 10718 E = X = UpdateExpr = nullptr; 10719 return ErrorFound != NoError; 10720 } 10721 10722 bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId, 10723 unsigned NoteId) { 10724 ExprAnalysisErrorCode ErrorFound = NoError; 10725 SourceLocation ErrorLoc, NoteLoc; 10726 SourceRange ErrorRange, NoteRange; 10727 // Allowed constructs are: 10728 // x++; 10729 // x--; 10730 // ++x; 10731 // --x; 10732 // x binop= expr; 10733 // x = x binop expr; 10734 // x = expr binop x; 10735 if (auto *AtomicBody = dyn_cast<Expr>(S)) { 10736 AtomicBody = AtomicBody->IgnoreParenImpCasts(); 10737 if (AtomicBody->getType()->isScalarType() || 10738 AtomicBody->isInstantiationDependent()) { 10739 if (const auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>( 10740 AtomicBody->IgnoreParenImpCasts())) { 10741 // Check for Compound Assignment Operation 10742 Op = BinaryOperator::getOpForCompoundAssignment( 10743 AtomicCompAssignOp->getOpcode()); 10744 OpLoc = AtomicCompAssignOp->getOperatorLoc(); 10745 E = AtomicCompAssignOp->getRHS(); 10746 X = AtomicCompAssignOp->getLHS()->IgnoreParens(); 10747 IsXLHSInRHSPart = true; 10748 } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>( 10749 AtomicBody->IgnoreParenImpCasts())) { 10750 // Check for Binary Operation 10751 if (checkBinaryOperation(AtomicBinOp, DiagId, NoteId)) 10752 return true; 10753 } else if (const auto *AtomicUnaryOp = dyn_cast<UnaryOperator>( 10754 AtomicBody->IgnoreParenImpCasts())) { 10755 // Check for Unary Operation 10756 if (AtomicUnaryOp->isIncrementDecrementOp()) { 10757 IsPostfixUpdate = AtomicUnaryOp->isPostfix(); 10758 Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub; 10759 OpLoc = AtomicUnaryOp->getOperatorLoc(); 10760 X = AtomicUnaryOp->getSubExpr()->IgnoreParens(); 10761 E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get(); 10762 IsXLHSInRHSPart = true; 10763 } else { 10764 ErrorFound = NotAnUnaryIncDecExpression; 10765 ErrorLoc = AtomicUnaryOp->getExprLoc(); 10766 ErrorRange = AtomicUnaryOp->getSourceRange(); 10767 NoteLoc = AtomicUnaryOp->getOperatorLoc(); 10768 NoteRange = SourceRange(NoteLoc, NoteLoc); 10769 } 10770 } else if (!AtomicBody->isInstantiationDependent()) { 10771 ErrorFound = NotABinaryOrUnaryExpression; 10772 NoteLoc = ErrorLoc = AtomicBody->getExprLoc(); 10773 NoteRange = ErrorRange = AtomicBody->getSourceRange(); 10774 } 10775 } else { 10776 ErrorFound = NotAScalarType; 10777 NoteLoc = ErrorLoc = AtomicBody->getBeginLoc(); 10778 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc); 10779 } 10780 } else { 10781 ErrorFound = NotAnExpression; 10782 NoteLoc = ErrorLoc = S->getBeginLoc(); 10783 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc); 10784 } 10785 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) { 10786 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange; 10787 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange; 10788 return true; 10789 } 10790 if (SemaRef.CurContext->isDependentContext()) 10791 E = X = UpdateExpr = nullptr; 10792 if (ErrorFound == NoError && E && X) { 10793 // Build an update expression of form 'OpaqueValueExpr(x) binop 10794 // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop 10795 // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression. 10796 auto *OVEX = new (SemaRef.getASTContext()) 10797 OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_PRValue); 10798 auto *OVEExpr = new (SemaRef.getASTContext()) 10799 OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_PRValue); 10800 ExprResult Update = 10801 SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr, 10802 IsXLHSInRHSPart ? OVEExpr : OVEX); 10803 if (Update.isInvalid()) 10804 return true; 10805 Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(), 10806 Sema::AA_Casting); 10807 if (Update.isInvalid()) 10808 return true; 10809 UpdateExpr = Update.get(); 10810 } 10811 return ErrorFound != NoError; 10812 } 10813 10814 StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses, 10815 Stmt *AStmt, 10816 SourceLocation StartLoc, 10817 SourceLocation EndLoc) { 10818 // Register location of the first atomic directive. 10819 DSAStack->addAtomicDirectiveLoc(StartLoc); 10820 if (!AStmt) 10821 return StmtError(); 10822 10823 // 1.2.2 OpenMP Language Terminology 10824 // Structured block - An executable statement with a single entry at the 10825 // top and a single exit at the bottom. 10826 // The point of exit cannot be a branch out of the structured block. 10827 // longjmp() and throw() must not violate the entry/exit criteria. 10828 OpenMPClauseKind AtomicKind = OMPC_unknown; 10829 SourceLocation AtomicKindLoc; 10830 OpenMPClauseKind MemOrderKind = OMPC_unknown; 10831 SourceLocation MemOrderLoc; 10832 for (const OMPClause *C : Clauses) { 10833 if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write || 10834 C->getClauseKind() == OMPC_update || 10835 C->getClauseKind() == OMPC_capture) { 10836 if (AtomicKind != OMPC_unknown) { 10837 Diag(C->getBeginLoc(), diag::err_omp_atomic_several_clauses) 10838 << SourceRange(C->getBeginLoc(), C->getEndLoc()); 10839 Diag(AtomicKindLoc, diag::note_omp_previous_mem_order_clause) 10840 << getOpenMPClauseName(AtomicKind); 10841 } else { 10842 AtomicKind = C->getClauseKind(); 10843 AtomicKindLoc = C->getBeginLoc(); 10844 } 10845 } 10846 if (C->getClauseKind() == OMPC_seq_cst || 10847 C->getClauseKind() == OMPC_acq_rel || 10848 C->getClauseKind() == OMPC_acquire || 10849 C->getClauseKind() == OMPC_release || 10850 C->getClauseKind() == OMPC_relaxed) { 10851 if (MemOrderKind != OMPC_unknown) { 10852 Diag(C->getBeginLoc(), diag::err_omp_several_mem_order_clauses) 10853 << getOpenMPDirectiveName(OMPD_atomic) << 0 10854 << SourceRange(C->getBeginLoc(), C->getEndLoc()); 10855 Diag(MemOrderLoc, diag::note_omp_previous_mem_order_clause) 10856 << getOpenMPClauseName(MemOrderKind); 10857 } else { 10858 MemOrderKind = C->getClauseKind(); 10859 MemOrderLoc = C->getBeginLoc(); 10860 } 10861 } 10862 } 10863 // OpenMP 5.0, 2.17.7 atomic Construct, Restrictions 10864 // If atomic-clause is read then memory-order-clause must not be acq_rel or 10865 // release. 10866 // If atomic-clause is write then memory-order-clause must not be acq_rel or 10867 // acquire. 10868 // If atomic-clause is update or not present then memory-order-clause must not 10869 // be acq_rel or acquire. 10870 if ((AtomicKind == OMPC_read && 10871 (MemOrderKind == OMPC_acq_rel || MemOrderKind == OMPC_release)) || 10872 ((AtomicKind == OMPC_write || AtomicKind == OMPC_update || 10873 AtomicKind == OMPC_unknown) && 10874 (MemOrderKind == OMPC_acq_rel || MemOrderKind == OMPC_acquire))) { 10875 SourceLocation Loc = AtomicKindLoc; 10876 if (AtomicKind == OMPC_unknown) 10877 Loc = StartLoc; 10878 Diag(Loc, diag::err_omp_atomic_incompatible_mem_order_clause) 10879 << getOpenMPClauseName(AtomicKind) 10880 << (AtomicKind == OMPC_unknown ? 1 : 0) 10881 << getOpenMPClauseName(MemOrderKind); 10882 Diag(MemOrderLoc, diag::note_omp_previous_mem_order_clause) 10883 << getOpenMPClauseName(MemOrderKind); 10884 } 10885 10886 Stmt *Body = AStmt; 10887 if (auto *EWC = dyn_cast<ExprWithCleanups>(Body)) 10888 Body = EWC->getSubExpr(); 10889 10890 Expr *X = nullptr; 10891 Expr *V = nullptr; 10892 Expr *E = nullptr; 10893 Expr *UE = nullptr; 10894 bool IsXLHSInRHSPart = false; 10895 bool IsPostfixUpdate = false; 10896 // OpenMP [2.12.6, atomic Construct] 10897 // In the next expressions: 10898 // * x and v (as applicable) are both l-value expressions with scalar type. 10899 // * During the execution of an atomic region, multiple syntactic 10900 // occurrences of x must designate the same storage location. 10901 // * Neither of v and expr (as applicable) may access the storage location 10902 // designated by x. 10903 // * Neither of x and expr (as applicable) may access the storage location 10904 // designated by v. 10905 // * expr is an expression with scalar type. 10906 // * binop is one of +, *, -, /, &, ^, |, <<, or >>. 10907 // * binop, binop=, ++, and -- are not overloaded operators. 10908 // * The expression x binop expr must be numerically equivalent to x binop 10909 // (expr). This requirement is satisfied if the operators in expr have 10910 // precedence greater than binop, or by using parentheses around expr or 10911 // subexpressions of expr. 10912 // * The expression expr binop x must be numerically equivalent to (expr) 10913 // binop x. This requirement is satisfied if the operators in expr have 10914 // precedence equal to or greater than binop, or by using parentheses around 10915 // expr or subexpressions of expr. 10916 // * For forms that allow multiple occurrences of x, the number of times 10917 // that x is evaluated is unspecified. 10918 if (AtomicKind == OMPC_read) { 10919 enum { 10920 NotAnExpression, 10921 NotAnAssignmentOp, 10922 NotAScalarType, 10923 NotAnLValue, 10924 NoError 10925 } ErrorFound = NoError; 10926 SourceLocation ErrorLoc, NoteLoc; 10927 SourceRange ErrorRange, NoteRange; 10928 // If clause is read: 10929 // v = x; 10930 if (const auto *AtomicBody = dyn_cast<Expr>(Body)) { 10931 const auto *AtomicBinOp = 10932 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts()); 10933 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) { 10934 X = AtomicBinOp->getRHS()->IgnoreParenImpCasts(); 10935 V = AtomicBinOp->getLHS()->IgnoreParenImpCasts(); 10936 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) && 10937 (V->isInstantiationDependent() || V->getType()->isScalarType())) { 10938 if (!X->isLValue() || !V->isLValue()) { 10939 const Expr *NotLValueExpr = X->isLValue() ? V : X; 10940 ErrorFound = NotAnLValue; 10941 ErrorLoc = AtomicBinOp->getExprLoc(); 10942 ErrorRange = AtomicBinOp->getSourceRange(); 10943 NoteLoc = NotLValueExpr->getExprLoc(); 10944 NoteRange = NotLValueExpr->getSourceRange(); 10945 } 10946 } else if (!X->isInstantiationDependent() || 10947 !V->isInstantiationDependent()) { 10948 const Expr *NotScalarExpr = 10949 (X->isInstantiationDependent() || X->getType()->isScalarType()) 10950 ? V 10951 : X; 10952 ErrorFound = NotAScalarType; 10953 ErrorLoc = AtomicBinOp->getExprLoc(); 10954 ErrorRange = AtomicBinOp->getSourceRange(); 10955 NoteLoc = NotScalarExpr->getExprLoc(); 10956 NoteRange = NotScalarExpr->getSourceRange(); 10957 } 10958 } else if (!AtomicBody->isInstantiationDependent()) { 10959 ErrorFound = NotAnAssignmentOp; 10960 ErrorLoc = AtomicBody->getExprLoc(); 10961 ErrorRange = AtomicBody->getSourceRange(); 10962 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc() 10963 : AtomicBody->getExprLoc(); 10964 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange() 10965 : AtomicBody->getSourceRange(); 10966 } 10967 } else { 10968 ErrorFound = NotAnExpression; 10969 NoteLoc = ErrorLoc = Body->getBeginLoc(); 10970 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc); 10971 } 10972 if (ErrorFound != NoError) { 10973 Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement) 10974 << ErrorRange; 10975 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound 10976 << NoteRange; 10977 return StmtError(); 10978 } 10979 if (CurContext->isDependentContext()) 10980 V = X = nullptr; 10981 } else if (AtomicKind == OMPC_write) { 10982 enum { 10983 NotAnExpression, 10984 NotAnAssignmentOp, 10985 NotAScalarType, 10986 NotAnLValue, 10987 NoError 10988 } ErrorFound = NoError; 10989 SourceLocation ErrorLoc, NoteLoc; 10990 SourceRange ErrorRange, NoteRange; 10991 // If clause is write: 10992 // x = expr; 10993 if (const auto *AtomicBody = dyn_cast<Expr>(Body)) { 10994 const auto *AtomicBinOp = 10995 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts()); 10996 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) { 10997 X = AtomicBinOp->getLHS(); 10998 E = AtomicBinOp->getRHS(); 10999 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) && 11000 (E->isInstantiationDependent() || E->getType()->isScalarType())) { 11001 if (!X->isLValue()) { 11002 ErrorFound = NotAnLValue; 11003 ErrorLoc = AtomicBinOp->getExprLoc(); 11004 ErrorRange = AtomicBinOp->getSourceRange(); 11005 NoteLoc = X->getExprLoc(); 11006 NoteRange = X->getSourceRange(); 11007 } 11008 } else if (!X->isInstantiationDependent() || 11009 !E->isInstantiationDependent()) { 11010 const Expr *NotScalarExpr = 11011 (X->isInstantiationDependent() || X->getType()->isScalarType()) 11012 ? E 11013 : X; 11014 ErrorFound = NotAScalarType; 11015 ErrorLoc = AtomicBinOp->getExprLoc(); 11016 ErrorRange = AtomicBinOp->getSourceRange(); 11017 NoteLoc = NotScalarExpr->getExprLoc(); 11018 NoteRange = NotScalarExpr->getSourceRange(); 11019 } 11020 } else if (!AtomicBody->isInstantiationDependent()) { 11021 ErrorFound = NotAnAssignmentOp; 11022 ErrorLoc = AtomicBody->getExprLoc(); 11023 ErrorRange = AtomicBody->getSourceRange(); 11024 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc() 11025 : AtomicBody->getExprLoc(); 11026 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange() 11027 : AtomicBody->getSourceRange(); 11028 } 11029 } else { 11030 ErrorFound = NotAnExpression; 11031 NoteLoc = ErrorLoc = Body->getBeginLoc(); 11032 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc); 11033 } 11034 if (ErrorFound != NoError) { 11035 Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement) 11036 << ErrorRange; 11037 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound 11038 << NoteRange; 11039 return StmtError(); 11040 } 11041 if (CurContext->isDependentContext()) 11042 E = X = nullptr; 11043 } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) { 11044 // If clause is update: 11045 // x++; 11046 // x--; 11047 // ++x; 11048 // --x; 11049 // x binop= expr; 11050 // x = x binop expr; 11051 // x = expr binop x; 11052 OpenMPAtomicUpdateChecker Checker(*this); 11053 if (Checker.checkStatement( 11054 Body, (AtomicKind == OMPC_update) 11055 ? diag::err_omp_atomic_update_not_expression_statement 11056 : diag::err_omp_atomic_not_expression_statement, 11057 diag::note_omp_atomic_update)) 11058 return StmtError(); 11059 if (!CurContext->isDependentContext()) { 11060 E = Checker.getExpr(); 11061 X = Checker.getX(); 11062 UE = Checker.getUpdateExpr(); 11063 IsXLHSInRHSPart = Checker.isXLHSInRHSPart(); 11064 } 11065 } else if (AtomicKind == OMPC_capture) { 11066 enum { 11067 NotAnAssignmentOp, 11068 NotACompoundStatement, 11069 NotTwoSubstatements, 11070 NotASpecificExpression, 11071 NoError 11072 } ErrorFound = NoError; 11073 SourceLocation ErrorLoc, NoteLoc; 11074 SourceRange ErrorRange, NoteRange; 11075 if (const auto *AtomicBody = dyn_cast<Expr>(Body)) { 11076 // If clause is a capture: 11077 // v = x++; 11078 // v = x--; 11079 // v = ++x; 11080 // v = --x; 11081 // v = x binop= expr; 11082 // v = x = x binop expr; 11083 // v = x = expr binop x; 11084 const auto *AtomicBinOp = 11085 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts()); 11086 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) { 11087 V = AtomicBinOp->getLHS(); 11088 Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts(); 11089 OpenMPAtomicUpdateChecker Checker(*this); 11090 if (Checker.checkStatement( 11091 Body, diag::err_omp_atomic_capture_not_expression_statement, 11092 diag::note_omp_atomic_update)) 11093 return StmtError(); 11094 E = Checker.getExpr(); 11095 X = Checker.getX(); 11096 UE = Checker.getUpdateExpr(); 11097 IsXLHSInRHSPart = Checker.isXLHSInRHSPart(); 11098 IsPostfixUpdate = Checker.isPostfixUpdate(); 11099 } else if (!AtomicBody->isInstantiationDependent()) { 11100 ErrorLoc = AtomicBody->getExprLoc(); 11101 ErrorRange = AtomicBody->getSourceRange(); 11102 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc() 11103 : AtomicBody->getExprLoc(); 11104 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange() 11105 : AtomicBody->getSourceRange(); 11106 ErrorFound = NotAnAssignmentOp; 11107 } 11108 if (ErrorFound != NoError) { 11109 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement) 11110 << ErrorRange; 11111 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange; 11112 return StmtError(); 11113 } 11114 if (CurContext->isDependentContext()) 11115 UE = V = E = X = nullptr; 11116 } else { 11117 // If clause is a capture: 11118 // { v = x; x = expr; } 11119 // { v = x; x++; } 11120 // { v = x; x--; } 11121 // { v = x; ++x; } 11122 // { v = x; --x; } 11123 // { v = x; x binop= expr; } 11124 // { v = x; x = x binop expr; } 11125 // { v = x; x = expr binop x; } 11126 // { x++; v = x; } 11127 // { x--; v = x; } 11128 // { ++x; v = x; } 11129 // { --x; v = x; } 11130 // { x binop= expr; v = x; } 11131 // { x = x binop expr; v = x; } 11132 // { x = expr binop x; v = x; } 11133 if (auto *CS = dyn_cast<CompoundStmt>(Body)) { 11134 // Check that this is { expr1; expr2; } 11135 if (CS->size() == 2) { 11136 Stmt *First = CS->body_front(); 11137 Stmt *Second = CS->body_back(); 11138 if (auto *EWC = dyn_cast<ExprWithCleanups>(First)) 11139 First = EWC->getSubExpr()->IgnoreParenImpCasts(); 11140 if (auto *EWC = dyn_cast<ExprWithCleanups>(Second)) 11141 Second = EWC->getSubExpr()->IgnoreParenImpCasts(); 11142 // Need to find what subexpression is 'v' and what is 'x'. 11143 OpenMPAtomicUpdateChecker Checker(*this); 11144 bool IsUpdateExprFound = !Checker.checkStatement(Second); 11145 BinaryOperator *BinOp = nullptr; 11146 if (IsUpdateExprFound) { 11147 BinOp = dyn_cast<BinaryOperator>(First); 11148 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign; 11149 } 11150 if (IsUpdateExprFound && !CurContext->isDependentContext()) { 11151 // { v = x; x++; } 11152 // { v = x; x--; } 11153 // { v = x; ++x; } 11154 // { v = x; --x; } 11155 // { v = x; x binop= expr; } 11156 // { v = x; x = x binop expr; } 11157 // { v = x; x = expr binop x; } 11158 // Check that the first expression has form v = x. 11159 Expr *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts(); 11160 llvm::FoldingSetNodeID XId, PossibleXId; 11161 Checker.getX()->Profile(XId, Context, /*Canonical=*/true); 11162 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true); 11163 IsUpdateExprFound = XId == PossibleXId; 11164 if (IsUpdateExprFound) { 11165 V = BinOp->getLHS(); 11166 X = Checker.getX(); 11167 E = Checker.getExpr(); 11168 UE = Checker.getUpdateExpr(); 11169 IsXLHSInRHSPart = Checker.isXLHSInRHSPart(); 11170 IsPostfixUpdate = true; 11171 } 11172 } 11173 if (!IsUpdateExprFound) { 11174 IsUpdateExprFound = !Checker.checkStatement(First); 11175 BinOp = nullptr; 11176 if (IsUpdateExprFound) { 11177 BinOp = dyn_cast<BinaryOperator>(Second); 11178 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign; 11179 } 11180 if (IsUpdateExprFound && !CurContext->isDependentContext()) { 11181 // { x++; v = x; } 11182 // { x--; v = x; } 11183 // { ++x; v = x; } 11184 // { --x; v = x; } 11185 // { x binop= expr; v = x; } 11186 // { x = x binop expr; v = x; } 11187 // { x = expr binop x; v = x; } 11188 // Check that the second expression has form v = x. 11189 Expr *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts(); 11190 llvm::FoldingSetNodeID XId, PossibleXId; 11191 Checker.getX()->Profile(XId, Context, /*Canonical=*/true); 11192 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true); 11193 IsUpdateExprFound = XId == PossibleXId; 11194 if (IsUpdateExprFound) { 11195 V = BinOp->getLHS(); 11196 X = Checker.getX(); 11197 E = Checker.getExpr(); 11198 UE = Checker.getUpdateExpr(); 11199 IsXLHSInRHSPart = Checker.isXLHSInRHSPart(); 11200 IsPostfixUpdate = false; 11201 } 11202 } 11203 } 11204 if (!IsUpdateExprFound) { 11205 // { v = x; x = expr; } 11206 auto *FirstExpr = dyn_cast<Expr>(First); 11207 auto *SecondExpr = dyn_cast<Expr>(Second); 11208 if (!FirstExpr || !SecondExpr || 11209 !(FirstExpr->isInstantiationDependent() || 11210 SecondExpr->isInstantiationDependent())) { 11211 auto *FirstBinOp = dyn_cast<BinaryOperator>(First); 11212 if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) { 11213 ErrorFound = NotAnAssignmentOp; 11214 NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc() 11215 : First->getBeginLoc(); 11216 NoteRange = ErrorRange = FirstBinOp 11217 ? FirstBinOp->getSourceRange() 11218 : SourceRange(ErrorLoc, ErrorLoc); 11219 } else { 11220 auto *SecondBinOp = dyn_cast<BinaryOperator>(Second); 11221 if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) { 11222 ErrorFound = NotAnAssignmentOp; 11223 NoteLoc = ErrorLoc = SecondBinOp 11224 ? SecondBinOp->getOperatorLoc() 11225 : Second->getBeginLoc(); 11226 NoteRange = ErrorRange = 11227 SecondBinOp ? SecondBinOp->getSourceRange() 11228 : SourceRange(ErrorLoc, ErrorLoc); 11229 } else { 11230 Expr *PossibleXRHSInFirst = 11231 FirstBinOp->getRHS()->IgnoreParenImpCasts(); 11232 Expr *PossibleXLHSInSecond = 11233 SecondBinOp->getLHS()->IgnoreParenImpCasts(); 11234 llvm::FoldingSetNodeID X1Id, X2Id; 11235 PossibleXRHSInFirst->Profile(X1Id, Context, 11236 /*Canonical=*/true); 11237 PossibleXLHSInSecond->Profile(X2Id, Context, 11238 /*Canonical=*/true); 11239 IsUpdateExprFound = X1Id == X2Id; 11240 if (IsUpdateExprFound) { 11241 V = FirstBinOp->getLHS(); 11242 X = SecondBinOp->getLHS(); 11243 E = SecondBinOp->getRHS(); 11244 UE = nullptr; 11245 IsXLHSInRHSPart = false; 11246 IsPostfixUpdate = true; 11247 } else { 11248 ErrorFound = NotASpecificExpression; 11249 ErrorLoc = FirstBinOp->getExprLoc(); 11250 ErrorRange = FirstBinOp->getSourceRange(); 11251 NoteLoc = SecondBinOp->getLHS()->getExprLoc(); 11252 NoteRange = SecondBinOp->getRHS()->getSourceRange(); 11253 } 11254 } 11255 } 11256 } 11257 } 11258 } else { 11259 NoteLoc = ErrorLoc = Body->getBeginLoc(); 11260 NoteRange = ErrorRange = 11261 SourceRange(Body->getBeginLoc(), Body->getBeginLoc()); 11262 ErrorFound = NotTwoSubstatements; 11263 } 11264 } else { 11265 NoteLoc = ErrorLoc = Body->getBeginLoc(); 11266 NoteRange = ErrorRange = 11267 SourceRange(Body->getBeginLoc(), Body->getBeginLoc()); 11268 ErrorFound = NotACompoundStatement; 11269 } 11270 if (ErrorFound != NoError) { 11271 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement) 11272 << ErrorRange; 11273 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange; 11274 return StmtError(); 11275 } 11276 if (CurContext->isDependentContext()) 11277 UE = V = E = X = nullptr; 11278 } 11279 } 11280 11281 setFunctionHasBranchProtectedScope(); 11282 11283 return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt, 11284 X, V, E, UE, IsXLHSInRHSPart, 11285 IsPostfixUpdate); 11286 } 11287 11288 StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses, 11289 Stmt *AStmt, 11290 SourceLocation StartLoc, 11291 SourceLocation EndLoc) { 11292 if (!AStmt) 11293 return StmtError(); 11294 11295 auto *CS = cast<CapturedStmt>(AStmt); 11296 // 1.2.2 OpenMP Language Terminology 11297 // Structured block - An executable statement with a single entry at the 11298 // top and a single exit at the bottom. 11299 // The point of exit cannot be a branch out of the structured block. 11300 // longjmp() and throw() must not violate the entry/exit criteria. 11301 CS->getCapturedDecl()->setNothrow(); 11302 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target); 11303 ThisCaptureLevel > 1; --ThisCaptureLevel) { 11304 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 11305 // 1.2.2 OpenMP Language Terminology 11306 // Structured block - An executable statement with a single entry at the 11307 // top and a single exit at the bottom. 11308 // The point of exit cannot be a branch out of the structured block. 11309 // longjmp() and throw() must not violate the entry/exit criteria. 11310 CS->getCapturedDecl()->setNothrow(); 11311 } 11312 11313 // OpenMP [2.16, Nesting of Regions] 11314 // If specified, a teams construct must be contained within a target 11315 // construct. That target construct must contain no statements or directives 11316 // outside of the teams construct. 11317 if (DSAStack->hasInnerTeamsRegion()) { 11318 const Stmt *S = CS->IgnoreContainers(/*IgnoreCaptured=*/true); 11319 bool OMPTeamsFound = true; 11320 if (const auto *CS = dyn_cast<CompoundStmt>(S)) { 11321 auto I = CS->body_begin(); 11322 while (I != CS->body_end()) { 11323 const auto *OED = dyn_cast<OMPExecutableDirective>(*I); 11324 if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind()) || 11325 OMPTeamsFound) { 11326 11327 OMPTeamsFound = false; 11328 break; 11329 } 11330 ++I; 11331 } 11332 assert(I != CS->body_end() && "Not found statement"); 11333 S = *I; 11334 } else { 11335 const auto *OED = dyn_cast<OMPExecutableDirective>(S); 11336 OMPTeamsFound = OED && isOpenMPTeamsDirective(OED->getDirectiveKind()); 11337 } 11338 if (!OMPTeamsFound) { 11339 Diag(StartLoc, diag::err_omp_target_contains_not_only_teams); 11340 Diag(DSAStack->getInnerTeamsRegionLoc(), 11341 diag::note_omp_nested_teams_construct_here); 11342 Diag(S->getBeginLoc(), diag::note_omp_nested_statement_here) 11343 << isa<OMPExecutableDirective>(S); 11344 return StmtError(); 11345 } 11346 } 11347 11348 setFunctionHasBranchProtectedScope(); 11349 11350 return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt); 11351 } 11352 11353 StmtResult 11354 Sema::ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses, 11355 Stmt *AStmt, SourceLocation StartLoc, 11356 SourceLocation EndLoc) { 11357 if (!AStmt) 11358 return StmtError(); 11359 11360 auto *CS = cast<CapturedStmt>(AStmt); 11361 // 1.2.2 OpenMP Language Terminology 11362 // Structured block - An executable statement with a single entry at the 11363 // top and a single exit at the bottom. 11364 // The point of exit cannot be a branch out of the structured block. 11365 // longjmp() and throw() must not violate the entry/exit criteria. 11366 CS->getCapturedDecl()->setNothrow(); 11367 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel); 11368 ThisCaptureLevel > 1; --ThisCaptureLevel) { 11369 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 11370 // 1.2.2 OpenMP Language Terminology 11371 // Structured block - An executable statement with a single entry at the 11372 // top and a single exit at the bottom. 11373 // The point of exit cannot be a branch out of the structured block. 11374 // longjmp() and throw() must not violate the entry/exit criteria. 11375 CS->getCapturedDecl()->setNothrow(); 11376 } 11377 11378 setFunctionHasBranchProtectedScope(); 11379 11380 return OMPTargetParallelDirective::Create( 11381 Context, StartLoc, EndLoc, Clauses, AStmt, 11382 DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion()); 11383 } 11384 11385 StmtResult Sema::ActOnOpenMPTargetParallelForDirective( 11386 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 11387 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 11388 if (!AStmt) 11389 return StmtError(); 11390 11391 auto *CS = cast<CapturedStmt>(AStmt); 11392 // 1.2.2 OpenMP Language Terminology 11393 // Structured block - An executable statement with a single entry at the 11394 // top and a single exit at the bottom. 11395 // The point of exit cannot be a branch out of the structured block. 11396 // longjmp() and throw() must not violate the entry/exit criteria. 11397 CS->getCapturedDecl()->setNothrow(); 11398 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for); 11399 ThisCaptureLevel > 1; --ThisCaptureLevel) { 11400 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 11401 // 1.2.2 OpenMP Language Terminology 11402 // Structured block - An executable statement with a single entry at the 11403 // top and a single exit at the bottom. 11404 // The point of exit cannot be a branch out of the structured block. 11405 // longjmp() and throw() must not violate the entry/exit criteria. 11406 CS->getCapturedDecl()->setNothrow(); 11407 } 11408 11409 OMPLoopBasedDirective::HelperExprs B; 11410 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 11411 // define the nested loops number. 11412 unsigned NestedLoopCount = 11413 checkOpenMPLoop(OMPD_target_parallel_for, getCollapseNumberExpr(Clauses), 11414 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack, 11415 VarsWithImplicitDSA, B); 11416 if (NestedLoopCount == 0) 11417 return StmtError(); 11418 11419 assert((CurContext->isDependentContext() || B.builtAll()) && 11420 "omp target parallel for loop exprs were not built"); 11421 11422 if (!CurContext->isDependentContext()) { 11423 // Finalize the clauses that need pre-built expressions for CodeGen. 11424 for (OMPClause *C : Clauses) { 11425 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 11426 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 11427 B.NumIterations, *this, CurScope, 11428 DSAStack)) 11429 return StmtError(); 11430 } 11431 } 11432 11433 setFunctionHasBranchProtectedScope(); 11434 return OMPTargetParallelForDirective::Create( 11435 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B, 11436 DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion()); 11437 } 11438 11439 /// Check for existence of a map clause in the list of clauses. 11440 static bool hasClauses(ArrayRef<OMPClause *> Clauses, 11441 const OpenMPClauseKind K) { 11442 return llvm::any_of( 11443 Clauses, [K](const OMPClause *C) { return C->getClauseKind() == K; }); 11444 } 11445 11446 template <typename... Params> 11447 static bool hasClauses(ArrayRef<OMPClause *> Clauses, const OpenMPClauseKind K, 11448 const Params... ClauseTypes) { 11449 return hasClauses(Clauses, K) || hasClauses(Clauses, ClauseTypes...); 11450 } 11451 11452 StmtResult Sema::ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses, 11453 Stmt *AStmt, 11454 SourceLocation StartLoc, 11455 SourceLocation EndLoc) { 11456 if (!AStmt) 11457 return StmtError(); 11458 11459 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 11460 11461 // OpenMP [2.12.2, target data Construct, Restrictions] 11462 // At least one map, use_device_addr or use_device_ptr clause must appear on 11463 // the directive. 11464 if (!hasClauses(Clauses, OMPC_map, OMPC_use_device_ptr) && 11465 (LangOpts.OpenMP < 50 || !hasClauses(Clauses, OMPC_use_device_addr))) { 11466 StringRef Expected; 11467 if (LangOpts.OpenMP < 50) 11468 Expected = "'map' or 'use_device_ptr'"; 11469 else 11470 Expected = "'map', 'use_device_ptr', or 'use_device_addr'"; 11471 Diag(StartLoc, diag::err_omp_no_clause_for_directive) 11472 << Expected << getOpenMPDirectiveName(OMPD_target_data); 11473 return StmtError(); 11474 } 11475 11476 setFunctionHasBranchProtectedScope(); 11477 11478 return OMPTargetDataDirective::Create(Context, StartLoc, EndLoc, Clauses, 11479 AStmt); 11480 } 11481 11482 StmtResult 11483 Sema::ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses, 11484 SourceLocation StartLoc, 11485 SourceLocation EndLoc, Stmt *AStmt) { 11486 if (!AStmt) 11487 return StmtError(); 11488 11489 auto *CS = cast<CapturedStmt>(AStmt); 11490 // 1.2.2 OpenMP Language Terminology 11491 // Structured block - An executable statement with a single entry at the 11492 // top and a single exit at the bottom. 11493 // The point of exit cannot be a branch out of the structured block. 11494 // longjmp() and throw() must not violate the entry/exit criteria. 11495 CS->getCapturedDecl()->setNothrow(); 11496 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_enter_data); 11497 ThisCaptureLevel > 1; --ThisCaptureLevel) { 11498 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 11499 // 1.2.2 OpenMP Language Terminology 11500 // Structured block - An executable statement with a single entry at the 11501 // top and a single exit at the bottom. 11502 // The point of exit cannot be a branch out of the structured block. 11503 // longjmp() and throw() must not violate the entry/exit criteria. 11504 CS->getCapturedDecl()->setNothrow(); 11505 } 11506 11507 // OpenMP [2.10.2, Restrictions, p. 99] 11508 // At least one map clause must appear on the directive. 11509 if (!hasClauses(Clauses, OMPC_map)) { 11510 Diag(StartLoc, diag::err_omp_no_clause_for_directive) 11511 << "'map'" << getOpenMPDirectiveName(OMPD_target_enter_data); 11512 return StmtError(); 11513 } 11514 11515 return OMPTargetEnterDataDirective::Create(Context, StartLoc, EndLoc, Clauses, 11516 AStmt); 11517 } 11518 11519 StmtResult 11520 Sema::ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses, 11521 SourceLocation StartLoc, 11522 SourceLocation EndLoc, Stmt *AStmt) { 11523 if (!AStmt) 11524 return StmtError(); 11525 11526 auto *CS = cast<CapturedStmt>(AStmt); 11527 // 1.2.2 OpenMP Language Terminology 11528 // Structured block - An executable statement with a single entry at the 11529 // top and a single exit at the bottom. 11530 // The point of exit cannot be a branch out of the structured block. 11531 // longjmp() and throw() must not violate the entry/exit criteria. 11532 CS->getCapturedDecl()->setNothrow(); 11533 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_exit_data); 11534 ThisCaptureLevel > 1; --ThisCaptureLevel) { 11535 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 11536 // 1.2.2 OpenMP Language Terminology 11537 // Structured block - An executable statement with a single entry at the 11538 // top and a single exit at the bottom. 11539 // The point of exit cannot be a branch out of the structured block. 11540 // longjmp() and throw() must not violate the entry/exit criteria. 11541 CS->getCapturedDecl()->setNothrow(); 11542 } 11543 11544 // OpenMP [2.10.3, Restrictions, p. 102] 11545 // At least one map clause must appear on the directive. 11546 if (!hasClauses(Clauses, OMPC_map)) { 11547 Diag(StartLoc, diag::err_omp_no_clause_for_directive) 11548 << "'map'" << getOpenMPDirectiveName(OMPD_target_exit_data); 11549 return StmtError(); 11550 } 11551 11552 return OMPTargetExitDataDirective::Create(Context, StartLoc, EndLoc, Clauses, 11553 AStmt); 11554 } 11555 11556 StmtResult Sema::ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses, 11557 SourceLocation StartLoc, 11558 SourceLocation EndLoc, 11559 Stmt *AStmt) { 11560 if (!AStmt) 11561 return StmtError(); 11562 11563 auto *CS = cast<CapturedStmt>(AStmt); 11564 // 1.2.2 OpenMP Language Terminology 11565 // Structured block - An executable statement with a single entry at the 11566 // top and a single exit at the bottom. 11567 // The point of exit cannot be a branch out of the structured block. 11568 // longjmp() and throw() must not violate the entry/exit criteria. 11569 CS->getCapturedDecl()->setNothrow(); 11570 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_update); 11571 ThisCaptureLevel > 1; --ThisCaptureLevel) { 11572 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 11573 // 1.2.2 OpenMP Language Terminology 11574 // Structured block - An executable statement with a single entry at the 11575 // top and a single exit at the bottom. 11576 // The point of exit cannot be a branch out of the structured block. 11577 // longjmp() and throw() must not violate the entry/exit criteria. 11578 CS->getCapturedDecl()->setNothrow(); 11579 } 11580 11581 if (!hasClauses(Clauses, OMPC_to, OMPC_from)) { 11582 Diag(StartLoc, diag::err_omp_at_least_one_motion_clause_required); 11583 return StmtError(); 11584 } 11585 return OMPTargetUpdateDirective::Create(Context, StartLoc, EndLoc, Clauses, 11586 AStmt); 11587 } 11588 11589 StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses, 11590 Stmt *AStmt, SourceLocation StartLoc, 11591 SourceLocation EndLoc) { 11592 if (!AStmt) 11593 return StmtError(); 11594 11595 auto *CS = cast<CapturedStmt>(AStmt); 11596 // 1.2.2 OpenMP Language Terminology 11597 // Structured block - An executable statement with a single entry at the 11598 // top and a single exit at the bottom. 11599 // The point of exit cannot be a branch out of the structured block. 11600 // longjmp() and throw() must not violate the entry/exit criteria. 11601 CS->getCapturedDecl()->setNothrow(); 11602 11603 setFunctionHasBranchProtectedScope(); 11604 11605 DSAStack->setParentTeamsRegionLoc(StartLoc); 11606 11607 return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt); 11608 } 11609 11610 StmtResult 11611 Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc, 11612 SourceLocation EndLoc, 11613 OpenMPDirectiveKind CancelRegion) { 11614 if (DSAStack->isParentNowaitRegion()) { 11615 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0; 11616 return StmtError(); 11617 } 11618 if (DSAStack->isParentOrderedRegion()) { 11619 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0; 11620 return StmtError(); 11621 } 11622 return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc, 11623 CancelRegion); 11624 } 11625 11626 StmtResult Sema::ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses, 11627 SourceLocation StartLoc, 11628 SourceLocation EndLoc, 11629 OpenMPDirectiveKind CancelRegion) { 11630 if (DSAStack->isParentNowaitRegion()) { 11631 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1; 11632 return StmtError(); 11633 } 11634 if (DSAStack->isParentOrderedRegion()) { 11635 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1; 11636 return StmtError(); 11637 } 11638 DSAStack->setParentCancelRegion(/*Cancel=*/true); 11639 return OMPCancelDirective::Create(Context, StartLoc, EndLoc, Clauses, 11640 CancelRegion); 11641 } 11642 11643 static bool checkReductionClauseWithNogroup(Sema &S, 11644 ArrayRef<OMPClause *> Clauses) { 11645 const OMPClause *ReductionClause = nullptr; 11646 const OMPClause *NogroupClause = nullptr; 11647 for (const OMPClause *C : Clauses) { 11648 if (C->getClauseKind() == OMPC_reduction) { 11649 ReductionClause = C; 11650 if (NogroupClause) 11651 break; 11652 continue; 11653 } 11654 if (C->getClauseKind() == OMPC_nogroup) { 11655 NogroupClause = C; 11656 if (ReductionClause) 11657 break; 11658 continue; 11659 } 11660 } 11661 if (ReductionClause && NogroupClause) { 11662 S.Diag(ReductionClause->getBeginLoc(), diag::err_omp_reduction_with_nogroup) 11663 << SourceRange(NogroupClause->getBeginLoc(), 11664 NogroupClause->getEndLoc()); 11665 return true; 11666 } 11667 return false; 11668 } 11669 11670 StmtResult Sema::ActOnOpenMPTaskLoopDirective( 11671 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 11672 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 11673 if (!AStmt) 11674 return StmtError(); 11675 11676 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 11677 OMPLoopBasedDirective::HelperExprs B; 11678 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 11679 // define the nested loops number. 11680 unsigned NestedLoopCount = 11681 checkOpenMPLoop(OMPD_taskloop, getCollapseNumberExpr(Clauses), 11682 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack, 11683 VarsWithImplicitDSA, B); 11684 if (NestedLoopCount == 0) 11685 return StmtError(); 11686 11687 assert((CurContext->isDependentContext() || B.builtAll()) && 11688 "omp for loop exprs were not built"); 11689 11690 // OpenMP, [2.9.2 taskloop Construct, Restrictions] 11691 // The grainsize clause and num_tasks clause are mutually exclusive and may 11692 // not appear on the same taskloop directive. 11693 if (checkMutuallyExclusiveClauses(*this, Clauses, 11694 {OMPC_grainsize, OMPC_num_tasks})) 11695 return StmtError(); 11696 // OpenMP, [2.9.2 taskloop Construct, Restrictions] 11697 // If a reduction clause is present on the taskloop directive, the nogroup 11698 // clause must not be specified. 11699 if (checkReductionClauseWithNogroup(*this, Clauses)) 11700 return StmtError(); 11701 11702 setFunctionHasBranchProtectedScope(); 11703 return OMPTaskLoopDirective::Create(Context, StartLoc, EndLoc, 11704 NestedLoopCount, Clauses, AStmt, B, 11705 DSAStack->isCancelRegion()); 11706 } 11707 11708 StmtResult Sema::ActOnOpenMPTaskLoopSimdDirective( 11709 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 11710 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 11711 if (!AStmt) 11712 return StmtError(); 11713 11714 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 11715 OMPLoopBasedDirective::HelperExprs B; 11716 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 11717 // define the nested loops number. 11718 unsigned NestedLoopCount = 11719 checkOpenMPLoop(OMPD_taskloop_simd, getCollapseNumberExpr(Clauses), 11720 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack, 11721 VarsWithImplicitDSA, B); 11722 if (NestedLoopCount == 0) 11723 return StmtError(); 11724 11725 assert((CurContext->isDependentContext() || B.builtAll()) && 11726 "omp for loop exprs were not built"); 11727 11728 if (!CurContext->isDependentContext()) { 11729 // Finalize the clauses that need pre-built expressions for CodeGen. 11730 for (OMPClause *C : Clauses) { 11731 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 11732 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 11733 B.NumIterations, *this, CurScope, 11734 DSAStack)) 11735 return StmtError(); 11736 } 11737 } 11738 11739 // OpenMP, [2.9.2 taskloop Construct, Restrictions] 11740 // The grainsize clause and num_tasks clause are mutually exclusive and may 11741 // not appear on the same taskloop directive. 11742 if (checkMutuallyExclusiveClauses(*this, Clauses, 11743 {OMPC_grainsize, OMPC_num_tasks})) 11744 return StmtError(); 11745 // OpenMP, [2.9.2 taskloop Construct, Restrictions] 11746 // If a reduction clause is present on the taskloop directive, the nogroup 11747 // clause must not be specified. 11748 if (checkReductionClauseWithNogroup(*this, Clauses)) 11749 return StmtError(); 11750 if (checkSimdlenSafelenSpecified(*this, Clauses)) 11751 return StmtError(); 11752 11753 setFunctionHasBranchProtectedScope(); 11754 return OMPTaskLoopSimdDirective::Create(Context, StartLoc, EndLoc, 11755 NestedLoopCount, Clauses, AStmt, B); 11756 } 11757 11758 StmtResult Sema::ActOnOpenMPMasterTaskLoopDirective( 11759 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 11760 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 11761 if (!AStmt) 11762 return StmtError(); 11763 11764 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 11765 OMPLoopBasedDirective::HelperExprs B; 11766 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 11767 // define the nested loops number. 11768 unsigned NestedLoopCount = 11769 checkOpenMPLoop(OMPD_master_taskloop, getCollapseNumberExpr(Clauses), 11770 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack, 11771 VarsWithImplicitDSA, B); 11772 if (NestedLoopCount == 0) 11773 return StmtError(); 11774 11775 assert((CurContext->isDependentContext() || B.builtAll()) && 11776 "omp for loop exprs were not built"); 11777 11778 // OpenMP, [2.9.2 taskloop Construct, Restrictions] 11779 // The grainsize clause and num_tasks clause are mutually exclusive and may 11780 // not appear on the same taskloop directive. 11781 if (checkMutuallyExclusiveClauses(*this, Clauses, 11782 {OMPC_grainsize, OMPC_num_tasks})) 11783 return StmtError(); 11784 // OpenMP, [2.9.2 taskloop Construct, Restrictions] 11785 // If a reduction clause is present on the taskloop directive, the nogroup 11786 // clause must not be specified. 11787 if (checkReductionClauseWithNogroup(*this, Clauses)) 11788 return StmtError(); 11789 11790 setFunctionHasBranchProtectedScope(); 11791 return OMPMasterTaskLoopDirective::Create(Context, StartLoc, EndLoc, 11792 NestedLoopCount, Clauses, AStmt, B, 11793 DSAStack->isCancelRegion()); 11794 } 11795 11796 StmtResult Sema::ActOnOpenMPMasterTaskLoopSimdDirective( 11797 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 11798 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 11799 if (!AStmt) 11800 return StmtError(); 11801 11802 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 11803 OMPLoopBasedDirective::HelperExprs B; 11804 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 11805 // define the nested loops number. 11806 unsigned NestedLoopCount = 11807 checkOpenMPLoop(OMPD_master_taskloop_simd, getCollapseNumberExpr(Clauses), 11808 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack, 11809 VarsWithImplicitDSA, B); 11810 if (NestedLoopCount == 0) 11811 return StmtError(); 11812 11813 assert((CurContext->isDependentContext() || B.builtAll()) && 11814 "omp for loop exprs were not built"); 11815 11816 if (!CurContext->isDependentContext()) { 11817 // Finalize the clauses that need pre-built expressions for CodeGen. 11818 for (OMPClause *C : Clauses) { 11819 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 11820 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 11821 B.NumIterations, *this, CurScope, 11822 DSAStack)) 11823 return StmtError(); 11824 } 11825 } 11826 11827 // OpenMP, [2.9.2 taskloop Construct, Restrictions] 11828 // The grainsize clause and num_tasks clause are mutually exclusive and may 11829 // not appear on the same taskloop directive. 11830 if (checkMutuallyExclusiveClauses(*this, Clauses, 11831 {OMPC_grainsize, OMPC_num_tasks})) 11832 return StmtError(); 11833 // OpenMP, [2.9.2 taskloop Construct, Restrictions] 11834 // If a reduction clause is present on the taskloop directive, the nogroup 11835 // clause must not be specified. 11836 if (checkReductionClauseWithNogroup(*this, Clauses)) 11837 return StmtError(); 11838 if (checkSimdlenSafelenSpecified(*this, Clauses)) 11839 return StmtError(); 11840 11841 setFunctionHasBranchProtectedScope(); 11842 return OMPMasterTaskLoopSimdDirective::Create( 11843 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 11844 } 11845 11846 StmtResult Sema::ActOnOpenMPParallelMasterTaskLoopDirective( 11847 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 11848 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 11849 if (!AStmt) 11850 return StmtError(); 11851 11852 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 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_parallel_master_taskloop); 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' or 'ordered' with number of loops, it will 11874 // define the nested loops number. 11875 unsigned NestedLoopCount = checkOpenMPLoop( 11876 OMPD_parallel_master_taskloop, getCollapseNumberExpr(Clauses), 11877 /*OrderedLoopCountExpr=*/nullptr, CS, *this, *DSAStack, 11878 VarsWithImplicitDSA, B); 11879 if (NestedLoopCount == 0) 11880 return StmtError(); 11881 11882 assert((CurContext->isDependentContext() || B.builtAll()) && 11883 "omp for loop exprs were not built"); 11884 11885 // OpenMP, [2.9.2 taskloop Construct, Restrictions] 11886 // The grainsize clause and num_tasks clause are mutually exclusive and may 11887 // not appear on the same taskloop directive. 11888 if (checkMutuallyExclusiveClauses(*this, Clauses, 11889 {OMPC_grainsize, OMPC_num_tasks})) 11890 return StmtError(); 11891 // OpenMP, [2.9.2 taskloop Construct, Restrictions] 11892 // If a reduction clause is present on the taskloop directive, the nogroup 11893 // clause must not be specified. 11894 if (checkReductionClauseWithNogroup(*this, Clauses)) 11895 return StmtError(); 11896 11897 setFunctionHasBranchProtectedScope(); 11898 return OMPParallelMasterTaskLoopDirective::Create( 11899 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B, 11900 DSAStack->isCancelRegion()); 11901 } 11902 11903 StmtResult Sema::ActOnOpenMPParallelMasterTaskLoopSimdDirective( 11904 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 11905 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 11906 if (!AStmt) 11907 return StmtError(); 11908 11909 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 11910 auto *CS = cast<CapturedStmt>(AStmt); 11911 // 1.2.2 OpenMP Language Terminology 11912 // Structured block - An executable statement with a single entry at the 11913 // top and a single exit at the bottom. 11914 // The point of exit cannot be a branch out of the structured block. 11915 // longjmp() and throw() must not violate the entry/exit criteria. 11916 CS->getCapturedDecl()->setNothrow(); 11917 for (int ThisCaptureLevel = 11918 getOpenMPCaptureLevels(OMPD_parallel_master_taskloop_simd); 11919 ThisCaptureLevel > 1; --ThisCaptureLevel) { 11920 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 11921 // 1.2.2 OpenMP Language Terminology 11922 // Structured block - An executable statement with a single entry at the 11923 // top and a single exit at the bottom. 11924 // The point of exit cannot be a branch out of the structured block. 11925 // longjmp() and throw() must not violate the entry/exit criteria. 11926 CS->getCapturedDecl()->setNothrow(); 11927 } 11928 11929 OMPLoopBasedDirective::HelperExprs B; 11930 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 11931 // define the nested loops number. 11932 unsigned NestedLoopCount = checkOpenMPLoop( 11933 OMPD_parallel_master_taskloop_simd, getCollapseNumberExpr(Clauses), 11934 /*OrderedLoopCountExpr=*/nullptr, CS, *this, *DSAStack, 11935 VarsWithImplicitDSA, B); 11936 if (NestedLoopCount == 0) 11937 return StmtError(); 11938 11939 assert((CurContext->isDependentContext() || B.builtAll()) && 11940 "omp for loop exprs were not built"); 11941 11942 if (!CurContext->isDependentContext()) { 11943 // Finalize the clauses that need pre-built expressions for CodeGen. 11944 for (OMPClause *C : Clauses) { 11945 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 11946 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 11947 B.NumIterations, *this, CurScope, 11948 DSAStack)) 11949 return StmtError(); 11950 } 11951 } 11952 11953 // OpenMP, [2.9.2 taskloop Construct, Restrictions] 11954 // The grainsize clause and num_tasks clause are mutually exclusive and may 11955 // not appear on the same taskloop directive. 11956 if (checkMutuallyExclusiveClauses(*this, Clauses, 11957 {OMPC_grainsize, OMPC_num_tasks})) 11958 return StmtError(); 11959 // OpenMP, [2.9.2 taskloop Construct, Restrictions] 11960 // If a reduction clause is present on the taskloop directive, the nogroup 11961 // clause must not be specified. 11962 if (checkReductionClauseWithNogroup(*this, Clauses)) 11963 return StmtError(); 11964 if (checkSimdlenSafelenSpecified(*this, Clauses)) 11965 return StmtError(); 11966 11967 setFunctionHasBranchProtectedScope(); 11968 return OMPParallelMasterTaskLoopSimdDirective::Create( 11969 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 11970 } 11971 11972 StmtResult Sema::ActOnOpenMPDistributeDirective( 11973 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 11974 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 11975 if (!AStmt) 11976 return StmtError(); 11977 11978 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 11979 OMPLoopBasedDirective::HelperExprs B; 11980 // In presence of clause 'collapse' with number of loops, it will 11981 // define the nested loops number. 11982 unsigned NestedLoopCount = 11983 checkOpenMPLoop(OMPD_distribute, getCollapseNumberExpr(Clauses), 11984 nullptr /*ordered not a clause on distribute*/, AStmt, 11985 *this, *DSAStack, VarsWithImplicitDSA, B); 11986 if (NestedLoopCount == 0) 11987 return StmtError(); 11988 11989 assert((CurContext->isDependentContext() || B.builtAll()) && 11990 "omp for loop exprs were not built"); 11991 11992 setFunctionHasBranchProtectedScope(); 11993 return OMPDistributeDirective::Create(Context, StartLoc, EndLoc, 11994 NestedLoopCount, Clauses, AStmt, B); 11995 } 11996 11997 StmtResult Sema::ActOnOpenMPDistributeParallelForDirective( 11998 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 11999 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 12000 if (!AStmt) 12001 return StmtError(); 12002 12003 auto *CS = cast<CapturedStmt>(AStmt); 12004 // 1.2.2 OpenMP Language Terminology 12005 // Structured block - An executable statement with a single entry at the 12006 // top and a single exit at the bottom. 12007 // The point of exit cannot be a branch out of the structured block. 12008 // longjmp() and throw() must not violate the entry/exit criteria. 12009 CS->getCapturedDecl()->setNothrow(); 12010 for (int ThisCaptureLevel = 12011 getOpenMPCaptureLevels(OMPD_distribute_parallel_for); 12012 ThisCaptureLevel > 1; --ThisCaptureLevel) { 12013 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 12014 // 1.2.2 OpenMP Language Terminology 12015 // Structured block - An executable statement with a single entry at the 12016 // top and a single exit at the bottom. 12017 // The point of exit cannot be a branch out of the structured block. 12018 // longjmp() and throw() must not violate the entry/exit criteria. 12019 CS->getCapturedDecl()->setNothrow(); 12020 } 12021 12022 OMPLoopBasedDirective::HelperExprs B; 12023 // In presence of clause 'collapse' with number of loops, it will 12024 // define the nested loops number. 12025 unsigned NestedLoopCount = checkOpenMPLoop( 12026 OMPD_distribute_parallel_for, getCollapseNumberExpr(Clauses), 12027 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack, 12028 VarsWithImplicitDSA, B); 12029 if (NestedLoopCount == 0) 12030 return StmtError(); 12031 12032 assert((CurContext->isDependentContext() || B.builtAll()) && 12033 "omp for loop exprs were not built"); 12034 12035 setFunctionHasBranchProtectedScope(); 12036 return OMPDistributeParallelForDirective::Create( 12037 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B, 12038 DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion()); 12039 } 12040 12041 StmtResult Sema::ActOnOpenMPDistributeParallelForSimdDirective( 12042 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 12043 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 12044 if (!AStmt) 12045 return StmtError(); 12046 12047 auto *CS = cast<CapturedStmt>(AStmt); 12048 // 1.2.2 OpenMP Language Terminology 12049 // Structured block - An executable statement with a single entry at the 12050 // top and a single exit at the bottom. 12051 // The point of exit cannot be a branch out of the structured block. 12052 // longjmp() and throw() must not violate the entry/exit criteria. 12053 CS->getCapturedDecl()->setNothrow(); 12054 for (int ThisCaptureLevel = 12055 getOpenMPCaptureLevels(OMPD_distribute_parallel_for_simd); 12056 ThisCaptureLevel > 1; --ThisCaptureLevel) { 12057 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 12058 // 1.2.2 OpenMP Language Terminology 12059 // Structured block - An executable statement with a single entry at the 12060 // top and a single exit at the bottom. 12061 // The point of exit cannot be a branch out of the structured block. 12062 // longjmp() and throw() must not violate the entry/exit criteria. 12063 CS->getCapturedDecl()->setNothrow(); 12064 } 12065 12066 OMPLoopBasedDirective::HelperExprs B; 12067 // In presence of clause 'collapse' with number of loops, it will 12068 // define the nested loops number. 12069 unsigned NestedLoopCount = checkOpenMPLoop( 12070 OMPD_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses), 12071 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack, 12072 VarsWithImplicitDSA, B); 12073 if (NestedLoopCount == 0) 12074 return StmtError(); 12075 12076 assert((CurContext->isDependentContext() || B.builtAll()) && 12077 "omp for loop exprs were not built"); 12078 12079 if (!CurContext->isDependentContext()) { 12080 // Finalize the clauses that need pre-built expressions for CodeGen. 12081 for (OMPClause *C : Clauses) { 12082 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 12083 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 12084 B.NumIterations, *this, CurScope, 12085 DSAStack)) 12086 return StmtError(); 12087 } 12088 } 12089 12090 if (checkSimdlenSafelenSpecified(*this, Clauses)) 12091 return StmtError(); 12092 12093 setFunctionHasBranchProtectedScope(); 12094 return OMPDistributeParallelForSimdDirective::Create( 12095 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 12096 } 12097 12098 StmtResult Sema::ActOnOpenMPDistributeSimdDirective( 12099 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 12100 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 12101 if (!AStmt) 12102 return StmtError(); 12103 12104 auto *CS = cast<CapturedStmt>(AStmt); 12105 // 1.2.2 OpenMP Language Terminology 12106 // Structured block - An executable statement with a single entry at the 12107 // top and a single exit at the bottom. 12108 // The point of exit cannot be a branch out of the structured block. 12109 // longjmp() and throw() must not violate the entry/exit criteria. 12110 CS->getCapturedDecl()->setNothrow(); 12111 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_distribute_simd); 12112 ThisCaptureLevel > 1; --ThisCaptureLevel) { 12113 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 12114 // 1.2.2 OpenMP Language Terminology 12115 // Structured block - An executable statement with a single entry at the 12116 // top and a single exit at the bottom. 12117 // The point of exit cannot be a branch out of the structured block. 12118 // longjmp() and throw() must not violate the entry/exit criteria. 12119 CS->getCapturedDecl()->setNothrow(); 12120 } 12121 12122 OMPLoopBasedDirective::HelperExprs B; 12123 // In presence of clause 'collapse' with number of loops, it will 12124 // define the nested loops number. 12125 unsigned NestedLoopCount = 12126 checkOpenMPLoop(OMPD_distribute_simd, getCollapseNumberExpr(Clauses), 12127 nullptr /*ordered not a clause on distribute*/, CS, *this, 12128 *DSAStack, VarsWithImplicitDSA, B); 12129 if (NestedLoopCount == 0) 12130 return StmtError(); 12131 12132 assert((CurContext->isDependentContext() || B.builtAll()) && 12133 "omp for loop exprs were not built"); 12134 12135 if (!CurContext->isDependentContext()) { 12136 // Finalize the clauses that need pre-built expressions for CodeGen. 12137 for (OMPClause *C : Clauses) { 12138 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 12139 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 12140 B.NumIterations, *this, CurScope, 12141 DSAStack)) 12142 return StmtError(); 12143 } 12144 } 12145 12146 if (checkSimdlenSafelenSpecified(*this, Clauses)) 12147 return StmtError(); 12148 12149 setFunctionHasBranchProtectedScope(); 12150 return OMPDistributeSimdDirective::Create(Context, StartLoc, EndLoc, 12151 NestedLoopCount, Clauses, AStmt, B); 12152 } 12153 12154 StmtResult Sema::ActOnOpenMPTargetParallelForSimdDirective( 12155 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 12156 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 12157 if (!AStmt) 12158 return StmtError(); 12159 12160 auto *CS = cast<CapturedStmt>(AStmt); 12161 // 1.2.2 OpenMP Language Terminology 12162 // Structured block - An executable statement with a single entry at the 12163 // top and a single exit at the bottom. 12164 // The point of exit cannot be a branch out of the structured block. 12165 // longjmp() and throw() must not violate the entry/exit criteria. 12166 CS->getCapturedDecl()->setNothrow(); 12167 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for); 12168 ThisCaptureLevel > 1; --ThisCaptureLevel) { 12169 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 12170 // 1.2.2 OpenMP Language Terminology 12171 // Structured block - An executable statement with a single entry at the 12172 // top and a single exit at the bottom. 12173 // The point of exit cannot be a branch out of the structured block. 12174 // longjmp() and throw() must not violate the entry/exit criteria. 12175 CS->getCapturedDecl()->setNothrow(); 12176 } 12177 12178 OMPLoopBasedDirective::HelperExprs B; 12179 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 12180 // define the nested loops number. 12181 unsigned NestedLoopCount = checkOpenMPLoop( 12182 OMPD_target_parallel_for_simd, getCollapseNumberExpr(Clauses), 12183 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack, 12184 VarsWithImplicitDSA, B); 12185 if (NestedLoopCount == 0) 12186 return StmtError(); 12187 12188 assert((CurContext->isDependentContext() || B.builtAll()) && 12189 "omp target parallel for simd loop exprs were not built"); 12190 12191 if (!CurContext->isDependentContext()) { 12192 // Finalize the clauses that need pre-built expressions for CodeGen. 12193 for (OMPClause *C : Clauses) { 12194 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 12195 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 12196 B.NumIterations, *this, CurScope, 12197 DSAStack)) 12198 return StmtError(); 12199 } 12200 } 12201 if (checkSimdlenSafelenSpecified(*this, Clauses)) 12202 return StmtError(); 12203 12204 setFunctionHasBranchProtectedScope(); 12205 return OMPTargetParallelForSimdDirective::Create( 12206 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 12207 } 12208 12209 StmtResult Sema::ActOnOpenMPTargetSimdDirective( 12210 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 12211 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 12212 if (!AStmt) 12213 return StmtError(); 12214 12215 auto *CS = cast<CapturedStmt>(AStmt); 12216 // 1.2.2 OpenMP Language Terminology 12217 // Structured block - An executable statement with a single entry at the 12218 // top and a single exit at the bottom. 12219 // The point of exit cannot be a branch out of the structured block. 12220 // longjmp() and throw() must not violate the entry/exit criteria. 12221 CS->getCapturedDecl()->setNothrow(); 12222 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_simd); 12223 ThisCaptureLevel > 1; --ThisCaptureLevel) { 12224 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 12225 // 1.2.2 OpenMP Language Terminology 12226 // Structured block - An executable statement with a single entry at the 12227 // top and a single exit at the bottom. 12228 // The point of exit cannot be a branch out of the structured block. 12229 // longjmp() and throw() must not violate the entry/exit criteria. 12230 CS->getCapturedDecl()->setNothrow(); 12231 } 12232 12233 OMPLoopBasedDirective::HelperExprs B; 12234 // In presence of clause 'collapse' with number of loops, it will define the 12235 // nested loops number. 12236 unsigned NestedLoopCount = 12237 checkOpenMPLoop(OMPD_target_simd, getCollapseNumberExpr(Clauses), 12238 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack, 12239 VarsWithImplicitDSA, B); 12240 if (NestedLoopCount == 0) 12241 return StmtError(); 12242 12243 assert((CurContext->isDependentContext() || B.builtAll()) && 12244 "omp target simd loop exprs were not built"); 12245 12246 if (!CurContext->isDependentContext()) { 12247 // Finalize the clauses that need pre-built expressions for CodeGen. 12248 for (OMPClause *C : Clauses) { 12249 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 12250 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 12251 B.NumIterations, *this, CurScope, 12252 DSAStack)) 12253 return StmtError(); 12254 } 12255 } 12256 12257 if (checkSimdlenSafelenSpecified(*this, Clauses)) 12258 return StmtError(); 12259 12260 setFunctionHasBranchProtectedScope(); 12261 return OMPTargetSimdDirective::Create(Context, StartLoc, EndLoc, 12262 NestedLoopCount, Clauses, AStmt, B); 12263 } 12264 12265 StmtResult Sema::ActOnOpenMPTeamsDistributeDirective( 12266 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 12267 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 12268 if (!AStmt) 12269 return StmtError(); 12270 12271 auto *CS = cast<CapturedStmt>(AStmt); 12272 // 1.2.2 OpenMP Language Terminology 12273 // Structured block - An executable statement with a single entry at the 12274 // top and a single exit at the bottom. 12275 // The point of exit cannot be a branch out of the structured block. 12276 // longjmp() and throw() must not violate the entry/exit criteria. 12277 CS->getCapturedDecl()->setNothrow(); 12278 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_teams_distribute); 12279 ThisCaptureLevel > 1; --ThisCaptureLevel) { 12280 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 12281 // 1.2.2 OpenMP Language Terminology 12282 // Structured block - An executable statement with a single entry at the 12283 // top and a single exit at the bottom. 12284 // The point of exit cannot be a branch out of the structured block. 12285 // longjmp() and throw() must not violate the entry/exit criteria. 12286 CS->getCapturedDecl()->setNothrow(); 12287 } 12288 12289 OMPLoopBasedDirective::HelperExprs B; 12290 // In presence of clause 'collapse' with number of loops, it will 12291 // define the nested loops number. 12292 unsigned NestedLoopCount = 12293 checkOpenMPLoop(OMPD_teams_distribute, getCollapseNumberExpr(Clauses), 12294 nullptr /*ordered not a clause on distribute*/, CS, *this, 12295 *DSAStack, VarsWithImplicitDSA, B); 12296 if (NestedLoopCount == 0) 12297 return StmtError(); 12298 12299 assert((CurContext->isDependentContext() || B.builtAll()) && 12300 "omp teams distribute loop exprs were not built"); 12301 12302 setFunctionHasBranchProtectedScope(); 12303 12304 DSAStack->setParentTeamsRegionLoc(StartLoc); 12305 12306 return OMPTeamsDistributeDirective::Create( 12307 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 12308 } 12309 12310 StmtResult Sema::ActOnOpenMPTeamsDistributeSimdDirective( 12311 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 12312 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 12313 if (!AStmt) 12314 return StmtError(); 12315 12316 auto *CS = cast<CapturedStmt>(AStmt); 12317 // 1.2.2 OpenMP Language Terminology 12318 // Structured block - An executable statement with a single entry at the 12319 // top and a single exit at the bottom. 12320 // The point of exit cannot be a branch out of the structured block. 12321 // longjmp() and throw() must not violate the entry/exit criteria. 12322 CS->getCapturedDecl()->setNothrow(); 12323 for (int ThisCaptureLevel = 12324 getOpenMPCaptureLevels(OMPD_teams_distribute_simd); 12325 ThisCaptureLevel > 1; --ThisCaptureLevel) { 12326 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 12327 // 1.2.2 OpenMP Language Terminology 12328 // Structured block - An executable statement with a single entry at the 12329 // top and a single exit at the bottom. 12330 // The point of exit cannot be a branch out of the structured block. 12331 // longjmp() and throw() must not violate the entry/exit criteria. 12332 CS->getCapturedDecl()->setNothrow(); 12333 } 12334 12335 OMPLoopBasedDirective::HelperExprs B; 12336 // In presence of clause 'collapse' with number of loops, it will 12337 // define the nested loops number. 12338 unsigned NestedLoopCount = checkOpenMPLoop( 12339 OMPD_teams_distribute_simd, getCollapseNumberExpr(Clauses), 12340 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack, 12341 VarsWithImplicitDSA, B); 12342 12343 if (NestedLoopCount == 0) 12344 return StmtError(); 12345 12346 assert((CurContext->isDependentContext() || B.builtAll()) && 12347 "omp teams distribute simd loop exprs were not built"); 12348 12349 if (!CurContext->isDependentContext()) { 12350 // Finalize the clauses that need pre-built expressions for CodeGen. 12351 for (OMPClause *C : Clauses) { 12352 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 12353 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 12354 B.NumIterations, *this, CurScope, 12355 DSAStack)) 12356 return StmtError(); 12357 } 12358 } 12359 12360 if (checkSimdlenSafelenSpecified(*this, Clauses)) 12361 return StmtError(); 12362 12363 setFunctionHasBranchProtectedScope(); 12364 12365 DSAStack->setParentTeamsRegionLoc(StartLoc); 12366 12367 return OMPTeamsDistributeSimdDirective::Create( 12368 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 12369 } 12370 12371 StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForSimdDirective( 12372 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 12373 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 12374 if (!AStmt) 12375 return StmtError(); 12376 12377 auto *CS = cast<CapturedStmt>(AStmt); 12378 // 1.2.2 OpenMP Language Terminology 12379 // Structured block - An executable statement with a single entry at the 12380 // top and a single exit at the bottom. 12381 // The point of exit cannot be a branch out of the structured block. 12382 // longjmp() and throw() must not violate the entry/exit criteria. 12383 CS->getCapturedDecl()->setNothrow(); 12384 12385 for (int ThisCaptureLevel = 12386 getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for_simd); 12387 ThisCaptureLevel > 1; --ThisCaptureLevel) { 12388 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 12389 // 1.2.2 OpenMP Language Terminology 12390 // Structured block - An executable statement with a single entry at the 12391 // top and a single exit at the bottom. 12392 // The point of exit cannot be a branch out of the structured block. 12393 // longjmp() and throw() must not violate the entry/exit criteria. 12394 CS->getCapturedDecl()->setNothrow(); 12395 } 12396 12397 OMPLoopBasedDirective::HelperExprs B; 12398 // In presence of clause 'collapse' with number of loops, it will 12399 // define the nested loops number. 12400 unsigned NestedLoopCount = checkOpenMPLoop( 12401 OMPD_teams_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses), 12402 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack, 12403 VarsWithImplicitDSA, B); 12404 12405 if (NestedLoopCount == 0) 12406 return StmtError(); 12407 12408 assert((CurContext->isDependentContext() || B.builtAll()) && 12409 "omp for loop exprs were not built"); 12410 12411 if (!CurContext->isDependentContext()) { 12412 // Finalize the clauses that need pre-built expressions for CodeGen. 12413 for (OMPClause *C : Clauses) { 12414 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 12415 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 12416 B.NumIterations, *this, CurScope, 12417 DSAStack)) 12418 return StmtError(); 12419 } 12420 } 12421 12422 if (checkSimdlenSafelenSpecified(*this, Clauses)) 12423 return StmtError(); 12424 12425 setFunctionHasBranchProtectedScope(); 12426 12427 DSAStack->setParentTeamsRegionLoc(StartLoc); 12428 12429 return OMPTeamsDistributeParallelForSimdDirective::Create( 12430 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 12431 } 12432 12433 StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForDirective( 12434 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 12435 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 12436 if (!AStmt) 12437 return StmtError(); 12438 12439 auto *CS = cast<CapturedStmt>(AStmt); 12440 // 1.2.2 OpenMP Language Terminology 12441 // Structured block - An executable statement with a single entry at the 12442 // top and a single exit at the bottom. 12443 // The point of exit cannot be a branch out of the structured block. 12444 // longjmp() and throw() must not violate the entry/exit criteria. 12445 CS->getCapturedDecl()->setNothrow(); 12446 12447 for (int ThisCaptureLevel = 12448 getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for); 12449 ThisCaptureLevel > 1; --ThisCaptureLevel) { 12450 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 12451 // 1.2.2 OpenMP Language Terminology 12452 // Structured block - An executable statement with a single entry at the 12453 // top and a single exit at the bottom. 12454 // The point of exit cannot be a branch out of the structured block. 12455 // longjmp() and throw() must not violate the entry/exit criteria. 12456 CS->getCapturedDecl()->setNothrow(); 12457 } 12458 12459 OMPLoopBasedDirective::HelperExprs B; 12460 // In presence of clause 'collapse' with number of loops, it will 12461 // define the nested loops number. 12462 unsigned NestedLoopCount = checkOpenMPLoop( 12463 OMPD_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses), 12464 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack, 12465 VarsWithImplicitDSA, B); 12466 12467 if (NestedLoopCount == 0) 12468 return StmtError(); 12469 12470 assert((CurContext->isDependentContext() || B.builtAll()) && 12471 "omp for loop exprs were not built"); 12472 12473 setFunctionHasBranchProtectedScope(); 12474 12475 DSAStack->setParentTeamsRegionLoc(StartLoc); 12476 12477 return OMPTeamsDistributeParallelForDirective::Create( 12478 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B, 12479 DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion()); 12480 } 12481 12482 StmtResult Sema::ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses, 12483 Stmt *AStmt, 12484 SourceLocation StartLoc, 12485 SourceLocation EndLoc) { 12486 if (!AStmt) 12487 return StmtError(); 12488 12489 auto *CS = cast<CapturedStmt>(AStmt); 12490 // 1.2.2 OpenMP Language Terminology 12491 // Structured block - An executable statement with a single entry at the 12492 // top and a single exit at the bottom. 12493 // The point of exit cannot be a branch out of the structured block. 12494 // longjmp() and throw() must not violate the entry/exit criteria. 12495 CS->getCapturedDecl()->setNothrow(); 12496 12497 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_teams); 12498 ThisCaptureLevel > 1; --ThisCaptureLevel) { 12499 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 12500 // 1.2.2 OpenMP Language Terminology 12501 // Structured block - An executable statement with a single entry at the 12502 // top and a single exit at the bottom. 12503 // The point of exit cannot be a branch out of the structured block. 12504 // longjmp() and throw() must not violate the entry/exit criteria. 12505 CS->getCapturedDecl()->setNothrow(); 12506 } 12507 setFunctionHasBranchProtectedScope(); 12508 12509 return OMPTargetTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, 12510 AStmt); 12511 } 12512 12513 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeDirective( 12514 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 12515 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 12516 if (!AStmt) 12517 return StmtError(); 12518 12519 auto *CS = cast<CapturedStmt>(AStmt); 12520 // 1.2.2 OpenMP Language Terminology 12521 // Structured block - An executable statement with a single entry at the 12522 // top and a single exit at the bottom. 12523 // The point of exit cannot be a branch out of the structured block. 12524 // longjmp() and throw() must not violate the entry/exit criteria. 12525 CS->getCapturedDecl()->setNothrow(); 12526 for (int ThisCaptureLevel = 12527 getOpenMPCaptureLevels(OMPD_target_teams_distribute); 12528 ThisCaptureLevel > 1; --ThisCaptureLevel) { 12529 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 12530 // 1.2.2 OpenMP Language Terminology 12531 // Structured block - An executable statement with a single entry at the 12532 // top and a single exit at the bottom. 12533 // The point of exit cannot be a branch out of the structured block. 12534 // longjmp() and throw() must not violate the entry/exit criteria. 12535 CS->getCapturedDecl()->setNothrow(); 12536 } 12537 12538 OMPLoopBasedDirective::HelperExprs B; 12539 // In presence of clause 'collapse' with number of loops, it will 12540 // define the nested loops number. 12541 unsigned NestedLoopCount = checkOpenMPLoop( 12542 OMPD_target_teams_distribute, getCollapseNumberExpr(Clauses), 12543 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack, 12544 VarsWithImplicitDSA, B); 12545 if (NestedLoopCount == 0) 12546 return StmtError(); 12547 12548 assert((CurContext->isDependentContext() || B.builtAll()) && 12549 "omp target teams distribute loop exprs were not built"); 12550 12551 setFunctionHasBranchProtectedScope(); 12552 return OMPTargetTeamsDistributeDirective::Create( 12553 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 12554 } 12555 12556 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForDirective( 12557 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 12558 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 12559 if (!AStmt) 12560 return StmtError(); 12561 12562 auto *CS = cast<CapturedStmt>(AStmt); 12563 // 1.2.2 OpenMP Language Terminology 12564 // Structured block - An executable statement with a single entry at the 12565 // top and a single exit at the bottom. 12566 // The point of exit cannot be a branch out of the structured block. 12567 // longjmp() and throw() must not violate the entry/exit criteria. 12568 CS->getCapturedDecl()->setNothrow(); 12569 for (int ThisCaptureLevel = 12570 getOpenMPCaptureLevels(OMPD_target_teams_distribute_parallel_for); 12571 ThisCaptureLevel > 1; --ThisCaptureLevel) { 12572 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 12573 // 1.2.2 OpenMP Language Terminology 12574 // Structured block - An executable statement with a single entry at the 12575 // top and a single exit at the bottom. 12576 // The point of exit cannot be a branch out of the structured block. 12577 // longjmp() and throw() must not violate the entry/exit criteria. 12578 CS->getCapturedDecl()->setNothrow(); 12579 } 12580 12581 OMPLoopBasedDirective::HelperExprs B; 12582 // In presence of clause 'collapse' with number of loops, it will 12583 // define the nested loops number. 12584 unsigned NestedLoopCount = checkOpenMPLoop( 12585 OMPD_target_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses), 12586 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack, 12587 VarsWithImplicitDSA, B); 12588 if (NestedLoopCount == 0) 12589 return StmtError(); 12590 12591 assert((CurContext->isDependentContext() || B.builtAll()) && 12592 "omp target teams distribute parallel for loop exprs were not built"); 12593 12594 if (!CurContext->isDependentContext()) { 12595 // Finalize the clauses that need pre-built expressions for CodeGen. 12596 for (OMPClause *C : Clauses) { 12597 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 12598 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 12599 B.NumIterations, *this, CurScope, 12600 DSAStack)) 12601 return StmtError(); 12602 } 12603 } 12604 12605 setFunctionHasBranchProtectedScope(); 12606 return OMPTargetTeamsDistributeParallelForDirective::Create( 12607 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B, 12608 DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion()); 12609 } 12610 12611 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective( 12612 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 12613 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 12614 if (!AStmt) 12615 return StmtError(); 12616 12617 auto *CS = cast<CapturedStmt>(AStmt); 12618 // 1.2.2 OpenMP Language Terminology 12619 // Structured block - An executable statement with a single entry at the 12620 // top and a single exit at the bottom. 12621 // The point of exit cannot be a branch out of the structured block. 12622 // longjmp() and throw() must not violate the entry/exit criteria. 12623 CS->getCapturedDecl()->setNothrow(); 12624 for (int ThisCaptureLevel = getOpenMPCaptureLevels( 12625 OMPD_target_teams_distribute_parallel_for_simd); 12626 ThisCaptureLevel > 1; --ThisCaptureLevel) { 12627 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 12628 // 1.2.2 OpenMP Language Terminology 12629 // Structured block - An executable statement with a single entry at the 12630 // top and a single exit at the bottom. 12631 // The point of exit cannot be a branch out of the structured block. 12632 // longjmp() and throw() must not violate the entry/exit criteria. 12633 CS->getCapturedDecl()->setNothrow(); 12634 } 12635 12636 OMPLoopBasedDirective::HelperExprs B; 12637 // In presence of clause 'collapse' with number of loops, it will 12638 // define the nested loops number. 12639 unsigned NestedLoopCount = 12640 checkOpenMPLoop(OMPD_target_teams_distribute_parallel_for_simd, 12641 getCollapseNumberExpr(Clauses), 12642 nullptr /*ordered not a clause on distribute*/, CS, *this, 12643 *DSAStack, VarsWithImplicitDSA, B); 12644 if (NestedLoopCount == 0) 12645 return StmtError(); 12646 12647 assert((CurContext->isDependentContext() || B.builtAll()) && 12648 "omp target teams distribute parallel for simd loop exprs were not " 12649 "built"); 12650 12651 if (!CurContext->isDependentContext()) { 12652 // Finalize the clauses that need pre-built expressions for CodeGen. 12653 for (OMPClause *C : Clauses) { 12654 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 12655 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 12656 B.NumIterations, *this, CurScope, 12657 DSAStack)) 12658 return StmtError(); 12659 } 12660 } 12661 12662 if (checkSimdlenSafelenSpecified(*this, Clauses)) 12663 return StmtError(); 12664 12665 setFunctionHasBranchProtectedScope(); 12666 return OMPTargetTeamsDistributeParallelForSimdDirective::Create( 12667 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 12668 } 12669 12670 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeSimdDirective( 12671 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 12672 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 12673 if (!AStmt) 12674 return StmtError(); 12675 12676 auto *CS = cast<CapturedStmt>(AStmt); 12677 // 1.2.2 OpenMP Language Terminology 12678 // Structured block - An executable statement with a single entry at the 12679 // top and a single exit at the bottom. 12680 // The point of exit cannot be a branch out of the structured block. 12681 // longjmp() and throw() must not violate the entry/exit criteria. 12682 CS->getCapturedDecl()->setNothrow(); 12683 for (int ThisCaptureLevel = 12684 getOpenMPCaptureLevels(OMPD_target_teams_distribute_simd); 12685 ThisCaptureLevel > 1; --ThisCaptureLevel) { 12686 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 12687 // 1.2.2 OpenMP Language Terminology 12688 // Structured block - An executable statement with a single entry at the 12689 // top and a single exit at the bottom. 12690 // The point of exit cannot be a branch out of the structured block. 12691 // longjmp() and throw() must not violate the entry/exit criteria. 12692 CS->getCapturedDecl()->setNothrow(); 12693 } 12694 12695 OMPLoopBasedDirective::HelperExprs B; 12696 // In presence of clause 'collapse' with number of loops, it will 12697 // define the nested loops number. 12698 unsigned NestedLoopCount = checkOpenMPLoop( 12699 OMPD_target_teams_distribute_simd, getCollapseNumberExpr(Clauses), 12700 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack, 12701 VarsWithImplicitDSA, B); 12702 if (NestedLoopCount == 0) 12703 return StmtError(); 12704 12705 assert((CurContext->isDependentContext() || B.builtAll()) && 12706 "omp target teams distribute simd loop exprs were not built"); 12707 12708 if (!CurContext->isDependentContext()) { 12709 // Finalize the clauses that need pre-built expressions for CodeGen. 12710 for (OMPClause *C : Clauses) { 12711 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 12712 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 12713 B.NumIterations, *this, CurScope, 12714 DSAStack)) 12715 return StmtError(); 12716 } 12717 } 12718 12719 if (checkSimdlenSafelenSpecified(*this, Clauses)) 12720 return StmtError(); 12721 12722 setFunctionHasBranchProtectedScope(); 12723 return OMPTargetTeamsDistributeSimdDirective::Create( 12724 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 12725 } 12726 12727 bool Sema::checkTransformableLoopNest( 12728 OpenMPDirectiveKind Kind, Stmt *AStmt, int NumLoops, 12729 SmallVectorImpl<OMPLoopBasedDirective::HelperExprs> &LoopHelpers, 12730 Stmt *&Body, 12731 SmallVectorImpl<SmallVector<llvm::PointerUnion<Stmt *, Decl *>, 0>> 12732 &OriginalInits) { 12733 OriginalInits.emplace_back(); 12734 bool Result = OMPLoopBasedDirective::doForAllLoops( 12735 AStmt->IgnoreContainers(), /*TryImperfectlyNestedLoops=*/false, NumLoops, 12736 [this, &LoopHelpers, &Body, &OriginalInits, Kind](unsigned Cnt, 12737 Stmt *CurStmt) { 12738 VarsWithInheritedDSAType TmpDSA; 12739 unsigned SingleNumLoops = 12740 checkOpenMPLoop(Kind, nullptr, nullptr, CurStmt, *this, *DSAStack, 12741 TmpDSA, LoopHelpers[Cnt]); 12742 if (SingleNumLoops == 0) 12743 return true; 12744 assert(SingleNumLoops == 1 && "Expect single loop iteration space"); 12745 if (auto *For = dyn_cast<ForStmt>(CurStmt)) { 12746 OriginalInits.back().push_back(For->getInit()); 12747 Body = For->getBody(); 12748 } else { 12749 assert(isa<CXXForRangeStmt>(CurStmt) && 12750 "Expected canonical for or range-based for loops."); 12751 auto *CXXFor = cast<CXXForRangeStmt>(CurStmt); 12752 OriginalInits.back().push_back(CXXFor->getBeginStmt()); 12753 Body = CXXFor->getBody(); 12754 } 12755 OriginalInits.emplace_back(); 12756 return false; 12757 }, 12758 [&OriginalInits](OMPLoopBasedDirective *Transform) { 12759 Stmt *DependentPreInits; 12760 if (auto *Dir = dyn_cast<OMPTileDirective>(Transform)) 12761 DependentPreInits = Dir->getPreInits(); 12762 else if (auto *Dir = dyn_cast<OMPUnrollDirective>(Transform)) 12763 DependentPreInits = Dir->getPreInits(); 12764 else 12765 llvm_unreachable("Unhandled loop transformation"); 12766 if (!DependentPreInits) 12767 return; 12768 for (Decl *C : cast<DeclStmt>(DependentPreInits)->getDeclGroup()) 12769 OriginalInits.back().push_back(C); 12770 }); 12771 assert(OriginalInits.back().empty() && "No preinit after innermost loop"); 12772 OriginalInits.pop_back(); 12773 return Result; 12774 } 12775 12776 StmtResult Sema::ActOnOpenMPTileDirective(ArrayRef<OMPClause *> Clauses, 12777 Stmt *AStmt, SourceLocation StartLoc, 12778 SourceLocation EndLoc) { 12779 auto SizesClauses = 12780 OMPExecutableDirective::getClausesOfKind<OMPSizesClause>(Clauses); 12781 if (SizesClauses.empty()) { 12782 // A missing 'sizes' clause is already reported by the parser. 12783 return StmtError(); 12784 } 12785 const OMPSizesClause *SizesClause = *SizesClauses.begin(); 12786 unsigned NumLoops = SizesClause->getNumSizes(); 12787 12788 // Empty statement should only be possible if there already was an error. 12789 if (!AStmt) 12790 return StmtError(); 12791 12792 // Verify and diagnose loop nest. 12793 SmallVector<OMPLoopBasedDirective::HelperExprs, 4> LoopHelpers(NumLoops); 12794 Stmt *Body = nullptr; 12795 SmallVector<SmallVector<llvm::PointerUnion<Stmt *, Decl *>, 0>, 4> 12796 OriginalInits; 12797 if (!checkTransformableLoopNest(OMPD_tile, AStmt, NumLoops, LoopHelpers, Body, 12798 OriginalInits)) 12799 return StmtError(); 12800 12801 // Delay tiling to when template is completely instantiated. 12802 if (CurContext->isDependentContext()) 12803 return OMPTileDirective::Create(Context, StartLoc, EndLoc, Clauses, 12804 NumLoops, AStmt, nullptr, nullptr); 12805 12806 SmallVector<Decl *, 4> PreInits; 12807 12808 // Create iteration variables for the generated loops. 12809 SmallVector<VarDecl *, 4> FloorIndVars; 12810 SmallVector<VarDecl *, 4> TileIndVars; 12811 FloorIndVars.resize(NumLoops); 12812 TileIndVars.resize(NumLoops); 12813 for (unsigned I = 0; I < NumLoops; ++I) { 12814 OMPLoopBasedDirective::HelperExprs &LoopHelper = LoopHelpers[I]; 12815 12816 assert(LoopHelper.Counters.size() == 1 && 12817 "Expect single-dimensional loop iteration space"); 12818 auto *OrigCntVar = cast<DeclRefExpr>(LoopHelper.Counters.front()); 12819 std::string OrigVarName = OrigCntVar->getNameInfo().getAsString(); 12820 DeclRefExpr *IterVarRef = cast<DeclRefExpr>(LoopHelper.IterationVarRef); 12821 QualType CntTy = IterVarRef->getType(); 12822 12823 // Iteration variable for the floor (i.e. outer) loop. 12824 { 12825 std::string FloorCntName = 12826 (Twine(".floor_") + llvm::utostr(I) + ".iv." + OrigVarName).str(); 12827 VarDecl *FloorCntDecl = 12828 buildVarDecl(*this, {}, CntTy, FloorCntName, nullptr, OrigCntVar); 12829 FloorIndVars[I] = FloorCntDecl; 12830 } 12831 12832 // Iteration variable for the tile (i.e. inner) loop. 12833 { 12834 std::string TileCntName = 12835 (Twine(".tile_") + llvm::utostr(I) + ".iv." + OrigVarName).str(); 12836 12837 // Reuse the iteration variable created by checkOpenMPLoop. It is also 12838 // used by the expressions to derive the original iteration variable's 12839 // value from the logical iteration number. 12840 auto *TileCntDecl = cast<VarDecl>(IterVarRef->getDecl()); 12841 TileCntDecl->setDeclName(&PP.getIdentifierTable().get(TileCntName)); 12842 TileIndVars[I] = TileCntDecl; 12843 } 12844 for (auto &P : OriginalInits[I]) { 12845 if (auto *D = P.dyn_cast<Decl *>()) 12846 PreInits.push_back(D); 12847 else if (auto *PI = dyn_cast_or_null<DeclStmt>(P.dyn_cast<Stmt *>())) 12848 PreInits.append(PI->decl_begin(), PI->decl_end()); 12849 } 12850 if (auto *PI = cast_or_null<DeclStmt>(LoopHelper.PreInits)) 12851 PreInits.append(PI->decl_begin(), PI->decl_end()); 12852 // Gather declarations for the data members used as counters. 12853 for (Expr *CounterRef : LoopHelper.Counters) { 12854 auto *CounterDecl = cast<DeclRefExpr>(CounterRef)->getDecl(); 12855 if (isa<OMPCapturedExprDecl>(CounterDecl)) 12856 PreInits.push_back(CounterDecl); 12857 } 12858 } 12859 12860 // Once the original iteration values are set, append the innermost body. 12861 Stmt *Inner = Body; 12862 12863 // Create tile loops from the inside to the outside. 12864 for (int I = NumLoops - 1; I >= 0; --I) { 12865 OMPLoopBasedDirective::HelperExprs &LoopHelper = LoopHelpers[I]; 12866 Expr *NumIterations = LoopHelper.NumIterations; 12867 auto *OrigCntVar = cast<DeclRefExpr>(LoopHelper.Counters[0]); 12868 QualType CntTy = OrigCntVar->getType(); 12869 Expr *DimTileSize = SizesClause->getSizesRefs()[I]; 12870 Scope *CurScope = getCurScope(); 12871 12872 // Commonly used variables. 12873 DeclRefExpr *TileIV = buildDeclRefExpr(*this, TileIndVars[I], CntTy, 12874 OrigCntVar->getExprLoc()); 12875 DeclRefExpr *FloorIV = buildDeclRefExpr(*this, FloorIndVars[I], CntTy, 12876 OrigCntVar->getExprLoc()); 12877 12878 // For init-statement: auto .tile.iv = .floor.iv 12879 AddInitializerToDecl(TileIndVars[I], DefaultLvalueConversion(FloorIV).get(), 12880 /*DirectInit=*/false); 12881 Decl *CounterDecl = TileIndVars[I]; 12882 StmtResult InitStmt = new (Context) 12883 DeclStmt(DeclGroupRef::Create(Context, &CounterDecl, 1), 12884 OrigCntVar->getBeginLoc(), OrigCntVar->getEndLoc()); 12885 if (!InitStmt.isUsable()) 12886 return StmtError(); 12887 12888 // For cond-expression: .tile.iv < min(.floor.iv + DimTileSize, 12889 // NumIterations) 12890 ExprResult EndOfTile = BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(), 12891 BO_Add, FloorIV, DimTileSize); 12892 if (!EndOfTile.isUsable()) 12893 return StmtError(); 12894 ExprResult IsPartialTile = 12895 BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(), BO_LT, 12896 NumIterations, EndOfTile.get()); 12897 if (!IsPartialTile.isUsable()) 12898 return StmtError(); 12899 ExprResult MinTileAndIterSpace = ActOnConditionalOp( 12900 LoopHelper.Cond->getBeginLoc(), LoopHelper.Cond->getEndLoc(), 12901 IsPartialTile.get(), NumIterations, EndOfTile.get()); 12902 if (!MinTileAndIterSpace.isUsable()) 12903 return StmtError(); 12904 ExprResult CondExpr = BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(), 12905 BO_LT, TileIV, MinTileAndIterSpace.get()); 12906 if (!CondExpr.isUsable()) 12907 return StmtError(); 12908 12909 // For incr-statement: ++.tile.iv 12910 ExprResult IncrStmt = 12911 BuildUnaryOp(CurScope, LoopHelper.Inc->getExprLoc(), UO_PreInc, TileIV); 12912 if (!IncrStmt.isUsable()) 12913 return StmtError(); 12914 12915 // Statements to set the original iteration variable's value from the 12916 // logical iteration number. 12917 // Generated for loop is: 12918 // Original_for_init; 12919 // for (auto .tile.iv = .floor.iv; .tile.iv < min(.floor.iv + DimTileSize, 12920 // NumIterations); ++.tile.iv) { 12921 // Original_Body; 12922 // Original_counter_update; 12923 // } 12924 // FIXME: If the innermost body is an loop itself, inserting these 12925 // statements stops it being recognized as a perfectly nested loop (e.g. 12926 // for applying tiling again). If this is the case, sink the expressions 12927 // further into the inner loop. 12928 SmallVector<Stmt *, 4> BodyParts; 12929 BodyParts.append(LoopHelper.Updates.begin(), LoopHelper.Updates.end()); 12930 BodyParts.push_back(Inner); 12931 Inner = CompoundStmt::Create(Context, BodyParts, Inner->getBeginLoc(), 12932 Inner->getEndLoc()); 12933 Inner = new (Context) 12934 ForStmt(Context, InitStmt.get(), CondExpr.get(), nullptr, 12935 IncrStmt.get(), Inner, LoopHelper.Init->getBeginLoc(), 12936 LoopHelper.Init->getBeginLoc(), LoopHelper.Inc->getEndLoc()); 12937 } 12938 12939 // Create floor loops from the inside to the outside. 12940 for (int I = NumLoops - 1; I >= 0; --I) { 12941 auto &LoopHelper = LoopHelpers[I]; 12942 Expr *NumIterations = LoopHelper.NumIterations; 12943 DeclRefExpr *OrigCntVar = cast<DeclRefExpr>(LoopHelper.Counters[0]); 12944 QualType CntTy = OrigCntVar->getType(); 12945 Expr *DimTileSize = SizesClause->getSizesRefs()[I]; 12946 Scope *CurScope = getCurScope(); 12947 12948 // Commonly used variables. 12949 DeclRefExpr *FloorIV = buildDeclRefExpr(*this, FloorIndVars[I], CntTy, 12950 OrigCntVar->getExprLoc()); 12951 12952 // For init-statement: auto .floor.iv = 0 12953 AddInitializerToDecl( 12954 FloorIndVars[I], 12955 ActOnIntegerConstant(LoopHelper.Init->getExprLoc(), 0).get(), 12956 /*DirectInit=*/false); 12957 Decl *CounterDecl = FloorIndVars[I]; 12958 StmtResult InitStmt = new (Context) 12959 DeclStmt(DeclGroupRef::Create(Context, &CounterDecl, 1), 12960 OrigCntVar->getBeginLoc(), OrigCntVar->getEndLoc()); 12961 if (!InitStmt.isUsable()) 12962 return StmtError(); 12963 12964 // For cond-expression: .floor.iv < NumIterations 12965 ExprResult CondExpr = BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(), 12966 BO_LT, FloorIV, NumIterations); 12967 if (!CondExpr.isUsable()) 12968 return StmtError(); 12969 12970 // For incr-statement: .floor.iv += DimTileSize 12971 ExprResult IncrStmt = BuildBinOp(CurScope, LoopHelper.Inc->getExprLoc(), 12972 BO_AddAssign, FloorIV, DimTileSize); 12973 if (!IncrStmt.isUsable()) 12974 return StmtError(); 12975 12976 Inner = new (Context) 12977 ForStmt(Context, InitStmt.get(), CondExpr.get(), nullptr, 12978 IncrStmt.get(), Inner, LoopHelper.Init->getBeginLoc(), 12979 LoopHelper.Init->getBeginLoc(), LoopHelper.Inc->getEndLoc()); 12980 } 12981 12982 return OMPTileDirective::Create(Context, StartLoc, EndLoc, Clauses, NumLoops, 12983 AStmt, Inner, 12984 buildPreInits(Context, PreInits)); 12985 } 12986 12987 StmtResult Sema::ActOnOpenMPUnrollDirective(ArrayRef<OMPClause *> Clauses, 12988 Stmt *AStmt, 12989 SourceLocation StartLoc, 12990 SourceLocation EndLoc) { 12991 // Empty statement should only be possible if there already was an error. 12992 if (!AStmt) 12993 return StmtError(); 12994 12995 if (checkMutuallyExclusiveClauses(*this, Clauses, {OMPC_partial, OMPC_full})) 12996 return StmtError(); 12997 12998 const OMPFullClause *FullClause = 12999 OMPExecutableDirective::getSingleClause<OMPFullClause>(Clauses); 13000 const OMPPartialClause *PartialClause = 13001 OMPExecutableDirective::getSingleClause<OMPPartialClause>(Clauses); 13002 assert(!(FullClause && PartialClause) && 13003 "mutual exclusivity must have been checked before"); 13004 13005 constexpr unsigned NumLoops = 1; 13006 Stmt *Body = nullptr; 13007 SmallVector<OMPLoopBasedDirective::HelperExprs, NumLoops> LoopHelpers( 13008 NumLoops); 13009 SmallVector<SmallVector<llvm::PointerUnion<Stmt *, Decl *>, 0>, NumLoops + 1> 13010 OriginalInits; 13011 if (!checkTransformableLoopNest(OMPD_unroll, AStmt, NumLoops, LoopHelpers, 13012 Body, OriginalInits)) 13013 return StmtError(); 13014 13015 unsigned NumGeneratedLoops = PartialClause ? 1 : 0; 13016 13017 // Delay unrolling to when template is completely instantiated. 13018 if (CurContext->isDependentContext()) 13019 return OMPUnrollDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt, 13020 NumGeneratedLoops, nullptr, nullptr); 13021 13022 OMPLoopBasedDirective::HelperExprs &LoopHelper = LoopHelpers.front(); 13023 13024 if (FullClause) { 13025 if (!VerifyPositiveIntegerConstantInClause( 13026 LoopHelper.NumIterations, OMPC_full, /*StrictlyPositive=*/false, 13027 /*SuppressExprDigs=*/true) 13028 .isUsable()) { 13029 Diag(AStmt->getBeginLoc(), diag::err_omp_unroll_full_variable_trip_count); 13030 Diag(FullClause->getBeginLoc(), diag::note_omp_directive_here) 13031 << "#pragma omp unroll full"; 13032 return StmtError(); 13033 } 13034 } 13035 13036 // The generated loop may only be passed to other loop-associated directive 13037 // when a partial clause is specified. Without the requirement it is 13038 // sufficient to generate loop unroll metadata at code-generation. 13039 if (NumGeneratedLoops == 0) 13040 return OMPUnrollDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt, 13041 NumGeneratedLoops, nullptr, nullptr); 13042 13043 // Otherwise, we need to provide a de-sugared/transformed AST that can be 13044 // associated with another loop directive. 13045 // 13046 // The canonical loop analysis return by checkTransformableLoopNest assumes 13047 // the following structure to be the same loop without transformations or 13048 // directives applied: \code OriginalInits; LoopHelper.PreInits; 13049 // LoopHelper.Counters; 13050 // for (; IV < LoopHelper.NumIterations; ++IV) { 13051 // LoopHelper.Updates; 13052 // Body; 13053 // } 13054 // \endcode 13055 // where IV is a variable declared and initialized to 0 in LoopHelper.PreInits 13056 // and referenced by LoopHelper.IterationVarRef. 13057 // 13058 // The unrolling directive transforms this into the following loop: 13059 // \code 13060 // OriginalInits; \ 13061 // LoopHelper.PreInits; > NewPreInits 13062 // LoopHelper.Counters; / 13063 // for (auto UIV = 0; UIV < LoopHelper.NumIterations; UIV+=Factor) { 13064 // #pragma clang loop unroll_count(Factor) 13065 // for (IV = UIV; IV < UIV + Factor && UIV < LoopHelper.NumIterations; ++IV) 13066 // { 13067 // LoopHelper.Updates; 13068 // Body; 13069 // } 13070 // } 13071 // \endcode 13072 // where UIV is a new logical iteration counter. IV must be the same VarDecl 13073 // as the original LoopHelper.IterationVarRef because LoopHelper.Updates 13074 // references it. If the partially unrolled loop is associated with another 13075 // loop directive (like an OMPForDirective), it will use checkOpenMPLoop to 13076 // analyze this loop, i.e. the outer loop must fulfill the constraints of an 13077 // OpenMP canonical loop. The inner loop is not an associable canonical loop 13078 // and only exists to defer its unrolling to LLVM's LoopUnroll instead of 13079 // doing it in the frontend (by adding loop metadata). NewPreInits becomes a 13080 // property of the OMPLoopBasedDirective instead of statements in 13081 // CompoundStatement. This is to allow the loop to become a non-outermost loop 13082 // of a canonical loop nest where these PreInits are emitted before the 13083 // outermost directive. 13084 13085 // Determine the PreInit declarations. 13086 SmallVector<Decl *, 4> PreInits; 13087 assert(OriginalInits.size() == 1 && 13088 "Expecting a single-dimensional loop iteration space"); 13089 for (auto &P : OriginalInits[0]) { 13090 if (auto *D = P.dyn_cast<Decl *>()) 13091 PreInits.push_back(D); 13092 else if (auto *PI = dyn_cast_or_null<DeclStmt>(P.dyn_cast<Stmt *>())) 13093 PreInits.append(PI->decl_begin(), PI->decl_end()); 13094 } 13095 if (auto *PI = cast_or_null<DeclStmt>(LoopHelper.PreInits)) 13096 PreInits.append(PI->decl_begin(), PI->decl_end()); 13097 // Gather declarations for the data members used as counters. 13098 for (Expr *CounterRef : LoopHelper.Counters) { 13099 auto *CounterDecl = cast<DeclRefExpr>(CounterRef)->getDecl(); 13100 if (isa<OMPCapturedExprDecl>(CounterDecl)) 13101 PreInits.push_back(CounterDecl); 13102 } 13103 13104 auto *IterationVarRef = cast<DeclRefExpr>(LoopHelper.IterationVarRef); 13105 QualType IVTy = IterationVarRef->getType(); 13106 assert(LoopHelper.Counters.size() == 1 && 13107 "Expecting a single-dimensional loop iteration space"); 13108 auto *OrigVar = cast<DeclRefExpr>(LoopHelper.Counters.front()); 13109 13110 // Determine the unroll factor. 13111 uint64_t Factor; 13112 SourceLocation FactorLoc; 13113 if (Expr *FactorVal = PartialClause->getFactor()) { 13114 Factor = 13115 FactorVal->getIntegerConstantExpr(Context).getValue().getZExtValue(); 13116 FactorLoc = FactorVal->getExprLoc(); 13117 } else { 13118 // TODO: Use a better profitability model. 13119 Factor = 2; 13120 } 13121 assert(Factor > 0 && "Expected positive unroll factor"); 13122 auto MakeFactorExpr = [this, Factor, IVTy, FactorLoc]() { 13123 return IntegerLiteral::Create( 13124 Context, llvm::APInt(Context.getIntWidth(IVTy), Factor), IVTy, 13125 FactorLoc); 13126 }; 13127 13128 // Iteration variable SourceLocations. 13129 SourceLocation OrigVarLoc = OrigVar->getExprLoc(); 13130 SourceLocation OrigVarLocBegin = OrigVar->getBeginLoc(); 13131 SourceLocation OrigVarLocEnd = OrigVar->getEndLoc(); 13132 13133 // Internal variable names. 13134 std::string OrigVarName = OrigVar->getNameInfo().getAsString(); 13135 std::string OuterIVName = (Twine(".unrolled.iv.") + OrigVarName).str(); 13136 std::string InnerIVName = (Twine(".unroll_inner.iv.") + OrigVarName).str(); 13137 std::string InnerTripCountName = 13138 (Twine(".unroll_inner.tripcount.") + OrigVarName).str(); 13139 13140 // Create the iteration variable for the unrolled loop. 13141 VarDecl *OuterIVDecl = 13142 buildVarDecl(*this, {}, IVTy, OuterIVName, nullptr, OrigVar); 13143 auto MakeOuterRef = [this, OuterIVDecl, IVTy, OrigVarLoc]() { 13144 return buildDeclRefExpr(*this, OuterIVDecl, IVTy, OrigVarLoc); 13145 }; 13146 13147 // Iteration variable for the inner loop: Reuse the iteration variable created 13148 // by checkOpenMPLoop. 13149 auto *InnerIVDecl = cast<VarDecl>(IterationVarRef->getDecl()); 13150 InnerIVDecl->setDeclName(&PP.getIdentifierTable().get(InnerIVName)); 13151 auto MakeInnerRef = [this, InnerIVDecl, IVTy, OrigVarLoc]() { 13152 return buildDeclRefExpr(*this, InnerIVDecl, IVTy, OrigVarLoc); 13153 }; 13154 13155 // Make a copy of the NumIterations expression for each use: By the AST 13156 // constraints, every expression object in a DeclContext must be unique. 13157 CaptureVars CopyTransformer(*this); 13158 auto MakeNumIterations = [&CopyTransformer, &LoopHelper]() -> Expr * { 13159 return AssertSuccess( 13160 CopyTransformer.TransformExpr(LoopHelper.NumIterations)); 13161 }; 13162 13163 // Inner For init-statement: auto .unroll_inner.iv = .unrolled.iv 13164 ExprResult LValueConv = DefaultLvalueConversion(MakeOuterRef()); 13165 AddInitializerToDecl(InnerIVDecl, LValueConv.get(), /*DirectInit=*/false); 13166 StmtResult InnerInit = new (Context) 13167 DeclStmt(DeclGroupRef(InnerIVDecl), OrigVarLocBegin, OrigVarLocEnd); 13168 if (!InnerInit.isUsable()) 13169 return StmtError(); 13170 13171 // Inner For cond-expression: 13172 // \code 13173 // .unroll_inner.iv < .unrolled.iv + Factor && 13174 // .unroll_inner.iv < NumIterations 13175 // \endcode 13176 // This conjunction of two conditions allows ScalarEvolution to derive the 13177 // maximum trip count of the inner loop. 13178 ExprResult EndOfTile = BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(), 13179 BO_Add, MakeOuterRef(), MakeFactorExpr()); 13180 if (!EndOfTile.isUsable()) 13181 return StmtError(); 13182 ExprResult InnerCond1 = BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(), 13183 BO_LE, MakeInnerRef(), EndOfTile.get()); 13184 if (!InnerCond1.isUsable()) 13185 return StmtError(); 13186 ExprResult InnerCond2 = 13187 BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(), BO_LE, MakeInnerRef(), 13188 MakeNumIterations()); 13189 if (!InnerCond2.isUsable()) 13190 return StmtError(); 13191 ExprResult InnerCond = 13192 BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(), BO_LAnd, 13193 InnerCond1.get(), InnerCond2.get()); 13194 if (!InnerCond.isUsable()) 13195 return StmtError(); 13196 13197 // Inner For incr-statement: ++.unroll_inner.iv 13198 ExprResult InnerIncr = BuildUnaryOp(CurScope, LoopHelper.Inc->getExprLoc(), 13199 UO_PreInc, MakeInnerRef()); 13200 if (!InnerIncr.isUsable()) 13201 return StmtError(); 13202 13203 // Inner For statement. 13204 SmallVector<Stmt *> InnerBodyStmts; 13205 InnerBodyStmts.append(LoopHelper.Updates.begin(), LoopHelper.Updates.end()); 13206 InnerBodyStmts.push_back(Body); 13207 CompoundStmt *InnerBody = CompoundStmt::Create( 13208 Context, InnerBodyStmts, Body->getBeginLoc(), Body->getEndLoc()); 13209 ForStmt *InnerFor = new (Context) 13210 ForStmt(Context, InnerInit.get(), InnerCond.get(), nullptr, 13211 InnerIncr.get(), InnerBody, LoopHelper.Init->getBeginLoc(), 13212 LoopHelper.Init->getBeginLoc(), LoopHelper.Inc->getEndLoc()); 13213 13214 // Unroll metadata for the inner loop. 13215 // This needs to take into account the remainder portion of the unrolled loop, 13216 // hence `unroll(full)` does not apply here, even though the LoopUnroll pass 13217 // supports multiple loop exits. Instead, unroll using a factor equivalent to 13218 // the maximum trip count, which will also generate a remainder loop. Just 13219 // `unroll(enable)` (which could have been useful if the user has not 13220 // specified a concrete factor; even though the outer loop cannot be 13221 // influenced anymore, would avoid more code bloat than necessary) will refuse 13222 // the loop because "Won't unroll; remainder loop could not be generated when 13223 // assuming runtime trip count". Even if it did work, it must not choose a 13224 // larger unroll factor than the maximum loop length, or it would always just 13225 // execute the remainder loop. 13226 LoopHintAttr *UnrollHintAttr = 13227 LoopHintAttr::CreateImplicit(Context, LoopHintAttr::UnrollCount, 13228 LoopHintAttr::Numeric, MakeFactorExpr()); 13229 AttributedStmt *InnerUnrolled = 13230 AttributedStmt::Create(Context, StartLoc, {UnrollHintAttr}, InnerFor); 13231 13232 // Outer For init-statement: auto .unrolled.iv = 0 13233 AddInitializerToDecl( 13234 OuterIVDecl, ActOnIntegerConstant(LoopHelper.Init->getExprLoc(), 0).get(), 13235 /*DirectInit=*/false); 13236 StmtResult OuterInit = new (Context) 13237 DeclStmt(DeclGroupRef(OuterIVDecl), OrigVarLocBegin, OrigVarLocEnd); 13238 if (!OuterInit.isUsable()) 13239 return StmtError(); 13240 13241 // Outer For cond-expression: .unrolled.iv < NumIterations 13242 ExprResult OuterConde = 13243 BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(), BO_LT, MakeOuterRef(), 13244 MakeNumIterations()); 13245 if (!OuterConde.isUsable()) 13246 return StmtError(); 13247 13248 // Outer For incr-statement: .unrolled.iv += Factor 13249 ExprResult OuterIncr = 13250 BuildBinOp(CurScope, LoopHelper.Inc->getExprLoc(), BO_AddAssign, 13251 MakeOuterRef(), MakeFactorExpr()); 13252 if (!OuterIncr.isUsable()) 13253 return StmtError(); 13254 13255 // Outer For statement. 13256 ForStmt *OuterFor = new (Context) 13257 ForStmt(Context, OuterInit.get(), OuterConde.get(), nullptr, 13258 OuterIncr.get(), InnerUnrolled, LoopHelper.Init->getBeginLoc(), 13259 LoopHelper.Init->getBeginLoc(), LoopHelper.Inc->getEndLoc()); 13260 13261 return OMPUnrollDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt, 13262 NumGeneratedLoops, OuterFor, 13263 buildPreInits(Context, PreInits)); 13264 } 13265 13266 OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr, 13267 SourceLocation StartLoc, 13268 SourceLocation LParenLoc, 13269 SourceLocation EndLoc) { 13270 OMPClause *Res = nullptr; 13271 switch (Kind) { 13272 case OMPC_final: 13273 Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc); 13274 break; 13275 case OMPC_num_threads: 13276 Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc); 13277 break; 13278 case OMPC_safelen: 13279 Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc); 13280 break; 13281 case OMPC_simdlen: 13282 Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc); 13283 break; 13284 case OMPC_allocator: 13285 Res = ActOnOpenMPAllocatorClause(Expr, StartLoc, LParenLoc, EndLoc); 13286 break; 13287 case OMPC_collapse: 13288 Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc); 13289 break; 13290 case OMPC_ordered: 13291 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr); 13292 break; 13293 case OMPC_num_teams: 13294 Res = ActOnOpenMPNumTeamsClause(Expr, StartLoc, LParenLoc, EndLoc); 13295 break; 13296 case OMPC_thread_limit: 13297 Res = ActOnOpenMPThreadLimitClause(Expr, StartLoc, LParenLoc, EndLoc); 13298 break; 13299 case OMPC_priority: 13300 Res = ActOnOpenMPPriorityClause(Expr, StartLoc, LParenLoc, EndLoc); 13301 break; 13302 case OMPC_grainsize: 13303 Res = ActOnOpenMPGrainsizeClause(Expr, StartLoc, LParenLoc, EndLoc); 13304 break; 13305 case OMPC_num_tasks: 13306 Res = ActOnOpenMPNumTasksClause(Expr, StartLoc, LParenLoc, EndLoc); 13307 break; 13308 case OMPC_hint: 13309 Res = ActOnOpenMPHintClause(Expr, StartLoc, LParenLoc, EndLoc); 13310 break; 13311 case OMPC_depobj: 13312 Res = ActOnOpenMPDepobjClause(Expr, StartLoc, LParenLoc, EndLoc); 13313 break; 13314 case OMPC_detach: 13315 Res = ActOnOpenMPDetachClause(Expr, StartLoc, LParenLoc, EndLoc); 13316 break; 13317 case OMPC_novariants: 13318 Res = ActOnOpenMPNovariantsClause(Expr, StartLoc, LParenLoc, EndLoc); 13319 break; 13320 case OMPC_nocontext: 13321 Res = ActOnOpenMPNocontextClause(Expr, StartLoc, LParenLoc, EndLoc); 13322 break; 13323 case OMPC_filter: 13324 Res = ActOnOpenMPFilterClause(Expr, StartLoc, LParenLoc, EndLoc); 13325 break; 13326 case OMPC_partial: 13327 Res = ActOnOpenMPPartialClause(Expr, StartLoc, LParenLoc, EndLoc); 13328 break; 13329 case OMPC_device: 13330 case OMPC_if: 13331 case OMPC_default: 13332 case OMPC_proc_bind: 13333 case OMPC_schedule: 13334 case OMPC_private: 13335 case OMPC_firstprivate: 13336 case OMPC_lastprivate: 13337 case OMPC_shared: 13338 case OMPC_reduction: 13339 case OMPC_task_reduction: 13340 case OMPC_in_reduction: 13341 case OMPC_linear: 13342 case OMPC_aligned: 13343 case OMPC_copyin: 13344 case OMPC_copyprivate: 13345 case OMPC_nowait: 13346 case OMPC_untied: 13347 case OMPC_mergeable: 13348 case OMPC_threadprivate: 13349 case OMPC_sizes: 13350 case OMPC_allocate: 13351 case OMPC_flush: 13352 case OMPC_read: 13353 case OMPC_write: 13354 case OMPC_update: 13355 case OMPC_capture: 13356 case OMPC_seq_cst: 13357 case OMPC_acq_rel: 13358 case OMPC_acquire: 13359 case OMPC_release: 13360 case OMPC_relaxed: 13361 case OMPC_depend: 13362 case OMPC_threads: 13363 case OMPC_simd: 13364 case OMPC_map: 13365 case OMPC_nogroup: 13366 case OMPC_dist_schedule: 13367 case OMPC_defaultmap: 13368 case OMPC_unknown: 13369 case OMPC_uniform: 13370 case OMPC_to: 13371 case OMPC_from: 13372 case OMPC_use_device_ptr: 13373 case OMPC_use_device_addr: 13374 case OMPC_is_device_ptr: 13375 case OMPC_unified_address: 13376 case OMPC_unified_shared_memory: 13377 case OMPC_reverse_offload: 13378 case OMPC_dynamic_allocators: 13379 case OMPC_atomic_default_mem_order: 13380 case OMPC_device_type: 13381 case OMPC_match: 13382 case OMPC_nontemporal: 13383 case OMPC_order: 13384 case OMPC_destroy: 13385 case OMPC_inclusive: 13386 case OMPC_exclusive: 13387 case OMPC_uses_allocators: 13388 case OMPC_affinity: 13389 case OMPC_when: 13390 default: 13391 llvm_unreachable("Clause is not allowed."); 13392 } 13393 return Res; 13394 } 13395 13396 // An OpenMP directive such as 'target parallel' has two captured regions: 13397 // for the 'target' and 'parallel' respectively. This function returns 13398 // the region in which to capture expressions associated with a clause. 13399 // A return value of OMPD_unknown signifies that the expression should not 13400 // be captured. 13401 static OpenMPDirectiveKind getOpenMPCaptureRegionForClause( 13402 OpenMPDirectiveKind DKind, OpenMPClauseKind CKind, unsigned OpenMPVersion, 13403 OpenMPDirectiveKind NameModifier = OMPD_unknown) { 13404 OpenMPDirectiveKind CaptureRegion = OMPD_unknown; 13405 switch (CKind) { 13406 case OMPC_if: 13407 switch (DKind) { 13408 case OMPD_target_parallel_for_simd: 13409 if (OpenMPVersion >= 50 && 13410 (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)) { 13411 CaptureRegion = OMPD_parallel; 13412 break; 13413 } 13414 LLVM_FALLTHROUGH; 13415 case OMPD_target_parallel: 13416 case OMPD_target_parallel_for: 13417 // If this clause applies to the nested 'parallel' region, capture within 13418 // the 'target' region, otherwise do not capture. 13419 if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel) 13420 CaptureRegion = OMPD_target; 13421 break; 13422 case OMPD_target_teams_distribute_parallel_for_simd: 13423 if (OpenMPVersion >= 50 && 13424 (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)) { 13425 CaptureRegion = OMPD_parallel; 13426 break; 13427 } 13428 LLVM_FALLTHROUGH; 13429 case OMPD_target_teams_distribute_parallel_for: 13430 // If this clause applies to the nested 'parallel' region, capture within 13431 // the 'teams' region, otherwise do not capture. 13432 if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel) 13433 CaptureRegion = OMPD_teams; 13434 break; 13435 case OMPD_teams_distribute_parallel_for_simd: 13436 if (OpenMPVersion >= 50 && 13437 (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)) { 13438 CaptureRegion = OMPD_parallel; 13439 break; 13440 } 13441 LLVM_FALLTHROUGH; 13442 case OMPD_teams_distribute_parallel_for: 13443 CaptureRegion = OMPD_teams; 13444 break; 13445 case OMPD_target_update: 13446 case OMPD_target_enter_data: 13447 case OMPD_target_exit_data: 13448 CaptureRegion = OMPD_task; 13449 break; 13450 case OMPD_parallel_master_taskloop: 13451 if (NameModifier == OMPD_unknown || NameModifier == OMPD_taskloop) 13452 CaptureRegion = OMPD_parallel; 13453 break; 13454 case OMPD_parallel_master_taskloop_simd: 13455 if ((OpenMPVersion <= 45 && NameModifier == OMPD_unknown) || 13456 NameModifier == OMPD_taskloop) { 13457 CaptureRegion = OMPD_parallel; 13458 break; 13459 } 13460 if (OpenMPVersion <= 45) 13461 break; 13462 if (NameModifier == OMPD_unknown || NameModifier == OMPD_simd) 13463 CaptureRegion = OMPD_taskloop; 13464 break; 13465 case OMPD_parallel_for_simd: 13466 if (OpenMPVersion <= 45) 13467 break; 13468 if (NameModifier == OMPD_unknown || NameModifier == OMPD_simd) 13469 CaptureRegion = OMPD_parallel; 13470 break; 13471 case OMPD_taskloop_simd: 13472 case OMPD_master_taskloop_simd: 13473 if (OpenMPVersion <= 45) 13474 break; 13475 if (NameModifier == OMPD_unknown || NameModifier == OMPD_simd) 13476 CaptureRegion = OMPD_taskloop; 13477 break; 13478 case OMPD_distribute_parallel_for_simd: 13479 if (OpenMPVersion <= 45) 13480 break; 13481 if (NameModifier == OMPD_unknown || NameModifier == OMPD_simd) 13482 CaptureRegion = OMPD_parallel; 13483 break; 13484 case OMPD_target_simd: 13485 if (OpenMPVersion >= 50 && 13486 (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)) 13487 CaptureRegion = OMPD_target; 13488 break; 13489 case OMPD_teams_distribute_simd: 13490 case OMPD_target_teams_distribute_simd: 13491 if (OpenMPVersion >= 50 && 13492 (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)) 13493 CaptureRegion = OMPD_teams; 13494 break; 13495 case OMPD_cancel: 13496 case OMPD_parallel: 13497 case OMPD_parallel_master: 13498 case OMPD_parallel_sections: 13499 case OMPD_parallel_for: 13500 case OMPD_target: 13501 case OMPD_target_teams: 13502 case OMPD_target_teams_distribute: 13503 case OMPD_distribute_parallel_for: 13504 case OMPD_task: 13505 case OMPD_taskloop: 13506 case OMPD_master_taskloop: 13507 case OMPD_target_data: 13508 case OMPD_simd: 13509 case OMPD_for_simd: 13510 case OMPD_distribute_simd: 13511 // Do not capture if-clause expressions. 13512 break; 13513 case OMPD_threadprivate: 13514 case OMPD_allocate: 13515 case OMPD_taskyield: 13516 case OMPD_barrier: 13517 case OMPD_taskwait: 13518 case OMPD_cancellation_point: 13519 case OMPD_flush: 13520 case OMPD_depobj: 13521 case OMPD_scan: 13522 case OMPD_declare_reduction: 13523 case OMPD_declare_mapper: 13524 case OMPD_declare_simd: 13525 case OMPD_declare_variant: 13526 case OMPD_begin_declare_variant: 13527 case OMPD_end_declare_variant: 13528 case OMPD_declare_target: 13529 case OMPD_end_declare_target: 13530 case OMPD_teams: 13531 case OMPD_tile: 13532 case OMPD_unroll: 13533 case OMPD_for: 13534 case OMPD_sections: 13535 case OMPD_section: 13536 case OMPD_single: 13537 case OMPD_master: 13538 case OMPD_masked: 13539 case OMPD_critical: 13540 case OMPD_taskgroup: 13541 case OMPD_distribute: 13542 case OMPD_ordered: 13543 case OMPD_atomic: 13544 case OMPD_teams_distribute: 13545 case OMPD_requires: 13546 case OMPD_metadirective: 13547 llvm_unreachable("Unexpected OpenMP directive with if-clause"); 13548 case OMPD_unknown: 13549 default: 13550 llvm_unreachable("Unknown OpenMP directive"); 13551 } 13552 break; 13553 case OMPC_num_threads: 13554 switch (DKind) { 13555 case OMPD_target_parallel: 13556 case OMPD_target_parallel_for: 13557 case OMPD_target_parallel_for_simd: 13558 CaptureRegion = OMPD_target; 13559 break; 13560 case OMPD_teams_distribute_parallel_for: 13561 case OMPD_teams_distribute_parallel_for_simd: 13562 case OMPD_target_teams_distribute_parallel_for: 13563 case OMPD_target_teams_distribute_parallel_for_simd: 13564 CaptureRegion = OMPD_teams; 13565 break; 13566 case OMPD_parallel: 13567 case OMPD_parallel_master: 13568 case OMPD_parallel_sections: 13569 case OMPD_parallel_for: 13570 case OMPD_parallel_for_simd: 13571 case OMPD_distribute_parallel_for: 13572 case OMPD_distribute_parallel_for_simd: 13573 case OMPD_parallel_master_taskloop: 13574 case OMPD_parallel_master_taskloop_simd: 13575 // Do not capture num_threads-clause expressions. 13576 break; 13577 case OMPD_target_data: 13578 case OMPD_target_enter_data: 13579 case OMPD_target_exit_data: 13580 case OMPD_target_update: 13581 case OMPD_target: 13582 case OMPD_target_simd: 13583 case OMPD_target_teams: 13584 case OMPD_target_teams_distribute: 13585 case OMPD_target_teams_distribute_simd: 13586 case OMPD_cancel: 13587 case OMPD_task: 13588 case OMPD_taskloop: 13589 case OMPD_taskloop_simd: 13590 case OMPD_master_taskloop: 13591 case OMPD_master_taskloop_simd: 13592 case OMPD_threadprivate: 13593 case OMPD_allocate: 13594 case OMPD_taskyield: 13595 case OMPD_barrier: 13596 case OMPD_taskwait: 13597 case OMPD_cancellation_point: 13598 case OMPD_flush: 13599 case OMPD_depobj: 13600 case OMPD_scan: 13601 case OMPD_declare_reduction: 13602 case OMPD_declare_mapper: 13603 case OMPD_declare_simd: 13604 case OMPD_declare_variant: 13605 case OMPD_begin_declare_variant: 13606 case OMPD_end_declare_variant: 13607 case OMPD_declare_target: 13608 case OMPD_end_declare_target: 13609 case OMPD_teams: 13610 case OMPD_simd: 13611 case OMPD_tile: 13612 case OMPD_unroll: 13613 case OMPD_for: 13614 case OMPD_for_simd: 13615 case OMPD_sections: 13616 case OMPD_section: 13617 case OMPD_single: 13618 case OMPD_master: 13619 case OMPD_masked: 13620 case OMPD_critical: 13621 case OMPD_taskgroup: 13622 case OMPD_distribute: 13623 case OMPD_ordered: 13624 case OMPD_atomic: 13625 case OMPD_distribute_simd: 13626 case OMPD_teams_distribute: 13627 case OMPD_teams_distribute_simd: 13628 case OMPD_requires: 13629 case OMPD_metadirective: 13630 llvm_unreachable("Unexpected OpenMP directive with num_threads-clause"); 13631 case OMPD_unknown: 13632 default: 13633 llvm_unreachable("Unknown OpenMP directive"); 13634 } 13635 break; 13636 case OMPC_num_teams: 13637 switch (DKind) { 13638 case OMPD_target_teams: 13639 case OMPD_target_teams_distribute: 13640 case OMPD_target_teams_distribute_simd: 13641 case OMPD_target_teams_distribute_parallel_for: 13642 case OMPD_target_teams_distribute_parallel_for_simd: 13643 CaptureRegion = OMPD_target; 13644 break; 13645 case OMPD_teams_distribute_parallel_for: 13646 case OMPD_teams_distribute_parallel_for_simd: 13647 case OMPD_teams: 13648 case OMPD_teams_distribute: 13649 case OMPD_teams_distribute_simd: 13650 // Do not capture num_teams-clause expressions. 13651 break; 13652 case OMPD_distribute_parallel_for: 13653 case OMPD_distribute_parallel_for_simd: 13654 case OMPD_task: 13655 case OMPD_taskloop: 13656 case OMPD_taskloop_simd: 13657 case OMPD_master_taskloop: 13658 case OMPD_master_taskloop_simd: 13659 case OMPD_parallel_master_taskloop: 13660 case OMPD_parallel_master_taskloop_simd: 13661 case OMPD_target_data: 13662 case OMPD_target_enter_data: 13663 case OMPD_target_exit_data: 13664 case OMPD_target_update: 13665 case OMPD_cancel: 13666 case OMPD_parallel: 13667 case OMPD_parallel_master: 13668 case OMPD_parallel_sections: 13669 case OMPD_parallel_for: 13670 case OMPD_parallel_for_simd: 13671 case OMPD_target: 13672 case OMPD_target_simd: 13673 case OMPD_target_parallel: 13674 case OMPD_target_parallel_for: 13675 case OMPD_target_parallel_for_simd: 13676 case OMPD_threadprivate: 13677 case OMPD_allocate: 13678 case OMPD_taskyield: 13679 case OMPD_barrier: 13680 case OMPD_taskwait: 13681 case OMPD_cancellation_point: 13682 case OMPD_flush: 13683 case OMPD_depobj: 13684 case OMPD_scan: 13685 case OMPD_declare_reduction: 13686 case OMPD_declare_mapper: 13687 case OMPD_declare_simd: 13688 case OMPD_declare_variant: 13689 case OMPD_begin_declare_variant: 13690 case OMPD_end_declare_variant: 13691 case OMPD_declare_target: 13692 case OMPD_end_declare_target: 13693 case OMPD_simd: 13694 case OMPD_tile: 13695 case OMPD_unroll: 13696 case OMPD_for: 13697 case OMPD_for_simd: 13698 case OMPD_sections: 13699 case OMPD_section: 13700 case OMPD_single: 13701 case OMPD_master: 13702 case OMPD_masked: 13703 case OMPD_critical: 13704 case OMPD_taskgroup: 13705 case OMPD_distribute: 13706 case OMPD_ordered: 13707 case OMPD_atomic: 13708 case OMPD_distribute_simd: 13709 case OMPD_requires: 13710 case OMPD_metadirective: 13711 llvm_unreachable("Unexpected OpenMP directive with num_teams-clause"); 13712 case OMPD_unknown: 13713 default: 13714 llvm_unreachable("Unknown OpenMP directive"); 13715 } 13716 break; 13717 case OMPC_thread_limit: 13718 switch (DKind) { 13719 case OMPD_target_teams: 13720 case OMPD_target_teams_distribute: 13721 case OMPD_target_teams_distribute_simd: 13722 case OMPD_target_teams_distribute_parallel_for: 13723 case OMPD_target_teams_distribute_parallel_for_simd: 13724 CaptureRegion = OMPD_target; 13725 break; 13726 case OMPD_teams_distribute_parallel_for: 13727 case OMPD_teams_distribute_parallel_for_simd: 13728 case OMPD_teams: 13729 case OMPD_teams_distribute: 13730 case OMPD_teams_distribute_simd: 13731 // Do not capture thread_limit-clause expressions. 13732 break; 13733 case OMPD_distribute_parallel_for: 13734 case OMPD_distribute_parallel_for_simd: 13735 case OMPD_task: 13736 case OMPD_taskloop: 13737 case OMPD_taskloop_simd: 13738 case OMPD_master_taskloop: 13739 case OMPD_master_taskloop_simd: 13740 case OMPD_parallel_master_taskloop: 13741 case OMPD_parallel_master_taskloop_simd: 13742 case OMPD_target_data: 13743 case OMPD_target_enter_data: 13744 case OMPD_target_exit_data: 13745 case OMPD_target_update: 13746 case OMPD_cancel: 13747 case OMPD_parallel: 13748 case OMPD_parallel_master: 13749 case OMPD_parallel_sections: 13750 case OMPD_parallel_for: 13751 case OMPD_parallel_for_simd: 13752 case OMPD_target: 13753 case OMPD_target_simd: 13754 case OMPD_target_parallel: 13755 case OMPD_target_parallel_for: 13756 case OMPD_target_parallel_for_simd: 13757 case OMPD_threadprivate: 13758 case OMPD_allocate: 13759 case OMPD_taskyield: 13760 case OMPD_barrier: 13761 case OMPD_taskwait: 13762 case OMPD_cancellation_point: 13763 case OMPD_flush: 13764 case OMPD_depobj: 13765 case OMPD_scan: 13766 case OMPD_declare_reduction: 13767 case OMPD_declare_mapper: 13768 case OMPD_declare_simd: 13769 case OMPD_declare_variant: 13770 case OMPD_begin_declare_variant: 13771 case OMPD_end_declare_variant: 13772 case OMPD_declare_target: 13773 case OMPD_end_declare_target: 13774 case OMPD_simd: 13775 case OMPD_tile: 13776 case OMPD_unroll: 13777 case OMPD_for: 13778 case OMPD_for_simd: 13779 case OMPD_sections: 13780 case OMPD_section: 13781 case OMPD_single: 13782 case OMPD_master: 13783 case OMPD_masked: 13784 case OMPD_critical: 13785 case OMPD_taskgroup: 13786 case OMPD_distribute: 13787 case OMPD_ordered: 13788 case OMPD_atomic: 13789 case OMPD_distribute_simd: 13790 case OMPD_requires: 13791 case OMPD_metadirective: 13792 llvm_unreachable("Unexpected OpenMP directive with thread_limit-clause"); 13793 case OMPD_unknown: 13794 default: 13795 llvm_unreachable("Unknown OpenMP directive"); 13796 } 13797 break; 13798 case OMPC_schedule: 13799 switch (DKind) { 13800 case OMPD_parallel_for: 13801 case OMPD_parallel_for_simd: 13802 case OMPD_distribute_parallel_for: 13803 case OMPD_distribute_parallel_for_simd: 13804 case OMPD_teams_distribute_parallel_for: 13805 case OMPD_teams_distribute_parallel_for_simd: 13806 case OMPD_target_parallel_for: 13807 case OMPD_target_parallel_for_simd: 13808 case OMPD_target_teams_distribute_parallel_for: 13809 case OMPD_target_teams_distribute_parallel_for_simd: 13810 CaptureRegion = OMPD_parallel; 13811 break; 13812 case OMPD_for: 13813 case OMPD_for_simd: 13814 // Do not capture schedule-clause expressions. 13815 break; 13816 case OMPD_task: 13817 case OMPD_taskloop: 13818 case OMPD_taskloop_simd: 13819 case OMPD_master_taskloop: 13820 case OMPD_master_taskloop_simd: 13821 case OMPD_parallel_master_taskloop: 13822 case OMPD_parallel_master_taskloop_simd: 13823 case OMPD_target_data: 13824 case OMPD_target_enter_data: 13825 case OMPD_target_exit_data: 13826 case OMPD_target_update: 13827 case OMPD_teams: 13828 case OMPD_teams_distribute: 13829 case OMPD_teams_distribute_simd: 13830 case OMPD_target_teams_distribute: 13831 case OMPD_target_teams_distribute_simd: 13832 case OMPD_target: 13833 case OMPD_target_simd: 13834 case OMPD_target_parallel: 13835 case OMPD_cancel: 13836 case OMPD_parallel: 13837 case OMPD_parallel_master: 13838 case OMPD_parallel_sections: 13839 case OMPD_threadprivate: 13840 case OMPD_allocate: 13841 case OMPD_taskyield: 13842 case OMPD_barrier: 13843 case OMPD_taskwait: 13844 case OMPD_cancellation_point: 13845 case OMPD_flush: 13846 case OMPD_depobj: 13847 case OMPD_scan: 13848 case OMPD_declare_reduction: 13849 case OMPD_declare_mapper: 13850 case OMPD_declare_simd: 13851 case OMPD_declare_variant: 13852 case OMPD_begin_declare_variant: 13853 case OMPD_end_declare_variant: 13854 case OMPD_declare_target: 13855 case OMPD_end_declare_target: 13856 case OMPD_simd: 13857 case OMPD_tile: 13858 case OMPD_unroll: 13859 case OMPD_sections: 13860 case OMPD_section: 13861 case OMPD_single: 13862 case OMPD_master: 13863 case OMPD_masked: 13864 case OMPD_critical: 13865 case OMPD_taskgroup: 13866 case OMPD_distribute: 13867 case OMPD_ordered: 13868 case OMPD_atomic: 13869 case OMPD_distribute_simd: 13870 case OMPD_target_teams: 13871 case OMPD_requires: 13872 case OMPD_metadirective: 13873 llvm_unreachable("Unexpected OpenMP directive with schedule clause"); 13874 case OMPD_unknown: 13875 default: 13876 llvm_unreachable("Unknown OpenMP directive"); 13877 } 13878 break; 13879 case OMPC_dist_schedule: 13880 switch (DKind) { 13881 case OMPD_teams_distribute_parallel_for: 13882 case OMPD_teams_distribute_parallel_for_simd: 13883 case OMPD_teams_distribute: 13884 case OMPD_teams_distribute_simd: 13885 case OMPD_target_teams_distribute_parallel_for: 13886 case OMPD_target_teams_distribute_parallel_for_simd: 13887 case OMPD_target_teams_distribute: 13888 case OMPD_target_teams_distribute_simd: 13889 CaptureRegion = OMPD_teams; 13890 break; 13891 case OMPD_distribute_parallel_for: 13892 case OMPD_distribute_parallel_for_simd: 13893 case OMPD_distribute: 13894 case OMPD_distribute_simd: 13895 // Do not capture dist_schedule-clause expressions. 13896 break; 13897 case OMPD_parallel_for: 13898 case OMPD_parallel_for_simd: 13899 case OMPD_target_parallel_for_simd: 13900 case OMPD_target_parallel_for: 13901 case OMPD_task: 13902 case OMPD_taskloop: 13903 case OMPD_taskloop_simd: 13904 case OMPD_master_taskloop: 13905 case OMPD_master_taskloop_simd: 13906 case OMPD_parallel_master_taskloop: 13907 case OMPD_parallel_master_taskloop_simd: 13908 case OMPD_target_data: 13909 case OMPD_target_enter_data: 13910 case OMPD_target_exit_data: 13911 case OMPD_target_update: 13912 case OMPD_teams: 13913 case OMPD_target: 13914 case OMPD_target_simd: 13915 case OMPD_target_parallel: 13916 case OMPD_cancel: 13917 case OMPD_parallel: 13918 case OMPD_parallel_master: 13919 case OMPD_parallel_sections: 13920 case OMPD_threadprivate: 13921 case OMPD_allocate: 13922 case OMPD_taskyield: 13923 case OMPD_barrier: 13924 case OMPD_taskwait: 13925 case OMPD_cancellation_point: 13926 case OMPD_flush: 13927 case OMPD_depobj: 13928 case OMPD_scan: 13929 case OMPD_declare_reduction: 13930 case OMPD_declare_mapper: 13931 case OMPD_declare_simd: 13932 case OMPD_declare_variant: 13933 case OMPD_begin_declare_variant: 13934 case OMPD_end_declare_variant: 13935 case OMPD_declare_target: 13936 case OMPD_end_declare_target: 13937 case OMPD_simd: 13938 case OMPD_tile: 13939 case OMPD_unroll: 13940 case OMPD_for: 13941 case OMPD_for_simd: 13942 case OMPD_sections: 13943 case OMPD_section: 13944 case OMPD_single: 13945 case OMPD_master: 13946 case OMPD_masked: 13947 case OMPD_critical: 13948 case OMPD_taskgroup: 13949 case OMPD_ordered: 13950 case OMPD_atomic: 13951 case OMPD_target_teams: 13952 case OMPD_requires: 13953 case OMPD_metadirective: 13954 llvm_unreachable("Unexpected OpenMP directive with dist_schedule clause"); 13955 case OMPD_unknown: 13956 default: 13957 llvm_unreachable("Unknown OpenMP directive"); 13958 } 13959 break; 13960 case OMPC_device: 13961 switch (DKind) { 13962 case OMPD_target_update: 13963 case OMPD_target_enter_data: 13964 case OMPD_target_exit_data: 13965 case OMPD_target: 13966 case OMPD_target_simd: 13967 case OMPD_target_teams: 13968 case OMPD_target_parallel: 13969 case OMPD_target_teams_distribute: 13970 case OMPD_target_teams_distribute_simd: 13971 case OMPD_target_parallel_for: 13972 case OMPD_target_parallel_for_simd: 13973 case OMPD_target_teams_distribute_parallel_for: 13974 case OMPD_target_teams_distribute_parallel_for_simd: 13975 case OMPD_dispatch: 13976 CaptureRegion = OMPD_task; 13977 break; 13978 case OMPD_target_data: 13979 case OMPD_interop: 13980 // Do not capture device-clause expressions. 13981 break; 13982 case OMPD_teams_distribute_parallel_for: 13983 case OMPD_teams_distribute_parallel_for_simd: 13984 case OMPD_teams: 13985 case OMPD_teams_distribute: 13986 case OMPD_teams_distribute_simd: 13987 case OMPD_distribute_parallel_for: 13988 case OMPD_distribute_parallel_for_simd: 13989 case OMPD_task: 13990 case OMPD_taskloop: 13991 case OMPD_taskloop_simd: 13992 case OMPD_master_taskloop: 13993 case OMPD_master_taskloop_simd: 13994 case OMPD_parallel_master_taskloop: 13995 case OMPD_parallel_master_taskloop_simd: 13996 case OMPD_cancel: 13997 case OMPD_parallel: 13998 case OMPD_parallel_master: 13999 case OMPD_parallel_sections: 14000 case OMPD_parallel_for: 14001 case OMPD_parallel_for_simd: 14002 case OMPD_threadprivate: 14003 case OMPD_allocate: 14004 case OMPD_taskyield: 14005 case OMPD_barrier: 14006 case OMPD_taskwait: 14007 case OMPD_cancellation_point: 14008 case OMPD_flush: 14009 case OMPD_depobj: 14010 case OMPD_scan: 14011 case OMPD_declare_reduction: 14012 case OMPD_declare_mapper: 14013 case OMPD_declare_simd: 14014 case OMPD_declare_variant: 14015 case OMPD_begin_declare_variant: 14016 case OMPD_end_declare_variant: 14017 case OMPD_declare_target: 14018 case OMPD_end_declare_target: 14019 case OMPD_simd: 14020 case OMPD_tile: 14021 case OMPD_unroll: 14022 case OMPD_for: 14023 case OMPD_for_simd: 14024 case OMPD_sections: 14025 case OMPD_section: 14026 case OMPD_single: 14027 case OMPD_master: 14028 case OMPD_masked: 14029 case OMPD_critical: 14030 case OMPD_taskgroup: 14031 case OMPD_distribute: 14032 case OMPD_ordered: 14033 case OMPD_atomic: 14034 case OMPD_distribute_simd: 14035 case OMPD_requires: 14036 case OMPD_metadirective: 14037 llvm_unreachable("Unexpected OpenMP directive with device-clause"); 14038 case OMPD_unknown: 14039 default: 14040 llvm_unreachable("Unknown OpenMP directive"); 14041 } 14042 break; 14043 case OMPC_grainsize: 14044 case OMPC_num_tasks: 14045 case OMPC_final: 14046 case OMPC_priority: 14047 switch (DKind) { 14048 case OMPD_task: 14049 case OMPD_taskloop: 14050 case OMPD_taskloop_simd: 14051 case OMPD_master_taskloop: 14052 case OMPD_master_taskloop_simd: 14053 break; 14054 case OMPD_parallel_master_taskloop: 14055 case OMPD_parallel_master_taskloop_simd: 14056 CaptureRegion = OMPD_parallel; 14057 break; 14058 case OMPD_target_update: 14059 case OMPD_target_enter_data: 14060 case OMPD_target_exit_data: 14061 case OMPD_target: 14062 case OMPD_target_simd: 14063 case OMPD_target_teams: 14064 case OMPD_target_parallel: 14065 case OMPD_target_teams_distribute: 14066 case OMPD_target_teams_distribute_simd: 14067 case OMPD_target_parallel_for: 14068 case OMPD_target_parallel_for_simd: 14069 case OMPD_target_teams_distribute_parallel_for: 14070 case OMPD_target_teams_distribute_parallel_for_simd: 14071 case OMPD_target_data: 14072 case OMPD_teams_distribute_parallel_for: 14073 case OMPD_teams_distribute_parallel_for_simd: 14074 case OMPD_teams: 14075 case OMPD_teams_distribute: 14076 case OMPD_teams_distribute_simd: 14077 case OMPD_distribute_parallel_for: 14078 case OMPD_distribute_parallel_for_simd: 14079 case OMPD_cancel: 14080 case OMPD_parallel: 14081 case OMPD_parallel_master: 14082 case OMPD_parallel_sections: 14083 case OMPD_parallel_for: 14084 case OMPD_parallel_for_simd: 14085 case OMPD_threadprivate: 14086 case OMPD_allocate: 14087 case OMPD_taskyield: 14088 case OMPD_barrier: 14089 case OMPD_taskwait: 14090 case OMPD_cancellation_point: 14091 case OMPD_flush: 14092 case OMPD_depobj: 14093 case OMPD_scan: 14094 case OMPD_declare_reduction: 14095 case OMPD_declare_mapper: 14096 case OMPD_declare_simd: 14097 case OMPD_declare_variant: 14098 case OMPD_begin_declare_variant: 14099 case OMPD_end_declare_variant: 14100 case OMPD_declare_target: 14101 case OMPD_end_declare_target: 14102 case OMPD_simd: 14103 case OMPD_tile: 14104 case OMPD_unroll: 14105 case OMPD_for: 14106 case OMPD_for_simd: 14107 case OMPD_sections: 14108 case OMPD_section: 14109 case OMPD_single: 14110 case OMPD_master: 14111 case OMPD_masked: 14112 case OMPD_critical: 14113 case OMPD_taskgroup: 14114 case OMPD_distribute: 14115 case OMPD_ordered: 14116 case OMPD_atomic: 14117 case OMPD_distribute_simd: 14118 case OMPD_requires: 14119 case OMPD_metadirective: 14120 llvm_unreachable("Unexpected OpenMP directive with grainsize-clause"); 14121 case OMPD_unknown: 14122 default: 14123 llvm_unreachable("Unknown OpenMP directive"); 14124 } 14125 break; 14126 case OMPC_novariants: 14127 case OMPC_nocontext: 14128 switch (DKind) { 14129 case OMPD_dispatch: 14130 CaptureRegion = OMPD_task; 14131 break; 14132 default: 14133 llvm_unreachable("Unexpected OpenMP directive"); 14134 } 14135 break; 14136 case OMPC_filter: 14137 // Do not capture filter-clause expressions. 14138 break; 14139 case OMPC_when: 14140 if (DKind == OMPD_metadirective) { 14141 CaptureRegion = OMPD_metadirective; 14142 } else if (DKind == OMPD_unknown) { 14143 llvm_unreachable("Unknown OpenMP directive"); 14144 } else { 14145 llvm_unreachable("Unexpected OpenMP directive with when clause"); 14146 } 14147 break; 14148 case OMPC_firstprivate: 14149 case OMPC_lastprivate: 14150 case OMPC_reduction: 14151 case OMPC_task_reduction: 14152 case OMPC_in_reduction: 14153 case OMPC_linear: 14154 case OMPC_default: 14155 case OMPC_proc_bind: 14156 case OMPC_safelen: 14157 case OMPC_simdlen: 14158 case OMPC_sizes: 14159 case OMPC_allocator: 14160 case OMPC_collapse: 14161 case OMPC_private: 14162 case OMPC_shared: 14163 case OMPC_aligned: 14164 case OMPC_copyin: 14165 case OMPC_copyprivate: 14166 case OMPC_ordered: 14167 case OMPC_nowait: 14168 case OMPC_untied: 14169 case OMPC_mergeable: 14170 case OMPC_threadprivate: 14171 case OMPC_allocate: 14172 case OMPC_flush: 14173 case OMPC_depobj: 14174 case OMPC_read: 14175 case OMPC_write: 14176 case OMPC_update: 14177 case OMPC_capture: 14178 case OMPC_seq_cst: 14179 case OMPC_acq_rel: 14180 case OMPC_acquire: 14181 case OMPC_release: 14182 case OMPC_relaxed: 14183 case OMPC_depend: 14184 case OMPC_threads: 14185 case OMPC_simd: 14186 case OMPC_map: 14187 case OMPC_nogroup: 14188 case OMPC_hint: 14189 case OMPC_defaultmap: 14190 case OMPC_unknown: 14191 case OMPC_uniform: 14192 case OMPC_to: 14193 case OMPC_from: 14194 case OMPC_use_device_ptr: 14195 case OMPC_use_device_addr: 14196 case OMPC_is_device_ptr: 14197 case OMPC_unified_address: 14198 case OMPC_unified_shared_memory: 14199 case OMPC_reverse_offload: 14200 case OMPC_dynamic_allocators: 14201 case OMPC_atomic_default_mem_order: 14202 case OMPC_device_type: 14203 case OMPC_match: 14204 case OMPC_nontemporal: 14205 case OMPC_order: 14206 case OMPC_destroy: 14207 case OMPC_detach: 14208 case OMPC_inclusive: 14209 case OMPC_exclusive: 14210 case OMPC_uses_allocators: 14211 case OMPC_affinity: 14212 default: 14213 llvm_unreachable("Unexpected OpenMP clause."); 14214 } 14215 return CaptureRegion; 14216 } 14217 14218 OMPClause *Sema::ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier, 14219 Expr *Condition, SourceLocation StartLoc, 14220 SourceLocation LParenLoc, 14221 SourceLocation NameModifierLoc, 14222 SourceLocation ColonLoc, 14223 SourceLocation EndLoc) { 14224 Expr *ValExpr = Condition; 14225 Stmt *HelperValStmt = nullptr; 14226 OpenMPDirectiveKind CaptureRegion = OMPD_unknown; 14227 if (!Condition->isValueDependent() && !Condition->isTypeDependent() && 14228 !Condition->isInstantiationDependent() && 14229 !Condition->containsUnexpandedParameterPack()) { 14230 ExprResult Val = CheckBooleanCondition(StartLoc, Condition); 14231 if (Val.isInvalid()) 14232 return nullptr; 14233 14234 ValExpr = Val.get(); 14235 14236 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective(); 14237 CaptureRegion = getOpenMPCaptureRegionForClause( 14238 DKind, OMPC_if, LangOpts.OpenMP, NameModifier); 14239 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) { 14240 ValExpr = MakeFullExpr(ValExpr).get(); 14241 llvm::MapVector<const Expr *, DeclRefExpr *> Captures; 14242 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 14243 HelperValStmt = buildPreInits(Context, Captures); 14244 } 14245 } 14246 14247 return new (Context) 14248 OMPIfClause(NameModifier, ValExpr, HelperValStmt, CaptureRegion, StartLoc, 14249 LParenLoc, NameModifierLoc, ColonLoc, EndLoc); 14250 } 14251 14252 OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition, 14253 SourceLocation StartLoc, 14254 SourceLocation LParenLoc, 14255 SourceLocation EndLoc) { 14256 Expr *ValExpr = Condition; 14257 Stmt *HelperValStmt = nullptr; 14258 OpenMPDirectiveKind CaptureRegion = OMPD_unknown; 14259 if (!Condition->isValueDependent() && !Condition->isTypeDependent() && 14260 !Condition->isInstantiationDependent() && 14261 !Condition->containsUnexpandedParameterPack()) { 14262 ExprResult Val = CheckBooleanCondition(StartLoc, Condition); 14263 if (Val.isInvalid()) 14264 return nullptr; 14265 14266 ValExpr = MakeFullExpr(Val.get()).get(); 14267 14268 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective(); 14269 CaptureRegion = 14270 getOpenMPCaptureRegionForClause(DKind, OMPC_final, LangOpts.OpenMP); 14271 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) { 14272 ValExpr = MakeFullExpr(ValExpr).get(); 14273 llvm::MapVector<const Expr *, DeclRefExpr *> Captures; 14274 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 14275 HelperValStmt = buildPreInits(Context, Captures); 14276 } 14277 } 14278 14279 return new (Context) OMPFinalClause(ValExpr, HelperValStmt, CaptureRegion, 14280 StartLoc, LParenLoc, EndLoc); 14281 } 14282 14283 ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc, 14284 Expr *Op) { 14285 if (!Op) 14286 return ExprError(); 14287 14288 class IntConvertDiagnoser : public ICEConvertDiagnoser { 14289 public: 14290 IntConvertDiagnoser() 14291 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {} 14292 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 14293 QualType T) override { 14294 return S.Diag(Loc, diag::err_omp_not_integral) << T; 14295 } 14296 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc, 14297 QualType T) override { 14298 return S.Diag(Loc, diag::err_omp_incomplete_type) << T; 14299 } 14300 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc, 14301 QualType T, 14302 QualType ConvTy) override { 14303 return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy; 14304 } 14305 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv, 14306 QualType ConvTy) override { 14307 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here) 14308 << ConvTy->isEnumeralType() << ConvTy; 14309 } 14310 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc, 14311 QualType T) override { 14312 return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T; 14313 } 14314 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv, 14315 QualType ConvTy) override { 14316 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here) 14317 << ConvTy->isEnumeralType() << ConvTy; 14318 } 14319 SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType, 14320 QualType) override { 14321 llvm_unreachable("conversion functions are permitted"); 14322 } 14323 } ConvertDiagnoser; 14324 return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser); 14325 } 14326 14327 static bool 14328 isNonNegativeIntegerValue(Expr *&ValExpr, Sema &SemaRef, OpenMPClauseKind CKind, 14329 bool StrictlyPositive, bool BuildCapture = false, 14330 OpenMPDirectiveKind DKind = OMPD_unknown, 14331 OpenMPDirectiveKind *CaptureRegion = nullptr, 14332 Stmt **HelperValStmt = nullptr) { 14333 if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() && 14334 !ValExpr->isInstantiationDependent()) { 14335 SourceLocation Loc = ValExpr->getExprLoc(); 14336 ExprResult Value = 14337 SemaRef.PerformOpenMPImplicitIntegerConversion(Loc, ValExpr); 14338 if (Value.isInvalid()) 14339 return false; 14340 14341 ValExpr = Value.get(); 14342 // The expression must evaluate to a non-negative integer value. 14343 if (Optional<llvm::APSInt> Result = 14344 ValExpr->getIntegerConstantExpr(SemaRef.Context)) { 14345 if (Result->isSigned() && 14346 !((!StrictlyPositive && Result->isNonNegative()) || 14347 (StrictlyPositive && Result->isStrictlyPositive()))) { 14348 SemaRef.Diag(Loc, diag::err_omp_negative_expression_in_clause) 14349 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0) 14350 << ValExpr->getSourceRange(); 14351 return false; 14352 } 14353 } 14354 if (!BuildCapture) 14355 return true; 14356 *CaptureRegion = 14357 getOpenMPCaptureRegionForClause(DKind, CKind, SemaRef.LangOpts.OpenMP); 14358 if (*CaptureRegion != OMPD_unknown && 14359 !SemaRef.CurContext->isDependentContext()) { 14360 ValExpr = SemaRef.MakeFullExpr(ValExpr).get(); 14361 llvm::MapVector<const Expr *, DeclRefExpr *> Captures; 14362 ValExpr = tryBuildCapture(SemaRef, ValExpr, Captures).get(); 14363 *HelperValStmt = buildPreInits(SemaRef.Context, Captures); 14364 } 14365 } 14366 return true; 14367 } 14368 14369 OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads, 14370 SourceLocation StartLoc, 14371 SourceLocation LParenLoc, 14372 SourceLocation EndLoc) { 14373 Expr *ValExpr = NumThreads; 14374 Stmt *HelperValStmt = nullptr; 14375 14376 // OpenMP [2.5, Restrictions] 14377 // The num_threads expression must evaluate to a positive integer value. 14378 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_threads, 14379 /*StrictlyPositive=*/true)) 14380 return nullptr; 14381 14382 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective(); 14383 OpenMPDirectiveKind CaptureRegion = 14384 getOpenMPCaptureRegionForClause(DKind, OMPC_num_threads, LangOpts.OpenMP); 14385 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) { 14386 ValExpr = MakeFullExpr(ValExpr).get(); 14387 llvm::MapVector<const Expr *, DeclRefExpr *> Captures; 14388 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 14389 HelperValStmt = buildPreInits(Context, Captures); 14390 } 14391 14392 return new (Context) OMPNumThreadsClause( 14393 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc); 14394 } 14395 14396 ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E, 14397 OpenMPClauseKind CKind, 14398 bool StrictlyPositive, 14399 bool SuppressExprDiags) { 14400 if (!E) 14401 return ExprError(); 14402 if (E->isValueDependent() || E->isTypeDependent() || 14403 E->isInstantiationDependent() || E->containsUnexpandedParameterPack()) 14404 return E; 14405 14406 llvm::APSInt Result; 14407 ExprResult ICE; 14408 if (SuppressExprDiags) { 14409 // Use a custom diagnoser that suppresses 'note' diagnostics about the 14410 // expression. 14411 struct SuppressedDiagnoser : public Sema::VerifyICEDiagnoser { 14412 SuppressedDiagnoser() : VerifyICEDiagnoser(/*Suppress=*/true) {} 14413 Sema::SemaDiagnosticBuilder diagnoseNotICE(Sema &S, 14414 SourceLocation Loc) override { 14415 llvm_unreachable("Diagnostic suppressed"); 14416 } 14417 } Diagnoser; 14418 ICE = VerifyIntegerConstantExpression(E, &Result, Diagnoser, AllowFold); 14419 } else { 14420 ICE = VerifyIntegerConstantExpression(E, &Result, /*FIXME*/ AllowFold); 14421 } 14422 if (ICE.isInvalid()) 14423 return ExprError(); 14424 14425 if ((StrictlyPositive && !Result.isStrictlyPositive()) || 14426 (!StrictlyPositive && !Result.isNonNegative())) { 14427 Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause) 14428 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0) 14429 << E->getSourceRange(); 14430 return ExprError(); 14431 } 14432 if (CKind == OMPC_aligned && !Result.isPowerOf2()) { 14433 Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two) 14434 << E->getSourceRange(); 14435 return ExprError(); 14436 } 14437 if (CKind == OMPC_collapse && DSAStack->getAssociatedLoops() == 1) 14438 DSAStack->setAssociatedLoops(Result.getExtValue()); 14439 else if (CKind == OMPC_ordered) 14440 DSAStack->setAssociatedLoops(Result.getExtValue()); 14441 return ICE; 14442 } 14443 14444 OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc, 14445 SourceLocation LParenLoc, 14446 SourceLocation EndLoc) { 14447 // OpenMP [2.8.1, simd construct, Description] 14448 // The parameter of the safelen clause must be a constant 14449 // positive integer expression. 14450 ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen); 14451 if (Safelen.isInvalid()) 14452 return nullptr; 14453 return new (Context) 14454 OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc); 14455 } 14456 14457 OMPClause *Sema::ActOnOpenMPSimdlenClause(Expr *Len, SourceLocation StartLoc, 14458 SourceLocation LParenLoc, 14459 SourceLocation EndLoc) { 14460 // OpenMP [2.8.1, simd construct, Description] 14461 // The parameter of the simdlen clause must be a constant 14462 // positive integer expression. 14463 ExprResult Simdlen = VerifyPositiveIntegerConstantInClause(Len, OMPC_simdlen); 14464 if (Simdlen.isInvalid()) 14465 return nullptr; 14466 return new (Context) 14467 OMPSimdlenClause(Simdlen.get(), StartLoc, LParenLoc, EndLoc); 14468 } 14469 14470 /// Tries to find omp_allocator_handle_t type. 14471 static bool findOMPAllocatorHandleT(Sema &S, SourceLocation Loc, 14472 DSAStackTy *Stack) { 14473 QualType OMPAllocatorHandleT = Stack->getOMPAllocatorHandleT(); 14474 if (!OMPAllocatorHandleT.isNull()) 14475 return true; 14476 // Build the predefined allocator expressions. 14477 bool ErrorFound = false; 14478 for (int I = 0; I < OMPAllocateDeclAttr::OMPUserDefinedMemAlloc; ++I) { 14479 auto AllocatorKind = static_cast<OMPAllocateDeclAttr::AllocatorTypeTy>(I); 14480 StringRef Allocator = 14481 OMPAllocateDeclAttr::ConvertAllocatorTypeTyToStr(AllocatorKind); 14482 DeclarationName AllocatorName = &S.getASTContext().Idents.get(Allocator); 14483 auto *VD = dyn_cast_or_null<ValueDecl>( 14484 S.LookupSingleName(S.TUScope, AllocatorName, Loc, Sema::LookupAnyName)); 14485 if (!VD) { 14486 ErrorFound = true; 14487 break; 14488 } 14489 QualType AllocatorType = 14490 VD->getType().getNonLValueExprType(S.getASTContext()); 14491 ExprResult Res = S.BuildDeclRefExpr(VD, AllocatorType, VK_LValue, Loc); 14492 if (!Res.isUsable()) { 14493 ErrorFound = true; 14494 break; 14495 } 14496 if (OMPAllocatorHandleT.isNull()) 14497 OMPAllocatorHandleT = AllocatorType; 14498 if (!S.getASTContext().hasSameType(OMPAllocatorHandleT, AllocatorType)) { 14499 ErrorFound = true; 14500 break; 14501 } 14502 Stack->setAllocator(AllocatorKind, Res.get()); 14503 } 14504 if (ErrorFound) { 14505 S.Diag(Loc, diag::err_omp_implied_type_not_found) 14506 << "omp_allocator_handle_t"; 14507 return false; 14508 } 14509 OMPAllocatorHandleT.addConst(); 14510 Stack->setOMPAllocatorHandleT(OMPAllocatorHandleT); 14511 return true; 14512 } 14513 14514 OMPClause *Sema::ActOnOpenMPAllocatorClause(Expr *A, SourceLocation StartLoc, 14515 SourceLocation LParenLoc, 14516 SourceLocation EndLoc) { 14517 // OpenMP [2.11.3, allocate Directive, Description] 14518 // allocator is an expression of omp_allocator_handle_t type. 14519 if (!findOMPAllocatorHandleT(*this, A->getExprLoc(), DSAStack)) 14520 return nullptr; 14521 14522 ExprResult Allocator = DefaultLvalueConversion(A); 14523 if (Allocator.isInvalid()) 14524 return nullptr; 14525 Allocator = PerformImplicitConversion(Allocator.get(), 14526 DSAStack->getOMPAllocatorHandleT(), 14527 Sema::AA_Initializing, 14528 /*AllowExplicit=*/true); 14529 if (Allocator.isInvalid()) 14530 return nullptr; 14531 return new (Context) 14532 OMPAllocatorClause(Allocator.get(), StartLoc, LParenLoc, EndLoc); 14533 } 14534 14535 OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops, 14536 SourceLocation StartLoc, 14537 SourceLocation LParenLoc, 14538 SourceLocation EndLoc) { 14539 // OpenMP [2.7.1, loop construct, Description] 14540 // OpenMP [2.8.1, simd construct, Description] 14541 // OpenMP [2.9.6, distribute construct, Description] 14542 // The parameter of the collapse clause must be a constant 14543 // positive integer expression. 14544 ExprResult NumForLoopsResult = 14545 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse); 14546 if (NumForLoopsResult.isInvalid()) 14547 return nullptr; 14548 return new (Context) 14549 OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc); 14550 } 14551 14552 OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc, 14553 SourceLocation EndLoc, 14554 SourceLocation LParenLoc, 14555 Expr *NumForLoops) { 14556 // OpenMP [2.7.1, loop construct, Description] 14557 // OpenMP [2.8.1, simd construct, Description] 14558 // OpenMP [2.9.6, distribute construct, Description] 14559 // The parameter of the ordered clause must be a constant 14560 // positive integer expression if any. 14561 if (NumForLoops && LParenLoc.isValid()) { 14562 ExprResult NumForLoopsResult = 14563 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_ordered); 14564 if (NumForLoopsResult.isInvalid()) 14565 return nullptr; 14566 NumForLoops = NumForLoopsResult.get(); 14567 } else { 14568 NumForLoops = nullptr; 14569 } 14570 auto *Clause = OMPOrderedClause::Create( 14571 Context, NumForLoops, NumForLoops ? DSAStack->getAssociatedLoops() : 0, 14572 StartLoc, LParenLoc, EndLoc); 14573 DSAStack->setOrderedRegion(/*IsOrdered=*/true, NumForLoops, Clause); 14574 return Clause; 14575 } 14576 14577 OMPClause *Sema::ActOnOpenMPSimpleClause( 14578 OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc, 14579 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) { 14580 OMPClause *Res = nullptr; 14581 switch (Kind) { 14582 case OMPC_default: 14583 Res = ActOnOpenMPDefaultClause(static_cast<DefaultKind>(Argument), 14584 ArgumentLoc, StartLoc, LParenLoc, EndLoc); 14585 break; 14586 case OMPC_proc_bind: 14587 Res = ActOnOpenMPProcBindClause(static_cast<ProcBindKind>(Argument), 14588 ArgumentLoc, StartLoc, LParenLoc, EndLoc); 14589 break; 14590 case OMPC_atomic_default_mem_order: 14591 Res = ActOnOpenMPAtomicDefaultMemOrderClause( 14592 static_cast<OpenMPAtomicDefaultMemOrderClauseKind>(Argument), 14593 ArgumentLoc, StartLoc, LParenLoc, EndLoc); 14594 break; 14595 case OMPC_order: 14596 Res = ActOnOpenMPOrderClause(static_cast<OpenMPOrderClauseKind>(Argument), 14597 ArgumentLoc, StartLoc, LParenLoc, EndLoc); 14598 break; 14599 case OMPC_update: 14600 Res = ActOnOpenMPUpdateClause(static_cast<OpenMPDependClauseKind>(Argument), 14601 ArgumentLoc, StartLoc, LParenLoc, EndLoc); 14602 break; 14603 case OMPC_if: 14604 case OMPC_final: 14605 case OMPC_num_threads: 14606 case OMPC_safelen: 14607 case OMPC_simdlen: 14608 case OMPC_sizes: 14609 case OMPC_allocator: 14610 case OMPC_collapse: 14611 case OMPC_schedule: 14612 case OMPC_private: 14613 case OMPC_firstprivate: 14614 case OMPC_lastprivate: 14615 case OMPC_shared: 14616 case OMPC_reduction: 14617 case OMPC_task_reduction: 14618 case OMPC_in_reduction: 14619 case OMPC_linear: 14620 case OMPC_aligned: 14621 case OMPC_copyin: 14622 case OMPC_copyprivate: 14623 case OMPC_ordered: 14624 case OMPC_nowait: 14625 case OMPC_untied: 14626 case OMPC_mergeable: 14627 case OMPC_threadprivate: 14628 case OMPC_allocate: 14629 case OMPC_flush: 14630 case OMPC_depobj: 14631 case OMPC_read: 14632 case OMPC_write: 14633 case OMPC_capture: 14634 case OMPC_seq_cst: 14635 case OMPC_acq_rel: 14636 case OMPC_acquire: 14637 case OMPC_release: 14638 case OMPC_relaxed: 14639 case OMPC_depend: 14640 case OMPC_device: 14641 case OMPC_threads: 14642 case OMPC_simd: 14643 case OMPC_map: 14644 case OMPC_num_teams: 14645 case OMPC_thread_limit: 14646 case OMPC_priority: 14647 case OMPC_grainsize: 14648 case OMPC_nogroup: 14649 case OMPC_num_tasks: 14650 case OMPC_hint: 14651 case OMPC_dist_schedule: 14652 case OMPC_defaultmap: 14653 case OMPC_unknown: 14654 case OMPC_uniform: 14655 case OMPC_to: 14656 case OMPC_from: 14657 case OMPC_use_device_ptr: 14658 case OMPC_use_device_addr: 14659 case OMPC_is_device_ptr: 14660 case OMPC_unified_address: 14661 case OMPC_unified_shared_memory: 14662 case OMPC_reverse_offload: 14663 case OMPC_dynamic_allocators: 14664 case OMPC_device_type: 14665 case OMPC_match: 14666 case OMPC_nontemporal: 14667 case OMPC_destroy: 14668 case OMPC_novariants: 14669 case OMPC_nocontext: 14670 case OMPC_detach: 14671 case OMPC_inclusive: 14672 case OMPC_exclusive: 14673 case OMPC_uses_allocators: 14674 case OMPC_affinity: 14675 case OMPC_when: 14676 default: 14677 llvm_unreachable("Clause is not allowed."); 14678 } 14679 return Res; 14680 } 14681 14682 static std::string 14683 getListOfPossibleValues(OpenMPClauseKind K, unsigned First, unsigned Last, 14684 ArrayRef<unsigned> Exclude = llvm::None) { 14685 SmallString<256> Buffer; 14686 llvm::raw_svector_ostream Out(Buffer); 14687 unsigned Skipped = Exclude.size(); 14688 auto S = Exclude.begin(), E = Exclude.end(); 14689 for (unsigned I = First; I < Last; ++I) { 14690 if (std::find(S, E, I) != E) { 14691 --Skipped; 14692 continue; 14693 } 14694 Out << "'" << getOpenMPSimpleClauseTypeName(K, I) << "'"; 14695 if (I + Skipped + 2 == Last) 14696 Out << " or "; 14697 else if (I + Skipped + 1 != Last) 14698 Out << ", "; 14699 } 14700 return std::string(Out.str()); 14701 } 14702 14703 OMPClause *Sema::ActOnOpenMPDefaultClause(DefaultKind Kind, 14704 SourceLocation KindKwLoc, 14705 SourceLocation StartLoc, 14706 SourceLocation LParenLoc, 14707 SourceLocation EndLoc) { 14708 if (Kind == OMP_DEFAULT_unknown) { 14709 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value) 14710 << getListOfPossibleValues(OMPC_default, /*First=*/0, 14711 /*Last=*/unsigned(OMP_DEFAULT_unknown)) 14712 << getOpenMPClauseName(OMPC_default); 14713 return nullptr; 14714 } 14715 14716 switch (Kind) { 14717 case OMP_DEFAULT_none: 14718 DSAStack->setDefaultDSANone(KindKwLoc); 14719 break; 14720 case OMP_DEFAULT_shared: 14721 DSAStack->setDefaultDSAShared(KindKwLoc); 14722 break; 14723 case OMP_DEFAULT_firstprivate: 14724 DSAStack->setDefaultDSAFirstPrivate(KindKwLoc); 14725 break; 14726 default: 14727 llvm_unreachable("DSA unexpected in OpenMP default clause"); 14728 } 14729 14730 return new (Context) 14731 OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc); 14732 } 14733 14734 OMPClause *Sema::ActOnOpenMPProcBindClause(ProcBindKind Kind, 14735 SourceLocation KindKwLoc, 14736 SourceLocation StartLoc, 14737 SourceLocation LParenLoc, 14738 SourceLocation EndLoc) { 14739 if (Kind == OMP_PROC_BIND_unknown) { 14740 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value) 14741 << getListOfPossibleValues(OMPC_proc_bind, 14742 /*First=*/unsigned(OMP_PROC_BIND_master), 14743 /*Last=*/ 14744 unsigned(LangOpts.OpenMP > 50 14745 ? OMP_PROC_BIND_primary 14746 : OMP_PROC_BIND_spread) + 14747 1) 14748 << getOpenMPClauseName(OMPC_proc_bind); 14749 return nullptr; 14750 } 14751 if (Kind == OMP_PROC_BIND_primary && LangOpts.OpenMP < 51) 14752 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value) 14753 << getListOfPossibleValues(OMPC_proc_bind, 14754 /*First=*/unsigned(OMP_PROC_BIND_master), 14755 /*Last=*/ 14756 unsigned(OMP_PROC_BIND_spread) + 1) 14757 << getOpenMPClauseName(OMPC_proc_bind); 14758 return new (Context) 14759 OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc); 14760 } 14761 14762 OMPClause *Sema::ActOnOpenMPAtomicDefaultMemOrderClause( 14763 OpenMPAtomicDefaultMemOrderClauseKind Kind, SourceLocation KindKwLoc, 14764 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) { 14765 if (Kind == OMPC_ATOMIC_DEFAULT_MEM_ORDER_unknown) { 14766 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value) 14767 << getListOfPossibleValues( 14768 OMPC_atomic_default_mem_order, /*First=*/0, 14769 /*Last=*/OMPC_ATOMIC_DEFAULT_MEM_ORDER_unknown) 14770 << getOpenMPClauseName(OMPC_atomic_default_mem_order); 14771 return nullptr; 14772 } 14773 return new (Context) OMPAtomicDefaultMemOrderClause(Kind, KindKwLoc, StartLoc, 14774 LParenLoc, EndLoc); 14775 } 14776 14777 OMPClause *Sema::ActOnOpenMPOrderClause(OpenMPOrderClauseKind Kind, 14778 SourceLocation KindKwLoc, 14779 SourceLocation StartLoc, 14780 SourceLocation LParenLoc, 14781 SourceLocation EndLoc) { 14782 if (Kind == OMPC_ORDER_unknown) { 14783 static_assert(OMPC_ORDER_unknown > 0, 14784 "OMPC_ORDER_unknown not greater than 0"); 14785 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value) 14786 << getListOfPossibleValues(OMPC_order, /*First=*/0, 14787 /*Last=*/OMPC_ORDER_unknown) 14788 << getOpenMPClauseName(OMPC_order); 14789 return nullptr; 14790 } 14791 return new (Context) 14792 OMPOrderClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc); 14793 } 14794 14795 OMPClause *Sema::ActOnOpenMPUpdateClause(OpenMPDependClauseKind Kind, 14796 SourceLocation KindKwLoc, 14797 SourceLocation StartLoc, 14798 SourceLocation LParenLoc, 14799 SourceLocation EndLoc) { 14800 if (Kind == OMPC_DEPEND_unknown || Kind == OMPC_DEPEND_source || 14801 Kind == OMPC_DEPEND_sink || Kind == OMPC_DEPEND_depobj) { 14802 unsigned Except[] = {OMPC_DEPEND_source, OMPC_DEPEND_sink, 14803 OMPC_DEPEND_depobj}; 14804 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value) 14805 << getListOfPossibleValues(OMPC_depend, /*First=*/0, 14806 /*Last=*/OMPC_DEPEND_unknown, Except) 14807 << getOpenMPClauseName(OMPC_update); 14808 return nullptr; 14809 } 14810 return OMPUpdateClause::Create(Context, StartLoc, LParenLoc, KindKwLoc, Kind, 14811 EndLoc); 14812 } 14813 14814 OMPClause *Sema::ActOnOpenMPSizesClause(ArrayRef<Expr *> SizeExprs, 14815 SourceLocation StartLoc, 14816 SourceLocation LParenLoc, 14817 SourceLocation EndLoc) { 14818 for (Expr *SizeExpr : SizeExprs) { 14819 ExprResult NumForLoopsResult = VerifyPositiveIntegerConstantInClause( 14820 SizeExpr, OMPC_sizes, /*StrictlyPositive=*/true); 14821 if (!NumForLoopsResult.isUsable()) 14822 return nullptr; 14823 } 14824 14825 DSAStack->setAssociatedLoops(SizeExprs.size()); 14826 return OMPSizesClause::Create(Context, StartLoc, LParenLoc, EndLoc, 14827 SizeExprs); 14828 } 14829 14830 OMPClause *Sema::ActOnOpenMPFullClause(SourceLocation StartLoc, 14831 SourceLocation EndLoc) { 14832 return OMPFullClause::Create(Context, StartLoc, EndLoc); 14833 } 14834 14835 OMPClause *Sema::ActOnOpenMPPartialClause(Expr *FactorExpr, 14836 SourceLocation StartLoc, 14837 SourceLocation LParenLoc, 14838 SourceLocation EndLoc) { 14839 if (FactorExpr) { 14840 // If an argument is specified, it must be a constant (or an unevaluated 14841 // template expression). 14842 ExprResult FactorResult = VerifyPositiveIntegerConstantInClause( 14843 FactorExpr, OMPC_partial, /*StrictlyPositive=*/true); 14844 if (FactorResult.isInvalid()) 14845 return nullptr; 14846 FactorExpr = FactorResult.get(); 14847 } 14848 14849 return OMPPartialClause::Create(Context, StartLoc, LParenLoc, EndLoc, 14850 FactorExpr); 14851 } 14852 14853 OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause( 14854 OpenMPClauseKind Kind, ArrayRef<unsigned> Argument, Expr *Expr, 14855 SourceLocation StartLoc, SourceLocation LParenLoc, 14856 ArrayRef<SourceLocation> ArgumentLoc, SourceLocation DelimLoc, 14857 SourceLocation EndLoc) { 14858 OMPClause *Res = nullptr; 14859 switch (Kind) { 14860 case OMPC_schedule: 14861 enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements }; 14862 assert(Argument.size() == NumberOfElements && 14863 ArgumentLoc.size() == NumberOfElements); 14864 Res = ActOnOpenMPScheduleClause( 14865 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier1]), 14866 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier2]), 14867 static_cast<OpenMPScheduleClauseKind>(Argument[ScheduleKind]), Expr, 14868 StartLoc, LParenLoc, ArgumentLoc[Modifier1], ArgumentLoc[Modifier2], 14869 ArgumentLoc[ScheduleKind], DelimLoc, EndLoc); 14870 break; 14871 case OMPC_if: 14872 assert(Argument.size() == 1 && ArgumentLoc.size() == 1); 14873 Res = ActOnOpenMPIfClause(static_cast<OpenMPDirectiveKind>(Argument.back()), 14874 Expr, StartLoc, LParenLoc, ArgumentLoc.back(), 14875 DelimLoc, EndLoc); 14876 break; 14877 case OMPC_dist_schedule: 14878 Res = ActOnOpenMPDistScheduleClause( 14879 static_cast<OpenMPDistScheduleClauseKind>(Argument.back()), Expr, 14880 StartLoc, LParenLoc, ArgumentLoc.back(), DelimLoc, EndLoc); 14881 break; 14882 case OMPC_defaultmap: 14883 enum { Modifier, DefaultmapKind }; 14884 Res = ActOnOpenMPDefaultmapClause( 14885 static_cast<OpenMPDefaultmapClauseModifier>(Argument[Modifier]), 14886 static_cast<OpenMPDefaultmapClauseKind>(Argument[DefaultmapKind]), 14887 StartLoc, LParenLoc, ArgumentLoc[Modifier], ArgumentLoc[DefaultmapKind], 14888 EndLoc); 14889 break; 14890 case OMPC_device: 14891 assert(Argument.size() == 1 && ArgumentLoc.size() == 1); 14892 Res = ActOnOpenMPDeviceClause( 14893 static_cast<OpenMPDeviceClauseModifier>(Argument.back()), Expr, 14894 StartLoc, LParenLoc, ArgumentLoc.back(), EndLoc); 14895 break; 14896 case OMPC_final: 14897 case OMPC_num_threads: 14898 case OMPC_safelen: 14899 case OMPC_simdlen: 14900 case OMPC_sizes: 14901 case OMPC_allocator: 14902 case OMPC_collapse: 14903 case OMPC_default: 14904 case OMPC_proc_bind: 14905 case OMPC_private: 14906 case OMPC_firstprivate: 14907 case OMPC_lastprivate: 14908 case OMPC_shared: 14909 case OMPC_reduction: 14910 case OMPC_task_reduction: 14911 case OMPC_in_reduction: 14912 case OMPC_linear: 14913 case OMPC_aligned: 14914 case OMPC_copyin: 14915 case OMPC_copyprivate: 14916 case OMPC_ordered: 14917 case OMPC_nowait: 14918 case OMPC_untied: 14919 case OMPC_mergeable: 14920 case OMPC_threadprivate: 14921 case OMPC_allocate: 14922 case OMPC_flush: 14923 case OMPC_depobj: 14924 case OMPC_read: 14925 case OMPC_write: 14926 case OMPC_update: 14927 case OMPC_capture: 14928 case OMPC_seq_cst: 14929 case OMPC_acq_rel: 14930 case OMPC_acquire: 14931 case OMPC_release: 14932 case OMPC_relaxed: 14933 case OMPC_depend: 14934 case OMPC_threads: 14935 case OMPC_simd: 14936 case OMPC_map: 14937 case OMPC_num_teams: 14938 case OMPC_thread_limit: 14939 case OMPC_priority: 14940 case OMPC_grainsize: 14941 case OMPC_nogroup: 14942 case OMPC_num_tasks: 14943 case OMPC_hint: 14944 case OMPC_unknown: 14945 case OMPC_uniform: 14946 case OMPC_to: 14947 case OMPC_from: 14948 case OMPC_use_device_ptr: 14949 case OMPC_use_device_addr: 14950 case OMPC_is_device_ptr: 14951 case OMPC_unified_address: 14952 case OMPC_unified_shared_memory: 14953 case OMPC_reverse_offload: 14954 case OMPC_dynamic_allocators: 14955 case OMPC_atomic_default_mem_order: 14956 case OMPC_device_type: 14957 case OMPC_match: 14958 case OMPC_nontemporal: 14959 case OMPC_order: 14960 case OMPC_destroy: 14961 case OMPC_novariants: 14962 case OMPC_nocontext: 14963 case OMPC_detach: 14964 case OMPC_inclusive: 14965 case OMPC_exclusive: 14966 case OMPC_uses_allocators: 14967 case OMPC_affinity: 14968 case OMPC_when: 14969 default: 14970 llvm_unreachable("Clause is not allowed."); 14971 } 14972 return Res; 14973 } 14974 14975 static bool checkScheduleModifiers(Sema &S, OpenMPScheduleClauseModifier M1, 14976 OpenMPScheduleClauseModifier M2, 14977 SourceLocation M1Loc, SourceLocation M2Loc) { 14978 if (M1 == OMPC_SCHEDULE_MODIFIER_unknown && M1Loc.isValid()) { 14979 SmallVector<unsigned, 2> Excluded; 14980 if (M2 != OMPC_SCHEDULE_MODIFIER_unknown) 14981 Excluded.push_back(M2); 14982 if (M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) 14983 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_monotonic); 14984 if (M2 == OMPC_SCHEDULE_MODIFIER_monotonic) 14985 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_nonmonotonic); 14986 S.Diag(M1Loc, diag::err_omp_unexpected_clause_value) 14987 << getListOfPossibleValues(OMPC_schedule, 14988 /*First=*/OMPC_SCHEDULE_MODIFIER_unknown + 1, 14989 /*Last=*/OMPC_SCHEDULE_MODIFIER_last, 14990 Excluded) 14991 << getOpenMPClauseName(OMPC_schedule); 14992 return true; 14993 } 14994 return false; 14995 } 14996 14997 OMPClause *Sema::ActOnOpenMPScheduleClause( 14998 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2, 14999 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc, 15000 SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc, 15001 SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) { 15002 if (checkScheduleModifiers(*this, M1, M2, M1Loc, M2Loc) || 15003 checkScheduleModifiers(*this, M2, M1, M2Loc, M1Loc)) 15004 return nullptr; 15005 // OpenMP, 2.7.1, Loop Construct, Restrictions 15006 // Either the monotonic modifier or the nonmonotonic modifier can be specified 15007 // but not both. 15008 if ((M1 == M2 && M1 != OMPC_SCHEDULE_MODIFIER_unknown) || 15009 (M1 == OMPC_SCHEDULE_MODIFIER_monotonic && 15010 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) || 15011 (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic && 15012 M2 == OMPC_SCHEDULE_MODIFIER_monotonic)) { 15013 Diag(M2Loc, diag::err_omp_unexpected_schedule_modifier) 15014 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M2) 15015 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M1); 15016 return nullptr; 15017 } 15018 if (Kind == OMPC_SCHEDULE_unknown) { 15019 std::string Values; 15020 if (M1Loc.isInvalid() && M2Loc.isInvalid()) { 15021 unsigned Exclude[] = {OMPC_SCHEDULE_unknown}; 15022 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0, 15023 /*Last=*/OMPC_SCHEDULE_MODIFIER_last, 15024 Exclude); 15025 } else { 15026 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0, 15027 /*Last=*/OMPC_SCHEDULE_unknown); 15028 } 15029 Diag(KindLoc, diag::err_omp_unexpected_clause_value) 15030 << Values << getOpenMPClauseName(OMPC_schedule); 15031 return nullptr; 15032 } 15033 // OpenMP, 2.7.1, Loop Construct, Restrictions 15034 // The nonmonotonic modifier can only be specified with schedule(dynamic) or 15035 // schedule(guided). 15036 // OpenMP 5.0 does not have this restriction. 15037 if (LangOpts.OpenMP < 50 && 15038 (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic || 15039 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) && 15040 Kind != OMPC_SCHEDULE_dynamic && Kind != OMPC_SCHEDULE_guided) { 15041 Diag(M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ? M1Loc : M2Loc, 15042 diag::err_omp_schedule_nonmonotonic_static); 15043 return nullptr; 15044 } 15045 Expr *ValExpr = ChunkSize; 15046 Stmt *HelperValStmt = nullptr; 15047 if (ChunkSize) { 15048 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() && 15049 !ChunkSize->isInstantiationDependent() && 15050 !ChunkSize->containsUnexpandedParameterPack()) { 15051 SourceLocation ChunkSizeLoc = ChunkSize->getBeginLoc(); 15052 ExprResult Val = 15053 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize); 15054 if (Val.isInvalid()) 15055 return nullptr; 15056 15057 ValExpr = Val.get(); 15058 15059 // OpenMP [2.7.1, Restrictions] 15060 // chunk_size must be a loop invariant integer expression with a positive 15061 // value. 15062 if (Optional<llvm::APSInt> Result = 15063 ValExpr->getIntegerConstantExpr(Context)) { 15064 if (Result->isSigned() && !Result->isStrictlyPositive()) { 15065 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause) 15066 << "schedule" << 1 << ChunkSize->getSourceRange(); 15067 return nullptr; 15068 } 15069 } else if (getOpenMPCaptureRegionForClause( 15070 DSAStack->getCurrentDirective(), OMPC_schedule, 15071 LangOpts.OpenMP) != OMPD_unknown && 15072 !CurContext->isDependentContext()) { 15073 ValExpr = MakeFullExpr(ValExpr).get(); 15074 llvm::MapVector<const Expr *, DeclRefExpr *> Captures; 15075 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 15076 HelperValStmt = buildPreInits(Context, Captures); 15077 } 15078 } 15079 } 15080 15081 return new (Context) 15082 OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, Kind, 15083 ValExpr, HelperValStmt, M1, M1Loc, M2, M2Loc); 15084 } 15085 15086 OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind, 15087 SourceLocation StartLoc, 15088 SourceLocation EndLoc) { 15089 OMPClause *Res = nullptr; 15090 switch (Kind) { 15091 case OMPC_ordered: 15092 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc); 15093 break; 15094 case OMPC_nowait: 15095 Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc); 15096 break; 15097 case OMPC_untied: 15098 Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc); 15099 break; 15100 case OMPC_mergeable: 15101 Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc); 15102 break; 15103 case OMPC_read: 15104 Res = ActOnOpenMPReadClause(StartLoc, EndLoc); 15105 break; 15106 case OMPC_write: 15107 Res = ActOnOpenMPWriteClause(StartLoc, EndLoc); 15108 break; 15109 case OMPC_update: 15110 Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc); 15111 break; 15112 case OMPC_capture: 15113 Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc); 15114 break; 15115 case OMPC_seq_cst: 15116 Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc); 15117 break; 15118 case OMPC_acq_rel: 15119 Res = ActOnOpenMPAcqRelClause(StartLoc, EndLoc); 15120 break; 15121 case OMPC_acquire: 15122 Res = ActOnOpenMPAcquireClause(StartLoc, EndLoc); 15123 break; 15124 case OMPC_release: 15125 Res = ActOnOpenMPReleaseClause(StartLoc, EndLoc); 15126 break; 15127 case OMPC_relaxed: 15128 Res = ActOnOpenMPRelaxedClause(StartLoc, EndLoc); 15129 break; 15130 case OMPC_threads: 15131 Res = ActOnOpenMPThreadsClause(StartLoc, EndLoc); 15132 break; 15133 case OMPC_simd: 15134 Res = ActOnOpenMPSIMDClause(StartLoc, EndLoc); 15135 break; 15136 case OMPC_nogroup: 15137 Res = ActOnOpenMPNogroupClause(StartLoc, EndLoc); 15138 break; 15139 case OMPC_unified_address: 15140 Res = ActOnOpenMPUnifiedAddressClause(StartLoc, EndLoc); 15141 break; 15142 case OMPC_unified_shared_memory: 15143 Res = ActOnOpenMPUnifiedSharedMemoryClause(StartLoc, EndLoc); 15144 break; 15145 case OMPC_reverse_offload: 15146 Res = ActOnOpenMPReverseOffloadClause(StartLoc, EndLoc); 15147 break; 15148 case OMPC_dynamic_allocators: 15149 Res = ActOnOpenMPDynamicAllocatorsClause(StartLoc, EndLoc); 15150 break; 15151 case OMPC_destroy: 15152 Res = ActOnOpenMPDestroyClause(/*InteropVar=*/nullptr, StartLoc, 15153 /*LParenLoc=*/SourceLocation(), 15154 /*VarLoc=*/SourceLocation(), EndLoc); 15155 break; 15156 case OMPC_full: 15157 Res = ActOnOpenMPFullClause(StartLoc, EndLoc); 15158 break; 15159 case OMPC_partial: 15160 Res = ActOnOpenMPPartialClause(nullptr, StartLoc, /*LParenLoc=*/{}, EndLoc); 15161 break; 15162 case OMPC_if: 15163 case OMPC_final: 15164 case OMPC_num_threads: 15165 case OMPC_safelen: 15166 case OMPC_simdlen: 15167 case OMPC_sizes: 15168 case OMPC_allocator: 15169 case OMPC_collapse: 15170 case OMPC_schedule: 15171 case OMPC_private: 15172 case OMPC_firstprivate: 15173 case OMPC_lastprivate: 15174 case OMPC_shared: 15175 case OMPC_reduction: 15176 case OMPC_task_reduction: 15177 case OMPC_in_reduction: 15178 case OMPC_linear: 15179 case OMPC_aligned: 15180 case OMPC_copyin: 15181 case OMPC_copyprivate: 15182 case OMPC_default: 15183 case OMPC_proc_bind: 15184 case OMPC_threadprivate: 15185 case OMPC_allocate: 15186 case OMPC_flush: 15187 case OMPC_depobj: 15188 case OMPC_depend: 15189 case OMPC_device: 15190 case OMPC_map: 15191 case OMPC_num_teams: 15192 case OMPC_thread_limit: 15193 case OMPC_priority: 15194 case OMPC_grainsize: 15195 case OMPC_num_tasks: 15196 case OMPC_hint: 15197 case OMPC_dist_schedule: 15198 case OMPC_defaultmap: 15199 case OMPC_unknown: 15200 case OMPC_uniform: 15201 case OMPC_to: 15202 case OMPC_from: 15203 case OMPC_use_device_ptr: 15204 case OMPC_use_device_addr: 15205 case OMPC_is_device_ptr: 15206 case OMPC_atomic_default_mem_order: 15207 case OMPC_device_type: 15208 case OMPC_match: 15209 case OMPC_nontemporal: 15210 case OMPC_order: 15211 case OMPC_novariants: 15212 case OMPC_nocontext: 15213 case OMPC_detach: 15214 case OMPC_inclusive: 15215 case OMPC_exclusive: 15216 case OMPC_uses_allocators: 15217 case OMPC_affinity: 15218 case OMPC_when: 15219 default: 15220 llvm_unreachable("Clause is not allowed."); 15221 } 15222 return Res; 15223 } 15224 15225 OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc, 15226 SourceLocation EndLoc) { 15227 DSAStack->setNowaitRegion(); 15228 return new (Context) OMPNowaitClause(StartLoc, EndLoc); 15229 } 15230 15231 OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc, 15232 SourceLocation EndLoc) { 15233 return new (Context) OMPUntiedClause(StartLoc, EndLoc); 15234 } 15235 15236 OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc, 15237 SourceLocation EndLoc) { 15238 return new (Context) OMPMergeableClause(StartLoc, EndLoc); 15239 } 15240 15241 OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc, 15242 SourceLocation EndLoc) { 15243 return new (Context) OMPReadClause(StartLoc, EndLoc); 15244 } 15245 15246 OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc, 15247 SourceLocation EndLoc) { 15248 return new (Context) OMPWriteClause(StartLoc, EndLoc); 15249 } 15250 15251 OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc, 15252 SourceLocation EndLoc) { 15253 return OMPUpdateClause::Create(Context, StartLoc, EndLoc); 15254 } 15255 15256 OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc, 15257 SourceLocation EndLoc) { 15258 return new (Context) OMPCaptureClause(StartLoc, EndLoc); 15259 } 15260 15261 OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc, 15262 SourceLocation EndLoc) { 15263 return new (Context) OMPSeqCstClause(StartLoc, EndLoc); 15264 } 15265 15266 OMPClause *Sema::ActOnOpenMPAcqRelClause(SourceLocation StartLoc, 15267 SourceLocation EndLoc) { 15268 return new (Context) OMPAcqRelClause(StartLoc, EndLoc); 15269 } 15270 15271 OMPClause *Sema::ActOnOpenMPAcquireClause(SourceLocation StartLoc, 15272 SourceLocation EndLoc) { 15273 return new (Context) OMPAcquireClause(StartLoc, EndLoc); 15274 } 15275 15276 OMPClause *Sema::ActOnOpenMPReleaseClause(SourceLocation StartLoc, 15277 SourceLocation EndLoc) { 15278 return new (Context) OMPReleaseClause(StartLoc, EndLoc); 15279 } 15280 15281 OMPClause *Sema::ActOnOpenMPRelaxedClause(SourceLocation StartLoc, 15282 SourceLocation EndLoc) { 15283 return new (Context) OMPRelaxedClause(StartLoc, EndLoc); 15284 } 15285 15286 OMPClause *Sema::ActOnOpenMPThreadsClause(SourceLocation StartLoc, 15287 SourceLocation EndLoc) { 15288 return new (Context) OMPThreadsClause(StartLoc, EndLoc); 15289 } 15290 15291 OMPClause *Sema::ActOnOpenMPSIMDClause(SourceLocation StartLoc, 15292 SourceLocation EndLoc) { 15293 return new (Context) OMPSIMDClause(StartLoc, EndLoc); 15294 } 15295 15296 OMPClause *Sema::ActOnOpenMPNogroupClause(SourceLocation StartLoc, 15297 SourceLocation EndLoc) { 15298 return new (Context) OMPNogroupClause(StartLoc, EndLoc); 15299 } 15300 15301 OMPClause *Sema::ActOnOpenMPUnifiedAddressClause(SourceLocation StartLoc, 15302 SourceLocation EndLoc) { 15303 return new (Context) OMPUnifiedAddressClause(StartLoc, EndLoc); 15304 } 15305 15306 OMPClause *Sema::ActOnOpenMPUnifiedSharedMemoryClause(SourceLocation StartLoc, 15307 SourceLocation EndLoc) { 15308 return new (Context) OMPUnifiedSharedMemoryClause(StartLoc, EndLoc); 15309 } 15310 15311 OMPClause *Sema::ActOnOpenMPReverseOffloadClause(SourceLocation StartLoc, 15312 SourceLocation EndLoc) { 15313 return new (Context) OMPReverseOffloadClause(StartLoc, EndLoc); 15314 } 15315 15316 OMPClause *Sema::ActOnOpenMPDynamicAllocatorsClause(SourceLocation StartLoc, 15317 SourceLocation EndLoc) { 15318 return new (Context) OMPDynamicAllocatorsClause(StartLoc, EndLoc); 15319 } 15320 15321 StmtResult Sema::ActOnOpenMPInteropDirective(ArrayRef<OMPClause *> Clauses, 15322 SourceLocation StartLoc, 15323 SourceLocation EndLoc) { 15324 15325 // OpenMP 5.1 [2.15.1, interop Construct, Restrictions] 15326 // At least one action-clause must appear on a directive. 15327 if (!hasClauses(Clauses, OMPC_init, OMPC_use, OMPC_destroy, OMPC_nowait)) { 15328 StringRef Expected = "'init', 'use', 'destroy', or 'nowait'"; 15329 Diag(StartLoc, diag::err_omp_no_clause_for_directive) 15330 << Expected << getOpenMPDirectiveName(OMPD_interop); 15331 return StmtError(); 15332 } 15333 15334 // OpenMP 5.1 [2.15.1, interop Construct, Restrictions] 15335 // A depend clause can only appear on the directive if a targetsync 15336 // interop-type is present or the interop-var was initialized with 15337 // the targetsync interop-type. 15338 15339 // If there is any 'init' clause diagnose if there is no 'init' clause with 15340 // interop-type of 'targetsync'. Cases involving other directives cannot be 15341 // diagnosed. 15342 const OMPDependClause *DependClause = nullptr; 15343 bool HasInitClause = false; 15344 bool IsTargetSync = false; 15345 for (const OMPClause *C : Clauses) { 15346 if (IsTargetSync) 15347 break; 15348 if (const auto *InitClause = dyn_cast<OMPInitClause>(C)) { 15349 HasInitClause = true; 15350 if (InitClause->getIsTargetSync()) 15351 IsTargetSync = true; 15352 } else if (const auto *DC = dyn_cast<OMPDependClause>(C)) { 15353 DependClause = DC; 15354 } 15355 } 15356 if (DependClause && HasInitClause && !IsTargetSync) { 15357 Diag(DependClause->getBeginLoc(), diag::err_omp_interop_bad_depend_clause); 15358 return StmtError(); 15359 } 15360 15361 // OpenMP 5.1 [2.15.1, interop Construct, Restrictions] 15362 // Each interop-var may be specified for at most one action-clause of each 15363 // interop construct. 15364 llvm::SmallPtrSet<const VarDecl *, 4> InteropVars; 15365 for (const OMPClause *C : Clauses) { 15366 OpenMPClauseKind ClauseKind = C->getClauseKind(); 15367 const DeclRefExpr *DRE = nullptr; 15368 SourceLocation VarLoc; 15369 15370 if (ClauseKind == OMPC_init) { 15371 const auto *IC = cast<OMPInitClause>(C); 15372 VarLoc = IC->getVarLoc(); 15373 DRE = dyn_cast_or_null<DeclRefExpr>(IC->getInteropVar()); 15374 } else if (ClauseKind == OMPC_use) { 15375 const auto *UC = cast<OMPUseClause>(C); 15376 VarLoc = UC->getVarLoc(); 15377 DRE = dyn_cast_or_null<DeclRefExpr>(UC->getInteropVar()); 15378 } else if (ClauseKind == OMPC_destroy) { 15379 const auto *DC = cast<OMPDestroyClause>(C); 15380 VarLoc = DC->getVarLoc(); 15381 DRE = dyn_cast_or_null<DeclRefExpr>(DC->getInteropVar()); 15382 } 15383 15384 if (!DRE) 15385 continue; 15386 15387 if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) { 15388 if (!InteropVars.insert(VD->getCanonicalDecl()).second) { 15389 Diag(VarLoc, diag::err_omp_interop_var_multiple_actions) << VD; 15390 return StmtError(); 15391 } 15392 } 15393 } 15394 15395 return OMPInteropDirective::Create(Context, StartLoc, EndLoc, Clauses); 15396 } 15397 15398 static bool isValidInteropVariable(Sema &SemaRef, Expr *InteropVarExpr, 15399 SourceLocation VarLoc, 15400 OpenMPClauseKind Kind) { 15401 if (InteropVarExpr->isValueDependent() || InteropVarExpr->isTypeDependent() || 15402 InteropVarExpr->isInstantiationDependent() || 15403 InteropVarExpr->containsUnexpandedParameterPack()) 15404 return true; 15405 15406 const auto *DRE = dyn_cast<DeclRefExpr>(InteropVarExpr); 15407 if (!DRE || !isa<VarDecl>(DRE->getDecl())) { 15408 SemaRef.Diag(VarLoc, diag::err_omp_interop_variable_expected) << 0; 15409 return false; 15410 } 15411 15412 // Interop variable should be of type omp_interop_t. 15413 bool HasError = false; 15414 QualType InteropType; 15415 LookupResult Result(SemaRef, &SemaRef.Context.Idents.get("omp_interop_t"), 15416 VarLoc, Sema::LookupOrdinaryName); 15417 if (SemaRef.LookupName(Result, SemaRef.getCurScope())) { 15418 NamedDecl *ND = Result.getFoundDecl(); 15419 if (const auto *TD = dyn_cast<TypeDecl>(ND)) { 15420 InteropType = QualType(TD->getTypeForDecl(), 0); 15421 } else { 15422 HasError = true; 15423 } 15424 } else { 15425 HasError = true; 15426 } 15427 15428 if (HasError) { 15429 SemaRef.Diag(VarLoc, diag::err_omp_implied_type_not_found) 15430 << "omp_interop_t"; 15431 return false; 15432 } 15433 15434 QualType VarType = InteropVarExpr->getType().getUnqualifiedType(); 15435 if (!SemaRef.Context.hasSameType(InteropType, VarType)) { 15436 SemaRef.Diag(VarLoc, diag::err_omp_interop_variable_wrong_type); 15437 return false; 15438 } 15439 15440 // OpenMP 5.1 [2.15.1, interop Construct, Restrictions] 15441 // The interop-var passed to init or destroy must be non-const. 15442 if ((Kind == OMPC_init || Kind == OMPC_destroy) && 15443 isConstNotMutableType(SemaRef, InteropVarExpr->getType())) { 15444 SemaRef.Diag(VarLoc, diag::err_omp_interop_variable_expected) 15445 << /*non-const*/ 1; 15446 return false; 15447 } 15448 return true; 15449 } 15450 15451 OMPClause * 15452 Sema::ActOnOpenMPInitClause(Expr *InteropVar, ArrayRef<Expr *> PrefExprs, 15453 bool IsTarget, bool IsTargetSync, 15454 SourceLocation StartLoc, SourceLocation LParenLoc, 15455 SourceLocation VarLoc, SourceLocation EndLoc) { 15456 15457 if (!isValidInteropVariable(*this, InteropVar, VarLoc, OMPC_init)) 15458 return nullptr; 15459 15460 // Check prefer_type values. These foreign-runtime-id values are either 15461 // string literals or constant integral expressions. 15462 for (const Expr *E : PrefExprs) { 15463 if (E->isValueDependent() || E->isTypeDependent() || 15464 E->isInstantiationDependent() || E->containsUnexpandedParameterPack()) 15465 continue; 15466 if (E->isIntegerConstantExpr(Context)) 15467 continue; 15468 if (isa<StringLiteral>(E)) 15469 continue; 15470 Diag(E->getExprLoc(), diag::err_omp_interop_prefer_type); 15471 return nullptr; 15472 } 15473 15474 return OMPInitClause::Create(Context, InteropVar, PrefExprs, IsTarget, 15475 IsTargetSync, StartLoc, LParenLoc, VarLoc, 15476 EndLoc); 15477 } 15478 15479 OMPClause *Sema::ActOnOpenMPUseClause(Expr *InteropVar, SourceLocation StartLoc, 15480 SourceLocation LParenLoc, 15481 SourceLocation VarLoc, 15482 SourceLocation EndLoc) { 15483 15484 if (!isValidInteropVariable(*this, InteropVar, VarLoc, OMPC_use)) 15485 return nullptr; 15486 15487 return new (Context) 15488 OMPUseClause(InteropVar, StartLoc, LParenLoc, VarLoc, EndLoc); 15489 } 15490 15491 OMPClause *Sema::ActOnOpenMPDestroyClause(Expr *InteropVar, 15492 SourceLocation StartLoc, 15493 SourceLocation LParenLoc, 15494 SourceLocation VarLoc, 15495 SourceLocation EndLoc) { 15496 if (InteropVar && 15497 !isValidInteropVariable(*this, InteropVar, VarLoc, OMPC_destroy)) 15498 return nullptr; 15499 15500 return new (Context) 15501 OMPDestroyClause(InteropVar, StartLoc, LParenLoc, VarLoc, EndLoc); 15502 } 15503 15504 OMPClause *Sema::ActOnOpenMPNovariantsClause(Expr *Condition, 15505 SourceLocation StartLoc, 15506 SourceLocation LParenLoc, 15507 SourceLocation EndLoc) { 15508 Expr *ValExpr = Condition; 15509 Stmt *HelperValStmt = nullptr; 15510 OpenMPDirectiveKind CaptureRegion = OMPD_unknown; 15511 if (!Condition->isValueDependent() && !Condition->isTypeDependent() && 15512 !Condition->isInstantiationDependent() && 15513 !Condition->containsUnexpandedParameterPack()) { 15514 ExprResult Val = CheckBooleanCondition(StartLoc, Condition); 15515 if (Val.isInvalid()) 15516 return nullptr; 15517 15518 ValExpr = MakeFullExpr(Val.get()).get(); 15519 15520 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective(); 15521 CaptureRegion = getOpenMPCaptureRegionForClause(DKind, OMPC_novariants, 15522 LangOpts.OpenMP); 15523 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) { 15524 ValExpr = MakeFullExpr(ValExpr).get(); 15525 llvm::MapVector<const Expr *, DeclRefExpr *> Captures; 15526 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 15527 HelperValStmt = buildPreInits(Context, Captures); 15528 } 15529 } 15530 15531 return new (Context) OMPNovariantsClause( 15532 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc); 15533 } 15534 15535 OMPClause *Sema::ActOnOpenMPNocontextClause(Expr *Condition, 15536 SourceLocation StartLoc, 15537 SourceLocation LParenLoc, 15538 SourceLocation EndLoc) { 15539 Expr *ValExpr = Condition; 15540 Stmt *HelperValStmt = nullptr; 15541 OpenMPDirectiveKind CaptureRegion = OMPD_unknown; 15542 if (!Condition->isValueDependent() && !Condition->isTypeDependent() && 15543 !Condition->isInstantiationDependent() && 15544 !Condition->containsUnexpandedParameterPack()) { 15545 ExprResult Val = CheckBooleanCondition(StartLoc, Condition); 15546 if (Val.isInvalid()) 15547 return nullptr; 15548 15549 ValExpr = MakeFullExpr(Val.get()).get(); 15550 15551 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective(); 15552 CaptureRegion = 15553 getOpenMPCaptureRegionForClause(DKind, OMPC_nocontext, LangOpts.OpenMP); 15554 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) { 15555 ValExpr = MakeFullExpr(ValExpr).get(); 15556 llvm::MapVector<const Expr *, DeclRefExpr *> Captures; 15557 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 15558 HelperValStmt = buildPreInits(Context, Captures); 15559 } 15560 } 15561 15562 return new (Context) OMPNocontextClause(ValExpr, HelperValStmt, CaptureRegion, 15563 StartLoc, LParenLoc, EndLoc); 15564 } 15565 15566 OMPClause *Sema::ActOnOpenMPFilterClause(Expr *ThreadID, 15567 SourceLocation StartLoc, 15568 SourceLocation LParenLoc, 15569 SourceLocation EndLoc) { 15570 Expr *ValExpr = ThreadID; 15571 Stmt *HelperValStmt = nullptr; 15572 15573 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective(); 15574 OpenMPDirectiveKind CaptureRegion = 15575 getOpenMPCaptureRegionForClause(DKind, OMPC_filter, LangOpts.OpenMP); 15576 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) { 15577 ValExpr = MakeFullExpr(ValExpr).get(); 15578 llvm::MapVector<const Expr *, DeclRefExpr *> Captures; 15579 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 15580 HelperValStmt = buildPreInits(Context, Captures); 15581 } 15582 15583 return new (Context) OMPFilterClause(ValExpr, HelperValStmt, CaptureRegion, 15584 StartLoc, LParenLoc, EndLoc); 15585 } 15586 15587 OMPClause *Sema::ActOnOpenMPVarListClause( 15588 OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *DepModOrTailExpr, 15589 const OMPVarListLocTy &Locs, SourceLocation ColonLoc, 15590 CXXScopeSpec &ReductionOrMapperIdScopeSpec, 15591 DeclarationNameInfo &ReductionOrMapperId, int ExtraModifier, 15592 ArrayRef<OpenMPMapModifierKind> MapTypeModifiers, 15593 ArrayRef<SourceLocation> MapTypeModifiersLoc, bool IsMapTypeImplicit, 15594 SourceLocation ExtraModifierLoc, 15595 ArrayRef<OpenMPMotionModifierKind> MotionModifiers, 15596 ArrayRef<SourceLocation> MotionModifiersLoc) { 15597 SourceLocation StartLoc = Locs.StartLoc; 15598 SourceLocation LParenLoc = Locs.LParenLoc; 15599 SourceLocation EndLoc = Locs.EndLoc; 15600 OMPClause *Res = nullptr; 15601 switch (Kind) { 15602 case OMPC_private: 15603 Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc); 15604 break; 15605 case OMPC_firstprivate: 15606 Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc); 15607 break; 15608 case OMPC_lastprivate: 15609 assert(0 <= ExtraModifier && ExtraModifier <= OMPC_LASTPRIVATE_unknown && 15610 "Unexpected lastprivate modifier."); 15611 Res = ActOnOpenMPLastprivateClause( 15612 VarList, static_cast<OpenMPLastprivateModifier>(ExtraModifier), 15613 ExtraModifierLoc, ColonLoc, StartLoc, LParenLoc, EndLoc); 15614 break; 15615 case OMPC_shared: 15616 Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc); 15617 break; 15618 case OMPC_reduction: 15619 assert(0 <= ExtraModifier && ExtraModifier <= OMPC_REDUCTION_unknown && 15620 "Unexpected lastprivate modifier."); 15621 Res = ActOnOpenMPReductionClause( 15622 VarList, static_cast<OpenMPReductionClauseModifier>(ExtraModifier), 15623 StartLoc, LParenLoc, ExtraModifierLoc, ColonLoc, EndLoc, 15624 ReductionOrMapperIdScopeSpec, ReductionOrMapperId); 15625 break; 15626 case OMPC_task_reduction: 15627 Res = ActOnOpenMPTaskReductionClause(VarList, StartLoc, LParenLoc, ColonLoc, 15628 EndLoc, ReductionOrMapperIdScopeSpec, 15629 ReductionOrMapperId); 15630 break; 15631 case OMPC_in_reduction: 15632 Res = ActOnOpenMPInReductionClause(VarList, StartLoc, LParenLoc, ColonLoc, 15633 EndLoc, ReductionOrMapperIdScopeSpec, 15634 ReductionOrMapperId); 15635 break; 15636 case OMPC_linear: 15637 assert(0 <= ExtraModifier && ExtraModifier <= OMPC_LINEAR_unknown && 15638 "Unexpected linear modifier."); 15639 Res = ActOnOpenMPLinearClause( 15640 VarList, DepModOrTailExpr, StartLoc, LParenLoc, 15641 static_cast<OpenMPLinearClauseKind>(ExtraModifier), ExtraModifierLoc, 15642 ColonLoc, EndLoc); 15643 break; 15644 case OMPC_aligned: 15645 Res = ActOnOpenMPAlignedClause(VarList, DepModOrTailExpr, StartLoc, 15646 LParenLoc, ColonLoc, EndLoc); 15647 break; 15648 case OMPC_copyin: 15649 Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc); 15650 break; 15651 case OMPC_copyprivate: 15652 Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc); 15653 break; 15654 case OMPC_flush: 15655 Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc); 15656 break; 15657 case OMPC_depend: 15658 assert(0 <= ExtraModifier && ExtraModifier <= OMPC_DEPEND_unknown && 15659 "Unexpected depend modifier."); 15660 Res = ActOnOpenMPDependClause( 15661 DepModOrTailExpr, static_cast<OpenMPDependClauseKind>(ExtraModifier), 15662 ExtraModifierLoc, ColonLoc, VarList, StartLoc, LParenLoc, EndLoc); 15663 break; 15664 case OMPC_map: 15665 assert(0 <= ExtraModifier && ExtraModifier <= OMPC_MAP_unknown && 15666 "Unexpected map modifier."); 15667 Res = ActOnOpenMPMapClause( 15668 MapTypeModifiers, MapTypeModifiersLoc, ReductionOrMapperIdScopeSpec, 15669 ReductionOrMapperId, static_cast<OpenMPMapClauseKind>(ExtraModifier), 15670 IsMapTypeImplicit, ExtraModifierLoc, ColonLoc, VarList, Locs); 15671 break; 15672 case OMPC_to: 15673 Res = ActOnOpenMPToClause(MotionModifiers, MotionModifiersLoc, 15674 ReductionOrMapperIdScopeSpec, ReductionOrMapperId, 15675 ColonLoc, VarList, Locs); 15676 break; 15677 case OMPC_from: 15678 Res = ActOnOpenMPFromClause(MotionModifiers, MotionModifiersLoc, 15679 ReductionOrMapperIdScopeSpec, 15680 ReductionOrMapperId, ColonLoc, VarList, Locs); 15681 break; 15682 case OMPC_use_device_ptr: 15683 Res = ActOnOpenMPUseDevicePtrClause(VarList, Locs); 15684 break; 15685 case OMPC_use_device_addr: 15686 Res = ActOnOpenMPUseDeviceAddrClause(VarList, Locs); 15687 break; 15688 case OMPC_is_device_ptr: 15689 Res = ActOnOpenMPIsDevicePtrClause(VarList, Locs); 15690 break; 15691 case OMPC_allocate: 15692 Res = ActOnOpenMPAllocateClause(DepModOrTailExpr, VarList, StartLoc, 15693 LParenLoc, ColonLoc, EndLoc); 15694 break; 15695 case OMPC_nontemporal: 15696 Res = ActOnOpenMPNontemporalClause(VarList, StartLoc, LParenLoc, EndLoc); 15697 break; 15698 case OMPC_inclusive: 15699 Res = ActOnOpenMPInclusiveClause(VarList, StartLoc, LParenLoc, EndLoc); 15700 break; 15701 case OMPC_exclusive: 15702 Res = ActOnOpenMPExclusiveClause(VarList, StartLoc, LParenLoc, EndLoc); 15703 break; 15704 case OMPC_affinity: 15705 Res = ActOnOpenMPAffinityClause(StartLoc, LParenLoc, ColonLoc, EndLoc, 15706 DepModOrTailExpr, VarList); 15707 break; 15708 case OMPC_if: 15709 case OMPC_depobj: 15710 case OMPC_final: 15711 case OMPC_num_threads: 15712 case OMPC_safelen: 15713 case OMPC_simdlen: 15714 case OMPC_sizes: 15715 case OMPC_allocator: 15716 case OMPC_collapse: 15717 case OMPC_default: 15718 case OMPC_proc_bind: 15719 case OMPC_schedule: 15720 case OMPC_ordered: 15721 case OMPC_nowait: 15722 case OMPC_untied: 15723 case OMPC_mergeable: 15724 case OMPC_threadprivate: 15725 case OMPC_read: 15726 case OMPC_write: 15727 case OMPC_update: 15728 case OMPC_capture: 15729 case OMPC_seq_cst: 15730 case OMPC_acq_rel: 15731 case OMPC_acquire: 15732 case OMPC_release: 15733 case OMPC_relaxed: 15734 case OMPC_device: 15735 case OMPC_threads: 15736 case OMPC_simd: 15737 case OMPC_num_teams: 15738 case OMPC_thread_limit: 15739 case OMPC_priority: 15740 case OMPC_grainsize: 15741 case OMPC_nogroup: 15742 case OMPC_num_tasks: 15743 case OMPC_hint: 15744 case OMPC_dist_schedule: 15745 case OMPC_defaultmap: 15746 case OMPC_unknown: 15747 case OMPC_uniform: 15748 case OMPC_unified_address: 15749 case OMPC_unified_shared_memory: 15750 case OMPC_reverse_offload: 15751 case OMPC_dynamic_allocators: 15752 case OMPC_atomic_default_mem_order: 15753 case OMPC_device_type: 15754 case OMPC_match: 15755 case OMPC_order: 15756 case OMPC_destroy: 15757 case OMPC_novariants: 15758 case OMPC_nocontext: 15759 case OMPC_detach: 15760 case OMPC_uses_allocators: 15761 case OMPC_when: 15762 default: 15763 llvm_unreachable("Clause is not allowed."); 15764 } 15765 return Res; 15766 } 15767 15768 ExprResult Sema::getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK, 15769 ExprObjectKind OK, SourceLocation Loc) { 15770 ExprResult Res = BuildDeclRefExpr( 15771 Capture, Capture->getType().getNonReferenceType(), VK_LValue, Loc); 15772 if (!Res.isUsable()) 15773 return ExprError(); 15774 if (OK == OK_Ordinary && !getLangOpts().CPlusPlus) { 15775 Res = CreateBuiltinUnaryOp(Loc, UO_Deref, Res.get()); 15776 if (!Res.isUsable()) 15777 return ExprError(); 15778 } 15779 if (VK != VK_LValue && Res.get()->isGLValue()) { 15780 Res = DefaultLvalueConversion(Res.get()); 15781 if (!Res.isUsable()) 15782 return ExprError(); 15783 } 15784 return Res; 15785 } 15786 15787 OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList, 15788 SourceLocation StartLoc, 15789 SourceLocation LParenLoc, 15790 SourceLocation EndLoc) { 15791 SmallVector<Expr *, 8> Vars; 15792 SmallVector<Expr *, 8> PrivateCopies; 15793 for (Expr *RefExpr : VarList) { 15794 assert(RefExpr && "NULL expr in OpenMP private clause."); 15795 SourceLocation ELoc; 15796 SourceRange ERange; 15797 Expr *SimpleRefExpr = RefExpr; 15798 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 15799 if (Res.second) { 15800 // It will be analyzed later. 15801 Vars.push_back(RefExpr); 15802 PrivateCopies.push_back(nullptr); 15803 } 15804 ValueDecl *D = Res.first; 15805 if (!D) 15806 continue; 15807 15808 QualType Type = D->getType(); 15809 auto *VD = dyn_cast<VarDecl>(D); 15810 15811 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3] 15812 // A variable that appears in a private clause must not have an incomplete 15813 // type or a reference type. 15814 if (RequireCompleteType(ELoc, Type, diag::err_omp_private_incomplete_type)) 15815 continue; 15816 Type = Type.getNonReferenceType(); 15817 15818 // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions] 15819 // A variable that is privatized must not have a const-qualified type 15820 // unless it is of class type with a mutable member. This restriction does 15821 // not apply to the firstprivate clause. 15822 // 15823 // OpenMP 3.1 [2.9.3.3, private clause, Restrictions] 15824 // A variable that appears in a private clause must not have a 15825 // const-qualified type unless it is of class type with a mutable member. 15826 if (rejectConstNotMutableType(*this, D, Type, OMPC_private, ELoc)) 15827 continue; 15828 15829 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 15830 // in a Construct] 15831 // Variables with the predetermined data-sharing attributes may not be 15832 // listed in data-sharing attributes clauses, except for the cases 15833 // listed below. For these exceptions only, listing a predetermined 15834 // variable in a data-sharing attribute clause is allowed and overrides 15835 // the variable's predetermined data-sharing attributes. 15836 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false); 15837 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) { 15838 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind) 15839 << getOpenMPClauseName(OMPC_private); 15840 reportOriginalDsa(*this, DSAStack, D, DVar); 15841 continue; 15842 } 15843 15844 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective(); 15845 // Variably modified types are not supported for tasks. 15846 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() && 15847 isOpenMPTaskingDirective(CurrDir)) { 15848 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported) 15849 << getOpenMPClauseName(OMPC_private) << Type 15850 << getOpenMPDirectiveName(CurrDir); 15851 bool IsDecl = 15852 !VD || 15853 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 15854 Diag(D->getLocation(), 15855 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 15856 << D; 15857 continue; 15858 } 15859 15860 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3] 15861 // A list item cannot appear in both a map clause and a data-sharing 15862 // attribute clause on the same construct 15863 // 15864 // OpenMP 5.0 [2.19.7.1, Restrictions, p.7] 15865 // A list item cannot appear in both a map clause and a data-sharing 15866 // attribute clause on the same construct unless the construct is a 15867 // combined construct. 15868 if ((LangOpts.OpenMP <= 45 && isOpenMPTargetExecutionDirective(CurrDir)) || 15869 CurrDir == OMPD_target) { 15870 OpenMPClauseKind ConflictKind; 15871 if (DSAStack->checkMappableExprComponentListsForDecl( 15872 VD, /*CurrentRegionOnly=*/true, 15873 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef, 15874 OpenMPClauseKind WhereFoundClauseKind) -> bool { 15875 ConflictKind = WhereFoundClauseKind; 15876 return true; 15877 })) { 15878 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa) 15879 << getOpenMPClauseName(OMPC_private) 15880 << getOpenMPClauseName(ConflictKind) 15881 << getOpenMPDirectiveName(CurrDir); 15882 reportOriginalDsa(*this, DSAStack, D, DVar); 15883 continue; 15884 } 15885 } 15886 15887 // OpenMP [2.9.3.3, Restrictions, C/C++, p.1] 15888 // A variable of class type (or array thereof) that appears in a private 15889 // clause requires an accessible, unambiguous default constructor for the 15890 // class type. 15891 // Generate helper private variable and initialize it with the default 15892 // value. The address of the original variable is replaced by the address of 15893 // the new private variable in CodeGen. This new variable is not added to 15894 // IdResolver, so the code in the OpenMP region uses original variable for 15895 // proper diagnostics. 15896 Type = Type.getUnqualifiedType(); 15897 VarDecl *VDPrivate = 15898 buildVarDecl(*this, ELoc, Type, D->getName(), 15899 D->hasAttrs() ? &D->getAttrs() : nullptr, 15900 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr); 15901 ActOnUninitializedDecl(VDPrivate); 15902 if (VDPrivate->isInvalidDecl()) 15903 continue; 15904 DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr( 15905 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc); 15906 15907 DeclRefExpr *Ref = nullptr; 15908 if (!VD && !CurContext->isDependentContext()) 15909 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false); 15910 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_private, Ref); 15911 Vars.push_back((VD || CurContext->isDependentContext()) 15912 ? RefExpr->IgnoreParens() 15913 : Ref); 15914 PrivateCopies.push_back(VDPrivateRefExpr); 15915 } 15916 15917 if (Vars.empty()) 15918 return nullptr; 15919 15920 return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars, 15921 PrivateCopies); 15922 } 15923 15924 OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList, 15925 SourceLocation StartLoc, 15926 SourceLocation LParenLoc, 15927 SourceLocation EndLoc) { 15928 SmallVector<Expr *, 8> Vars; 15929 SmallVector<Expr *, 8> PrivateCopies; 15930 SmallVector<Expr *, 8> Inits; 15931 SmallVector<Decl *, 4> ExprCaptures; 15932 bool IsImplicitClause = 15933 StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid(); 15934 SourceLocation ImplicitClauseLoc = DSAStack->getConstructLoc(); 15935 15936 for (Expr *RefExpr : VarList) { 15937 assert(RefExpr && "NULL expr in OpenMP firstprivate clause."); 15938 SourceLocation ELoc; 15939 SourceRange ERange; 15940 Expr *SimpleRefExpr = RefExpr; 15941 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 15942 if (Res.second) { 15943 // It will be analyzed later. 15944 Vars.push_back(RefExpr); 15945 PrivateCopies.push_back(nullptr); 15946 Inits.push_back(nullptr); 15947 } 15948 ValueDecl *D = Res.first; 15949 if (!D) 15950 continue; 15951 15952 ELoc = IsImplicitClause ? ImplicitClauseLoc : ELoc; 15953 QualType Type = D->getType(); 15954 auto *VD = dyn_cast<VarDecl>(D); 15955 15956 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3] 15957 // A variable that appears in a private clause must not have an incomplete 15958 // type or a reference type. 15959 if (RequireCompleteType(ELoc, Type, 15960 diag::err_omp_firstprivate_incomplete_type)) 15961 continue; 15962 Type = Type.getNonReferenceType(); 15963 15964 // OpenMP [2.9.3.4, Restrictions, C/C++, p.1] 15965 // A variable of class type (or array thereof) that appears in a private 15966 // clause requires an accessible, unambiguous copy constructor for the 15967 // class type. 15968 QualType ElemType = Context.getBaseElementType(Type).getNonReferenceType(); 15969 15970 // If an implicit firstprivate variable found it was checked already. 15971 DSAStackTy::DSAVarData TopDVar; 15972 if (!IsImplicitClause) { 15973 DSAStackTy::DSAVarData DVar = 15974 DSAStack->getTopDSA(D, /*FromParent=*/false); 15975 TopDVar = DVar; 15976 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective(); 15977 bool IsConstant = ElemType.isConstant(Context); 15978 // OpenMP [2.4.13, Data-sharing Attribute Clauses] 15979 // A list item that specifies a given variable may not appear in more 15980 // than one clause on the same directive, except that a variable may be 15981 // specified in both firstprivate and lastprivate clauses. 15982 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3] 15983 // A list item may appear in a firstprivate or lastprivate clause but not 15984 // both. 15985 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate && 15986 (isOpenMPDistributeDirective(CurrDir) || 15987 DVar.CKind != OMPC_lastprivate) && 15988 DVar.RefExpr) { 15989 Diag(ELoc, diag::err_omp_wrong_dsa) 15990 << getOpenMPClauseName(DVar.CKind) 15991 << getOpenMPClauseName(OMPC_firstprivate); 15992 reportOriginalDsa(*this, DSAStack, D, DVar); 15993 continue; 15994 } 15995 15996 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 15997 // in a Construct] 15998 // Variables with the predetermined data-sharing attributes may not be 15999 // listed in data-sharing attributes clauses, except for the cases 16000 // listed below. For these exceptions only, listing a predetermined 16001 // variable in a data-sharing attribute clause is allowed and overrides 16002 // the variable's predetermined data-sharing attributes. 16003 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 16004 // in a Construct, C/C++, p.2] 16005 // Variables with const-qualified type having no mutable member may be 16006 // listed in a firstprivate clause, even if they are static data members. 16007 if (!(IsConstant || (VD && VD->isStaticDataMember())) && !DVar.RefExpr && 16008 DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) { 16009 Diag(ELoc, diag::err_omp_wrong_dsa) 16010 << getOpenMPClauseName(DVar.CKind) 16011 << getOpenMPClauseName(OMPC_firstprivate); 16012 reportOriginalDsa(*this, DSAStack, D, DVar); 16013 continue; 16014 } 16015 16016 // OpenMP [2.9.3.4, Restrictions, p.2] 16017 // A list item that is private within a parallel region must not appear 16018 // in a firstprivate clause on a worksharing construct if any of the 16019 // worksharing regions arising from the worksharing construct ever bind 16020 // to any of the parallel regions arising from the parallel construct. 16021 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3] 16022 // A list item that is private within a teams region must not appear in a 16023 // firstprivate clause on a distribute construct if any of the distribute 16024 // regions arising from the distribute construct ever bind to any of the 16025 // teams regions arising from the teams construct. 16026 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3] 16027 // A list item that appears in a reduction clause of a teams construct 16028 // must not appear in a firstprivate clause on a distribute construct if 16029 // any of the distribute regions arising from the distribute construct 16030 // ever bind to any of the teams regions arising from the teams construct. 16031 if ((isOpenMPWorksharingDirective(CurrDir) || 16032 isOpenMPDistributeDirective(CurrDir)) && 16033 !isOpenMPParallelDirective(CurrDir) && 16034 !isOpenMPTeamsDirective(CurrDir)) { 16035 DVar = DSAStack->getImplicitDSA(D, true); 16036 if (DVar.CKind != OMPC_shared && 16037 (isOpenMPParallelDirective(DVar.DKind) || 16038 isOpenMPTeamsDirective(DVar.DKind) || 16039 DVar.DKind == OMPD_unknown)) { 16040 Diag(ELoc, diag::err_omp_required_access) 16041 << getOpenMPClauseName(OMPC_firstprivate) 16042 << getOpenMPClauseName(OMPC_shared); 16043 reportOriginalDsa(*this, DSAStack, D, DVar); 16044 continue; 16045 } 16046 } 16047 // OpenMP [2.9.3.4, Restrictions, p.3] 16048 // A list item that appears in a reduction clause of a parallel construct 16049 // must not appear in a firstprivate clause on a worksharing or task 16050 // construct if any of the worksharing or task regions arising from the 16051 // worksharing or task construct ever bind to any of the parallel regions 16052 // arising from the parallel construct. 16053 // OpenMP [2.9.3.4, Restrictions, p.4] 16054 // A list item that appears in a reduction clause in worksharing 16055 // construct must not appear in a firstprivate clause in a task construct 16056 // encountered during execution of any of the worksharing regions arising 16057 // from the worksharing construct. 16058 if (isOpenMPTaskingDirective(CurrDir)) { 16059 DVar = DSAStack->hasInnermostDSA( 16060 D, 16061 [](OpenMPClauseKind C, bool AppliedToPointee) { 16062 return C == OMPC_reduction && !AppliedToPointee; 16063 }, 16064 [](OpenMPDirectiveKind K) { 16065 return isOpenMPParallelDirective(K) || 16066 isOpenMPWorksharingDirective(K) || 16067 isOpenMPTeamsDirective(K); 16068 }, 16069 /*FromParent=*/true); 16070 if (DVar.CKind == OMPC_reduction && 16071 (isOpenMPParallelDirective(DVar.DKind) || 16072 isOpenMPWorksharingDirective(DVar.DKind) || 16073 isOpenMPTeamsDirective(DVar.DKind))) { 16074 Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate) 16075 << getOpenMPDirectiveName(DVar.DKind); 16076 reportOriginalDsa(*this, DSAStack, D, DVar); 16077 continue; 16078 } 16079 } 16080 16081 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3] 16082 // A list item cannot appear in both a map clause and a data-sharing 16083 // attribute clause on the same construct 16084 // 16085 // OpenMP 5.0 [2.19.7.1, Restrictions, p.7] 16086 // A list item cannot appear in both a map clause and a data-sharing 16087 // attribute clause on the same construct unless the construct is a 16088 // combined construct. 16089 if ((LangOpts.OpenMP <= 45 && 16090 isOpenMPTargetExecutionDirective(CurrDir)) || 16091 CurrDir == OMPD_target) { 16092 OpenMPClauseKind ConflictKind; 16093 if (DSAStack->checkMappableExprComponentListsForDecl( 16094 VD, /*CurrentRegionOnly=*/true, 16095 [&ConflictKind]( 16096 OMPClauseMappableExprCommon::MappableExprComponentListRef, 16097 OpenMPClauseKind WhereFoundClauseKind) { 16098 ConflictKind = WhereFoundClauseKind; 16099 return true; 16100 })) { 16101 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa) 16102 << getOpenMPClauseName(OMPC_firstprivate) 16103 << getOpenMPClauseName(ConflictKind) 16104 << getOpenMPDirectiveName(DSAStack->getCurrentDirective()); 16105 reportOriginalDsa(*this, DSAStack, D, DVar); 16106 continue; 16107 } 16108 } 16109 } 16110 16111 // Variably modified types are not supported for tasks. 16112 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() && 16113 isOpenMPTaskingDirective(DSAStack->getCurrentDirective())) { 16114 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported) 16115 << getOpenMPClauseName(OMPC_firstprivate) << Type 16116 << getOpenMPDirectiveName(DSAStack->getCurrentDirective()); 16117 bool IsDecl = 16118 !VD || 16119 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 16120 Diag(D->getLocation(), 16121 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 16122 << D; 16123 continue; 16124 } 16125 16126 Type = Type.getUnqualifiedType(); 16127 VarDecl *VDPrivate = 16128 buildVarDecl(*this, ELoc, Type, D->getName(), 16129 D->hasAttrs() ? &D->getAttrs() : nullptr, 16130 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr); 16131 // Generate helper private variable and initialize it with the value of the 16132 // original variable. The address of the original variable is replaced by 16133 // the address of the new private variable in the CodeGen. This new variable 16134 // is not added to IdResolver, so the code in the OpenMP region uses 16135 // original variable for proper diagnostics and variable capturing. 16136 Expr *VDInitRefExpr = nullptr; 16137 // For arrays generate initializer for single element and replace it by the 16138 // original array element in CodeGen. 16139 if (Type->isArrayType()) { 16140 VarDecl *VDInit = 16141 buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, D->getName()); 16142 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc); 16143 Expr *Init = DefaultLvalueConversion(VDInitRefExpr).get(); 16144 ElemType = ElemType.getUnqualifiedType(); 16145 VarDecl *VDInitTemp = buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, 16146 ".firstprivate.temp"); 16147 InitializedEntity Entity = 16148 InitializedEntity::InitializeVariable(VDInitTemp); 16149 InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc); 16150 16151 InitializationSequence InitSeq(*this, Entity, Kind, Init); 16152 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init); 16153 if (Result.isInvalid()) 16154 VDPrivate->setInvalidDecl(); 16155 else 16156 VDPrivate->setInit(Result.getAs<Expr>()); 16157 // Remove temp variable declaration. 16158 Context.Deallocate(VDInitTemp); 16159 } else { 16160 VarDecl *VDInit = buildVarDecl(*this, RefExpr->getExprLoc(), Type, 16161 ".firstprivate.temp"); 16162 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(), 16163 RefExpr->getExprLoc()); 16164 AddInitializerToDecl(VDPrivate, 16165 DefaultLvalueConversion(VDInitRefExpr).get(), 16166 /*DirectInit=*/false); 16167 } 16168 if (VDPrivate->isInvalidDecl()) { 16169 if (IsImplicitClause) { 16170 Diag(RefExpr->getExprLoc(), 16171 diag::note_omp_task_predetermined_firstprivate_here); 16172 } 16173 continue; 16174 } 16175 CurContext->addDecl(VDPrivate); 16176 DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr( 16177 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), 16178 RefExpr->getExprLoc()); 16179 DeclRefExpr *Ref = nullptr; 16180 if (!VD && !CurContext->isDependentContext()) { 16181 if (TopDVar.CKind == OMPC_lastprivate) { 16182 Ref = TopDVar.PrivateCopy; 16183 } else { 16184 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true); 16185 if (!isOpenMPCapturedDecl(D)) 16186 ExprCaptures.push_back(Ref->getDecl()); 16187 } 16188 } 16189 if (!IsImplicitClause) 16190 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref); 16191 Vars.push_back((VD || CurContext->isDependentContext()) 16192 ? RefExpr->IgnoreParens() 16193 : Ref); 16194 PrivateCopies.push_back(VDPrivateRefExpr); 16195 Inits.push_back(VDInitRefExpr); 16196 } 16197 16198 if (Vars.empty()) 16199 return nullptr; 16200 16201 return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, 16202 Vars, PrivateCopies, Inits, 16203 buildPreInits(Context, ExprCaptures)); 16204 } 16205 16206 OMPClause *Sema::ActOnOpenMPLastprivateClause( 16207 ArrayRef<Expr *> VarList, OpenMPLastprivateModifier LPKind, 16208 SourceLocation LPKindLoc, SourceLocation ColonLoc, SourceLocation StartLoc, 16209 SourceLocation LParenLoc, SourceLocation EndLoc) { 16210 if (LPKind == OMPC_LASTPRIVATE_unknown && LPKindLoc.isValid()) { 16211 assert(ColonLoc.isValid() && "Colon location must be valid."); 16212 Diag(LPKindLoc, diag::err_omp_unexpected_clause_value) 16213 << getListOfPossibleValues(OMPC_lastprivate, /*First=*/0, 16214 /*Last=*/OMPC_LASTPRIVATE_unknown) 16215 << getOpenMPClauseName(OMPC_lastprivate); 16216 return nullptr; 16217 } 16218 16219 SmallVector<Expr *, 8> Vars; 16220 SmallVector<Expr *, 8> SrcExprs; 16221 SmallVector<Expr *, 8> DstExprs; 16222 SmallVector<Expr *, 8> AssignmentOps; 16223 SmallVector<Decl *, 4> ExprCaptures; 16224 SmallVector<Expr *, 4> ExprPostUpdates; 16225 for (Expr *RefExpr : VarList) { 16226 assert(RefExpr && "NULL expr in OpenMP lastprivate clause."); 16227 SourceLocation ELoc; 16228 SourceRange ERange; 16229 Expr *SimpleRefExpr = RefExpr; 16230 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 16231 if (Res.second) { 16232 // It will be analyzed later. 16233 Vars.push_back(RefExpr); 16234 SrcExprs.push_back(nullptr); 16235 DstExprs.push_back(nullptr); 16236 AssignmentOps.push_back(nullptr); 16237 } 16238 ValueDecl *D = Res.first; 16239 if (!D) 16240 continue; 16241 16242 QualType Type = D->getType(); 16243 auto *VD = dyn_cast<VarDecl>(D); 16244 16245 // OpenMP [2.14.3.5, Restrictions, C/C++, p.2] 16246 // A variable that appears in a lastprivate clause must not have an 16247 // incomplete type or a reference type. 16248 if (RequireCompleteType(ELoc, Type, 16249 diag::err_omp_lastprivate_incomplete_type)) 16250 continue; 16251 Type = Type.getNonReferenceType(); 16252 16253 // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions] 16254 // A variable that is privatized must not have a const-qualified type 16255 // unless it is of class type with a mutable member. This restriction does 16256 // not apply to the firstprivate clause. 16257 // 16258 // OpenMP 3.1 [2.9.3.5, lastprivate clause, Restrictions] 16259 // A variable that appears in a lastprivate clause must not have a 16260 // const-qualified type unless it is of class type with a mutable member. 16261 if (rejectConstNotMutableType(*this, D, Type, OMPC_lastprivate, ELoc)) 16262 continue; 16263 16264 // OpenMP 5.0 [2.19.4.5 lastprivate Clause, Restrictions] 16265 // A list item that appears in a lastprivate clause with the conditional 16266 // modifier must be a scalar variable. 16267 if (LPKind == OMPC_LASTPRIVATE_conditional && !Type->isScalarType()) { 16268 Diag(ELoc, diag::err_omp_lastprivate_conditional_non_scalar); 16269 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) == 16270 VarDecl::DeclarationOnly; 16271 Diag(D->getLocation(), 16272 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 16273 << D; 16274 continue; 16275 } 16276 16277 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective(); 16278 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced 16279 // in a Construct] 16280 // Variables with the predetermined data-sharing attributes may not be 16281 // listed in data-sharing attributes clauses, except for the cases 16282 // listed below. 16283 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3] 16284 // A list item may appear in a firstprivate or lastprivate clause but not 16285 // both. 16286 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false); 16287 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate && 16288 (isOpenMPDistributeDirective(CurrDir) || 16289 DVar.CKind != OMPC_firstprivate) && 16290 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) { 16291 Diag(ELoc, diag::err_omp_wrong_dsa) 16292 << getOpenMPClauseName(DVar.CKind) 16293 << getOpenMPClauseName(OMPC_lastprivate); 16294 reportOriginalDsa(*this, DSAStack, D, DVar); 16295 continue; 16296 } 16297 16298 // OpenMP [2.14.3.5, Restrictions, p.2] 16299 // A list item that is private within a parallel region, or that appears in 16300 // the reduction clause of a parallel construct, must not appear in a 16301 // lastprivate clause on a worksharing construct if any of the corresponding 16302 // worksharing regions ever binds to any of the corresponding parallel 16303 // regions. 16304 DSAStackTy::DSAVarData TopDVar = DVar; 16305 if (isOpenMPWorksharingDirective(CurrDir) && 16306 !isOpenMPParallelDirective(CurrDir) && 16307 !isOpenMPTeamsDirective(CurrDir)) { 16308 DVar = DSAStack->getImplicitDSA(D, true); 16309 if (DVar.CKind != OMPC_shared) { 16310 Diag(ELoc, diag::err_omp_required_access) 16311 << getOpenMPClauseName(OMPC_lastprivate) 16312 << getOpenMPClauseName(OMPC_shared); 16313 reportOriginalDsa(*this, DSAStack, D, DVar); 16314 continue; 16315 } 16316 } 16317 16318 // OpenMP [2.14.3.5, Restrictions, C++, p.1,2] 16319 // A variable of class type (or array thereof) that appears in a 16320 // lastprivate clause requires an accessible, unambiguous default 16321 // constructor for the class type, unless the list item is also specified 16322 // in a firstprivate clause. 16323 // A variable of class type (or array thereof) that appears in a 16324 // lastprivate clause requires an accessible, unambiguous copy assignment 16325 // operator for the class type. 16326 Type = Context.getBaseElementType(Type).getNonReferenceType(); 16327 VarDecl *SrcVD = buildVarDecl(*this, ERange.getBegin(), 16328 Type.getUnqualifiedType(), ".lastprivate.src", 16329 D->hasAttrs() ? &D->getAttrs() : nullptr); 16330 DeclRefExpr *PseudoSrcExpr = 16331 buildDeclRefExpr(*this, SrcVD, Type.getUnqualifiedType(), ELoc); 16332 VarDecl *DstVD = 16333 buildVarDecl(*this, ERange.getBegin(), Type, ".lastprivate.dst", 16334 D->hasAttrs() ? &D->getAttrs() : nullptr); 16335 DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc); 16336 // For arrays generate assignment operation for single element and replace 16337 // it by the original array element in CodeGen. 16338 ExprResult AssignmentOp = BuildBinOp(/*S=*/nullptr, ELoc, BO_Assign, 16339 PseudoDstExpr, PseudoSrcExpr); 16340 if (AssignmentOp.isInvalid()) 16341 continue; 16342 AssignmentOp = 16343 ActOnFinishFullExpr(AssignmentOp.get(), ELoc, /*DiscardedValue*/ false); 16344 if (AssignmentOp.isInvalid()) 16345 continue; 16346 16347 DeclRefExpr *Ref = nullptr; 16348 if (!VD && !CurContext->isDependentContext()) { 16349 if (TopDVar.CKind == OMPC_firstprivate) { 16350 Ref = TopDVar.PrivateCopy; 16351 } else { 16352 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false); 16353 if (!isOpenMPCapturedDecl(D)) 16354 ExprCaptures.push_back(Ref->getDecl()); 16355 } 16356 if ((TopDVar.CKind == OMPC_firstprivate && !TopDVar.PrivateCopy) || 16357 (!isOpenMPCapturedDecl(D) && 16358 Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>())) { 16359 ExprResult RefRes = DefaultLvalueConversion(Ref); 16360 if (!RefRes.isUsable()) 16361 continue; 16362 ExprResult PostUpdateRes = 16363 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr, 16364 RefRes.get()); 16365 if (!PostUpdateRes.isUsable()) 16366 continue; 16367 ExprPostUpdates.push_back( 16368 IgnoredValueConversions(PostUpdateRes.get()).get()); 16369 } 16370 } 16371 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_lastprivate, Ref); 16372 Vars.push_back((VD || CurContext->isDependentContext()) 16373 ? RefExpr->IgnoreParens() 16374 : Ref); 16375 SrcExprs.push_back(PseudoSrcExpr); 16376 DstExprs.push_back(PseudoDstExpr); 16377 AssignmentOps.push_back(AssignmentOp.get()); 16378 } 16379 16380 if (Vars.empty()) 16381 return nullptr; 16382 16383 return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, 16384 Vars, SrcExprs, DstExprs, AssignmentOps, 16385 LPKind, LPKindLoc, ColonLoc, 16386 buildPreInits(Context, ExprCaptures), 16387 buildPostUpdate(*this, ExprPostUpdates)); 16388 } 16389 16390 OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList, 16391 SourceLocation StartLoc, 16392 SourceLocation LParenLoc, 16393 SourceLocation EndLoc) { 16394 SmallVector<Expr *, 8> Vars; 16395 for (Expr *RefExpr : VarList) { 16396 assert(RefExpr && "NULL expr in OpenMP lastprivate clause."); 16397 SourceLocation ELoc; 16398 SourceRange ERange; 16399 Expr *SimpleRefExpr = RefExpr; 16400 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 16401 if (Res.second) { 16402 // It will be analyzed later. 16403 Vars.push_back(RefExpr); 16404 } 16405 ValueDecl *D = Res.first; 16406 if (!D) 16407 continue; 16408 16409 auto *VD = dyn_cast<VarDecl>(D); 16410 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 16411 // in a Construct] 16412 // Variables with the predetermined data-sharing attributes may not be 16413 // listed in data-sharing attributes clauses, except for the cases 16414 // listed below. For these exceptions only, listing a predetermined 16415 // variable in a data-sharing attribute clause is allowed and overrides 16416 // the variable's predetermined data-sharing attributes. 16417 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false); 16418 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared && 16419 DVar.RefExpr) { 16420 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind) 16421 << getOpenMPClauseName(OMPC_shared); 16422 reportOriginalDsa(*this, DSAStack, D, DVar); 16423 continue; 16424 } 16425 16426 DeclRefExpr *Ref = nullptr; 16427 if (!VD && isOpenMPCapturedDecl(D) && !CurContext->isDependentContext()) 16428 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true); 16429 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_shared, Ref); 16430 Vars.push_back((VD || !Ref || CurContext->isDependentContext()) 16431 ? RefExpr->IgnoreParens() 16432 : Ref); 16433 } 16434 16435 if (Vars.empty()) 16436 return nullptr; 16437 16438 return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars); 16439 } 16440 16441 namespace { 16442 class DSARefChecker : public StmtVisitor<DSARefChecker, bool> { 16443 DSAStackTy *Stack; 16444 16445 public: 16446 bool VisitDeclRefExpr(DeclRefExpr *E) { 16447 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) { 16448 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, /*FromParent=*/false); 16449 if (DVar.CKind == OMPC_shared && !DVar.RefExpr) 16450 return false; 16451 if (DVar.CKind != OMPC_unknown) 16452 return true; 16453 DSAStackTy::DSAVarData DVarPrivate = Stack->hasDSA( 16454 VD, 16455 [](OpenMPClauseKind C, bool AppliedToPointee) { 16456 return isOpenMPPrivate(C) && !AppliedToPointee; 16457 }, 16458 [](OpenMPDirectiveKind) { return true; }, 16459 /*FromParent=*/true); 16460 return DVarPrivate.CKind != OMPC_unknown; 16461 } 16462 return false; 16463 } 16464 bool VisitStmt(Stmt *S) { 16465 for (Stmt *Child : S->children()) { 16466 if (Child && Visit(Child)) 16467 return true; 16468 } 16469 return false; 16470 } 16471 explicit DSARefChecker(DSAStackTy *S) : Stack(S) {} 16472 }; 16473 } // namespace 16474 16475 namespace { 16476 // Transform MemberExpression for specified FieldDecl of current class to 16477 // DeclRefExpr to specified OMPCapturedExprDecl. 16478 class TransformExprToCaptures : public TreeTransform<TransformExprToCaptures> { 16479 typedef TreeTransform<TransformExprToCaptures> BaseTransform; 16480 ValueDecl *Field = nullptr; 16481 DeclRefExpr *CapturedExpr = nullptr; 16482 16483 public: 16484 TransformExprToCaptures(Sema &SemaRef, ValueDecl *FieldDecl) 16485 : BaseTransform(SemaRef), Field(FieldDecl), CapturedExpr(nullptr) {} 16486 16487 ExprResult TransformMemberExpr(MemberExpr *E) { 16488 if (isa<CXXThisExpr>(E->getBase()->IgnoreParenImpCasts()) && 16489 E->getMemberDecl() == Field) { 16490 CapturedExpr = buildCapture(SemaRef, Field, E, /*WithInit=*/false); 16491 return CapturedExpr; 16492 } 16493 return BaseTransform::TransformMemberExpr(E); 16494 } 16495 DeclRefExpr *getCapturedExpr() { return CapturedExpr; } 16496 }; 16497 } // namespace 16498 16499 template <typename T, typename U> 16500 static T filterLookupForUDReductionAndMapper( 16501 SmallVectorImpl<U> &Lookups, const llvm::function_ref<T(ValueDecl *)> Gen) { 16502 for (U &Set : Lookups) { 16503 for (auto *D : Set) { 16504 if (T Res = Gen(cast<ValueDecl>(D))) 16505 return Res; 16506 } 16507 } 16508 return T(); 16509 } 16510 16511 static NamedDecl *findAcceptableDecl(Sema &SemaRef, NamedDecl *D) { 16512 assert(!LookupResult::isVisible(SemaRef, D) && "not in slow case"); 16513 16514 for (auto RD : D->redecls()) { 16515 // Don't bother with extra checks if we already know this one isn't visible. 16516 if (RD == D) 16517 continue; 16518 16519 auto ND = cast<NamedDecl>(RD); 16520 if (LookupResult::isVisible(SemaRef, ND)) 16521 return ND; 16522 } 16523 16524 return nullptr; 16525 } 16526 16527 static void 16528 argumentDependentLookup(Sema &SemaRef, const DeclarationNameInfo &Id, 16529 SourceLocation Loc, QualType Ty, 16530 SmallVectorImpl<UnresolvedSet<8>> &Lookups) { 16531 // Find all of the associated namespaces and classes based on the 16532 // arguments we have. 16533 Sema::AssociatedNamespaceSet AssociatedNamespaces; 16534 Sema::AssociatedClassSet AssociatedClasses; 16535 OpaqueValueExpr OVE(Loc, Ty, VK_LValue); 16536 SemaRef.FindAssociatedClassesAndNamespaces(Loc, &OVE, AssociatedNamespaces, 16537 AssociatedClasses); 16538 16539 // C++ [basic.lookup.argdep]p3: 16540 // Let X be the lookup set produced by unqualified lookup (3.4.1) 16541 // and let Y be the lookup set produced by argument dependent 16542 // lookup (defined as follows). If X contains [...] then Y is 16543 // empty. Otherwise Y is the set of declarations found in the 16544 // namespaces associated with the argument types as described 16545 // below. The set of declarations found by the lookup of the name 16546 // is the union of X and Y. 16547 // 16548 // Here, we compute Y and add its members to the overloaded 16549 // candidate set. 16550 for (auto *NS : AssociatedNamespaces) { 16551 // When considering an associated namespace, the lookup is the 16552 // same as the lookup performed when the associated namespace is 16553 // used as a qualifier (3.4.3.2) except that: 16554 // 16555 // -- Any using-directives in the associated namespace are 16556 // ignored. 16557 // 16558 // -- Any namespace-scope friend functions declared in 16559 // associated classes are visible within their respective 16560 // namespaces even if they are not visible during an ordinary 16561 // lookup (11.4). 16562 DeclContext::lookup_result R = NS->lookup(Id.getName()); 16563 for (auto *D : R) { 16564 auto *Underlying = D; 16565 if (auto *USD = dyn_cast<UsingShadowDecl>(D)) 16566 Underlying = USD->getTargetDecl(); 16567 16568 if (!isa<OMPDeclareReductionDecl>(Underlying) && 16569 !isa<OMPDeclareMapperDecl>(Underlying)) 16570 continue; 16571 16572 if (!SemaRef.isVisible(D)) { 16573 D = findAcceptableDecl(SemaRef, D); 16574 if (!D) 16575 continue; 16576 if (auto *USD = dyn_cast<UsingShadowDecl>(D)) 16577 Underlying = USD->getTargetDecl(); 16578 } 16579 Lookups.emplace_back(); 16580 Lookups.back().addDecl(Underlying); 16581 } 16582 } 16583 } 16584 16585 static ExprResult 16586 buildDeclareReductionRef(Sema &SemaRef, SourceLocation Loc, SourceRange Range, 16587 Scope *S, CXXScopeSpec &ReductionIdScopeSpec, 16588 const DeclarationNameInfo &ReductionId, QualType Ty, 16589 CXXCastPath &BasePath, Expr *UnresolvedReduction) { 16590 if (ReductionIdScopeSpec.isInvalid()) 16591 return ExprError(); 16592 SmallVector<UnresolvedSet<8>, 4> Lookups; 16593 if (S) { 16594 LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName); 16595 Lookup.suppressDiagnostics(); 16596 while (S && SemaRef.LookupParsedName(Lookup, S, &ReductionIdScopeSpec)) { 16597 NamedDecl *D = Lookup.getRepresentativeDecl(); 16598 do { 16599 S = S->getParent(); 16600 } while (S && !S->isDeclScope(D)); 16601 if (S) 16602 S = S->getParent(); 16603 Lookups.emplace_back(); 16604 Lookups.back().append(Lookup.begin(), Lookup.end()); 16605 Lookup.clear(); 16606 } 16607 } else if (auto *ULE = 16608 cast_or_null<UnresolvedLookupExpr>(UnresolvedReduction)) { 16609 Lookups.push_back(UnresolvedSet<8>()); 16610 Decl *PrevD = nullptr; 16611 for (NamedDecl *D : ULE->decls()) { 16612 if (D == PrevD) 16613 Lookups.push_back(UnresolvedSet<8>()); 16614 else if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(D)) 16615 Lookups.back().addDecl(DRD); 16616 PrevD = D; 16617 } 16618 } 16619 if (SemaRef.CurContext->isDependentContext() || Ty->isDependentType() || 16620 Ty->isInstantiationDependentType() || 16621 Ty->containsUnexpandedParameterPack() || 16622 filterLookupForUDReductionAndMapper<bool>(Lookups, [](ValueDecl *D) { 16623 return !D->isInvalidDecl() && 16624 (D->getType()->isDependentType() || 16625 D->getType()->isInstantiationDependentType() || 16626 D->getType()->containsUnexpandedParameterPack()); 16627 })) { 16628 UnresolvedSet<8> ResSet; 16629 for (const UnresolvedSet<8> &Set : Lookups) { 16630 if (Set.empty()) 16631 continue; 16632 ResSet.append(Set.begin(), Set.end()); 16633 // The last item marks the end of all declarations at the specified scope. 16634 ResSet.addDecl(Set[Set.size() - 1]); 16635 } 16636 return UnresolvedLookupExpr::Create( 16637 SemaRef.Context, /*NamingClass=*/nullptr, 16638 ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), ReductionId, 16639 /*ADL=*/true, /*Overloaded=*/true, ResSet.begin(), ResSet.end()); 16640 } 16641 // Lookup inside the classes. 16642 // C++ [over.match.oper]p3: 16643 // For a unary operator @ with an operand of a type whose 16644 // cv-unqualified version is T1, and for a binary operator @ with 16645 // a left operand of a type whose cv-unqualified version is T1 and 16646 // a right operand of a type whose cv-unqualified version is T2, 16647 // three sets of candidate functions, designated member 16648 // candidates, non-member candidates and built-in candidates, are 16649 // constructed as follows: 16650 // -- If T1 is a complete class type or a class currently being 16651 // defined, the set of member candidates is the result of the 16652 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise, 16653 // the set of member candidates is empty. 16654 LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName); 16655 Lookup.suppressDiagnostics(); 16656 if (const auto *TyRec = Ty->getAs<RecordType>()) { 16657 // Complete the type if it can be completed. 16658 // If the type is neither complete nor being defined, bail out now. 16659 if (SemaRef.isCompleteType(Loc, Ty) || TyRec->isBeingDefined() || 16660 TyRec->getDecl()->getDefinition()) { 16661 Lookup.clear(); 16662 SemaRef.LookupQualifiedName(Lookup, TyRec->getDecl()); 16663 if (Lookup.empty()) { 16664 Lookups.emplace_back(); 16665 Lookups.back().append(Lookup.begin(), Lookup.end()); 16666 } 16667 } 16668 } 16669 // Perform ADL. 16670 if (SemaRef.getLangOpts().CPlusPlus) 16671 argumentDependentLookup(SemaRef, ReductionId, Loc, Ty, Lookups); 16672 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>( 16673 Lookups, [&SemaRef, Ty](ValueDecl *D) -> ValueDecl * { 16674 if (!D->isInvalidDecl() && 16675 SemaRef.Context.hasSameType(D->getType(), Ty)) 16676 return D; 16677 return nullptr; 16678 })) 16679 return SemaRef.BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(), 16680 VK_LValue, Loc); 16681 if (SemaRef.getLangOpts().CPlusPlus) { 16682 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>( 16683 Lookups, [&SemaRef, Ty, Loc](ValueDecl *D) -> ValueDecl * { 16684 if (!D->isInvalidDecl() && 16685 SemaRef.IsDerivedFrom(Loc, Ty, D->getType()) && 16686 !Ty.isMoreQualifiedThan(D->getType())) 16687 return D; 16688 return nullptr; 16689 })) { 16690 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 16691 /*DetectVirtual=*/false); 16692 if (SemaRef.IsDerivedFrom(Loc, Ty, VD->getType(), Paths)) { 16693 if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType( 16694 VD->getType().getUnqualifiedType()))) { 16695 if (SemaRef.CheckBaseClassAccess( 16696 Loc, VD->getType(), Ty, Paths.front(), 16697 /*DiagID=*/0) != Sema::AR_inaccessible) { 16698 SemaRef.BuildBasePathArray(Paths, BasePath); 16699 return SemaRef.BuildDeclRefExpr( 16700 VD, VD->getType().getNonReferenceType(), VK_LValue, Loc); 16701 } 16702 } 16703 } 16704 } 16705 } 16706 if (ReductionIdScopeSpec.isSet()) { 16707 SemaRef.Diag(Loc, diag::err_omp_not_resolved_reduction_identifier) 16708 << Ty << Range; 16709 return ExprError(); 16710 } 16711 return ExprEmpty(); 16712 } 16713 16714 namespace { 16715 /// Data for the reduction-based clauses. 16716 struct ReductionData { 16717 /// List of original reduction items. 16718 SmallVector<Expr *, 8> Vars; 16719 /// List of private copies of the reduction items. 16720 SmallVector<Expr *, 8> Privates; 16721 /// LHS expressions for the reduction_op expressions. 16722 SmallVector<Expr *, 8> LHSs; 16723 /// RHS expressions for the reduction_op expressions. 16724 SmallVector<Expr *, 8> RHSs; 16725 /// Reduction operation expression. 16726 SmallVector<Expr *, 8> ReductionOps; 16727 /// inscan copy operation expressions. 16728 SmallVector<Expr *, 8> InscanCopyOps; 16729 /// inscan copy temp array expressions for prefix sums. 16730 SmallVector<Expr *, 8> InscanCopyArrayTemps; 16731 /// inscan copy temp array element expressions for prefix sums. 16732 SmallVector<Expr *, 8> InscanCopyArrayElems; 16733 /// Taskgroup descriptors for the corresponding reduction items in 16734 /// in_reduction clauses. 16735 SmallVector<Expr *, 8> TaskgroupDescriptors; 16736 /// List of captures for clause. 16737 SmallVector<Decl *, 4> ExprCaptures; 16738 /// List of postupdate expressions. 16739 SmallVector<Expr *, 4> ExprPostUpdates; 16740 /// Reduction modifier. 16741 unsigned RedModifier = 0; 16742 ReductionData() = delete; 16743 /// Reserves required memory for the reduction data. 16744 ReductionData(unsigned Size, unsigned Modifier = 0) : RedModifier(Modifier) { 16745 Vars.reserve(Size); 16746 Privates.reserve(Size); 16747 LHSs.reserve(Size); 16748 RHSs.reserve(Size); 16749 ReductionOps.reserve(Size); 16750 if (RedModifier == OMPC_REDUCTION_inscan) { 16751 InscanCopyOps.reserve(Size); 16752 InscanCopyArrayTemps.reserve(Size); 16753 InscanCopyArrayElems.reserve(Size); 16754 } 16755 TaskgroupDescriptors.reserve(Size); 16756 ExprCaptures.reserve(Size); 16757 ExprPostUpdates.reserve(Size); 16758 } 16759 /// Stores reduction item and reduction operation only (required for dependent 16760 /// reduction item). 16761 void push(Expr *Item, Expr *ReductionOp) { 16762 Vars.emplace_back(Item); 16763 Privates.emplace_back(nullptr); 16764 LHSs.emplace_back(nullptr); 16765 RHSs.emplace_back(nullptr); 16766 ReductionOps.emplace_back(ReductionOp); 16767 TaskgroupDescriptors.emplace_back(nullptr); 16768 if (RedModifier == OMPC_REDUCTION_inscan) { 16769 InscanCopyOps.push_back(nullptr); 16770 InscanCopyArrayTemps.push_back(nullptr); 16771 InscanCopyArrayElems.push_back(nullptr); 16772 } 16773 } 16774 /// Stores reduction data. 16775 void push(Expr *Item, Expr *Private, Expr *LHS, Expr *RHS, Expr *ReductionOp, 16776 Expr *TaskgroupDescriptor, Expr *CopyOp, Expr *CopyArrayTemp, 16777 Expr *CopyArrayElem) { 16778 Vars.emplace_back(Item); 16779 Privates.emplace_back(Private); 16780 LHSs.emplace_back(LHS); 16781 RHSs.emplace_back(RHS); 16782 ReductionOps.emplace_back(ReductionOp); 16783 TaskgroupDescriptors.emplace_back(TaskgroupDescriptor); 16784 if (RedModifier == OMPC_REDUCTION_inscan) { 16785 InscanCopyOps.push_back(CopyOp); 16786 InscanCopyArrayTemps.push_back(CopyArrayTemp); 16787 InscanCopyArrayElems.push_back(CopyArrayElem); 16788 } else { 16789 assert(CopyOp == nullptr && CopyArrayTemp == nullptr && 16790 CopyArrayElem == nullptr && 16791 "Copy operation must be used for inscan reductions only."); 16792 } 16793 } 16794 }; 16795 } // namespace 16796 16797 static bool checkOMPArraySectionConstantForReduction( 16798 ASTContext &Context, const OMPArraySectionExpr *OASE, bool &SingleElement, 16799 SmallVectorImpl<llvm::APSInt> &ArraySizes) { 16800 const Expr *Length = OASE->getLength(); 16801 if (Length == nullptr) { 16802 // For array sections of the form [1:] or [:], we would need to analyze 16803 // the lower bound... 16804 if (OASE->getColonLocFirst().isValid()) 16805 return false; 16806 16807 // This is an array subscript which has implicit length 1! 16808 SingleElement = true; 16809 ArraySizes.push_back(llvm::APSInt::get(1)); 16810 } else { 16811 Expr::EvalResult Result; 16812 if (!Length->EvaluateAsInt(Result, Context)) 16813 return false; 16814 16815 llvm::APSInt ConstantLengthValue = Result.Val.getInt(); 16816 SingleElement = (ConstantLengthValue.getSExtValue() == 1); 16817 ArraySizes.push_back(ConstantLengthValue); 16818 } 16819 16820 // Get the base of this array section and walk up from there. 16821 const Expr *Base = OASE->getBase()->IgnoreParenImpCasts(); 16822 16823 // We require length = 1 for all array sections except the right-most to 16824 // guarantee that the memory region is contiguous and has no holes in it. 16825 while (const auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base)) { 16826 Length = TempOASE->getLength(); 16827 if (Length == nullptr) { 16828 // For array sections of the form [1:] or [:], we would need to analyze 16829 // the lower bound... 16830 if (OASE->getColonLocFirst().isValid()) 16831 return false; 16832 16833 // This is an array subscript which has implicit length 1! 16834 ArraySizes.push_back(llvm::APSInt::get(1)); 16835 } else { 16836 Expr::EvalResult Result; 16837 if (!Length->EvaluateAsInt(Result, Context)) 16838 return false; 16839 16840 llvm::APSInt ConstantLengthValue = Result.Val.getInt(); 16841 if (ConstantLengthValue.getSExtValue() != 1) 16842 return false; 16843 16844 ArraySizes.push_back(ConstantLengthValue); 16845 } 16846 Base = TempOASE->getBase()->IgnoreParenImpCasts(); 16847 } 16848 16849 // If we have a single element, we don't need to add the implicit lengths. 16850 if (!SingleElement) { 16851 while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) { 16852 // Has implicit length 1! 16853 ArraySizes.push_back(llvm::APSInt::get(1)); 16854 Base = TempASE->getBase()->IgnoreParenImpCasts(); 16855 } 16856 } 16857 16858 // This array section can be privatized as a single value or as a constant 16859 // sized array. 16860 return true; 16861 } 16862 16863 static BinaryOperatorKind 16864 getRelatedCompoundReductionOp(BinaryOperatorKind BOK) { 16865 if (BOK == BO_Add) 16866 return BO_AddAssign; 16867 if (BOK == BO_Mul) 16868 return BO_MulAssign; 16869 if (BOK == BO_And) 16870 return BO_AndAssign; 16871 if (BOK == BO_Or) 16872 return BO_OrAssign; 16873 if (BOK == BO_Xor) 16874 return BO_XorAssign; 16875 return BOK; 16876 } 16877 16878 static bool actOnOMPReductionKindClause( 16879 Sema &S, DSAStackTy *Stack, OpenMPClauseKind ClauseKind, 16880 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, 16881 SourceLocation ColonLoc, SourceLocation EndLoc, 16882 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId, 16883 ArrayRef<Expr *> UnresolvedReductions, ReductionData &RD) { 16884 DeclarationName DN = ReductionId.getName(); 16885 OverloadedOperatorKind OOK = DN.getCXXOverloadedOperator(); 16886 BinaryOperatorKind BOK = BO_Comma; 16887 16888 ASTContext &Context = S.Context; 16889 // OpenMP [2.14.3.6, reduction clause] 16890 // C 16891 // reduction-identifier is either an identifier or one of the following 16892 // operators: +, -, *, &, |, ^, && and || 16893 // C++ 16894 // reduction-identifier is either an id-expression or one of the following 16895 // operators: +, -, *, &, |, ^, && and || 16896 switch (OOK) { 16897 case OO_Plus: 16898 case OO_Minus: 16899 BOK = BO_Add; 16900 break; 16901 case OO_Star: 16902 BOK = BO_Mul; 16903 break; 16904 case OO_Amp: 16905 BOK = BO_And; 16906 break; 16907 case OO_Pipe: 16908 BOK = BO_Or; 16909 break; 16910 case OO_Caret: 16911 BOK = BO_Xor; 16912 break; 16913 case OO_AmpAmp: 16914 BOK = BO_LAnd; 16915 break; 16916 case OO_PipePipe: 16917 BOK = BO_LOr; 16918 break; 16919 case OO_New: 16920 case OO_Delete: 16921 case OO_Array_New: 16922 case OO_Array_Delete: 16923 case OO_Slash: 16924 case OO_Percent: 16925 case OO_Tilde: 16926 case OO_Exclaim: 16927 case OO_Equal: 16928 case OO_Less: 16929 case OO_Greater: 16930 case OO_LessEqual: 16931 case OO_GreaterEqual: 16932 case OO_PlusEqual: 16933 case OO_MinusEqual: 16934 case OO_StarEqual: 16935 case OO_SlashEqual: 16936 case OO_PercentEqual: 16937 case OO_CaretEqual: 16938 case OO_AmpEqual: 16939 case OO_PipeEqual: 16940 case OO_LessLess: 16941 case OO_GreaterGreater: 16942 case OO_LessLessEqual: 16943 case OO_GreaterGreaterEqual: 16944 case OO_EqualEqual: 16945 case OO_ExclaimEqual: 16946 case OO_Spaceship: 16947 case OO_PlusPlus: 16948 case OO_MinusMinus: 16949 case OO_Comma: 16950 case OO_ArrowStar: 16951 case OO_Arrow: 16952 case OO_Call: 16953 case OO_Subscript: 16954 case OO_Conditional: 16955 case OO_Coawait: 16956 case NUM_OVERLOADED_OPERATORS: 16957 llvm_unreachable("Unexpected reduction identifier"); 16958 case OO_None: 16959 if (IdentifierInfo *II = DN.getAsIdentifierInfo()) { 16960 if (II->isStr("max")) 16961 BOK = BO_GT; 16962 else if (II->isStr("min")) 16963 BOK = BO_LT; 16964 } 16965 break; 16966 } 16967 SourceRange ReductionIdRange; 16968 if (ReductionIdScopeSpec.isValid()) 16969 ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc()); 16970 else 16971 ReductionIdRange.setBegin(ReductionId.getBeginLoc()); 16972 ReductionIdRange.setEnd(ReductionId.getEndLoc()); 16973 16974 auto IR = UnresolvedReductions.begin(), ER = UnresolvedReductions.end(); 16975 bool FirstIter = true; 16976 for (Expr *RefExpr : VarList) { 16977 assert(RefExpr && "nullptr expr in OpenMP reduction clause."); 16978 // OpenMP [2.1, C/C++] 16979 // A list item is a variable or array section, subject to the restrictions 16980 // specified in Section 2.4 on page 42 and in each of the sections 16981 // describing clauses and directives for which a list appears. 16982 // OpenMP [2.14.3.3, Restrictions, p.1] 16983 // A variable that is part of another variable (as an array or 16984 // structure element) cannot appear in a private clause. 16985 if (!FirstIter && IR != ER) 16986 ++IR; 16987 FirstIter = false; 16988 SourceLocation ELoc; 16989 SourceRange ERange; 16990 Expr *SimpleRefExpr = RefExpr; 16991 auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange, 16992 /*AllowArraySection=*/true); 16993 if (Res.second) { 16994 // Try to find 'declare reduction' corresponding construct before using 16995 // builtin/overloaded operators. 16996 QualType Type = Context.DependentTy; 16997 CXXCastPath BasePath; 16998 ExprResult DeclareReductionRef = buildDeclareReductionRef( 16999 S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec, 17000 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR); 17001 Expr *ReductionOp = nullptr; 17002 if (S.CurContext->isDependentContext() && 17003 (DeclareReductionRef.isUnset() || 17004 isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) 17005 ReductionOp = DeclareReductionRef.get(); 17006 // It will be analyzed later. 17007 RD.push(RefExpr, ReductionOp); 17008 } 17009 ValueDecl *D = Res.first; 17010 if (!D) 17011 continue; 17012 17013 Expr *TaskgroupDescriptor = nullptr; 17014 QualType Type; 17015 auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr->IgnoreParens()); 17016 auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr->IgnoreParens()); 17017 if (ASE) { 17018 Type = ASE->getType().getNonReferenceType(); 17019 } else if (OASE) { 17020 QualType BaseType = 17021 OMPArraySectionExpr::getBaseOriginalType(OASE->getBase()); 17022 if (const auto *ATy = BaseType->getAsArrayTypeUnsafe()) 17023 Type = ATy->getElementType(); 17024 else 17025 Type = BaseType->getPointeeType(); 17026 Type = Type.getNonReferenceType(); 17027 } else { 17028 Type = Context.getBaseElementType(D->getType().getNonReferenceType()); 17029 } 17030 auto *VD = dyn_cast<VarDecl>(D); 17031 17032 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3] 17033 // A variable that appears in a private clause must not have an incomplete 17034 // type or a reference type. 17035 if (S.RequireCompleteType(ELoc, D->getType(), 17036 diag::err_omp_reduction_incomplete_type)) 17037 continue; 17038 // OpenMP [2.14.3.6, reduction clause, Restrictions] 17039 // A list item that appears in a reduction clause must not be 17040 // const-qualified. 17041 if (rejectConstNotMutableType(S, D, Type, ClauseKind, ELoc, 17042 /*AcceptIfMutable*/ false, ASE || OASE)) 17043 continue; 17044 17045 OpenMPDirectiveKind CurrDir = Stack->getCurrentDirective(); 17046 // OpenMP [2.9.3.6, Restrictions, C/C++, p.4] 17047 // If a list-item is a reference type then it must bind to the same object 17048 // for all threads of the team. 17049 if (!ASE && !OASE) { 17050 if (VD) { 17051 VarDecl *VDDef = VD->getDefinition(); 17052 if (VD->getType()->isReferenceType() && VDDef && VDDef->hasInit()) { 17053 DSARefChecker Check(Stack); 17054 if (Check.Visit(VDDef->getInit())) { 17055 S.Diag(ELoc, diag::err_omp_reduction_ref_type_arg) 17056 << getOpenMPClauseName(ClauseKind) << ERange; 17057 S.Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef; 17058 continue; 17059 } 17060 } 17061 } 17062 17063 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced 17064 // in a Construct] 17065 // Variables with the predetermined data-sharing attributes may not be 17066 // listed in data-sharing attributes clauses, except for the cases 17067 // listed below. For these exceptions only, listing a predetermined 17068 // variable in a data-sharing attribute clause is allowed and overrides 17069 // the variable's predetermined data-sharing attributes. 17070 // OpenMP [2.14.3.6, Restrictions, p.3] 17071 // Any number of reduction clauses can be specified on the directive, 17072 // but a list item can appear only once in the reduction clauses for that 17073 // directive. 17074 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(D, /*FromParent=*/false); 17075 if (DVar.CKind == OMPC_reduction) { 17076 S.Diag(ELoc, diag::err_omp_once_referenced) 17077 << getOpenMPClauseName(ClauseKind); 17078 if (DVar.RefExpr) 17079 S.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced); 17080 continue; 17081 } 17082 if (DVar.CKind != OMPC_unknown) { 17083 S.Diag(ELoc, diag::err_omp_wrong_dsa) 17084 << getOpenMPClauseName(DVar.CKind) 17085 << getOpenMPClauseName(OMPC_reduction); 17086 reportOriginalDsa(S, Stack, D, DVar); 17087 continue; 17088 } 17089 17090 // OpenMP [2.14.3.6, Restrictions, p.1] 17091 // A list item that appears in a reduction clause of a worksharing 17092 // construct must be shared in the parallel regions to which any of the 17093 // worksharing regions arising from the worksharing construct bind. 17094 if (isOpenMPWorksharingDirective(CurrDir) && 17095 !isOpenMPParallelDirective(CurrDir) && 17096 !isOpenMPTeamsDirective(CurrDir)) { 17097 DVar = Stack->getImplicitDSA(D, true); 17098 if (DVar.CKind != OMPC_shared) { 17099 S.Diag(ELoc, diag::err_omp_required_access) 17100 << getOpenMPClauseName(OMPC_reduction) 17101 << getOpenMPClauseName(OMPC_shared); 17102 reportOriginalDsa(S, Stack, D, DVar); 17103 continue; 17104 } 17105 } 17106 } else { 17107 // Threadprivates cannot be shared between threads, so dignose if the base 17108 // is a threadprivate variable. 17109 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(D, /*FromParent=*/false); 17110 if (DVar.CKind == OMPC_threadprivate) { 17111 S.Diag(ELoc, diag::err_omp_wrong_dsa) 17112 << getOpenMPClauseName(DVar.CKind) 17113 << getOpenMPClauseName(OMPC_reduction); 17114 reportOriginalDsa(S, Stack, D, DVar); 17115 continue; 17116 } 17117 } 17118 17119 // Try to find 'declare reduction' corresponding construct before using 17120 // builtin/overloaded operators. 17121 CXXCastPath BasePath; 17122 ExprResult DeclareReductionRef = buildDeclareReductionRef( 17123 S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec, 17124 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR); 17125 if (DeclareReductionRef.isInvalid()) 17126 continue; 17127 if (S.CurContext->isDependentContext() && 17128 (DeclareReductionRef.isUnset() || 17129 isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) { 17130 RD.push(RefExpr, DeclareReductionRef.get()); 17131 continue; 17132 } 17133 if (BOK == BO_Comma && DeclareReductionRef.isUnset()) { 17134 // Not allowed reduction identifier is found. 17135 S.Diag(ReductionId.getBeginLoc(), 17136 diag::err_omp_unknown_reduction_identifier) 17137 << Type << ReductionIdRange; 17138 continue; 17139 } 17140 17141 // OpenMP [2.14.3.6, reduction clause, Restrictions] 17142 // The type of a list item that appears in a reduction clause must be valid 17143 // for the reduction-identifier. For a max or min reduction in C, the type 17144 // of the list item must be an allowed arithmetic data type: char, int, 17145 // float, double, or _Bool, possibly modified with long, short, signed, or 17146 // unsigned. For a max or min reduction in C++, the type of the list item 17147 // must be an allowed arithmetic data type: char, wchar_t, int, float, 17148 // double, or bool, possibly modified with long, short, signed, or unsigned. 17149 if (DeclareReductionRef.isUnset()) { 17150 if ((BOK == BO_GT || BOK == BO_LT) && 17151 !(Type->isScalarType() || 17152 (S.getLangOpts().CPlusPlus && Type->isArithmeticType()))) { 17153 S.Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg) 17154 << getOpenMPClauseName(ClauseKind) << S.getLangOpts().CPlusPlus; 17155 if (!ASE && !OASE) { 17156 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) == 17157 VarDecl::DeclarationOnly; 17158 S.Diag(D->getLocation(), 17159 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 17160 << D; 17161 } 17162 continue; 17163 } 17164 if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) && 17165 !S.getLangOpts().CPlusPlus && Type->isFloatingType()) { 17166 S.Diag(ELoc, diag::err_omp_clause_floating_type_arg) 17167 << getOpenMPClauseName(ClauseKind); 17168 if (!ASE && !OASE) { 17169 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) == 17170 VarDecl::DeclarationOnly; 17171 S.Diag(D->getLocation(), 17172 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 17173 << D; 17174 } 17175 continue; 17176 } 17177 } 17178 17179 Type = Type.getNonLValueExprType(Context).getUnqualifiedType(); 17180 VarDecl *LHSVD = buildVarDecl(S, ELoc, Type, ".reduction.lhs", 17181 D->hasAttrs() ? &D->getAttrs() : nullptr); 17182 VarDecl *RHSVD = buildVarDecl(S, ELoc, Type, D->getName(), 17183 D->hasAttrs() ? &D->getAttrs() : nullptr); 17184 QualType PrivateTy = Type; 17185 17186 // Try if we can determine constant lengths for all array sections and avoid 17187 // the VLA. 17188 bool ConstantLengthOASE = false; 17189 if (OASE) { 17190 bool SingleElement; 17191 llvm::SmallVector<llvm::APSInt, 4> ArraySizes; 17192 ConstantLengthOASE = checkOMPArraySectionConstantForReduction( 17193 Context, OASE, SingleElement, ArraySizes); 17194 17195 // If we don't have a single element, we must emit a constant array type. 17196 if (ConstantLengthOASE && !SingleElement) { 17197 for (llvm::APSInt &Size : ArraySizes) 17198 PrivateTy = Context.getConstantArrayType(PrivateTy, Size, nullptr, 17199 ArrayType::Normal, 17200 /*IndexTypeQuals=*/0); 17201 } 17202 } 17203 17204 if ((OASE && !ConstantLengthOASE) || 17205 (!OASE && !ASE && 17206 D->getType().getNonReferenceType()->isVariablyModifiedType())) { 17207 if (!Context.getTargetInfo().isVLASupported()) { 17208 if (isOpenMPTargetExecutionDirective(Stack->getCurrentDirective())) { 17209 S.Diag(ELoc, diag::err_omp_reduction_vla_unsupported) << !!OASE; 17210 S.Diag(ELoc, diag::note_vla_unsupported); 17211 continue; 17212 } else { 17213 S.targetDiag(ELoc, diag::err_omp_reduction_vla_unsupported) << !!OASE; 17214 S.targetDiag(ELoc, diag::note_vla_unsupported); 17215 } 17216 } 17217 // For arrays/array sections only: 17218 // Create pseudo array type for private copy. The size for this array will 17219 // be generated during codegen. 17220 // For array subscripts or single variables Private Ty is the same as Type 17221 // (type of the variable or single array element). 17222 PrivateTy = Context.getVariableArrayType( 17223 Type, 17224 new (Context) 17225 OpaqueValueExpr(ELoc, Context.getSizeType(), VK_PRValue), 17226 ArrayType::Normal, /*IndexTypeQuals=*/0, SourceRange()); 17227 } else if (!ASE && !OASE && 17228 Context.getAsArrayType(D->getType().getNonReferenceType())) { 17229 PrivateTy = D->getType().getNonReferenceType(); 17230 } 17231 // Private copy. 17232 VarDecl *PrivateVD = 17233 buildVarDecl(S, ELoc, PrivateTy, D->getName(), 17234 D->hasAttrs() ? &D->getAttrs() : nullptr, 17235 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr); 17236 // Add initializer for private variable. 17237 Expr *Init = nullptr; 17238 DeclRefExpr *LHSDRE = buildDeclRefExpr(S, LHSVD, Type, ELoc); 17239 DeclRefExpr *RHSDRE = buildDeclRefExpr(S, RHSVD, Type, ELoc); 17240 if (DeclareReductionRef.isUsable()) { 17241 auto *DRDRef = DeclareReductionRef.getAs<DeclRefExpr>(); 17242 auto *DRD = cast<OMPDeclareReductionDecl>(DRDRef->getDecl()); 17243 if (DRD->getInitializer()) { 17244 Init = DRDRef; 17245 RHSVD->setInit(DRDRef); 17246 RHSVD->setInitStyle(VarDecl::CallInit); 17247 } 17248 } else { 17249 switch (BOK) { 17250 case BO_Add: 17251 case BO_Xor: 17252 case BO_Or: 17253 case BO_LOr: 17254 // '+', '-', '^', '|', '||' reduction ops - initializer is '0'. 17255 if (Type->isScalarType() || Type->isAnyComplexType()) 17256 Init = S.ActOnIntegerConstant(ELoc, /*Val=*/0).get(); 17257 break; 17258 case BO_Mul: 17259 case BO_LAnd: 17260 if (Type->isScalarType() || Type->isAnyComplexType()) { 17261 // '*' and '&&' reduction ops - initializer is '1'. 17262 Init = S.ActOnIntegerConstant(ELoc, /*Val=*/1).get(); 17263 } 17264 break; 17265 case BO_And: { 17266 // '&' reduction op - initializer is '~0'. 17267 QualType OrigType = Type; 17268 if (auto *ComplexTy = OrigType->getAs<ComplexType>()) 17269 Type = ComplexTy->getElementType(); 17270 if (Type->isRealFloatingType()) { 17271 llvm::APFloat InitValue = llvm::APFloat::getAllOnesValue( 17272 Context.getFloatTypeSemantics(Type)); 17273 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true, 17274 Type, ELoc); 17275 } else if (Type->isScalarType()) { 17276 uint64_t Size = Context.getTypeSize(Type); 17277 QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0); 17278 llvm::APInt InitValue = llvm::APInt::getAllOnes(Size); 17279 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc); 17280 } 17281 if (Init && OrigType->isAnyComplexType()) { 17282 // Init = 0xFFFF + 0xFFFFi; 17283 auto *Im = new (Context) ImaginaryLiteral(Init, OrigType); 17284 Init = S.CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get(); 17285 } 17286 Type = OrigType; 17287 break; 17288 } 17289 case BO_LT: 17290 case BO_GT: { 17291 // 'min' reduction op - initializer is 'Largest representable number in 17292 // the reduction list item type'. 17293 // 'max' reduction op - initializer is 'Least representable number in 17294 // the reduction list item type'. 17295 if (Type->isIntegerType() || Type->isPointerType()) { 17296 bool IsSigned = Type->hasSignedIntegerRepresentation(); 17297 uint64_t Size = Context.getTypeSize(Type); 17298 QualType IntTy = 17299 Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned); 17300 llvm::APInt InitValue = 17301 (BOK != BO_LT) ? IsSigned ? llvm::APInt::getSignedMinValue(Size) 17302 : llvm::APInt::getMinValue(Size) 17303 : IsSigned ? llvm::APInt::getSignedMaxValue(Size) 17304 : llvm::APInt::getMaxValue(Size); 17305 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc); 17306 if (Type->isPointerType()) { 17307 // Cast to pointer type. 17308 ExprResult CastExpr = S.BuildCStyleCastExpr( 17309 ELoc, Context.getTrivialTypeSourceInfo(Type, ELoc), ELoc, Init); 17310 if (CastExpr.isInvalid()) 17311 continue; 17312 Init = CastExpr.get(); 17313 } 17314 } else if (Type->isRealFloatingType()) { 17315 llvm::APFloat InitValue = llvm::APFloat::getLargest( 17316 Context.getFloatTypeSemantics(Type), BOK != BO_LT); 17317 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true, 17318 Type, ELoc); 17319 } 17320 break; 17321 } 17322 case BO_PtrMemD: 17323 case BO_PtrMemI: 17324 case BO_MulAssign: 17325 case BO_Div: 17326 case BO_Rem: 17327 case BO_Sub: 17328 case BO_Shl: 17329 case BO_Shr: 17330 case BO_LE: 17331 case BO_GE: 17332 case BO_EQ: 17333 case BO_NE: 17334 case BO_Cmp: 17335 case BO_AndAssign: 17336 case BO_XorAssign: 17337 case BO_OrAssign: 17338 case BO_Assign: 17339 case BO_AddAssign: 17340 case BO_SubAssign: 17341 case BO_DivAssign: 17342 case BO_RemAssign: 17343 case BO_ShlAssign: 17344 case BO_ShrAssign: 17345 case BO_Comma: 17346 llvm_unreachable("Unexpected reduction operation"); 17347 } 17348 } 17349 if (Init && DeclareReductionRef.isUnset()) { 17350 S.AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false); 17351 // Store initializer for single element in private copy. Will be used 17352 // during codegen. 17353 PrivateVD->setInit(RHSVD->getInit()); 17354 PrivateVD->setInitStyle(RHSVD->getInitStyle()); 17355 } else if (!Init) { 17356 S.ActOnUninitializedDecl(RHSVD); 17357 // Store initializer for single element in private copy. Will be used 17358 // during codegen. 17359 PrivateVD->setInit(RHSVD->getInit()); 17360 PrivateVD->setInitStyle(RHSVD->getInitStyle()); 17361 } 17362 if (RHSVD->isInvalidDecl()) 17363 continue; 17364 if (!RHSVD->hasInit() && DeclareReductionRef.isUnset()) { 17365 S.Diag(ELoc, diag::err_omp_reduction_id_not_compatible) 17366 << Type << ReductionIdRange; 17367 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) == 17368 VarDecl::DeclarationOnly; 17369 S.Diag(D->getLocation(), 17370 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 17371 << D; 17372 continue; 17373 } 17374 DeclRefExpr *PrivateDRE = buildDeclRefExpr(S, PrivateVD, PrivateTy, ELoc); 17375 ExprResult ReductionOp; 17376 if (DeclareReductionRef.isUsable()) { 17377 QualType RedTy = DeclareReductionRef.get()->getType(); 17378 QualType PtrRedTy = Context.getPointerType(RedTy); 17379 ExprResult LHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, LHSDRE); 17380 ExprResult RHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RHSDRE); 17381 if (!BasePath.empty()) { 17382 LHS = S.DefaultLvalueConversion(LHS.get()); 17383 RHS = S.DefaultLvalueConversion(RHS.get()); 17384 LHS = ImplicitCastExpr::Create( 17385 Context, PtrRedTy, CK_UncheckedDerivedToBase, LHS.get(), &BasePath, 17386 LHS.get()->getValueKind(), FPOptionsOverride()); 17387 RHS = ImplicitCastExpr::Create( 17388 Context, PtrRedTy, CK_UncheckedDerivedToBase, RHS.get(), &BasePath, 17389 RHS.get()->getValueKind(), FPOptionsOverride()); 17390 } 17391 FunctionProtoType::ExtProtoInfo EPI; 17392 QualType Params[] = {PtrRedTy, PtrRedTy}; 17393 QualType FnTy = Context.getFunctionType(Context.VoidTy, Params, EPI); 17394 auto *OVE = new (Context) OpaqueValueExpr( 17395 ELoc, Context.getPointerType(FnTy), VK_PRValue, OK_Ordinary, 17396 S.DefaultLvalueConversion(DeclareReductionRef.get()).get()); 17397 Expr *Args[] = {LHS.get(), RHS.get()}; 17398 ReductionOp = 17399 CallExpr::Create(Context, OVE, Args, Context.VoidTy, VK_PRValue, ELoc, 17400 S.CurFPFeatureOverrides()); 17401 } else { 17402 BinaryOperatorKind CombBOK = getRelatedCompoundReductionOp(BOK); 17403 if (Type->isRecordType() && CombBOK != BOK) { 17404 Sema::TentativeAnalysisScope Trap(S); 17405 ReductionOp = 17406 S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(), 17407 CombBOK, LHSDRE, RHSDRE); 17408 } 17409 if (!ReductionOp.isUsable()) { 17410 ReductionOp = 17411 S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(), BOK, 17412 LHSDRE, RHSDRE); 17413 if (ReductionOp.isUsable()) { 17414 if (BOK != BO_LT && BOK != BO_GT) { 17415 ReductionOp = 17416 S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(), 17417 BO_Assign, LHSDRE, ReductionOp.get()); 17418 } else { 17419 auto *ConditionalOp = new (Context) 17420 ConditionalOperator(ReductionOp.get(), ELoc, LHSDRE, ELoc, 17421 RHSDRE, Type, VK_LValue, OK_Ordinary); 17422 ReductionOp = 17423 S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(), 17424 BO_Assign, LHSDRE, ConditionalOp); 17425 } 17426 } 17427 } 17428 if (ReductionOp.isUsable()) 17429 ReductionOp = S.ActOnFinishFullExpr(ReductionOp.get(), 17430 /*DiscardedValue*/ false); 17431 if (!ReductionOp.isUsable()) 17432 continue; 17433 } 17434 17435 // Add copy operations for inscan reductions. 17436 // LHS = RHS; 17437 ExprResult CopyOpRes, TempArrayRes, TempArrayElem; 17438 if (ClauseKind == OMPC_reduction && 17439 RD.RedModifier == OMPC_REDUCTION_inscan) { 17440 ExprResult RHS = S.DefaultLvalueConversion(RHSDRE); 17441 CopyOpRes = S.BuildBinOp(Stack->getCurScope(), ELoc, BO_Assign, LHSDRE, 17442 RHS.get()); 17443 if (!CopyOpRes.isUsable()) 17444 continue; 17445 CopyOpRes = 17446 S.ActOnFinishFullExpr(CopyOpRes.get(), /*DiscardedValue=*/true); 17447 if (!CopyOpRes.isUsable()) 17448 continue; 17449 // For simd directive and simd-based directives in simd mode no need to 17450 // construct temp array, need just a single temp element. 17451 if (Stack->getCurrentDirective() == OMPD_simd || 17452 (S.getLangOpts().OpenMPSimd && 17453 isOpenMPSimdDirective(Stack->getCurrentDirective()))) { 17454 VarDecl *TempArrayVD = 17455 buildVarDecl(S, ELoc, PrivateTy, D->getName(), 17456 D->hasAttrs() ? &D->getAttrs() : nullptr); 17457 // Add a constructor to the temp decl. 17458 S.ActOnUninitializedDecl(TempArrayVD); 17459 TempArrayRes = buildDeclRefExpr(S, TempArrayVD, PrivateTy, ELoc); 17460 } else { 17461 // Build temp array for prefix sum. 17462 auto *Dim = new (S.Context) 17463 OpaqueValueExpr(ELoc, S.Context.getSizeType(), VK_PRValue); 17464 QualType ArrayTy = 17465 S.Context.getVariableArrayType(PrivateTy, Dim, ArrayType::Normal, 17466 /*IndexTypeQuals=*/0, {ELoc, ELoc}); 17467 VarDecl *TempArrayVD = 17468 buildVarDecl(S, ELoc, ArrayTy, D->getName(), 17469 D->hasAttrs() ? &D->getAttrs() : nullptr); 17470 // Add a constructor to the temp decl. 17471 S.ActOnUninitializedDecl(TempArrayVD); 17472 TempArrayRes = buildDeclRefExpr(S, TempArrayVD, ArrayTy, ELoc); 17473 TempArrayElem = 17474 S.DefaultFunctionArrayLvalueConversion(TempArrayRes.get()); 17475 auto *Idx = new (S.Context) 17476 OpaqueValueExpr(ELoc, S.Context.getSizeType(), VK_PRValue); 17477 TempArrayElem = S.CreateBuiltinArraySubscriptExpr(TempArrayElem.get(), 17478 ELoc, Idx, ELoc); 17479 } 17480 } 17481 17482 // OpenMP [2.15.4.6, Restrictions, p.2] 17483 // A list item that appears in an in_reduction clause of a task construct 17484 // must appear in a task_reduction clause of a construct associated with a 17485 // taskgroup region that includes the participating task in its taskgroup 17486 // set. The construct associated with the innermost region that meets this 17487 // condition must specify the same reduction-identifier as the in_reduction 17488 // clause. 17489 if (ClauseKind == OMPC_in_reduction) { 17490 SourceRange ParentSR; 17491 BinaryOperatorKind ParentBOK; 17492 const Expr *ParentReductionOp = nullptr; 17493 Expr *ParentBOKTD = nullptr, *ParentReductionOpTD = nullptr; 17494 DSAStackTy::DSAVarData ParentBOKDSA = 17495 Stack->getTopMostTaskgroupReductionData(D, ParentSR, ParentBOK, 17496 ParentBOKTD); 17497 DSAStackTy::DSAVarData ParentReductionOpDSA = 17498 Stack->getTopMostTaskgroupReductionData( 17499 D, ParentSR, ParentReductionOp, ParentReductionOpTD); 17500 bool IsParentBOK = ParentBOKDSA.DKind != OMPD_unknown; 17501 bool IsParentReductionOp = ParentReductionOpDSA.DKind != OMPD_unknown; 17502 if ((DeclareReductionRef.isUnset() && IsParentReductionOp) || 17503 (DeclareReductionRef.isUsable() && IsParentBOK) || 17504 (IsParentBOK && BOK != ParentBOK) || IsParentReductionOp) { 17505 bool EmitError = true; 17506 if (IsParentReductionOp && DeclareReductionRef.isUsable()) { 17507 llvm::FoldingSetNodeID RedId, ParentRedId; 17508 ParentReductionOp->Profile(ParentRedId, Context, /*Canonical=*/true); 17509 DeclareReductionRef.get()->Profile(RedId, Context, 17510 /*Canonical=*/true); 17511 EmitError = RedId != ParentRedId; 17512 } 17513 if (EmitError) { 17514 S.Diag(ReductionId.getBeginLoc(), 17515 diag::err_omp_reduction_identifier_mismatch) 17516 << ReductionIdRange << RefExpr->getSourceRange(); 17517 S.Diag(ParentSR.getBegin(), 17518 diag::note_omp_previous_reduction_identifier) 17519 << ParentSR 17520 << (IsParentBOK ? ParentBOKDSA.RefExpr 17521 : ParentReductionOpDSA.RefExpr) 17522 ->getSourceRange(); 17523 continue; 17524 } 17525 } 17526 TaskgroupDescriptor = IsParentBOK ? ParentBOKTD : ParentReductionOpTD; 17527 } 17528 17529 DeclRefExpr *Ref = nullptr; 17530 Expr *VarsExpr = RefExpr->IgnoreParens(); 17531 if (!VD && !S.CurContext->isDependentContext()) { 17532 if (ASE || OASE) { 17533 TransformExprToCaptures RebuildToCapture(S, D); 17534 VarsExpr = 17535 RebuildToCapture.TransformExpr(RefExpr->IgnoreParens()).get(); 17536 Ref = RebuildToCapture.getCapturedExpr(); 17537 } else { 17538 VarsExpr = Ref = buildCapture(S, D, SimpleRefExpr, /*WithInit=*/false); 17539 } 17540 if (!S.isOpenMPCapturedDecl(D)) { 17541 RD.ExprCaptures.emplace_back(Ref->getDecl()); 17542 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) { 17543 ExprResult RefRes = S.DefaultLvalueConversion(Ref); 17544 if (!RefRes.isUsable()) 17545 continue; 17546 ExprResult PostUpdateRes = 17547 S.BuildBinOp(Stack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr, 17548 RefRes.get()); 17549 if (!PostUpdateRes.isUsable()) 17550 continue; 17551 if (isOpenMPTaskingDirective(Stack->getCurrentDirective()) || 17552 Stack->getCurrentDirective() == OMPD_taskgroup) { 17553 S.Diag(RefExpr->getExprLoc(), 17554 diag::err_omp_reduction_non_addressable_expression) 17555 << RefExpr->getSourceRange(); 17556 continue; 17557 } 17558 RD.ExprPostUpdates.emplace_back( 17559 S.IgnoredValueConversions(PostUpdateRes.get()).get()); 17560 } 17561 } 17562 } 17563 // All reduction items are still marked as reduction (to do not increase 17564 // code base size). 17565 unsigned Modifier = RD.RedModifier; 17566 // Consider task_reductions as reductions with task modifier. Required for 17567 // correct analysis of in_reduction clauses. 17568 if (CurrDir == OMPD_taskgroup && ClauseKind == OMPC_task_reduction) 17569 Modifier = OMPC_REDUCTION_task; 17570 Stack->addDSA(D, RefExpr->IgnoreParens(), OMPC_reduction, Ref, Modifier, 17571 ASE || OASE); 17572 if (Modifier == OMPC_REDUCTION_task && 17573 (CurrDir == OMPD_taskgroup || 17574 ((isOpenMPParallelDirective(CurrDir) || 17575 isOpenMPWorksharingDirective(CurrDir)) && 17576 !isOpenMPSimdDirective(CurrDir)))) { 17577 if (DeclareReductionRef.isUsable()) 17578 Stack->addTaskgroupReductionData(D, ReductionIdRange, 17579 DeclareReductionRef.get()); 17580 else 17581 Stack->addTaskgroupReductionData(D, ReductionIdRange, BOK); 17582 } 17583 RD.push(VarsExpr, PrivateDRE, LHSDRE, RHSDRE, ReductionOp.get(), 17584 TaskgroupDescriptor, CopyOpRes.get(), TempArrayRes.get(), 17585 TempArrayElem.get()); 17586 } 17587 return RD.Vars.empty(); 17588 } 17589 17590 OMPClause *Sema::ActOnOpenMPReductionClause( 17591 ArrayRef<Expr *> VarList, OpenMPReductionClauseModifier Modifier, 17592 SourceLocation StartLoc, SourceLocation LParenLoc, 17593 SourceLocation ModifierLoc, SourceLocation ColonLoc, SourceLocation EndLoc, 17594 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId, 17595 ArrayRef<Expr *> UnresolvedReductions) { 17596 if (ModifierLoc.isValid() && Modifier == OMPC_REDUCTION_unknown) { 17597 Diag(LParenLoc, diag::err_omp_unexpected_clause_value) 17598 << getListOfPossibleValues(OMPC_reduction, /*First=*/0, 17599 /*Last=*/OMPC_REDUCTION_unknown) 17600 << getOpenMPClauseName(OMPC_reduction); 17601 return nullptr; 17602 } 17603 // OpenMP 5.0, 2.19.5.4 reduction Clause, Restrictions 17604 // A reduction clause with the inscan reduction-modifier may only appear on a 17605 // worksharing-loop construct, a worksharing-loop SIMD construct, a simd 17606 // construct, a parallel worksharing-loop construct or a parallel 17607 // worksharing-loop SIMD construct. 17608 if (Modifier == OMPC_REDUCTION_inscan && 17609 (DSAStack->getCurrentDirective() != OMPD_for && 17610 DSAStack->getCurrentDirective() != OMPD_for_simd && 17611 DSAStack->getCurrentDirective() != OMPD_simd && 17612 DSAStack->getCurrentDirective() != OMPD_parallel_for && 17613 DSAStack->getCurrentDirective() != OMPD_parallel_for_simd)) { 17614 Diag(ModifierLoc, diag::err_omp_wrong_inscan_reduction); 17615 return nullptr; 17616 } 17617 17618 ReductionData RD(VarList.size(), Modifier); 17619 if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_reduction, VarList, 17620 StartLoc, LParenLoc, ColonLoc, EndLoc, 17621 ReductionIdScopeSpec, ReductionId, 17622 UnresolvedReductions, RD)) 17623 return nullptr; 17624 17625 return OMPReductionClause::Create( 17626 Context, StartLoc, LParenLoc, ModifierLoc, ColonLoc, EndLoc, Modifier, 17627 RD.Vars, ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId, 17628 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, RD.InscanCopyOps, 17629 RD.InscanCopyArrayTemps, RD.InscanCopyArrayElems, 17630 buildPreInits(Context, RD.ExprCaptures), 17631 buildPostUpdate(*this, RD.ExprPostUpdates)); 17632 } 17633 17634 OMPClause *Sema::ActOnOpenMPTaskReductionClause( 17635 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, 17636 SourceLocation ColonLoc, SourceLocation EndLoc, 17637 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId, 17638 ArrayRef<Expr *> UnresolvedReductions) { 17639 ReductionData RD(VarList.size()); 17640 if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_task_reduction, VarList, 17641 StartLoc, LParenLoc, ColonLoc, EndLoc, 17642 ReductionIdScopeSpec, ReductionId, 17643 UnresolvedReductions, RD)) 17644 return nullptr; 17645 17646 return OMPTaskReductionClause::Create( 17647 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars, 17648 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId, 17649 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, 17650 buildPreInits(Context, RD.ExprCaptures), 17651 buildPostUpdate(*this, RD.ExprPostUpdates)); 17652 } 17653 17654 OMPClause *Sema::ActOnOpenMPInReductionClause( 17655 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, 17656 SourceLocation ColonLoc, SourceLocation EndLoc, 17657 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId, 17658 ArrayRef<Expr *> UnresolvedReductions) { 17659 ReductionData RD(VarList.size()); 17660 if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_in_reduction, VarList, 17661 StartLoc, LParenLoc, ColonLoc, EndLoc, 17662 ReductionIdScopeSpec, ReductionId, 17663 UnresolvedReductions, RD)) 17664 return nullptr; 17665 17666 return OMPInReductionClause::Create( 17667 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars, 17668 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId, 17669 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, RD.TaskgroupDescriptors, 17670 buildPreInits(Context, RD.ExprCaptures), 17671 buildPostUpdate(*this, RD.ExprPostUpdates)); 17672 } 17673 17674 bool Sema::CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind, 17675 SourceLocation LinLoc) { 17676 if ((!LangOpts.CPlusPlus && LinKind != OMPC_LINEAR_val) || 17677 LinKind == OMPC_LINEAR_unknown) { 17678 Diag(LinLoc, diag::err_omp_wrong_linear_modifier) << LangOpts.CPlusPlus; 17679 return true; 17680 } 17681 return false; 17682 } 17683 17684 bool Sema::CheckOpenMPLinearDecl(const ValueDecl *D, SourceLocation ELoc, 17685 OpenMPLinearClauseKind LinKind, QualType Type, 17686 bool IsDeclareSimd) { 17687 const auto *VD = dyn_cast_or_null<VarDecl>(D); 17688 // A variable must not have an incomplete type or a reference type. 17689 if (RequireCompleteType(ELoc, Type, diag::err_omp_linear_incomplete_type)) 17690 return true; 17691 if ((LinKind == OMPC_LINEAR_uval || LinKind == OMPC_LINEAR_ref) && 17692 !Type->isReferenceType()) { 17693 Diag(ELoc, diag::err_omp_wrong_linear_modifier_non_reference) 17694 << Type << getOpenMPSimpleClauseTypeName(OMPC_linear, LinKind); 17695 return true; 17696 } 17697 Type = Type.getNonReferenceType(); 17698 17699 // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions] 17700 // A variable that is privatized must not have a const-qualified type 17701 // unless it is of class type with a mutable member. This restriction does 17702 // not apply to the firstprivate clause, nor to the linear clause on 17703 // declarative directives (like declare simd). 17704 if (!IsDeclareSimd && 17705 rejectConstNotMutableType(*this, D, Type, OMPC_linear, ELoc)) 17706 return true; 17707 17708 // A list item must be of integral or pointer type. 17709 Type = Type.getUnqualifiedType().getCanonicalType(); 17710 const auto *Ty = Type.getTypePtrOrNull(); 17711 if (!Ty || (LinKind != OMPC_LINEAR_ref && !Ty->isDependentType() && 17712 !Ty->isIntegralType(Context) && !Ty->isPointerType())) { 17713 Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << Type; 17714 if (D) { 17715 bool IsDecl = 17716 !VD || 17717 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 17718 Diag(D->getLocation(), 17719 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 17720 << D; 17721 } 17722 return true; 17723 } 17724 return false; 17725 } 17726 17727 OMPClause *Sema::ActOnOpenMPLinearClause( 17728 ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc, 17729 SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind, 17730 SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc) { 17731 SmallVector<Expr *, 8> Vars; 17732 SmallVector<Expr *, 8> Privates; 17733 SmallVector<Expr *, 8> Inits; 17734 SmallVector<Decl *, 4> ExprCaptures; 17735 SmallVector<Expr *, 4> ExprPostUpdates; 17736 if (CheckOpenMPLinearModifier(LinKind, LinLoc)) 17737 LinKind = OMPC_LINEAR_val; 17738 for (Expr *RefExpr : VarList) { 17739 assert(RefExpr && "NULL expr in OpenMP linear clause."); 17740 SourceLocation ELoc; 17741 SourceRange ERange; 17742 Expr *SimpleRefExpr = RefExpr; 17743 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 17744 if (Res.second) { 17745 // It will be analyzed later. 17746 Vars.push_back(RefExpr); 17747 Privates.push_back(nullptr); 17748 Inits.push_back(nullptr); 17749 } 17750 ValueDecl *D = Res.first; 17751 if (!D) 17752 continue; 17753 17754 QualType Type = D->getType(); 17755 auto *VD = dyn_cast<VarDecl>(D); 17756 17757 // OpenMP [2.14.3.7, linear clause] 17758 // A list-item cannot appear in more than one linear clause. 17759 // A list-item that appears in a linear clause cannot appear in any 17760 // other data-sharing attribute clause. 17761 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false); 17762 if (DVar.RefExpr) { 17763 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind) 17764 << getOpenMPClauseName(OMPC_linear); 17765 reportOriginalDsa(*this, DSAStack, D, DVar); 17766 continue; 17767 } 17768 17769 if (CheckOpenMPLinearDecl(D, ELoc, LinKind, Type)) 17770 continue; 17771 Type = Type.getNonReferenceType().getUnqualifiedType().getCanonicalType(); 17772 17773 // Build private copy of original var. 17774 VarDecl *Private = 17775 buildVarDecl(*this, ELoc, Type, D->getName(), 17776 D->hasAttrs() ? &D->getAttrs() : nullptr, 17777 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr); 17778 DeclRefExpr *PrivateRef = buildDeclRefExpr(*this, Private, Type, ELoc); 17779 // Build var to save initial value. 17780 VarDecl *Init = buildVarDecl(*this, ELoc, Type, ".linear.start"); 17781 Expr *InitExpr; 17782 DeclRefExpr *Ref = nullptr; 17783 if (!VD && !CurContext->isDependentContext()) { 17784 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false); 17785 if (!isOpenMPCapturedDecl(D)) { 17786 ExprCaptures.push_back(Ref->getDecl()); 17787 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) { 17788 ExprResult RefRes = DefaultLvalueConversion(Ref); 17789 if (!RefRes.isUsable()) 17790 continue; 17791 ExprResult PostUpdateRes = 17792 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, 17793 SimpleRefExpr, RefRes.get()); 17794 if (!PostUpdateRes.isUsable()) 17795 continue; 17796 ExprPostUpdates.push_back( 17797 IgnoredValueConversions(PostUpdateRes.get()).get()); 17798 } 17799 } 17800 } 17801 if (LinKind == OMPC_LINEAR_uval) 17802 InitExpr = VD ? VD->getInit() : SimpleRefExpr; 17803 else 17804 InitExpr = VD ? SimpleRefExpr : Ref; 17805 AddInitializerToDecl(Init, DefaultLvalueConversion(InitExpr).get(), 17806 /*DirectInit=*/false); 17807 DeclRefExpr *InitRef = buildDeclRefExpr(*this, Init, Type, ELoc); 17808 17809 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_linear, Ref); 17810 Vars.push_back((VD || CurContext->isDependentContext()) 17811 ? RefExpr->IgnoreParens() 17812 : Ref); 17813 Privates.push_back(PrivateRef); 17814 Inits.push_back(InitRef); 17815 } 17816 17817 if (Vars.empty()) 17818 return nullptr; 17819 17820 Expr *StepExpr = Step; 17821 Expr *CalcStepExpr = nullptr; 17822 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() && 17823 !Step->isInstantiationDependent() && 17824 !Step->containsUnexpandedParameterPack()) { 17825 SourceLocation StepLoc = Step->getBeginLoc(); 17826 ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step); 17827 if (Val.isInvalid()) 17828 return nullptr; 17829 StepExpr = Val.get(); 17830 17831 // Build var to save the step value. 17832 VarDecl *SaveVar = 17833 buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step"); 17834 ExprResult SaveRef = 17835 buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc); 17836 ExprResult CalcStep = 17837 BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr); 17838 CalcStep = ActOnFinishFullExpr(CalcStep.get(), /*DiscardedValue*/ false); 17839 17840 // Warn about zero linear step (it would be probably better specified as 17841 // making corresponding variables 'const'). 17842 if (Optional<llvm::APSInt> Result = 17843 StepExpr->getIntegerConstantExpr(Context)) { 17844 if (!Result->isNegative() && !Result->isStrictlyPositive()) 17845 Diag(StepLoc, diag::warn_omp_linear_step_zero) 17846 << Vars[0] << (Vars.size() > 1); 17847 } else if (CalcStep.isUsable()) { 17848 // Calculate the step beforehand instead of doing this on each iteration. 17849 // (This is not used if the number of iterations may be kfold-ed). 17850 CalcStepExpr = CalcStep.get(); 17851 } 17852 } 17853 17854 return OMPLinearClause::Create(Context, StartLoc, LParenLoc, LinKind, LinLoc, 17855 ColonLoc, EndLoc, Vars, Privates, Inits, 17856 StepExpr, CalcStepExpr, 17857 buildPreInits(Context, ExprCaptures), 17858 buildPostUpdate(*this, ExprPostUpdates)); 17859 } 17860 17861 static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV, 17862 Expr *NumIterations, Sema &SemaRef, 17863 Scope *S, DSAStackTy *Stack) { 17864 // Walk the vars and build update/final expressions for the CodeGen. 17865 SmallVector<Expr *, 8> Updates; 17866 SmallVector<Expr *, 8> Finals; 17867 SmallVector<Expr *, 8> UsedExprs; 17868 Expr *Step = Clause.getStep(); 17869 Expr *CalcStep = Clause.getCalcStep(); 17870 // OpenMP [2.14.3.7, linear clause] 17871 // If linear-step is not specified it is assumed to be 1. 17872 if (!Step) 17873 Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get(); 17874 else if (CalcStep) 17875 Step = cast<BinaryOperator>(CalcStep)->getLHS(); 17876 bool HasErrors = false; 17877 auto CurInit = Clause.inits().begin(); 17878 auto CurPrivate = Clause.privates().begin(); 17879 OpenMPLinearClauseKind LinKind = Clause.getModifier(); 17880 for (Expr *RefExpr : Clause.varlists()) { 17881 SourceLocation ELoc; 17882 SourceRange ERange; 17883 Expr *SimpleRefExpr = RefExpr; 17884 auto Res = getPrivateItem(SemaRef, SimpleRefExpr, ELoc, ERange); 17885 ValueDecl *D = Res.first; 17886 if (Res.second || !D) { 17887 Updates.push_back(nullptr); 17888 Finals.push_back(nullptr); 17889 HasErrors = true; 17890 continue; 17891 } 17892 auto &&Info = Stack->isLoopControlVariable(D); 17893 // OpenMP [2.15.11, distribute simd Construct] 17894 // A list item may not appear in a linear clause, unless it is the loop 17895 // iteration variable. 17896 if (isOpenMPDistributeDirective(Stack->getCurrentDirective()) && 17897 isOpenMPSimdDirective(Stack->getCurrentDirective()) && !Info.first) { 17898 SemaRef.Diag(ELoc, 17899 diag::err_omp_linear_distribute_var_non_loop_iteration); 17900 Updates.push_back(nullptr); 17901 Finals.push_back(nullptr); 17902 HasErrors = true; 17903 continue; 17904 } 17905 Expr *InitExpr = *CurInit; 17906 17907 // Build privatized reference to the current linear var. 17908 auto *DE = cast<DeclRefExpr>(SimpleRefExpr); 17909 Expr *CapturedRef; 17910 if (LinKind == OMPC_LINEAR_uval) 17911 CapturedRef = cast<VarDecl>(DE->getDecl())->getInit(); 17912 else 17913 CapturedRef = 17914 buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()), 17915 DE->getType().getUnqualifiedType(), DE->getExprLoc(), 17916 /*RefersToCapture=*/true); 17917 17918 // Build update: Var = InitExpr + IV * Step 17919 ExprResult Update; 17920 if (!Info.first) 17921 Update = buildCounterUpdate( 17922 SemaRef, S, RefExpr->getExprLoc(), *CurPrivate, InitExpr, IV, Step, 17923 /*Subtract=*/false, /*IsNonRectangularLB=*/false); 17924 else 17925 Update = *CurPrivate; 17926 Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getBeginLoc(), 17927 /*DiscardedValue*/ false); 17928 17929 // Build final: Var = InitExpr + NumIterations * Step 17930 ExprResult Final; 17931 if (!Info.first) 17932 Final = 17933 buildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), CapturedRef, 17934 InitExpr, NumIterations, Step, /*Subtract=*/false, 17935 /*IsNonRectangularLB=*/false); 17936 else 17937 Final = *CurPrivate; 17938 Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getBeginLoc(), 17939 /*DiscardedValue*/ false); 17940 17941 if (!Update.isUsable() || !Final.isUsable()) { 17942 Updates.push_back(nullptr); 17943 Finals.push_back(nullptr); 17944 UsedExprs.push_back(nullptr); 17945 HasErrors = true; 17946 } else { 17947 Updates.push_back(Update.get()); 17948 Finals.push_back(Final.get()); 17949 if (!Info.first) 17950 UsedExprs.push_back(SimpleRefExpr); 17951 } 17952 ++CurInit; 17953 ++CurPrivate; 17954 } 17955 if (Expr *S = Clause.getStep()) 17956 UsedExprs.push_back(S); 17957 // Fill the remaining part with the nullptr. 17958 UsedExprs.append(Clause.varlist_size() + 1 - UsedExprs.size(), nullptr); 17959 Clause.setUpdates(Updates); 17960 Clause.setFinals(Finals); 17961 Clause.setUsedExprs(UsedExprs); 17962 return HasErrors; 17963 } 17964 17965 OMPClause *Sema::ActOnOpenMPAlignedClause( 17966 ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc, 17967 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) { 17968 SmallVector<Expr *, 8> Vars; 17969 for (Expr *RefExpr : VarList) { 17970 assert(RefExpr && "NULL expr in OpenMP linear clause."); 17971 SourceLocation ELoc; 17972 SourceRange ERange; 17973 Expr *SimpleRefExpr = RefExpr; 17974 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 17975 if (Res.second) { 17976 // It will be analyzed later. 17977 Vars.push_back(RefExpr); 17978 } 17979 ValueDecl *D = Res.first; 17980 if (!D) 17981 continue; 17982 17983 QualType QType = D->getType(); 17984 auto *VD = dyn_cast<VarDecl>(D); 17985 17986 // OpenMP [2.8.1, simd construct, Restrictions] 17987 // The type of list items appearing in the aligned clause must be 17988 // array, pointer, reference to array, or reference to pointer. 17989 QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType(); 17990 const Type *Ty = QType.getTypePtrOrNull(); 17991 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) { 17992 Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr) 17993 << QType << getLangOpts().CPlusPlus << ERange; 17994 bool IsDecl = 17995 !VD || 17996 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 17997 Diag(D->getLocation(), 17998 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 17999 << D; 18000 continue; 18001 } 18002 18003 // OpenMP [2.8.1, simd construct, Restrictions] 18004 // A list-item cannot appear in more than one aligned clause. 18005 if (const Expr *PrevRef = DSAStack->addUniqueAligned(D, SimpleRefExpr)) { 18006 Diag(ELoc, diag::err_omp_used_in_clause_twice) 18007 << 0 << getOpenMPClauseName(OMPC_aligned) << ERange; 18008 Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa) 18009 << getOpenMPClauseName(OMPC_aligned); 18010 continue; 18011 } 18012 18013 DeclRefExpr *Ref = nullptr; 18014 if (!VD && isOpenMPCapturedDecl(D)) 18015 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true); 18016 Vars.push_back(DefaultFunctionArrayConversion( 18017 (VD || !Ref) ? RefExpr->IgnoreParens() : Ref) 18018 .get()); 18019 } 18020 18021 // OpenMP [2.8.1, simd construct, Description] 18022 // The parameter of the aligned clause, alignment, must be a constant 18023 // positive integer expression. 18024 // If no optional parameter is specified, implementation-defined default 18025 // alignments for SIMD instructions on the target platforms are assumed. 18026 if (Alignment != nullptr) { 18027 ExprResult AlignResult = 18028 VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned); 18029 if (AlignResult.isInvalid()) 18030 return nullptr; 18031 Alignment = AlignResult.get(); 18032 } 18033 if (Vars.empty()) 18034 return nullptr; 18035 18036 return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc, 18037 EndLoc, Vars, Alignment); 18038 } 18039 18040 OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList, 18041 SourceLocation StartLoc, 18042 SourceLocation LParenLoc, 18043 SourceLocation EndLoc) { 18044 SmallVector<Expr *, 8> Vars; 18045 SmallVector<Expr *, 8> SrcExprs; 18046 SmallVector<Expr *, 8> DstExprs; 18047 SmallVector<Expr *, 8> AssignmentOps; 18048 for (Expr *RefExpr : VarList) { 18049 assert(RefExpr && "NULL expr in OpenMP copyin clause."); 18050 if (isa<DependentScopeDeclRefExpr>(RefExpr)) { 18051 // It will be analyzed later. 18052 Vars.push_back(RefExpr); 18053 SrcExprs.push_back(nullptr); 18054 DstExprs.push_back(nullptr); 18055 AssignmentOps.push_back(nullptr); 18056 continue; 18057 } 18058 18059 SourceLocation ELoc = RefExpr->getExprLoc(); 18060 // OpenMP [2.1, C/C++] 18061 // A list item is a variable name. 18062 // OpenMP [2.14.4.1, Restrictions, p.1] 18063 // A list item that appears in a copyin clause must be threadprivate. 18064 auto *DE = dyn_cast<DeclRefExpr>(RefExpr); 18065 if (!DE || !isa<VarDecl>(DE->getDecl())) { 18066 Diag(ELoc, diag::err_omp_expected_var_name_member_expr) 18067 << 0 << RefExpr->getSourceRange(); 18068 continue; 18069 } 18070 18071 Decl *D = DE->getDecl(); 18072 auto *VD = cast<VarDecl>(D); 18073 18074 QualType Type = VD->getType(); 18075 if (Type->isDependentType() || Type->isInstantiationDependentType()) { 18076 // It will be analyzed later. 18077 Vars.push_back(DE); 18078 SrcExprs.push_back(nullptr); 18079 DstExprs.push_back(nullptr); 18080 AssignmentOps.push_back(nullptr); 18081 continue; 18082 } 18083 18084 // OpenMP [2.14.4.1, Restrictions, C/C++, p.1] 18085 // A list item that appears in a copyin clause must be threadprivate. 18086 if (!DSAStack->isThreadPrivate(VD)) { 18087 Diag(ELoc, diag::err_omp_required_access) 18088 << getOpenMPClauseName(OMPC_copyin) 18089 << getOpenMPDirectiveName(OMPD_threadprivate); 18090 continue; 18091 } 18092 18093 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2] 18094 // A variable of class type (or array thereof) that appears in a 18095 // copyin clause requires an accessible, unambiguous copy assignment 18096 // operator for the class type. 18097 QualType ElemType = Context.getBaseElementType(Type).getNonReferenceType(); 18098 VarDecl *SrcVD = 18099 buildVarDecl(*this, DE->getBeginLoc(), ElemType.getUnqualifiedType(), 18100 ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr); 18101 DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr( 18102 *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc()); 18103 VarDecl *DstVD = 18104 buildVarDecl(*this, DE->getBeginLoc(), ElemType, ".copyin.dst", 18105 VD->hasAttrs() ? &VD->getAttrs() : nullptr); 18106 DeclRefExpr *PseudoDstExpr = 18107 buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc()); 18108 // For arrays generate assignment operation for single element and replace 18109 // it by the original array element in CodeGen. 18110 ExprResult AssignmentOp = 18111 BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign, PseudoDstExpr, 18112 PseudoSrcExpr); 18113 if (AssignmentOp.isInvalid()) 18114 continue; 18115 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(), 18116 /*DiscardedValue*/ false); 18117 if (AssignmentOp.isInvalid()) 18118 continue; 18119 18120 DSAStack->addDSA(VD, DE, OMPC_copyin); 18121 Vars.push_back(DE); 18122 SrcExprs.push_back(PseudoSrcExpr); 18123 DstExprs.push_back(PseudoDstExpr); 18124 AssignmentOps.push_back(AssignmentOp.get()); 18125 } 18126 18127 if (Vars.empty()) 18128 return nullptr; 18129 18130 return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars, 18131 SrcExprs, DstExprs, AssignmentOps); 18132 } 18133 18134 OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList, 18135 SourceLocation StartLoc, 18136 SourceLocation LParenLoc, 18137 SourceLocation EndLoc) { 18138 SmallVector<Expr *, 8> Vars; 18139 SmallVector<Expr *, 8> SrcExprs; 18140 SmallVector<Expr *, 8> DstExprs; 18141 SmallVector<Expr *, 8> AssignmentOps; 18142 for (Expr *RefExpr : VarList) { 18143 assert(RefExpr && "NULL expr in OpenMP linear clause."); 18144 SourceLocation ELoc; 18145 SourceRange ERange; 18146 Expr *SimpleRefExpr = RefExpr; 18147 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 18148 if (Res.second) { 18149 // It will be analyzed later. 18150 Vars.push_back(RefExpr); 18151 SrcExprs.push_back(nullptr); 18152 DstExprs.push_back(nullptr); 18153 AssignmentOps.push_back(nullptr); 18154 } 18155 ValueDecl *D = Res.first; 18156 if (!D) 18157 continue; 18158 18159 QualType Type = D->getType(); 18160 auto *VD = dyn_cast<VarDecl>(D); 18161 18162 // OpenMP [2.14.4.2, Restrictions, p.2] 18163 // A list item that appears in a copyprivate clause may not appear in a 18164 // private or firstprivate clause on the single construct. 18165 if (!VD || !DSAStack->isThreadPrivate(VD)) { 18166 DSAStackTy::DSAVarData DVar = 18167 DSAStack->getTopDSA(D, /*FromParent=*/false); 18168 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate && 18169 DVar.RefExpr) { 18170 Diag(ELoc, diag::err_omp_wrong_dsa) 18171 << getOpenMPClauseName(DVar.CKind) 18172 << getOpenMPClauseName(OMPC_copyprivate); 18173 reportOriginalDsa(*this, DSAStack, D, DVar); 18174 continue; 18175 } 18176 18177 // OpenMP [2.11.4.2, Restrictions, p.1] 18178 // All list items that appear in a copyprivate clause must be either 18179 // threadprivate or private in the enclosing context. 18180 if (DVar.CKind == OMPC_unknown) { 18181 DVar = DSAStack->getImplicitDSA(D, false); 18182 if (DVar.CKind == OMPC_shared) { 18183 Diag(ELoc, diag::err_omp_required_access) 18184 << getOpenMPClauseName(OMPC_copyprivate) 18185 << "threadprivate or private in the enclosing context"; 18186 reportOriginalDsa(*this, DSAStack, D, DVar); 18187 continue; 18188 } 18189 } 18190 } 18191 18192 // Variably modified types are not supported. 18193 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) { 18194 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported) 18195 << getOpenMPClauseName(OMPC_copyprivate) << Type 18196 << getOpenMPDirectiveName(DSAStack->getCurrentDirective()); 18197 bool IsDecl = 18198 !VD || 18199 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 18200 Diag(D->getLocation(), 18201 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 18202 << D; 18203 continue; 18204 } 18205 18206 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2] 18207 // A variable of class type (or array thereof) that appears in a 18208 // copyin clause requires an accessible, unambiguous copy assignment 18209 // operator for the class type. 18210 Type = Context.getBaseElementType(Type.getNonReferenceType()) 18211 .getUnqualifiedType(); 18212 VarDecl *SrcVD = 18213 buildVarDecl(*this, RefExpr->getBeginLoc(), Type, ".copyprivate.src", 18214 D->hasAttrs() ? &D->getAttrs() : nullptr); 18215 DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr(*this, SrcVD, Type, ELoc); 18216 VarDecl *DstVD = 18217 buildVarDecl(*this, RefExpr->getBeginLoc(), Type, ".copyprivate.dst", 18218 D->hasAttrs() ? &D->getAttrs() : nullptr); 18219 DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc); 18220 ExprResult AssignmentOp = BuildBinOp( 18221 DSAStack->getCurScope(), ELoc, BO_Assign, PseudoDstExpr, PseudoSrcExpr); 18222 if (AssignmentOp.isInvalid()) 18223 continue; 18224 AssignmentOp = 18225 ActOnFinishFullExpr(AssignmentOp.get(), ELoc, /*DiscardedValue*/ false); 18226 if (AssignmentOp.isInvalid()) 18227 continue; 18228 18229 // No need to mark vars as copyprivate, they are already threadprivate or 18230 // implicitly private. 18231 assert(VD || isOpenMPCapturedDecl(D)); 18232 Vars.push_back( 18233 VD ? RefExpr->IgnoreParens() 18234 : buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false)); 18235 SrcExprs.push_back(PseudoSrcExpr); 18236 DstExprs.push_back(PseudoDstExpr); 18237 AssignmentOps.push_back(AssignmentOp.get()); 18238 } 18239 18240 if (Vars.empty()) 18241 return nullptr; 18242 18243 return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, 18244 Vars, SrcExprs, DstExprs, AssignmentOps); 18245 } 18246 18247 OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList, 18248 SourceLocation StartLoc, 18249 SourceLocation LParenLoc, 18250 SourceLocation EndLoc) { 18251 if (VarList.empty()) 18252 return nullptr; 18253 18254 return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList); 18255 } 18256 18257 /// Tries to find omp_depend_t. type. 18258 static bool findOMPDependT(Sema &S, SourceLocation Loc, DSAStackTy *Stack, 18259 bool Diagnose = true) { 18260 QualType OMPDependT = Stack->getOMPDependT(); 18261 if (!OMPDependT.isNull()) 18262 return true; 18263 IdentifierInfo *II = &S.PP.getIdentifierTable().get("omp_depend_t"); 18264 ParsedType PT = S.getTypeName(*II, Loc, S.getCurScope()); 18265 if (!PT.getAsOpaquePtr() || PT.get().isNull()) { 18266 if (Diagnose) 18267 S.Diag(Loc, diag::err_omp_implied_type_not_found) << "omp_depend_t"; 18268 return false; 18269 } 18270 Stack->setOMPDependT(PT.get()); 18271 return true; 18272 } 18273 18274 OMPClause *Sema::ActOnOpenMPDepobjClause(Expr *Depobj, SourceLocation StartLoc, 18275 SourceLocation LParenLoc, 18276 SourceLocation EndLoc) { 18277 if (!Depobj) 18278 return nullptr; 18279 18280 bool OMPDependTFound = findOMPDependT(*this, StartLoc, DSAStack); 18281 18282 // OpenMP 5.0, 2.17.10.1 depobj Construct 18283 // depobj is an lvalue expression of type omp_depend_t. 18284 if (!Depobj->isTypeDependent() && !Depobj->isValueDependent() && 18285 !Depobj->isInstantiationDependent() && 18286 !Depobj->containsUnexpandedParameterPack() && 18287 (OMPDependTFound && 18288 !Context.typesAreCompatible(DSAStack->getOMPDependT(), Depobj->getType(), 18289 /*CompareUnqualified=*/true))) { 18290 Diag(Depobj->getExprLoc(), diag::err_omp_expected_omp_depend_t_lvalue) 18291 << 0 << Depobj->getType() << Depobj->getSourceRange(); 18292 } 18293 18294 if (!Depobj->isLValue()) { 18295 Diag(Depobj->getExprLoc(), diag::err_omp_expected_omp_depend_t_lvalue) 18296 << 1 << Depobj->getSourceRange(); 18297 } 18298 18299 return OMPDepobjClause::Create(Context, StartLoc, LParenLoc, EndLoc, Depobj); 18300 } 18301 18302 OMPClause * 18303 Sema::ActOnOpenMPDependClause(Expr *DepModifier, OpenMPDependClauseKind DepKind, 18304 SourceLocation DepLoc, SourceLocation ColonLoc, 18305 ArrayRef<Expr *> VarList, SourceLocation StartLoc, 18306 SourceLocation LParenLoc, SourceLocation EndLoc) { 18307 if (DSAStack->getCurrentDirective() == OMPD_ordered && 18308 DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink) { 18309 Diag(DepLoc, diag::err_omp_unexpected_clause_value) 18310 << "'source' or 'sink'" << getOpenMPClauseName(OMPC_depend); 18311 return nullptr; 18312 } 18313 if ((DSAStack->getCurrentDirective() != OMPD_ordered || 18314 DSAStack->getCurrentDirective() == OMPD_depobj) && 18315 (DepKind == OMPC_DEPEND_unknown || DepKind == OMPC_DEPEND_source || 18316 DepKind == OMPC_DEPEND_sink || 18317 ((LangOpts.OpenMP < 50 || 18318 DSAStack->getCurrentDirective() == OMPD_depobj) && 18319 DepKind == OMPC_DEPEND_depobj))) { 18320 SmallVector<unsigned, 3> Except; 18321 Except.push_back(OMPC_DEPEND_source); 18322 Except.push_back(OMPC_DEPEND_sink); 18323 if (LangOpts.OpenMP < 50 || DSAStack->getCurrentDirective() == OMPD_depobj) 18324 Except.push_back(OMPC_DEPEND_depobj); 18325 std::string Expected = (LangOpts.OpenMP >= 50 && !DepModifier) 18326 ? "depend modifier(iterator) or " 18327 : ""; 18328 Diag(DepLoc, diag::err_omp_unexpected_clause_value) 18329 << Expected + getListOfPossibleValues(OMPC_depend, /*First=*/0, 18330 /*Last=*/OMPC_DEPEND_unknown, 18331 Except) 18332 << getOpenMPClauseName(OMPC_depend); 18333 return nullptr; 18334 } 18335 if (DepModifier && 18336 (DepKind == OMPC_DEPEND_source || DepKind == OMPC_DEPEND_sink)) { 18337 Diag(DepModifier->getExprLoc(), 18338 diag::err_omp_depend_sink_source_with_modifier); 18339 return nullptr; 18340 } 18341 if (DepModifier && 18342 !DepModifier->getType()->isSpecificBuiltinType(BuiltinType::OMPIterator)) 18343 Diag(DepModifier->getExprLoc(), diag::err_omp_depend_modifier_not_iterator); 18344 18345 SmallVector<Expr *, 8> Vars; 18346 DSAStackTy::OperatorOffsetTy OpsOffs; 18347 llvm::APSInt DepCounter(/*BitWidth=*/32); 18348 llvm::APSInt TotalDepCount(/*BitWidth=*/32); 18349 if (DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) { 18350 if (const Expr *OrderedCountExpr = 18351 DSAStack->getParentOrderedRegionParam().first) { 18352 TotalDepCount = OrderedCountExpr->EvaluateKnownConstInt(Context); 18353 TotalDepCount.setIsUnsigned(/*Val=*/true); 18354 } 18355 } 18356 for (Expr *RefExpr : VarList) { 18357 assert(RefExpr && "NULL expr in OpenMP shared clause."); 18358 if (isa<DependentScopeDeclRefExpr>(RefExpr)) { 18359 // It will be analyzed later. 18360 Vars.push_back(RefExpr); 18361 continue; 18362 } 18363 18364 SourceLocation ELoc = RefExpr->getExprLoc(); 18365 Expr *SimpleExpr = RefExpr->IgnoreParenCasts(); 18366 if (DepKind == OMPC_DEPEND_sink) { 18367 if (DSAStack->getParentOrderedRegionParam().first && 18368 DepCounter >= TotalDepCount) { 18369 Diag(ELoc, diag::err_omp_depend_sink_unexpected_expr); 18370 continue; 18371 } 18372 ++DepCounter; 18373 // OpenMP [2.13.9, Summary] 18374 // depend(dependence-type : vec), where dependence-type is: 18375 // 'sink' and where vec is the iteration vector, which has the form: 18376 // x1 [+- d1], x2 [+- d2 ], . . . , xn [+- dn] 18377 // where n is the value specified by the ordered clause in the loop 18378 // directive, xi denotes the loop iteration variable of the i-th nested 18379 // loop associated with the loop directive, and di is a constant 18380 // non-negative integer. 18381 if (CurContext->isDependentContext()) { 18382 // It will be analyzed later. 18383 Vars.push_back(RefExpr); 18384 continue; 18385 } 18386 SimpleExpr = SimpleExpr->IgnoreImplicit(); 18387 OverloadedOperatorKind OOK = OO_None; 18388 SourceLocation OOLoc; 18389 Expr *LHS = SimpleExpr; 18390 Expr *RHS = nullptr; 18391 if (auto *BO = dyn_cast<BinaryOperator>(SimpleExpr)) { 18392 OOK = BinaryOperator::getOverloadedOperator(BO->getOpcode()); 18393 OOLoc = BO->getOperatorLoc(); 18394 LHS = BO->getLHS()->IgnoreParenImpCasts(); 18395 RHS = BO->getRHS()->IgnoreParenImpCasts(); 18396 } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(SimpleExpr)) { 18397 OOK = OCE->getOperator(); 18398 OOLoc = OCE->getOperatorLoc(); 18399 LHS = OCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts(); 18400 RHS = OCE->getArg(/*Arg=*/1)->IgnoreParenImpCasts(); 18401 } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SimpleExpr)) { 18402 OOK = MCE->getMethodDecl() 18403 ->getNameInfo() 18404 .getName() 18405 .getCXXOverloadedOperator(); 18406 OOLoc = MCE->getCallee()->getExprLoc(); 18407 LHS = MCE->getImplicitObjectArgument()->IgnoreParenImpCasts(); 18408 RHS = MCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts(); 18409 } 18410 SourceLocation ELoc; 18411 SourceRange ERange; 18412 auto Res = getPrivateItem(*this, LHS, ELoc, ERange); 18413 if (Res.second) { 18414 // It will be analyzed later. 18415 Vars.push_back(RefExpr); 18416 } 18417 ValueDecl *D = Res.first; 18418 if (!D) 18419 continue; 18420 18421 if (OOK != OO_Plus && OOK != OO_Minus && (RHS || OOK != OO_None)) { 18422 Diag(OOLoc, diag::err_omp_depend_sink_expected_plus_minus); 18423 continue; 18424 } 18425 if (RHS) { 18426 ExprResult RHSRes = VerifyPositiveIntegerConstantInClause( 18427 RHS, OMPC_depend, /*StrictlyPositive=*/false); 18428 if (RHSRes.isInvalid()) 18429 continue; 18430 } 18431 if (!CurContext->isDependentContext() && 18432 DSAStack->getParentOrderedRegionParam().first && 18433 DepCounter != DSAStack->isParentLoopControlVariable(D).first) { 18434 const ValueDecl *VD = 18435 DSAStack->getParentLoopControlVariable(DepCounter.getZExtValue()); 18436 if (VD) 18437 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration) 18438 << 1 << VD; 18439 else 18440 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration) << 0; 18441 continue; 18442 } 18443 OpsOffs.emplace_back(RHS, OOK); 18444 } else { 18445 bool OMPDependTFound = LangOpts.OpenMP >= 50; 18446 if (OMPDependTFound) 18447 OMPDependTFound = findOMPDependT(*this, StartLoc, DSAStack, 18448 DepKind == OMPC_DEPEND_depobj); 18449 if (DepKind == OMPC_DEPEND_depobj) { 18450 // OpenMP 5.0, 2.17.11 depend Clause, Restrictions, C/C++ 18451 // List items used in depend clauses with the depobj dependence type 18452 // must be expressions of the omp_depend_t type. 18453 if (!RefExpr->isValueDependent() && !RefExpr->isTypeDependent() && 18454 !RefExpr->isInstantiationDependent() && 18455 !RefExpr->containsUnexpandedParameterPack() && 18456 (OMPDependTFound && 18457 !Context.hasSameUnqualifiedType(DSAStack->getOMPDependT(), 18458 RefExpr->getType()))) { 18459 Diag(ELoc, diag::err_omp_expected_omp_depend_t_lvalue) 18460 << 0 << RefExpr->getType() << RefExpr->getSourceRange(); 18461 continue; 18462 } 18463 if (!RefExpr->isLValue()) { 18464 Diag(ELoc, diag::err_omp_expected_omp_depend_t_lvalue) 18465 << 1 << RefExpr->getType() << RefExpr->getSourceRange(); 18466 continue; 18467 } 18468 } else { 18469 // OpenMP 5.0 [2.17.11, Restrictions] 18470 // List items used in depend clauses cannot be zero-length array 18471 // sections. 18472 QualType ExprTy = RefExpr->getType().getNonReferenceType(); 18473 const auto *OASE = dyn_cast<OMPArraySectionExpr>(SimpleExpr); 18474 if (OASE) { 18475 QualType BaseType = 18476 OMPArraySectionExpr::getBaseOriginalType(OASE->getBase()); 18477 if (const auto *ATy = BaseType->getAsArrayTypeUnsafe()) 18478 ExprTy = ATy->getElementType(); 18479 else 18480 ExprTy = BaseType->getPointeeType(); 18481 ExprTy = ExprTy.getNonReferenceType(); 18482 const Expr *Length = OASE->getLength(); 18483 Expr::EvalResult Result; 18484 if (Length && !Length->isValueDependent() && 18485 Length->EvaluateAsInt(Result, Context) && 18486 Result.Val.getInt().isZero()) { 18487 Diag(ELoc, 18488 diag::err_omp_depend_zero_length_array_section_not_allowed) 18489 << SimpleExpr->getSourceRange(); 18490 continue; 18491 } 18492 } 18493 18494 // OpenMP 5.0, 2.17.11 depend Clause, Restrictions, C/C++ 18495 // List items used in depend clauses with the in, out, inout or 18496 // mutexinoutset dependence types cannot be expressions of the 18497 // omp_depend_t type. 18498 if (!RefExpr->isValueDependent() && !RefExpr->isTypeDependent() && 18499 !RefExpr->isInstantiationDependent() && 18500 !RefExpr->containsUnexpandedParameterPack() && 18501 (OMPDependTFound && 18502 DSAStack->getOMPDependT().getTypePtr() == ExprTy.getTypePtr())) { 18503 Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item) 18504 << (LangOpts.OpenMP >= 50 ? 1 : 0) << 1 18505 << RefExpr->getSourceRange(); 18506 continue; 18507 } 18508 18509 auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr); 18510 if (!RefExpr->IgnoreParenImpCasts()->isLValue() || 18511 (ASE && !ASE->getBase()->isTypeDependent() && 18512 !ASE->getBase() 18513 ->getType() 18514 .getNonReferenceType() 18515 ->isPointerType() && 18516 !ASE->getBase()->getType().getNonReferenceType()->isArrayType())) { 18517 Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item) 18518 << (LangOpts.OpenMP >= 50 ? 1 : 0) 18519 << (LangOpts.OpenMP >= 50 ? 1 : 0) << RefExpr->getSourceRange(); 18520 continue; 18521 } 18522 18523 ExprResult Res; 18524 { 18525 Sema::TentativeAnalysisScope Trap(*this); 18526 Res = CreateBuiltinUnaryOp(ELoc, UO_AddrOf, 18527 RefExpr->IgnoreParenImpCasts()); 18528 } 18529 if (!Res.isUsable() && !isa<OMPArraySectionExpr>(SimpleExpr) && 18530 !isa<OMPArrayShapingExpr>(SimpleExpr)) { 18531 Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item) 18532 << (LangOpts.OpenMP >= 50 ? 1 : 0) 18533 << (LangOpts.OpenMP >= 50 ? 1 : 0) << RefExpr->getSourceRange(); 18534 continue; 18535 } 18536 } 18537 } 18538 Vars.push_back(RefExpr->IgnoreParenImpCasts()); 18539 } 18540 18541 if (!CurContext->isDependentContext() && DepKind == OMPC_DEPEND_sink && 18542 TotalDepCount > VarList.size() && 18543 DSAStack->getParentOrderedRegionParam().first && 18544 DSAStack->getParentLoopControlVariable(VarList.size() + 1)) { 18545 Diag(EndLoc, diag::err_omp_depend_sink_expected_loop_iteration) 18546 << 1 << DSAStack->getParentLoopControlVariable(VarList.size() + 1); 18547 } 18548 if (DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink && 18549 Vars.empty()) 18550 return nullptr; 18551 18552 auto *C = OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc, 18553 DepModifier, DepKind, DepLoc, ColonLoc, 18554 Vars, TotalDepCount.getZExtValue()); 18555 if ((DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) && 18556 DSAStack->isParentOrderedRegion()) 18557 DSAStack->addDoacrossDependClause(C, OpsOffs); 18558 return C; 18559 } 18560 18561 OMPClause *Sema::ActOnOpenMPDeviceClause(OpenMPDeviceClauseModifier Modifier, 18562 Expr *Device, SourceLocation StartLoc, 18563 SourceLocation LParenLoc, 18564 SourceLocation ModifierLoc, 18565 SourceLocation EndLoc) { 18566 assert((ModifierLoc.isInvalid() || LangOpts.OpenMP >= 50) && 18567 "Unexpected device modifier in OpenMP < 50."); 18568 18569 bool ErrorFound = false; 18570 if (ModifierLoc.isValid() && Modifier == OMPC_DEVICE_unknown) { 18571 std::string Values = 18572 getListOfPossibleValues(OMPC_device, /*First=*/0, OMPC_DEVICE_unknown); 18573 Diag(ModifierLoc, diag::err_omp_unexpected_clause_value) 18574 << Values << getOpenMPClauseName(OMPC_device); 18575 ErrorFound = true; 18576 } 18577 18578 Expr *ValExpr = Device; 18579 Stmt *HelperValStmt = nullptr; 18580 18581 // OpenMP [2.9.1, Restrictions] 18582 // The device expression must evaluate to a non-negative integer value. 18583 ErrorFound = !isNonNegativeIntegerValue(ValExpr, *this, OMPC_device, 18584 /*StrictlyPositive=*/false) || 18585 ErrorFound; 18586 if (ErrorFound) 18587 return nullptr; 18588 18589 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective(); 18590 OpenMPDirectiveKind CaptureRegion = 18591 getOpenMPCaptureRegionForClause(DKind, OMPC_device, LangOpts.OpenMP); 18592 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) { 18593 ValExpr = MakeFullExpr(ValExpr).get(); 18594 llvm::MapVector<const Expr *, DeclRefExpr *> Captures; 18595 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 18596 HelperValStmt = buildPreInits(Context, Captures); 18597 } 18598 18599 return new (Context) 18600 OMPDeviceClause(Modifier, ValExpr, HelperValStmt, CaptureRegion, StartLoc, 18601 LParenLoc, ModifierLoc, EndLoc); 18602 } 18603 18604 static bool checkTypeMappable(SourceLocation SL, SourceRange SR, Sema &SemaRef, 18605 DSAStackTy *Stack, QualType QTy, 18606 bool FullCheck = true) { 18607 if (SemaRef.RequireCompleteType(SL, QTy, diag::err_incomplete_type)) 18608 return false; 18609 if (FullCheck && !SemaRef.CurContext->isDependentContext() && 18610 !QTy.isTriviallyCopyableType(SemaRef.Context)) 18611 SemaRef.Diag(SL, diag::warn_omp_non_trivial_type_mapped) << QTy << SR; 18612 return true; 18613 } 18614 18615 /// Return true if it can be proven that the provided array expression 18616 /// (array section or array subscript) does NOT specify the whole size of the 18617 /// array whose base type is \a BaseQTy. 18618 static bool checkArrayExpressionDoesNotReferToWholeSize(Sema &SemaRef, 18619 const Expr *E, 18620 QualType BaseQTy) { 18621 const auto *OASE = dyn_cast<OMPArraySectionExpr>(E); 18622 18623 // If this is an array subscript, it refers to the whole size if the size of 18624 // the dimension is constant and equals 1. Also, an array section assumes the 18625 // format of an array subscript if no colon is used. 18626 if (isa<ArraySubscriptExpr>(E) || 18627 (OASE && OASE->getColonLocFirst().isInvalid())) { 18628 if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr())) 18629 return ATy->getSize().getSExtValue() != 1; 18630 // Size can't be evaluated statically. 18631 return false; 18632 } 18633 18634 assert(OASE && "Expecting array section if not an array subscript."); 18635 const Expr *LowerBound = OASE->getLowerBound(); 18636 const Expr *Length = OASE->getLength(); 18637 18638 // If there is a lower bound that does not evaluates to zero, we are not 18639 // covering the whole dimension. 18640 if (LowerBound) { 18641 Expr::EvalResult Result; 18642 if (!LowerBound->EvaluateAsInt(Result, SemaRef.getASTContext())) 18643 return false; // Can't get the integer value as a constant. 18644 18645 llvm::APSInt ConstLowerBound = Result.Val.getInt(); 18646 if (ConstLowerBound.getSExtValue()) 18647 return true; 18648 } 18649 18650 // If we don't have a length we covering the whole dimension. 18651 if (!Length) 18652 return false; 18653 18654 // If the base is a pointer, we don't have a way to get the size of the 18655 // pointee. 18656 if (BaseQTy->isPointerType()) 18657 return false; 18658 18659 // We can only check if the length is the same as the size of the dimension 18660 // if we have a constant array. 18661 const auto *CATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()); 18662 if (!CATy) 18663 return false; 18664 18665 Expr::EvalResult Result; 18666 if (!Length->EvaluateAsInt(Result, SemaRef.getASTContext())) 18667 return false; // Can't get the integer value as a constant. 18668 18669 llvm::APSInt ConstLength = Result.Val.getInt(); 18670 return CATy->getSize().getSExtValue() != ConstLength.getSExtValue(); 18671 } 18672 18673 // Return true if it can be proven that the provided array expression (array 18674 // section or array subscript) does NOT specify a single element of the array 18675 // whose base type is \a BaseQTy. 18676 static bool checkArrayExpressionDoesNotReferToUnitySize(Sema &SemaRef, 18677 const Expr *E, 18678 QualType BaseQTy) { 18679 const auto *OASE = dyn_cast<OMPArraySectionExpr>(E); 18680 18681 // An array subscript always refer to a single element. Also, an array section 18682 // assumes the format of an array subscript if no colon is used. 18683 if (isa<ArraySubscriptExpr>(E) || 18684 (OASE && OASE->getColonLocFirst().isInvalid())) 18685 return false; 18686 18687 assert(OASE && "Expecting array section if not an array subscript."); 18688 const Expr *Length = OASE->getLength(); 18689 18690 // If we don't have a length we have to check if the array has unitary size 18691 // for this dimension. Also, we should always expect a length if the base type 18692 // is pointer. 18693 if (!Length) { 18694 if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr())) 18695 return ATy->getSize().getSExtValue() != 1; 18696 // We cannot assume anything. 18697 return false; 18698 } 18699 18700 // Check if the length evaluates to 1. 18701 Expr::EvalResult Result; 18702 if (!Length->EvaluateAsInt(Result, SemaRef.getASTContext())) 18703 return false; // Can't get the integer value as a constant. 18704 18705 llvm::APSInt ConstLength = Result.Val.getInt(); 18706 return ConstLength.getSExtValue() != 1; 18707 } 18708 18709 // The base of elements of list in a map clause have to be either: 18710 // - a reference to variable or field. 18711 // - a member expression. 18712 // - an array expression. 18713 // 18714 // E.g. if we have the expression 'r.S.Arr[:12]', we want to retrieve the 18715 // reference to 'r'. 18716 // 18717 // If we have: 18718 // 18719 // struct SS { 18720 // Bla S; 18721 // foo() { 18722 // #pragma omp target map (S.Arr[:12]); 18723 // } 18724 // } 18725 // 18726 // We want to retrieve the member expression 'this->S'; 18727 18728 // OpenMP 5.0 [2.19.7.1, map Clause, Restrictions, p.2] 18729 // If a list item is an array section, it must specify contiguous storage. 18730 // 18731 // For this restriction it is sufficient that we make sure only references 18732 // to variables or fields and array expressions, and that no array sections 18733 // exist except in the rightmost expression (unless they cover the whole 18734 // dimension of the array). E.g. these would be invalid: 18735 // 18736 // r.ArrS[3:5].Arr[6:7] 18737 // 18738 // r.ArrS[3:5].x 18739 // 18740 // but these would be valid: 18741 // r.ArrS[3].Arr[6:7] 18742 // 18743 // r.ArrS[3].x 18744 namespace { 18745 class MapBaseChecker final : public StmtVisitor<MapBaseChecker, bool> { 18746 Sema &SemaRef; 18747 OpenMPClauseKind CKind = OMPC_unknown; 18748 OpenMPDirectiveKind DKind = OMPD_unknown; 18749 OMPClauseMappableExprCommon::MappableExprComponentList &Components; 18750 bool IsNonContiguous = false; 18751 bool NoDiagnose = false; 18752 const Expr *RelevantExpr = nullptr; 18753 bool AllowUnitySizeArraySection = true; 18754 bool AllowWholeSizeArraySection = true; 18755 bool AllowAnotherPtr = true; 18756 SourceLocation ELoc; 18757 SourceRange ERange; 18758 18759 void emitErrorMsg() { 18760 // If nothing else worked, this is not a valid map clause expression. 18761 if (SemaRef.getLangOpts().OpenMP < 50) { 18762 SemaRef.Diag(ELoc, 18763 diag::err_omp_expected_named_var_member_or_array_expression) 18764 << ERange; 18765 } else { 18766 SemaRef.Diag(ELoc, diag::err_omp_non_lvalue_in_map_or_motion_clauses) 18767 << getOpenMPClauseName(CKind) << ERange; 18768 } 18769 } 18770 18771 public: 18772 bool VisitDeclRefExpr(DeclRefExpr *DRE) { 18773 if (!isa<VarDecl>(DRE->getDecl())) { 18774 emitErrorMsg(); 18775 return false; 18776 } 18777 assert(!RelevantExpr && "RelevantExpr is expected to be nullptr"); 18778 RelevantExpr = DRE; 18779 // Record the component. 18780 Components.emplace_back(DRE, DRE->getDecl(), IsNonContiguous); 18781 return true; 18782 } 18783 18784 bool VisitMemberExpr(MemberExpr *ME) { 18785 Expr *E = ME; 18786 Expr *BaseE = ME->getBase()->IgnoreParenCasts(); 18787 18788 if (isa<CXXThisExpr>(BaseE)) { 18789 assert(!RelevantExpr && "RelevantExpr is expected to be nullptr"); 18790 // We found a base expression: this->Val. 18791 RelevantExpr = ME; 18792 } else { 18793 E = BaseE; 18794 } 18795 18796 if (!isa<FieldDecl>(ME->getMemberDecl())) { 18797 if (!NoDiagnose) { 18798 SemaRef.Diag(ELoc, diag::err_omp_expected_access_to_data_field) 18799 << ME->getSourceRange(); 18800 return false; 18801 } 18802 if (RelevantExpr) 18803 return false; 18804 return Visit(E); 18805 } 18806 18807 auto *FD = cast<FieldDecl>(ME->getMemberDecl()); 18808 18809 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3] 18810 // A bit-field cannot appear in a map clause. 18811 // 18812 if (FD->isBitField()) { 18813 if (!NoDiagnose) { 18814 SemaRef.Diag(ELoc, diag::err_omp_bit_fields_forbidden_in_clause) 18815 << ME->getSourceRange() << getOpenMPClauseName(CKind); 18816 return false; 18817 } 18818 if (RelevantExpr) 18819 return false; 18820 return Visit(E); 18821 } 18822 18823 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1] 18824 // If the type of a list item is a reference to a type T then the type 18825 // will be considered to be T for all purposes of this clause. 18826 QualType CurType = BaseE->getType().getNonReferenceType(); 18827 18828 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.2] 18829 // A list item cannot be a variable that is a member of a structure with 18830 // a union type. 18831 // 18832 if (CurType->isUnionType()) { 18833 if (!NoDiagnose) { 18834 SemaRef.Diag(ELoc, diag::err_omp_union_type_not_allowed) 18835 << ME->getSourceRange(); 18836 return false; 18837 } 18838 return RelevantExpr || Visit(E); 18839 } 18840 18841 // If we got a member expression, we should not expect any array section 18842 // before that: 18843 // 18844 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.7] 18845 // If a list item is an element of a structure, only the rightmost symbol 18846 // of the variable reference can be an array section. 18847 // 18848 AllowUnitySizeArraySection = false; 18849 AllowWholeSizeArraySection = false; 18850 18851 // Record the component. 18852 Components.emplace_back(ME, FD, IsNonContiguous); 18853 return RelevantExpr || Visit(E); 18854 } 18855 18856 bool VisitArraySubscriptExpr(ArraySubscriptExpr *AE) { 18857 Expr *E = AE->getBase()->IgnoreParenImpCasts(); 18858 18859 if (!E->getType()->isAnyPointerType() && !E->getType()->isArrayType()) { 18860 if (!NoDiagnose) { 18861 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name) 18862 << 0 << AE->getSourceRange(); 18863 return false; 18864 } 18865 return RelevantExpr || Visit(E); 18866 } 18867 18868 // If we got an array subscript that express the whole dimension we 18869 // can have any array expressions before. If it only expressing part of 18870 // the dimension, we can only have unitary-size array expressions. 18871 if (checkArrayExpressionDoesNotReferToWholeSize(SemaRef, AE, 18872 E->getType())) 18873 AllowWholeSizeArraySection = false; 18874 18875 if (const auto *TE = dyn_cast<CXXThisExpr>(E->IgnoreParenCasts())) { 18876 Expr::EvalResult Result; 18877 if (!AE->getIdx()->isValueDependent() && 18878 AE->getIdx()->EvaluateAsInt(Result, SemaRef.getASTContext()) && 18879 !Result.Val.getInt().isZero()) { 18880 SemaRef.Diag(AE->getIdx()->getExprLoc(), 18881 diag::err_omp_invalid_map_this_expr); 18882 SemaRef.Diag(AE->getIdx()->getExprLoc(), 18883 diag::note_omp_invalid_subscript_on_this_ptr_map); 18884 } 18885 assert(!RelevantExpr && "RelevantExpr is expected to be nullptr"); 18886 RelevantExpr = TE; 18887 } 18888 18889 // Record the component - we don't have any declaration associated. 18890 Components.emplace_back(AE, nullptr, IsNonContiguous); 18891 18892 return RelevantExpr || Visit(E); 18893 } 18894 18895 bool VisitOMPArraySectionExpr(OMPArraySectionExpr *OASE) { 18896 // After OMP 5.0 Array section in reduction clause will be implicitly 18897 // mapped 18898 assert(!(SemaRef.getLangOpts().OpenMP < 50 && NoDiagnose) && 18899 "Array sections cannot be implicitly mapped."); 18900 Expr *E = OASE->getBase()->IgnoreParenImpCasts(); 18901 QualType CurType = 18902 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType(); 18903 18904 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1] 18905 // If the type of a list item is a reference to a type T then the type 18906 // will be considered to be T for all purposes of this clause. 18907 if (CurType->isReferenceType()) 18908 CurType = CurType->getPointeeType(); 18909 18910 bool IsPointer = CurType->isAnyPointerType(); 18911 18912 if (!IsPointer && !CurType->isArrayType()) { 18913 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name) 18914 << 0 << OASE->getSourceRange(); 18915 return false; 18916 } 18917 18918 bool NotWhole = 18919 checkArrayExpressionDoesNotReferToWholeSize(SemaRef, OASE, CurType); 18920 bool NotUnity = 18921 checkArrayExpressionDoesNotReferToUnitySize(SemaRef, OASE, CurType); 18922 18923 if (AllowWholeSizeArraySection) { 18924 // Any array section is currently allowed. Allowing a whole size array 18925 // section implies allowing a unity array section as well. 18926 // 18927 // If this array section refers to the whole dimension we can still 18928 // accept other array sections before this one, except if the base is a 18929 // pointer. Otherwise, only unitary sections are accepted. 18930 if (NotWhole || IsPointer) 18931 AllowWholeSizeArraySection = false; 18932 } else if (DKind == OMPD_target_update && 18933 SemaRef.getLangOpts().OpenMP >= 50) { 18934 if (IsPointer && !AllowAnotherPtr) 18935 SemaRef.Diag(ELoc, diag::err_omp_section_length_undefined) 18936 << /*array of unknown bound */ 1; 18937 else 18938 IsNonContiguous = true; 18939 } else if (AllowUnitySizeArraySection && NotUnity) { 18940 // A unity or whole array section is not allowed and that is not 18941 // compatible with the properties of the current array section. 18942 if (NoDiagnose) 18943 return false; 18944 SemaRef.Diag( 18945 ELoc, diag::err_array_section_does_not_specify_contiguous_storage) 18946 << OASE->getSourceRange(); 18947 return false; 18948 } 18949 18950 if (IsPointer) 18951 AllowAnotherPtr = false; 18952 18953 if (const auto *TE = dyn_cast<CXXThisExpr>(E)) { 18954 Expr::EvalResult ResultR; 18955 Expr::EvalResult ResultL; 18956 if (!OASE->getLength()->isValueDependent() && 18957 OASE->getLength()->EvaluateAsInt(ResultR, SemaRef.getASTContext()) && 18958 !ResultR.Val.getInt().isOne()) { 18959 SemaRef.Diag(OASE->getLength()->getExprLoc(), 18960 diag::err_omp_invalid_map_this_expr); 18961 SemaRef.Diag(OASE->getLength()->getExprLoc(), 18962 diag::note_omp_invalid_length_on_this_ptr_mapping); 18963 } 18964 if (OASE->getLowerBound() && !OASE->getLowerBound()->isValueDependent() && 18965 OASE->getLowerBound()->EvaluateAsInt(ResultL, 18966 SemaRef.getASTContext()) && 18967 !ResultL.Val.getInt().isZero()) { 18968 SemaRef.Diag(OASE->getLowerBound()->getExprLoc(), 18969 diag::err_omp_invalid_map_this_expr); 18970 SemaRef.Diag(OASE->getLowerBound()->getExprLoc(), 18971 diag::note_omp_invalid_lower_bound_on_this_ptr_mapping); 18972 } 18973 assert(!RelevantExpr && "RelevantExpr is expected to be nullptr"); 18974 RelevantExpr = TE; 18975 } 18976 18977 // Record the component - we don't have any declaration associated. 18978 Components.emplace_back(OASE, nullptr, /*IsNonContiguous=*/false); 18979 return RelevantExpr || Visit(E); 18980 } 18981 bool VisitOMPArrayShapingExpr(OMPArrayShapingExpr *E) { 18982 Expr *Base = E->getBase(); 18983 18984 // Record the component - we don't have any declaration associated. 18985 Components.emplace_back(E, nullptr, IsNonContiguous); 18986 18987 return Visit(Base->IgnoreParenImpCasts()); 18988 } 18989 18990 bool VisitUnaryOperator(UnaryOperator *UO) { 18991 if (SemaRef.getLangOpts().OpenMP < 50 || !UO->isLValue() || 18992 UO->getOpcode() != UO_Deref) { 18993 emitErrorMsg(); 18994 return false; 18995 } 18996 if (!RelevantExpr) { 18997 // Record the component if haven't found base decl. 18998 Components.emplace_back(UO, nullptr, /*IsNonContiguous=*/false); 18999 } 19000 return RelevantExpr || Visit(UO->getSubExpr()->IgnoreParenImpCasts()); 19001 } 19002 bool VisitBinaryOperator(BinaryOperator *BO) { 19003 if (SemaRef.getLangOpts().OpenMP < 50 || !BO->getType()->isPointerType()) { 19004 emitErrorMsg(); 19005 return false; 19006 } 19007 19008 // Pointer arithmetic is the only thing we expect to happen here so after we 19009 // make sure the binary operator is a pointer type, the we only thing need 19010 // to to is to visit the subtree that has the same type as root (so that we 19011 // know the other subtree is just an offset) 19012 Expr *LE = BO->getLHS()->IgnoreParenImpCasts(); 19013 Expr *RE = BO->getRHS()->IgnoreParenImpCasts(); 19014 Components.emplace_back(BO, nullptr, false); 19015 assert((LE->getType().getTypePtr() == BO->getType().getTypePtr() || 19016 RE->getType().getTypePtr() == BO->getType().getTypePtr()) && 19017 "Either LHS or RHS have base decl inside"); 19018 if (BO->getType().getTypePtr() == LE->getType().getTypePtr()) 19019 return RelevantExpr || Visit(LE); 19020 return RelevantExpr || Visit(RE); 19021 } 19022 bool VisitCXXThisExpr(CXXThisExpr *CTE) { 19023 assert(!RelevantExpr && "RelevantExpr is expected to be nullptr"); 19024 RelevantExpr = CTE; 19025 Components.emplace_back(CTE, nullptr, IsNonContiguous); 19026 return true; 19027 } 19028 bool VisitCXXOperatorCallExpr(CXXOperatorCallExpr *COCE) { 19029 assert(!RelevantExpr && "RelevantExpr is expected to be nullptr"); 19030 Components.emplace_back(COCE, nullptr, IsNonContiguous); 19031 return true; 19032 } 19033 bool VisitOpaqueValueExpr(OpaqueValueExpr *E) { 19034 Expr *Source = E->getSourceExpr(); 19035 if (!Source) { 19036 emitErrorMsg(); 19037 return false; 19038 } 19039 return Visit(Source); 19040 } 19041 bool VisitStmt(Stmt *) { 19042 emitErrorMsg(); 19043 return false; 19044 } 19045 const Expr *getFoundBase() const { 19046 return RelevantExpr; 19047 } 19048 explicit MapBaseChecker( 19049 Sema &SemaRef, OpenMPClauseKind CKind, OpenMPDirectiveKind DKind, 19050 OMPClauseMappableExprCommon::MappableExprComponentList &Components, 19051 bool NoDiagnose, SourceLocation &ELoc, SourceRange &ERange) 19052 : SemaRef(SemaRef), CKind(CKind), DKind(DKind), Components(Components), 19053 NoDiagnose(NoDiagnose), ELoc(ELoc), ERange(ERange) {} 19054 }; 19055 } // namespace 19056 19057 /// Return the expression of the base of the mappable expression or null if it 19058 /// cannot be determined and do all the necessary checks to see if the expression 19059 /// is valid as a standalone mappable expression. In the process, record all the 19060 /// components of the expression. 19061 static const Expr *checkMapClauseExpressionBase( 19062 Sema &SemaRef, Expr *E, 19063 OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents, 19064 OpenMPClauseKind CKind, OpenMPDirectiveKind DKind, bool NoDiagnose) { 19065 SourceLocation ELoc = E->getExprLoc(); 19066 SourceRange ERange = E->getSourceRange(); 19067 MapBaseChecker Checker(SemaRef, CKind, DKind, CurComponents, NoDiagnose, ELoc, 19068 ERange); 19069 if (Checker.Visit(E->IgnoreParens())) { 19070 // Check if the highest dimension array section has length specified 19071 if (SemaRef.getLangOpts().OpenMP >= 50 && !CurComponents.empty() && 19072 (CKind == OMPC_to || CKind == OMPC_from)) { 19073 auto CI = CurComponents.rbegin(); 19074 auto CE = CurComponents.rend(); 19075 for (; CI != CE; ++CI) { 19076 const auto *OASE = 19077 dyn_cast<OMPArraySectionExpr>(CI->getAssociatedExpression()); 19078 if (!OASE) 19079 continue; 19080 if (OASE && OASE->getLength()) 19081 break; 19082 SemaRef.Diag(ELoc, diag::err_array_section_does_not_specify_length) 19083 << ERange; 19084 } 19085 } 19086 return Checker.getFoundBase(); 19087 } 19088 return nullptr; 19089 } 19090 19091 // Return true if expression E associated with value VD has conflicts with other 19092 // map information. 19093 static bool checkMapConflicts( 19094 Sema &SemaRef, DSAStackTy *DSAS, const ValueDecl *VD, const Expr *E, 19095 bool CurrentRegionOnly, 19096 OMPClauseMappableExprCommon::MappableExprComponentListRef CurComponents, 19097 OpenMPClauseKind CKind) { 19098 assert(VD && E); 19099 SourceLocation ELoc = E->getExprLoc(); 19100 SourceRange ERange = E->getSourceRange(); 19101 19102 // In order to easily check the conflicts we need to match each component of 19103 // the expression under test with the components of the expressions that are 19104 // already in the stack. 19105 19106 assert(!CurComponents.empty() && "Map clause expression with no components!"); 19107 assert(CurComponents.back().getAssociatedDeclaration() == VD && 19108 "Map clause expression with unexpected base!"); 19109 19110 // Variables to help detecting enclosing problems in data environment nests. 19111 bool IsEnclosedByDataEnvironmentExpr = false; 19112 const Expr *EnclosingExpr = nullptr; 19113 19114 bool FoundError = DSAS->checkMappableExprComponentListsForDecl( 19115 VD, CurrentRegionOnly, 19116 [&IsEnclosedByDataEnvironmentExpr, &SemaRef, VD, CurrentRegionOnly, ELoc, 19117 ERange, CKind, &EnclosingExpr, 19118 CurComponents](OMPClauseMappableExprCommon::MappableExprComponentListRef 19119 StackComponents, 19120 OpenMPClauseKind Kind) { 19121 if (CKind == Kind && SemaRef.LangOpts.OpenMP >= 50) 19122 return false; 19123 assert(!StackComponents.empty() && 19124 "Map clause expression with no components!"); 19125 assert(StackComponents.back().getAssociatedDeclaration() == VD && 19126 "Map clause expression with unexpected base!"); 19127 (void)VD; 19128 19129 // The whole expression in the stack. 19130 const Expr *RE = StackComponents.front().getAssociatedExpression(); 19131 19132 // Expressions must start from the same base. Here we detect at which 19133 // point both expressions diverge from each other and see if we can 19134 // detect if the memory referred to both expressions is contiguous and 19135 // do not overlap. 19136 auto CI = CurComponents.rbegin(); 19137 auto CE = CurComponents.rend(); 19138 auto SI = StackComponents.rbegin(); 19139 auto SE = StackComponents.rend(); 19140 for (; CI != CE && SI != SE; ++CI, ++SI) { 19141 19142 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.3] 19143 // At most one list item can be an array item derived from a given 19144 // variable in map clauses of the same construct. 19145 if (CurrentRegionOnly && 19146 (isa<ArraySubscriptExpr>(CI->getAssociatedExpression()) || 19147 isa<OMPArraySectionExpr>(CI->getAssociatedExpression()) || 19148 isa<OMPArrayShapingExpr>(CI->getAssociatedExpression())) && 19149 (isa<ArraySubscriptExpr>(SI->getAssociatedExpression()) || 19150 isa<OMPArraySectionExpr>(SI->getAssociatedExpression()) || 19151 isa<OMPArrayShapingExpr>(SI->getAssociatedExpression()))) { 19152 SemaRef.Diag(CI->getAssociatedExpression()->getExprLoc(), 19153 diag::err_omp_multiple_array_items_in_map_clause) 19154 << CI->getAssociatedExpression()->getSourceRange(); 19155 SemaRef.Diag(SI->getAssociatedExpression()->getExprLoc(), 19156 diag::note_used_here) 19157 << SI->getAssociatedExpression()->getSourceRange(); 19158 return true; 19159 } 19160 19161 // Do both expressions have the same kind? 19162 if (CI->getAssociatedExpression()->getStmtClass() != 19163 SI->getAssociatedExpression()->getStmtClass()) 19164 break; 19165 19166 // Are we dealing with different variables/fields? 19167 if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration()) 19168 break; 19169 } 19170 // Check if the extra components of the expressions in the enclosing 19171 // data environment are redundant for the current base declaration. 19172 // If they are, the maps completely overlap, which is legal. 19173 for (; SI != SE; ++SI) { 19174 QualType Type; 19175 if (const auto *ASE = 19176 dyn_cast<ArraySubscriptExpr>(SI->getAssociatedExpression())) { 19177 Type = ASE->getBase()->IgnoreParenImpCasts()->getType(); 19178 } else if (const auto *OASE = dyn_cast<OMPArraySectionExpr>( 19179 SI->getAssociatedExpression())) { 19180 const Expr *E = OASE->getBase()->IgnoreParenImpCasts(); 19181 Type = 19182 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType(); 19183 } else if (const auto *OASE = dyn_cast<OMPArrayShapingExpr>( 19184 SI->getAssociatedExpression())) { 19185 Type = OASE->getBase()->getType()->getPointeeType(); 19186 } 19187 if (Type.isNull() || Type->isAnyPointerType() || 19188 checkArrayExpressionDoesNotReferToWholeSize( 19189 SemaRef, SI->getAssociatedExpression(), Type)) 19190 break; 19191 } 19192 19193 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4] 19194 // List items of map clauses in the same construct must not share 19195 // original storage. 19196 // 19197 // If the expressions are exactly the same or one is a subset of the 19198 // other, it means they are sharing storage. 19199 if (CI == CE && SI == SE) { 19200 if (CurrentRegionOnly) { 19201 if (CKind == OMPC_map) { 19202 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange; 19203 } else { 19204 assert(CKind == OMPC_to || CKind == OMPC_from); 19205 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update) 19206 << ERange; 19207 } 19208 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here) 19209 << RE->getSourceRange(); 19210 return true; 19211 } 19212 // If we find the same expression in the enclosing data environment, 19213 // that is legal. 19214 IsEnclosedByDataEnvironmentExpr = true; 19215 return false; 19216 } 19217 19218 QualType DerivedType = 19219 std::prev(CI)->getAssociatedDeclaration()->getType(); 19220 SourceLocation DerivedLoc = 19221 std::prev(CI)->getAssociatedExpression()->getExprLoc(); 19222 19223 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1] 19224 // If the type of a list item is a reference to a type T then the type 19225 // will be considered to be T for all purposes of this clause. 19226 DerivedType = DerivedType.getNonReferenceType(); 19227 19228 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.1] 19229 // A variable for which the type is pointer and an array section 19230 // derived from that variable must not appear as list items of map 19231 // clauses of the same construct. 19232 // 19233 // Also, cover one of the cases in: 19234 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5] 19235 // If any part of the original storage of a list item has corresponding 19236 // storage in the device data environment, all of the original storage 19237 // must have corresponding storage in the device data environment. 19238 // 19239 if (DerivedType->isAnyPointerType()) { 19240 if (CI == CE || SI == SE) { 19241 SemaRef.Diag( 19242 DerivedLoc, 19243 diag::err_omp_pointer_mapped_along_with_derived_section) 19244 << DerivedLoc; 19245 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here) 19246 << RE->getSourceRange(); 19247 return true; 19248 } 19249 if (CI->getAssociatedExpression()->getStmtClass() != 19250 SI->getAssociatedExpression()->getStmtClass() || 19251 CI->getAssociatedDeclaration()->getCanonicalDecl() == 19252 SI->getAssociatedDeclaration()->getCanonicalDecl()) { 19253 assert(CI != CE && SI != SE); 19254 SemaRef.Diag(DerivedLoc, diag::err_omp_same_pointer_dereferenced) 19255 << DerivedLoc; 19256 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here) 19257 << RE->getSourceRange(); 19258 return true; 19259 } 19260 } 19261 19262 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4] 19263 // List items of map clauses in the same construct must not share 19264 // original storage. 19265 // 19266 // An expression is a subset of the other. 19267 if (CurrentRegionOnly && (CI == CE || SI == SE)) { 19268 if (CKind == OMPC_map) { 19269 if (CI != CE || SI != SE) { 19270 // Allow constructs like this: map(s, s.ptr[0:1]), where s.ptr is 19271 // a pointer. 19272 auto Begin = 19273 CI != CE ? CurComponents.begin() : StackComponents.begin(); 19274 auto End = CI != CE ? CurComponents.end() : StackComponents.end(); 19275 auto It = Begin; 19276 while (It != End && !It->getAssociatedDeclaration()) 19277 std::advance(It, 1); 19278 assert(It != End && 19279 "Expected at least one component with the declaration."); 19280 if (It != Begin && It->getAssociatedDeclaration() 19281 ->getType() 19282 .getCanonicalType() 19283 ->isAnyPointerType()) { 19284 IsEnclosedByDataEnvironmentExpr = false; 19285 EnclosingExpr = nullptr; 19286 return false; 19287 } 19288 } 19289 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange; 19290 } else { 19291 assert(CKind == OMPC_to || CKind == OMPC_from); 19292 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update) 19293 << ERange; 19294 } 19295 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here) 19296 << RE->getSourceRange(); 19297 return true; 19298 } 19299 19300 // The current expression uses the same base as other expression in the 19301 // data environment but does not contain it completely. 19302 if (!CurrentRegionOnly && SI != SE) 19303 EnclosingExpr = RE; 19304 19305 // The current expression is a subset of the expression in the data 19306 // environment. 19307 IsEnclosedByDataEnvironmentExpr |= 19308 (!CurrentRegionOnly && CI != CE && SI == SE); 19309 19310 return false; 19311 }); 19312 19313 if (CurrentRegionOnly) 19314 return FoundError; 19315 19316 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5] 19317 // If any part of the original storage of a list item has corresponding 19318 // storage in the device data environment, all of the original storage must 19319 // have corresponding storage in the device data environment. 19320 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.6] 19321 // If a list item is an element of a structure, and a different element of 19322 // the structure has a corresponding list item in the device data environment 19323 // prior to a task encountering the construct associated with the map clause, 19324 // then the list item must also have a corresponding list item in the device 19325 // data environment prior to the task encountering the construct. 19326 // 19327 if (EnclosingExpr && !IsEnclosedByDataEnvironmentExpr) { 19328 SemaRef.Diag(ELoc, 19329 diag::err_omp_original_storage_is_shared_and_does_not_contain) 19330 << ERange; 19331 SemaRef.Diag(EnclosingExpr->getExprLoc(), diag::note_used_here) 19332 << EnclosingExpr->getSourceRange(); 19333 return true; 19334 } 19335 19336 return FoundError; 19337 } 19338 19339 // Look up the user-defined mapper given the mapper name and mapped type, and 19340 // build a reference to it. 19341 static ExprResult buildUserDefinedMapperRef(Sema &SemaRef, Scope *S, 19342 CXXScopeSpec &MapperIdScopeSpec, 19343 const DeclarationNameInfo &MapperId, 19344 QualType Type, 19345 Expr *UnresolvedMapper) { 19346 if (MapperIdScopeSpec.isInvalid()) 19347 return ExprError(); 19348 // Get the actual type for the array type. 19349 if (Type->isArrayType()) { 19350 assert(Type->getAsArrayTypeUnsafe() && "Expect to get a valid array type"); 19351 Type = Type->getAsArrayTypeUnsafe()->getElementType().getCanonicalType(); 19352 } 19353 // Find all user-defined mappers with the given MapperId. 19354 SmallVector<UnresolvedSet<8>, 4> Lookups; 19355 LookupResult Lookup(SemaRef, MapperId, Sema::LookupOMPMapperName); 19356 Lookup.suppressDiagnostics(); 19357 if (S) { 19358 while (S && SemaRef.LookupParsedName(Lookup, S, &MapperIdScopeSpec)) { 19359 NamedDecl *D = Lookup.getRepresentativeDecl(); 19360 while (S && !S->isDeclScope(D)) 19361 S = S->getParent(); 19362 if (S) 19363 S = S->getParent(); 19364 Lookups.emplace_back(); 19365 Lookups.back().append(Lookup.begin(), Lookup.end()); 19366 Lookup.clear(); 19367 } 19368 } else if (auto *ULE = cast_or_null<UnresolvedLookupExpr>(UnresolvedMapper)) { 19369 // Extract the user-defined mappers with the given MapperId. 19370 Lookups.push_back(UnresolvedSet<8>()); 19371 for (NamedDecl *D : ULE->decls()) { 19372 auto *DMD = cast<OMPDeclareMapperDecl>(D); 19373 assert(DMD && "Expect valid OMPDeclareMapperDecl during instantiation."); 19374 Lookups.back().addDecl(DMD); 19375 } 19376 } 19377 // Defer the lookup for dependent types. The results will be passed through 19378 // UnresolvedMapper on instantiation. 19379 if (SemaRef.CurContext->isDependentContext() || Type->isDependentType() || 19380 Type->isInstantiationDependentType() || 19381 Type->containsUnexpandedParameterPack() || 19382 filterLookupForUDReductionAndMapper<bool>(Lookups, [](ValueDecl *D) { 19383 return !D->isInvalidDecl() && 19384 (D->getType()->isDependentType() || 19385 D->getType()->isInstantiationDependentType() || 19386 D->getType()->containsUnexpandedParameterPack()); 19387 })) { 19388 UnresolvedSet<8> URS; 19389 for (const UnresolvedSet<8> &Set : Lookups) { 19390 if (Set.empty()) 19391 continue; 19392 URS.append(Set.begin(), Set.end()); 19393 } 19394 return UnresolvedLookupExpr::Create( 19395 SemaRef.Context, /*NamingClass=*/nullptr, 19396 MapperIdScopeSpec.getWithLocInContext(SemaRef.Context), MapperId, 19397 /*ADL=*/false, /*Overloaded=*/true, URS.begin(), URS.end()); 19398 } 19399 SourceLocation Loc = MapperId.getLoc(); 19400 // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions 19401 // The type must be of struct, union or class type in C and C++ 19402 if (!Type->isStructureOrClassType() && !Type->isUnionType() && 19403 (MapperIdScopeSpec.isSet() || MapperId.getAsString() != "default")) { 19404 SemaRef.Diag(Loc, diag::err_omp_mapper_wrong_type); 19405 return ExprError(); 19406 } 19407 // Perform argument dependent lookup. 19408 if (SemaRef.getLangOpts().CPlusPlus && !MapperIdScopeSpec.isSet()) 19409 argumentDependentLookup(SemaRef, MapperId, Loc, Type, Lookups); 19410 // Return the first user-defined mapper with the desired type. 19411 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>( 19412 Lookups, [&SemaRef, Type](ValueDecl *D) -> ValueDecl * { 19413 if (!D->isInvalidDecl() && 19414 SemaRef.Context.hasSameType(D->getType(), Type)) 19415 return D; 19416 return nullptr; 19417 })) 19418 return SemaRef.BuildDeclRefExpr(VD, Type, VK_LValue, Loc); 19419 // Find the first user-defined mapper with a type derived from the desired 19420 // type. 19421 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>( 19422 Lookups, [&SemaRef, Type, Loc](ValueDecl *D) -> ValueDecl * { 19423 if (!D->isInvalidDecl() && 19424 SemaRef.IsDerivedFrom(Loc, Type, D->getType()) && 19425 !Type.isMoreQualifiedThan(D->getType())) 19426 return D; 19427 return nullptr; 19428 })) { 19429 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 19430 /*DetectVirtual=*/false); 19431 if (SemaRef.IsDerivedFrom(Loc, Type, VD->getType(), Paths)) { 19432 if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType( 19433 VD->getType().getUnqualifiedType()))) { 19434 if (SemaRef.CheckBaseClassAccess( 19435 Loc, VD->getType(), Type, Paths.front(), 19436 /*DiagID=*/0) != Sema::AR_inaccessible) { 19437 return SemaRef.BuildDeclRefExpr(VD, Type, VK_LValue, Loc); 19438 } 19439 } 19440 } 19441 } 19442 // Report error if a mapper is specified, but cannot be found. 19443 if (MapperIdScopeSpec.isSet() || MapperId.getAsString() != "default") { 19444 SemaRef.Diag(Loc, diag::err_omp_invalid_mapper) 19445 << Type << MapperId.getName(); 19446 return ExprError(); 19447 } 19448 return ExprEmpty(); 19449 } 19450 19451 namespace { 19452 // Utility struct that gathers all the related lists associated with a mappable 19453 // expression. 19454 struct MappableVarListInfo { 19455 // The list of expressions. 19456 ArrayRef<Expr *> VarList; 19457 // The list of processed expressions. 19458 SmallVector<Expr *, 16> ProcessedVarList; 19459 // The mappble components for each expression. 19460 OMPClauseMappableExprCommon::MappableExprComponentLists VarComponents; 19461 // The base declaration of the variable. 19462 SmallVector<ValueDecl *, 16> VarBaseDeclarations; 19463 // The reference to the user-defined mapper associated with every expression. 19464 SmallVector<Expr *, 16> UDMapperList; 19465 19466 MappableVarListInfo(ArrayRef<Expr *> VarList) : VarList(VarList) { 19467 // We have a list of components and base declarations for each entry in the 19468 // variable list. 19469 VarComponents.reserve(VarList.size()); 19470 VarBaseDeclarations.reserve(VarList.size()); 19471 } 19472 }; 19473 } 19474 19475 // Check the validity of the provided variable list for the provided clause kind 19476 // \a CKind. In the check process the valid expressions, mappable expression 19477 // components, variables, and user-defined mappers are extracted and used to 19478 // fill \a ProcessedVarList, \a VarComponents, \a VarBaseDeclarations, and \a 19479 // UDMapperList in MVLI. \a MapType, \a IsMapTypeImplicit, \a MapperIdScopeSpec, 19480 // and \a MapperId are expected to be valid if the clause kind is 'map'. 19481 static void checkMappableExpressionList( 19482 Sema &SemaRef, DSAStackTy *DSAS, OpenMPClauseKind CKind, 19483 MappableVarListInfo &MVLI, SourceLocation StartLoc, 19484 CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo MapperId, 19485 ArrayRef<Expr *> UnresolvedMappers, 19486 OpenMPMapClauseKind MapType = OMPC_MAP_unknown, 19487 ArrayRef<OpenMPMapModifierKind> Modifiers = None, 19488 bool IsMapTypeImplicit = false, bool NoDiagnose = false) { 19489 // We only expect mappable expressions in 'to', 'from', and 'map' clauses. 19490 assert((CKind == OMPC_map || CKind == OMPC_to || CKind == OMPC_from) && 19491 "Unexpected clause kind with mappable expressions!"); 19492 19493 // If the identifier of user-defined mapper is not specified, it is "default". 19494 // We do not change the actual name in this clause to distinguish whether a 19495 // mapper is specified explicitly, i.e., it is not explicitly specified when 19496 // MapperId.getName() is empty. 19497 if (!MapperId.getName() || MapperId.getName().isEmpty()) { 19498 auto &DeclNames = SemaRef.getASTContext().DeclarationNames; 19499 MapperId.setName(DeclNames.getIdentifier( 19500 &SemaRef.getASTContext().Idents.get("default"))); 19501 MapperId.setLoc(StartLoc); 19502 } 19503 19504 // Iterators to find the current unresolved mapper expression. 19505 auto UMIt = UnresolvedMappers.begin(), UMEnd = UnresolvedMappers.end(); 19506 bool UpdateUMIt = false; 19507 Expr *UnresolvedMapper = nullptr; 19508 19509 bool HasHoldModifier = 19510 llvm::is_contained(Modifiers, OMPC_MAP_MODIFIER_ompx_hold); 19511 19512 // Keep track of the mappable components and base declarations in this clause. 19513 // Each entry in the list is going to have a list of components associated. We 19514 // record each set of the components so that we can build the clause later on. 19515 // In the end we should have the same amount of declarations and component 19516 // lists. 19517 19518 for (Expr *RE : MVLI.VarList) { 19519 assert(RE && "Null expr in omp to/from/map clause"); 19520 SourceLocation ELoc = RE->getExprLoc(); 19521 19522 // Find the current unresolved mapper expression. 19523 if (UpdateUMIt && UMIt != UMEnd) { 19524 UMIt++; 19525 assert( 19526 UMIt != UMEnd && 19527 "Expect the size of UnresolvedMappers to match with that of VarList"); 19528 } 19529 UpdateUMIt = true; 19530 if (UMIt != UMEnd) 19531 UnresolvedMapper = *UMIt; 19532 19533 const Expr *VE = RE->IgnoreParenLValueCasts(); 19534 19535 if (VE->isValueDependent() || VE->isTypeDependent() || 19536 VE->isInstantiationDependent() || 19537 VE->containsUnexpandedParameterPack()) { 19538 // Try to find the associated user-defined mapper. 19539 ExprResult ER = buildUserDefinedMapperRef( 19540 SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId, 19541 VE->getType().getCanonicalType(), UnresolvedMapper); 19542 if (ER.isInvalid()) 19543 continue; 19544 MVLI.UDMapperList.push_back(ER.get()); 19545 // We can only analyze this information once the missing information is 19546 // resolved. 19547 MVLI.ProcessedVarList.push_back(RE); 19548 continue; 19549 } 19550 19551 Expr *SimpleExpr = RE->IgnoreParenCasts(); 19552 19553 if (!RE->isLValue()) { 19554 if (SemaRef.getLangOpts().OpenMP < 50) { 19555 SemaRef.Diag( 19556 ELoc, diag::err_omp_expected_named_var_member_or_array_expression) 19557 << RE->getSourceRange(); 19558 } else { 19559 SemaRef.Diag(ELoc, diag::err_omp_non_lvalue_in_map_or_motion_clauses) 19560 << getOpenMPClauseName(CKind) << RE->getSourceRange(); 19561 } 19562 continue; 19563 } 19564 19565 OMPClauseMappableExprCommon::MappableExprComponentList CurComponents; 19566 ValueDecl *CurDeclaration = nullptr; 19567 19568 // Obtain the array or member expression bases if required. Also, fill the 19569 // components array with all the components identified in the process. 19570 const Expr *BE = 19571 checkMapClauseExpressionBase(SemaRef, SimpleExpr, CurComponents, CKind, 19572 DSAS->getCurrentDirective(), NoDiagnose); 19573 if (!BE) 19574 continue; 19575 19576 assert(!CurComponents.empty() && 19577 "Invalid mappable expression information."); 19578 19579 if (const auto *TE = dyn_cast<CXXThisExpr>(BE)) { 19580 // Add store "this" pointer to class in DSAStackTy for future checking 19581 DSAS->addMappedClassesQualTypes(TE->getType()); 19582 // Try to find the associated user-defined mapper. 19583 ExprResult ER = buildUserDefinedMapperRef( 19584 SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId, 19585 VE->getType().getCanonicalType(), UnresolvedMapper); 19586 if (ER.isInvalid()) 19587 continue; 19588 MVLI.UDMapperList.push_back(ER.get()); 19589 // Skip restriction checking for variable or field declarations 19590 MVLI.ProcessedVarList.push_back(RE); 19591 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1); 19592 MVLI.VarComponents.back().append(CurComponents.begin(), 19593 CurComponents.end()); 19594 MVLI.VarBaseDeclarations.push_back(nullptr); 19595 continue; 19596 } 19597 19598 // For the following checks, we rely on the base declaration which is 19599 // expected to be associated with the last component. The declaration is 19600 // expected to be a variable or a field (if 'this' is being mapped). 19601 CurDeclaration = CurComponents.back().getAssociatedDeclaration(); 19602 assert(CurDeclaration && "Null decl on map clause."); 19603 assert( 19604 CurDeclaration->isCanonicalDecl() && 19605 "Expecting components to have associated only canonical declarations."); 19606 19607 auto *VD = dyn_cast<VarDecl>(CurDeclaration); 19608 const auto *FD = dyn_cast<FieldDecl>(CurDeclaration); 19609 19610 assert((VD || FD) && "Only variables or fields are expected here!"); 19611 (void)FD; 19612 19613 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.10] 19614 // threadprivate variables cannot appear in a map clause. 19615 // OpenMP 4.5 [2.10.5, target update Construct] 19616 // threadprivate variables cannot appear in a from clause. 19617 if (VD && DSAS->isThreadPrivate(VD)) { 19618 if (NoDiagnose) 19619 continue; 19620 DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false); 19621 SemaRef.Diag(ELoc, diag::err_omp_threadprivate_in_clause) 19622 << getOpenMPClauseName(CKind); 19623 reportOriginalDsa(SemaRef, DSAS, VD, DVar); 19624 continue; 19625 } 19626 19627 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9] 19628 // A list item cannot appear in both a map clause and a data-sharing 19629 // attribute clause on the same construct. 19630 19631 // Check conflicts with other map clause expressions. We check the conflicts 19632 // with the current construct separately from the enclosing data 19633 // environment, because the restrictions are different. We only have to 19634 // check conflicts across regions for the map clauses. 19635 if (checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr, 19636 /*CurrentRegionOnly=*/true, CurComponents, CKind)) 19637 break; 19638 if (CKind == OMPC_map && 19639 (SemaRef.getLangOpts().OpenMP <= 45 || StartLoc.isValid()) && 19640 checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr, 19641 /*CurrentRegionOnly=*/false, CurComponents, CKind)) 19642 break; 19643 19644 // OpenMP 4.5 [2.10.5, target update Construct] 19645 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1] 19646 // If the type of a list item is a reference to a type T then the type will 19647 // be considered to be T for all purposes of this clause. 19648 auto I = llvm::find_if( 19649 CurComponents, 19650 [](const OMPClauseMappableExprCommon::MappableComponent &MC) { 19651 return MC.getAssociatedDeclaration(); 19652 }); 19653 assert(I != CurComponents.end() && "Null decl on map clause."); 19654 (void)I; 19655 QualType Type; 19656 auto *ASE = dyn_cast<ArraySubscriptExpr>(VE->IgnoreParens()); 19657 auto *OASE = dyn_cast<OMPArraySectionExpr>(VE->IgnoreParens()); 19658 auto *OAShE = dyn_cast<OMPArrayShapingExpr>(VE->IgnoreParens()); 19659 if (ASE) { 19660 Type = ASE->getType().getNonReferenceType(); 19661 } else if (OASE) { 19662 QualType BaseType = 19663 OMPArraySectionExpr::getBaseOriginalType(OASE->getBase()); 19664 if (const auto *ATy = BaseType->getAsArrayTypeUnsafe()) 19665 Type = ATy->getElementType(); 19666 else 19667 Type = BaseType->getPointeeType(); 19668 Type = Type.getNonReferenceType(); 19669 } else if (OAShE) { 19670 Type = OAShE->getBase()->getType()->getPointeeType(); 19671 } else { 19672 Type = VE->getType(); 19673 } 19674 19675 // OpenMP 4.5 [2.10.5, target update Construct, Restrictions, p.4] 19676 // A list item in a to or from clause must have a mappable type. 19677 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9] 19678 // A list item must have a mappable type. 19679 if (!checkTypeMappable(VE->getExprLoc(), VE->getSourceRange(), SemaRef, 19680 DSAS, Type, /*FullCheck=*/true)) 19681 continue; 19682 19683 if (CKind == OMPC_map) { 19684 // target enter data 19685 // OpenMP [2.10.2, Restrictions, p. 99] 19686 // A map-type must be specified in all map clauses and must be either 19687 // to or alloc. 19688 OpenMPDirectiveKind DKind = DSAS->getCurrentDirective(); 19689 if (DKind == OMPD_target_enter_data && 19690 !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_alloc)) { 19691 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive) 19692 << (IsMapTypeImplicit ? 1 : 0) 19693 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType) 19694 << getOpenMPDirectiveName(DKind); 19695 continue; 19696 } 19697 19698 // target exit_data 19699 // OpenMP [2.10.3, Restrictions, p. 102] 19700 // A map-type must be specified in all map clauses and must be either 19701 // from, release, or delete. 19702 if (DKind == OMPD_target_exit_data && 19703 !(MapType == OMPC_MAP_from || MapType == OMPC_MAP_release || 19704 MapType == OMPC_MAP_delete)) { 19705 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive) 19706 << (IsMapTypeImplicit ? 1 : 0) 19707 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType) 19708 << getOpenMPDirectiveName(DKind); 19709 continue; 19710 } 19711 19712 // The 'ompx_hold' modifier is specifically intended to be used on a 19713 // 'target' or 'target data' directive to prevent data from being unmapped 19714 // during the associated statement. It is not permitted on a 'target 19715 // enter data' or 'target exit data' directive, which have no associated 19716 // statement. 19717 if ((DKind == OMPD_target_enter_data || DKind == OMPD_target_exit_data) && 19718 HasHoldModifier) { 19719 SemaRef.Diag(StartLoc, 19720 diag::err_omp_invalid_map_type_modifier_for_directive) 19721 << getOpenMPSimpleClauseTypeName(OMPC_map, 19722 OMPC_MAP_MODIFIER_ompx_hold) 19723 << getOpenMPDirectiveName(DKind); 19724 continue; 19725 } 19726 19727 // target, target data 19728 // OpenMP 5.0 [2.12.2, Restrictions, p. 163] 19729 // OpenMP 5.0 [2.12.5, Restrictions, p. 174] 19730 // A map-type in a map clause must be to, from, tofrom or alloc 19731 if ((DKind == OMPD_target_data || 19732 isOpenMPTargetExecutionDirective(DKind)) && 19733 !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_from || 19734 MapType == OMPC_MAP_tofrom || MapType == OMPC_MAP_alloc)) { 19735 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive) 19736 << (IsMapTypeImplicit ? 1 : 0) 19737 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType) 19738 << getOpenMPDirectiveName(DKind); 19739 continue; 19740 } 19741 19742 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3] 19743 // A list item cannot appear in both a map clause and a data-sharing 19744 // attribute clause on the same construct 19745 // 19746 // OpenMP 5.0 [2.19.7.1, Restrictions, p.7] 19747 // A list item cannot appear in both a map clause and a data-sharing 19748 // attribute clause on the same construct unless the construct is a 19749 // combined construct. 19750 if (VD && ((SemaRef.LangOpts.OpenMP <= 45 && 19751 isOpenMPTargetExecutionDirective(DKind)) || 19752 DKind == OMPD_target)) { 19753 DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false); 19754 if (isOpenMPPrivate(DVar.CKind)) { 19755 SemaRef.Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa) 19756 << getOpenMPClauseName(DVar.CKind) 19757 << getOpenMPClauseName(OMPC_map) 19758 << getOpenMPDirectiveName(DSAS->getCurrentDirective()); 19759 reportOriginalDsa(SemaRef, DSAS, CurDeclaration, DVar); 19760 continue; 19761 } 19762 } 19763 } 19764 19765 // Try to find the associated user-defined mapper. 19766 ExprResult ER = buildUserDefinedMapperRef( 19767 SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId, 19768 Type.getCanonicalType(), UnresolvedMapper); 19769 if (ER.isInvalid()) 19770 continue; 19771 MVLI.UDMapperList.push_back(ER.get()); 19772 19773 // Save the current expression. 19774 MVLI.ProcessedVarList.push_back(RE); 19775 19776 // Store the components in the stack so that they can be used to check 19777 // against other clauses later on. 19778 DSAS->addMappableExpressionComponents(CurDeclaration, CurComponents, 19779 /*WhereFoundClauseKind=*/OMPC_map); 19780 19781 // Save the components and declaration to create the clause. For purposes of 19782 // the clause creation, any component list that has has base 'this' uses 19783 // null as base declaration. 19784 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1); 19785 MVLI.VarComponents.back().append(CurComponents.begin(), 19786 CurComponents.end()); 19787 MVLI.VarBaseDeclarations.push_back(isa<MemberExpr>(BE) ? nullptr 19788 : CurDeclaration); 19789 } 19790 } 19791 19792 OMPClause *Sema::ActOnOpenMPMapClause( 19793 ArrayRef<OpenMPMapModifierKind> MapTypeModifiers, 19794 ArrayRef<SourceLocation> MapTypeModifiersLoc, 19795 CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo &MapperId, 19796 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit, SourceLocation MapLoc, 19797 SourceLocation ColonLoc, ArrayRef<Expr *> VarList, 19798 const OMPVarListLocTy &Locs, bool NoDiagnose, 19799 ArrayRef<Expr *> UnresolvedMappers) { 19800 OpenMPMapModifierKind Modifiers[] = { 19801 OMPC_MAP_MODIFIER_unknown, OMPC_MAP_MODIFIER_unknown, 19802 OMPC_MAP_MODIFIER_unknown, OMPC_MAP_MODIFIER_unknown, 19803 OMPC_MAP_MODIFIER_unknown}; 19804 SourceLocation ModifiersLoc[NumberOfOMPMapClauseModifiers]; 19805 19806 // Process map-type-modifiers, flag errors for duplicate modifiers. 19807 unsigned Count = 0; 19808 for (unsigned I = 0, E = MapTypeModifiers.size(); I < E; ++I) { 19809 if (MapTypeModifiers[I] != OMPC_MAP_MODIFIER_unknown && 19810 llvm::is_contained(Modifiers, MapTypeModifiers[I])) { 19811 Diag(MapTypeModifiersLoc[I], diag::err_omp_duplicate_map_type_modifier); 19812 continue; 19813 } 19814 assert(Count < NumberOfOMPMapClauseModifiers && 19815 "Modifiers exceed the allowed number of map type modifiers"); 19816 Modifiers[Count] = MapTypeModifiers[I]; 19817 ModifiersLoc[Count] = MapTypeModifiersLoc[I]; 19818 ++Count; 19819 } 19820 19821 MappableVarListInfo MVLI(VarList); 19822 checkMappableExpressionList(*this, DSAStack, OMPC_map, MVLI, Locs.StartLoc, 19823 MapperIdScopeSpec, MapperId, UnresolvedMappers, 19824 MapType, Modifiers, IsMapTypeImplicit, 19825 NoDiagnose); 19826 19827 // We need to produce a map clause even if we don't have variables so that 19828 // other diagnostics related with non-existing map clauses are accurate. 19829 return OMPMapClause::Create(Context, Locs, MVLI.ProcessedVarList, 19830 MVLI.VarBaseDeclarations, MVLI.VarComponents, 19831 MVLI.UDMapperList, Modifiers, ModifiersLoc, 19832 MapperIdScopeSpec.getWithLocInContext(Context), 19833 MapperId, MapType, IsMapTypeImplicit, MapLoc); 19834 } 19835 19836 QualType Sema::ActOnOpenMPDeclareReductionType(SourceLocation TyLoc, 19837 TypeResult ParsedType) { 19838 assert(ParsedType.isUsable()); 19839 19840 QualType ReductionType = GetTypeFromParser(ParsedType.get()); 19841 if (ReductionType.isNull()) 19842 return QualType(); 19843 19844 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions, C\C++ 19845 // A type name in a declare reduction directive cannot be a function type, an 19846 // array type, a reference type, or a type qualified with const, volatile or 19847 // restrict. 19848 if (ReductionType.hasQualifiers()) { 19849 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 0; 19850 return QualType(); 19851 } 19852 19853 if (ReductionType->isFunctionType()) { 19854 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 1; 19855 return QualType(); 19856 } 19857 if (ReductionType->isReferenceType()) { 19858 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 2; 19859 return QualType(); 19860 } 19861 if (ReductionType->isArrayType()) { 19862 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 3; 19863 return QualType(); 19864 } 19865 return ReductionType; 19866 } 19867 19868 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveStart( 19869 Scope *S, DeclContext *DC, DeclarationName Name, 19870 ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes, 19871 AccessSpecifier AS, Decl *PrevDeclInScope) { 19872 SmallVector<Decl *, 8> Decls; 19873 Decls.reserve(ReductionTypes.size()); 19874 19875 LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPReductionName, 19876 forRedeclarationInCurContext()); 19877 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions 19878 // A reduction-identifier may not be re-declared in the current scope for the 19879 // same type or for a type that is compatible according to the base language 19880 // rules. 19881 llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes; 19882 OMPDeclareReductionDecl *PrevDRD = nullptr; 19883 bool InCompoundScope = true; 19884 if (S != nullptr) { 19885 // Find previous declaration with the same name not referenced in other 19886 // declarations. 19887 FunctionScopeInfo *ParentFn = getEnclosingFunction(); 19888 InCompoundScope = 19889 (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty(); 19890 LookupName(Lookup, S); 19891 FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false, 19892 /*AllowInlineNamespace=*/false); 19893 llvm::DenseMap<OMPDeclareReductionDecl *, bool> UsedAsPrevious; 19894 LookupResult::Filter Filter = Lookup.makeFilter(); 19895 while (Filter.hasNext()) { 19896 auto *PrevDecl = cast<OMPDeclareReductionDecl>(Filter.next()); 19897 if (InCompoundScope) { 19898 auto I = UsedAsPrevious.find(PrevDecl); 19899 if (I == UsedAsPrevious.end()) 19900 UsedAsPrevious[PrevDecl] = false; 19901 if (OMPDeclareReductionDecl *D = PrevDecl->getPrevDeclInScope()) 19902 UsedAsPrevious[D] = true; 19903 } 19904 PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] = 19905 PrevDecl->getLocation(); 19906 } 19907 Filter.done(); 19908 if (InCompoundScope) { 19909 for (const auto &PrevData : UsedAsPrevious) { 19910 if (!PrevData.second) { 19911 PrevDRD = PrevData.first; 19912 break; 19913 } 19914 } 19915 } 19916 } else if (PrevDeclInScope != nullptr) { 19917 auto *PrevDRDInScope = PrevDRD = 19918 cast<OMPDeclareReductionDecl>(PrevDeclInScope); 19919 do { 19920 PreviousRedeclTypes[PrevDRDInScope->getType().getCanonicalType()] = 19921 PrevDRDInScope->getLocation(); 19922 PrevDRDInScope = PrevDRDInScope->getPrevDeclInScope(); 19923 } while (PrevDRDInScope != nullptr); 19924 } 19925 for (const auto &TyData : ReductionTypes) { 19926 const auto I = PreviousRedeclTypes.find(TyData.first.getCanonicalType()); 19927 bool Invalid = false; 19928 if (I != PreviousRedeclTypes.end()) { 19929 Diag(TyData.second, diag::err_omp_declare_reduction_redefinition) 19930 << TyData.first; 19931 Diag(I->second, diag::note_previous_definition); 19932 Invalid = true; 19933 } 19934 PreviousRedeclTypes[TyData.first.getCanonicalType()] = TyData.second; 19935 auto *DRD = OMPDeclareReductionDecl::Create(Context, DC, TyData.second, 19936 Name, TyData.first, PrevDRD); 19937 DC->addDecl(DRD); 19938 DRD->setAccess(AS); 19939 Decls.push_back(DRD); 19940 if (Invalid) 19941 DRD->setInvalidDecl(); 19942 else 19943 PrevDRD = DRD; 19944 } 19945 19946 return DeclGroupPtrTy::make( 19947 DeclGroupRef::Create(Context, Decls.begin(), Decls.size())); 19948 } 19949 19950 void Sema::ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D) { 19951 auto *DRD = cast<OMPDeclareReductionDecl>(D); 19952 19953 // Enter new function scope. 19954 PushFunctionScope(); 19955 setFunctionHasBranchProtectedScope(); 19956 getCurFunction()->setHasOMPDeclareReductionCombiner(); 19957 19958 if (S != nullptr) 19959 PushDeclContext(S, DRD); 19960 else 19961 CurContext = DRD; 19962 19963 PushExpressionEvaluationContext( 19964 ExpressionEvaluationContext::PotentiallyEvaluated); 19965 19966 QualType ReductionType = DRD->getType(); 19967 // Create 'T* omp_parm;T omp_in;'. All references to 'omp_in' will 19968 // be replaced by '*omp_parm' during codegen. This required because 'omp_in' 19969 // uses semantics of argument handles by value, but it should be passed by 19970 // reference. C lang does not support references, so pass all parameters as 19971 // pointers. 19972 // Create 'T omp_in;' variable. 19973 VarDecl *OmpInParm = 19974 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_in"); 19975 // Create 'T* omp_parm;T omp_out;'. All references to 'omp_out' will 19976 // be replaced by '*omp_parm' during codegen. This required because 'omp_out' 19977 // uses semantics of argument handles by value, but it should be passed by 19978 // reference. C lang does not support references, so pass all parameters as 19979 // pointers. 19980 // Create 'T omp_out;' variable. 19981 VarDecl *OmpOutParm = 19982 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_out"); 19983 if (S != nullptr) { 19984 PushOnScopeChains(OmpInParm, S); 19985 PushOnScopeChains(OmpOutParm, S); 19986 } else { 19987 DRD->addDecl(OmpInParm); 19988 DRD->addDecl(OmpOutParm); 19989 } 19990 Expr *InE = 19991 ::buildDeclRefExpr(*this, OmpInParm, ReductionType, D->getLocation()); 19992 Expr *OutE = 19993 ::buildDeclRefExpr(*this, OmpOutParm, ReductionType, D->getLocation()); 19994 DRD->setCombinerData(InE, OutE); 19995 } 19996 19997 void Sema::ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner) { 19998 auto *DRD = cast<OMPDeclareReductionDecl>(D); 19999 DiscardCleanupsInEvaluationContext(); 20000 PopExpressionEvaluationContext(); 20001 20002 PopDeclContext(); 20003 PopFunctionScopeInfo(); 20004 20005 if (Combiner != nullptr) 20006 DRD->setCombiner(Combiner); 20007 else 20008 DRD->setInvalidDecl(); 20009 } 20010 20011 VarDecl *Sema::ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D) { 20012 auto *DRD = cast<OMPDeclareReductionDecl>(D); 20013 20014 // Enter new function scope. 20015 PushFunctionScope(); 20016 setFunctionHasBranchProtectedScope(); 20017 20018 if (S != nullptr) 20019 PushDeclContext(S, DRD); 20020 else 20021 CurContext = DRD; 20022 20023 PushExpressionEvaluationContext( 20024 ExpressionEvaluationContext::PotentiallyEvaluated); 20025 20026 QualType ReductionType = DRD->getType(); 20027 // Create 'T* omp_parm;T omp_priv;'. All references to 'omp_priv' will 20028 // be replaced by '*omp_parm' during codegen. This required because 'omp_priv' 20029 // uses semantics of argument handles by value, but it should be passed by 20030 // reference. C lang does not support references, so pass all parameters as 20031 // pointers. 20032 // Create 'T omp_priv;' variable. 20033 VarDecl *OmpPrivParm = 20034 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_priv"); 20035 // Create 'T* omp_parm;T omp_orig;'. All references to 'omp_orig' will 20036 // be replaced by '*omp_parm' during codegen. This required because 'omp_orig' 20037 // uses semantics of argument handles by value, but it should be passed by 20038 // reference. C lang does not support references, so pass all parameters as 20039 // pointers. 20040 // Create 'T omp_orig;' variable. 20041 VarDecl *OmpOrigParm = 20042 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_orig"); 20043 if (S != nullptr) { 20044 PushOnScopeChains(OmpPrivParm, S); 20045 PushOnScopeChains(OmpOrigParm, S); 20046 } else { 20047 DRD->addDecl(OmpPrivParm); 20048 DRD->addDecl(OmpOrigParm); 20049 } 20050 Expr *OrigE = 20051 ::buildDeclRefExpr(*this, OmpOrigParm, ReductionType, D->getLocation()); 20052 Expr *PrivE = 20053 ::buildDeclRefExpr(*this, OmpPrivParm, ReductionType, D->getLocation()); 20054 DRD->setInitializerData(OrigE, PrivE); 20055 return OmpPrivParm; 20056 } 20057 20058 void Sema::ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer, 20059 VarDecl *OmpPrivParm) { 20060 auto *DRD = cast<OMPDeclareReductionDecl>(D); 20061 DiscardCleanupsInEvaluationContext(); 20062 PopExpressionEvaluationContext(); 20063 20064 PopDeclContext(); 20065 PopFunctionScopeInfo(); 20066 20067 if (Initializer != nullptr) { 20068 DRD->setInitializer(Initializer, OMPDeclareReductionDecl::CallInit); 20069 } else if (OmpPrivParm->hasInit()) { 20070 DRD->setInitializer(OmpPrivParm->getInit(), 20071 OmpPrivParm->isDirectInit() 20072 ? OMPDeclareReductionDecl::DirectInit 20073 : OMPDeclareReductionDecl::CopyInit); 20074 } else { 20075 DRD->setInvalidDecl(); 20076 } 20077 } 20078 20079 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveEnd( 20080 Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid) { 20081 for (Decl *D : DeclReductions.get()) { 20082 if (IsValid) { 20083 if (S) 20084 PushOnScopeChains(cast<OMPDeclareReductionDecl>(D), S, 20085 /*AddToContext=*/false); 20086 } else { 20087 D->setInvalidDecl(); 20088 } 20089 } 20090 return DeclReductions; 20091 } 20092 20093 TypeResult Sema::ActOnOpenMPDeclareMapperVarDecl(Scope *S, Declarator &D) { 20094 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 20095 QualType T = TInfo->getType(); 20096 if (D.isInvalidType()) 20097 return true; 20098 20099 if (getLangOpts().CPlusPlus) { 20100 // Check that there are no default arguments (C++ only). 20101 CheckExtraCXXDefaultArguments(D); 20102 } 20103 20104 return CreateParsedType(T, TInfo); 20105 } 20106 20107 QualType Sema::ActOnOpenMPDeclareMapperType(SourceLocation TyLoc, 20108 TypeResult ParsedType) { 20109 assert(ParsedType.isUsable() && "Expect usable parsed mapper type"); 20110 20111 QualType MapperType = GetTypeFromParser(ParsedType.get()); 20112 assert(!MapperType.isNull() && "Expect valid mapper type"); 20113 20114 // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions 20115 // The type must be of struct, union or class type in C and C++ 20116 if (!MapperType->isStructureOrClassType() && !MapperType->isUnionType()) { 20117 Diag(TyLoc, diag::err_omp_mapper_wrong_type); 20118 return QualType(); 20119 } 20120 return MapperType; 20121 } 20122 20123 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareMapperDirective( 20124 Scope *S, DeclContext *DC, DeclarationName Name, QualType MapperType, 20125 SourceLocation StartLoc, DeclarationName VN, AccessSpecifier AS, 20126 Expr *MapperVarRef, ArrayRef<OMPClause *> Clauses, Decl *PrevDeclInScope) { 20127 LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPMapperName, 20128 forRedeclarationInCurContext()); 20129 // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions 20130 // A mapper-identifier may not be redeclared in the current scope for the 20131 // same type or for a type that is compatible according to the base language 20132 // rules. 20133 llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes; 20134 OMPDeclareMapperDecl *PrevDMD = nullptr; 20135 bool InCompoundScope = true; 20136 if (S != nullptr) { 20137 // Find previous declaration with the same name not referenced in other 20138 // declarations. 20139 FunctionScopeInfo *ParentFn = getEnclosingFunction(); 20140 InCompoundScope = 20141 (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty(); 20142 LookupName(Lookup, S); 20143 FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false, 20144 /*AllowInlineNamespace=*/false); 20145 llvm::DenseMap<OMPDeclareMapperDecl *, bool> UsedAsPrevious; 20146 LookupResult::Filter Filter = Lookup.makeFilter(); 20147 while (Filter.hasNext()) { 20148 auto *PrevDecl = cast<OMPDeclareMapperDecl>(Filter.next()); 20149 if (InCompoundScope) { 20150 auto I = UsedAsPrevious.find(PrevDecl); 20151 if (I == UsedAsPrevious.end()) 20152 UsedAsPrevious[PrevDecl] = false; 20153 if (OMPDeclareMapperDecl *D = PrevDecl->getPrevDeclInScope()) 20154 UsedAsPrevious[D] = true; 20155 } 20156 PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] = 20157 PrevDecl->getLocation(); 20158 } 20159 Filter.done(); 20160 if (InCompoundScope) { 20161 for (const auto &PrevData : UsedAsPrevious) { 20162 if (!PrevData.second) { 20163 PrevDMD = PrevData.first; 20164 break; 20165 } 20166 } 20167 } 20168 } else if (PrevDeclInScope) { 20169 auto *PrevDMDInScope = PrevDMD = 20170 cast<OMPDeclareMapperDecl>(PrevDeclInScope); 20171 do { 20172 PreviousRedeclTypes[PrevDMDInScope->getType().getCanonicalType()] = 20173 PrevDMDInScope->getLocation(); 20174 PrevDMDInScope = PrevDMDInScope->getPrevDeclInScope(); 20175 } while (PrevDMDInScope != nullptr); 20176 } 20177 const auto I = PreviousRedeclTypes.find(MapperType.getCanonicalType()); 20178 bool Invalid = false; 20179 if (I != PreviousRedeclTypes.end()) { 20180 Diag(StartLoc, diag::err_omp_declare_mapper_redefinition) 20181 << MapperType << Name; 20182 Diag(I->second, diag::note_previous_definition); 20183 Invalid = true; 20184 } 20185 // Build expressions for implicit maps of data members with 'default' 20186 // mappers. 20187 SmallVector<OMPClause *, 4> ClausesWithImplicit(Clauses.begin(), 20188 Clauses.end()); 20189 if (LangOpts.OpenMP >= 50) 20190 processImplicitMapsWithDefaultMappers(*this, DSAStack, ClausesWithImplicit); 20191 auto *DMD = 20192 OMPDeclareMapperDecl::Create(Context, DC, StartLoc, Name, MapperType, VN, 20193 ClausesWithImplicit, PrevDMD); 20194 if (S) 20195 PushOnScopeChains(DMD, S); 20196 else 20197 DC->addDecl(DMD); 20198 DMD->setAccess(AS); 20199 if (Invalid) 20200 DMD->setInvalidDecl(); 20201 20202 auto *VD = cast<DeclRefExpr>(MapperVarRef)->getDecl(); 20203 VD->setDeclContext(DMD); 20204 VD->setLexicalDeclContext(DMD); 20205 DMD->addDecl(VD); 20206 DMD->setMapperVarRef(MapperVarRef); 20207 20208 return DeclGroupPtrTy::make(DeclGroupRef(DMD)); 20209 } 20210 20211 ExprResult 20212 Sema::ActOnOpenMPDeclareMapperDirectiveVarDecl(Scope *S, QualType MapperType, 20213 SourceLocation StartLoc, 20214 DeclarationName VN) { 20215 TypeSourceInfo *TInfo = 20216 Context.getTrivialTypeSourceInfo(MapperType, StartLoc); 20217 auto *VD = VarDecl::Create(Context, Context.getTranslationUnitDecl(), 20218 StartLoc, StartLoc, VN.getAsIdentifierInfo(), 20219 MapperType, TInfo, SC_None); 20220 if (S) 20221 PushOnScopeChains(VD, S, /*AddToContext=*/false); 20222 Expr *E = buildDeclRefExpr(*this, VD, MapperType, StartLoc); 20223 DSAStack->addDeclareMapperVarRef(E); 20224 return E; 20225 } 20226 20227 bool Sema::isOpenMPDeclareMapperVarDeclAllowed(const VarDecl *VD) const { 20228 assert(LangOpts.OpenMP && "Expected OpenMP mode."); 20229 const Expr *Ref = DSAStack->getDeclareMapperVarRef(); 20230 if (const auto *DRE = cast_or_null<DeclRefExpr>(Ref)) { 20231 if (VD->getCanonicalDecl() == DRE->getDecl()->getCanonicalDecl()) 20232 return true; 20233 if (VD->isUsableInConstantExpressions(Context)) 20234 return true; 20235 return false; 20236 } 20237 return true; 20238 } 20239 20240 const ValueDecl *Sema::getOpenMPDeclareMapperVarName() const { 20241 assert(LangOpts.OpenMP && "Expected OpenMP mode."); 20242 return cast<DeclRefExpr>(DSAStack->getDeclareMapperVarRef())->getDecl(); 20243 } 20244 20245 OMPClause *Sema::ActOnOpenMPNumTeamsClause(Expr *NumTeams, 20246 SourceLocation StartLoc, 20247 SourceLocation LParenLoc, 20248 SourceLocation EndLoc) { 20249 Expr *ValExpr = NumTeams; 20250 Stmt *HelperValStmt = nullptr; 20251 20252 // OpenMP [teams Constrcut, Restrictions] 20253 // The num_teams expression must evaluate to a positive integer value. 20254 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_teams, 20255 /*StrictlyPositive=*/true)) 20256 return nullptr; 20257 20258 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective(); 20259 OpenMPDirectiveKind CaptureRegion = 20260 getOpenMPCaptureRegionForClause(DKind, OMPC_num_teams, LangOpts.OpenMP); 20261 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) { 20262 ValExpr = MakeFullExpr(ValExpr).get(); 20263 llvm::MapVector<const Expr *, DeclRefExpr *> Captures; 20264 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 20265 HelperValStmt = buildPreInits(Context, Captures); 20266 } 20267 20268 return new (Context) OMPNumTeamsClause(ValExpr, HelperValStmt, CaptureRegion, 20269 StartLoc, LParenLoc, EndLoc); 20270 } 20271 20272 OMPClause *Sema::ActOnOpenMPThreadLimitClause(Expr *ThreadLimit, 20273 SourceLocation StartLoc, 20274 SourceLocation LParenLoc, 20275 SourceLocation EndLoc) { 20276 Expr *ValExpr = ThreadLimit; 20277 Stmt *HelperValStmt = nullptr; 20278 20279 // OpenMP [teams Constrcut, Restrictions] 20280 // The thread_limit expression must evaluate to a positive integer value. 20281 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_thread_limit, 20282 /*StrictlyPositive=*/true)) 20283 return nullptr; 20284 20285 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective(); 20286 OpenMPDirectiveKind CaptureRegion = getOpenMPCaptureRegionForClause( 20287 DKind, OMPC_thread_limit, LangOpts.OpenMP); 20288 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) { 20289 ValExpr = MakeFullExpr(ValExpr).get(); 20290 llvm::MapVector<const Expr *, DeclRefExpr *> Captures; 20291 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 20292 HelperValStmt = buildPreInits(Context, Captures); 20293 } 20294 20295 return new (Context) OMPThreadLimitClause( 20296 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc); 20297 } 20298 20299 OMPClause *Sema::ActOnOpenMPPriorityClause(Expr *Priority, 20300 SourceLocation StartLoc, 20301 SourceLocation LParenLoc, 20302 SourceLocation EndLoc) { 20303 Expr *ValExpr = Priority; 20304 Stmt *HelperValStmt = nullptr; 20305 OpenMPDirectiveKind CaptureRegion = OMPD_unknown; 20306 20307 // OpenMP [2.9.1, task Constrcut] 20308 // The priority-value is a non-negative numerical scalar expression. 20309 if (!isNonNegativeIntegerValue( 20310 ValExpr, *this, OMPC_priority, 20311 /*StrictlyPositive=*/false, /*BuildCapture=*/true, 20312 DSAStack->getCurrentDirective(), &CaptureRegion, &HelperValStmt)) 20313 return nullptr; 20314 20315 return new (Context) OMPPriorityClause(ValExpr, HelperValStmt, CaptureRegion, 20316 StartLoc, LParenLoc, EndLoc); 20317 } 20318 20319 OMPClause *Sema::ActOnOpenMPGrainsizeClause(Expr *Grainsize, 20320 SourceLocation StartLoc, 20321 SourceLocation LParenLoc, 20322 SourceLocation EndLoc) { 20323 Expr *ValExpr = Grainsize; 20324 Stmt *HelperValStmt = nullptr; 20325 OpenMPDirectiveKind CaptureRegion = OMPD_unknown; 20326 20327 // OpenMP [2.9.2, taskloop Constrcut] 20328 // The parameter of the grainsize clause must be a positive integer 20329 // expression. 20330 if (!isNonNegativeIntegerValue( 20331 ValExpr, *this, OMPC_grainsize, 20332 /*StrictlyPositive=*/true, /*BuildCapture=*/true, 20333 DSAStack->getCurrentDirective(), &CaptureRegion, &HelperValStmt)) 20334 return nullptr; 20335 20336 return new (Context) OMPGrainsizeClause(ValExpr, HelperValStmt, CaptureRegion, 20337 StartLoc, LParenLoc, EndLoc); 20338 } 20339 20340 OMPClause *Sema::ActOnOpenMPNumTasksClause(Expr *NumTasks, 20341 SourceLocation StartLoc, 20342 SourceLocation LParenLoc, 20343 SourceLocation EndLoc) { 20344 Expr *ValExpr = NumTasks; 20345 Stmt *HelperValStmt = nullptr; 20346 OpenMPDirectiveKind CaptureRegion = OMPD_unknown; 20347 20348 // OpenMP [2.9.2, taskloop Constrcut] 20349 // The parameter of the num_tasks clause must be a positive integer 20350 // expression. 20351 if (!isNonNegativeIntegerValue( 20352 ValExpr, *this, OMPC_num_tasks, 20353 /*StrictlyPositive=*/true, /*BuildCapture=*/true, 20354 DSAStack->getCurrentDirective(), &CaptureRegion, &HelperValStmt)) 20355 return nullptr; 20356 20357 return new (Context) OMPNumTasksClause(ValExpr, HelperValStmt, CaptureRegion, 20358 StartLoc, LParenLoc, EndLoc); 20359 } 20360 20361 OMPClause *Sema::ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc, 20362 SourceLocation LParenLoc, 20363 SourceLocation EndLoc) { 20364 // OpenMP [2.13.2, critical construct, Description] 20365 // ... where hint-expression is an integer constant expression that evaluates 20366 // to a valid lock hint. 20367 ExprResult HintExpr = VerifyPositiveIntegerConstantInClause(Hint, OMPC_hint); 20368 if (HintExpr.isInvalid()) 20369 return nullptr; 20370 return new (Context) 20371 OMPHintClause(HintExpr.get(), StartLoc, LParenLoc, EndLoc); 20372 } 20373 20374 /// Tries to find omp_event_handle_t type. 20375 static bool findOMPEventHandleT(Sema &S, SourceLocation Loc, 20376 DSAStackTy *Stack) { 20377 QualType OMPEventHandleT = Stack->getOMPEventHandleT(); 20378 if (!OMPEventHandleT.isNull()) 20379 return true; 20380 IdentifierInfo *II = &S.PP.getIdentifierTable().get("omp_event_handle_t"); 20381 ParsedType PT = S.getTypeName(*II, Loc, S.getCurScope()); 20382 if (!PT.getAsOpaquePtr() || PT.get().isNull()) { 20383 S.Diag(Loc, diag::err_omp_implied_type_not_found) << "omp_event_handle_t"; 20384 return false; 20385 } 20386 Stack->setOMPEventHandleT(PT.get()); 20387 return true; 20388 } 20389 20390 OMPClause *Sema::ActOnOpenMPDetachClause(Expr *Evt, SourceLocation StartLoc, 20391 SourceLocation LParenLoc, 20392 SourceLocation EndLoc) { 20393 if (!Evt->isValueDependent() && !Evt->isTypeDependent() && 20394 !Evt->isInstantiationDependent() && 20395 !Evt->containsUnexpandedParameterPack()) { 20396 if (!findOMPEventHandleT(*this, Evt->getExprLoc(), DSAStack)) 20397 return nullptr; 20398 // OpenMP 5.0, 2.10.1 task Construct. 20399 // event-handle is a variable of the omp_event_handle_t type. 20400 auto *Ref = dyn_cast<DeclRefExpr>(Evt->IgnoreParenImpCasts()); 20401 if (!Ref) { 20402 Diag(Evt->getExprLoc(), diag::err_omp_var_expected) 20403 << "omp_event_handle_t" << 0 << Evt->getSourceRange(); 20404 return nullptr; 20405 } 20406 auto *VD = dyn_cast_or_null<VarDecl>(Ref->getDecl()); 20407 if (!VD) { 20408 Diag(Evt->getExprLoc(), diag::err_omp_var_expected) 20409 << "omp_event_handle_t" << 0 << Evt->getSourceRange(); 20410 return nullptr; 20411 } 20412 if (!Context.hasSameUnqualifiedType(DSAStack->getOMPEventHandleT(), 20413 VD->getType()) || 20414 VD->getType().isConstant(Context)) { 20415 Diag(Evt->getExprLoc(), diag::err_omp_var_expected) 20416 << "omp_event_handle_t" << 1 << VD->getType() 20417 << Evt->getSourceRange(); 20418 return nullptr; 20419 } 20420 // OpenMP 5.0, 2.10.1 task Construct 20421 // [detach clause]... The event-handle will be considered as if it was 20422 // specified on a firstprivate clause. 20423 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, /*FromParent=*/false); 20424 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate && 20425 DVar.RefExpr) { 20426 Diag(Evt->getExprLoc(), diag::err_omp_wrong_dsa) 20427 << getOpenMPClauseName(DVar.CKind) 20428 << getOpenMPClauseName(OMPC_firstprivate); 20429 reportOriginalDsa(*this, DSAStack, VD, DVar); 20430 return nullptr; 20431 } 20432 } 20433 20434 return new (Context) OMPDetachClause(Evt, StartLoc, LParenLoc, EndLoc); 20435 } 20436 20437 OMPClause *Sema::ActOnOpenMPDistScheduleClause( 20438 OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc, 20439 SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc, 20440 SourceLocation EndLoc) { 20441 if (Kind == OMPC_DIST_SCHEDULE_unknown) { 20442 std::string Values; 20443 Values += "'"; 20444 Values += getOpenMPSimpleClauseTypeName(OMPC_dist_schedule, 0); 20445 Values += "'"; 20446 Diag(KindLoc, diag::err_omp_unexpected_clause_value) 20447 << Values << getOpenMPClauseName(OMPC_dist_schedule); 20448 return nullptr; 20449 } 20450 Expr *ValExpr = ChunkSize; 20451 Stmt *HelperValStmt = nullptr; 20452 if (ChunkSize) { 20453 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() && 20454 !ChunkSize->isInstantiationDependent() && 20455 !ChunkSize->containsUnexpandedParameterPack()) { 20456 SourceLocation ChunkSizeLoc = ChunkSize->getBeginLoc(); 20457 ExprResult Val = 20458 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize); 20459 if (Val.isInvalid()) 20460 return nullptr; 20461 20462 ValExpr = Val.get(); 20463 20464 // OpenMP [2.7.1, Restrictions] 20465 // chunk_size must be a loop invariant integer expression with a positive 20466 // value. 20467 if (Optional<llvm::APSInt> Result = 20468 ValExpr->getIntegerConstantExpr(Context)) { 20469 if (Result->isSigned() && !Result->isStrictlyPositive()) { 20470 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause) 20471 << "dist_schedule" << ChunkSize->getSourceRange(); 20472 return nullptr; 20473 } 20474 } else if (getOpenMPCaptureRegionForClause( 20475 DSAStack->getCurrentDirective(), OMPC_dist_schedule, 20476 LangOpts.OpenMP) != OMPD_unknown && 20477 !CurContext->isDependentContext()) { 20478 ValExpr = MakeFullExpr(ValExpr).get(); 20479 llvm::MapVector<const Expr *, DeclRefExpr *> Captures; 20480 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 20481 HelperValStmt = buildPreInits(Context, Captures); 20482 } 20483 } 20484 } 20485 20486 return new (Context) 20487 OMPDistScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, 20488 Kind, ValExpr, HelperValStmt); 20489 } 20490 20491 OMPClause *Sema::ActOnOpenMPDefaultmapClause( 20492 OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind, 20493 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc, 20494 SourceLocation KindLoc, SourceLocation EndLoc) { 20495 if (getLangOpts().OpenMP < 50) { 20496 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom || 20497 Kind != OMPC_DEFAULTMAP_scalar) { 20498 std::string Value; 20499 SourceLocation Loc; 20500 Value += "'"; 20501 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom) { 20502 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap, 20503 OMPC_DEFAULTMAP_MODIFIER_tofrom); 20504 Loc = MLoc; 20505 } else { 20506 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap, 20507 OMPC_DEFAULTMAP_scalar); 20508 Loc = KindLoc; 20509 } 20510 Value += "'"; 20511 Diag(Loc, diag::err_omp_unexpected_clause_value) 20512 << Value << getOpenMPClauseName(OMPC_defaultmap); 20513 return nullptr; 20514 } 20515 } else { 20516 bool isDefaultmapModifier = (M != OMPC_DEFAULTMAP_MODIFIER_unknown); 20517 bool isDefaultmapKind = (Kind != OMPC_DEFAULTMAP_unknown) || 20518 (LangOpts.OpenMP >= 50 && KindLoc.isInvalid()); 20519 if (!isDefaultmapKind || !isDefaultmapModifier) { 20520 StringRef KindValue = "'scalar', 'aggregate', 'pointer'"; 20521 if (LangOpts.OpenMP == 50) { 20522 StringRef ModifierValue = "'alloc', 'from', 'to', 'tofrom', " 20523 "'firstprivate', 'none', 'default'"; 20524 if (!isDefaultmapKind && isDefaultmapModifier) { 20525 Diag(KindLoc, diag::err_omp_unexpected_clause_value) 20526 << KindValue << getOpenMPClauseName(OMPC_defaultmap); 20527 } else if (isDefaultmapKind && !isDefaultmapModifier) { 20528 Diag(MLoc, diag::err_omp_unexpected_clause_value) 20529 << ModifierValue << getOpenMPClauseName(OMPC_defaultmap); 20530 } else { 20531 Diag(MLoc, diag::err_omp_unexpected_clause_value) 20532 << ModifierValue << getOpenMPClauseName(OMPC_defaultmap); 20533 Diag(KindLoc, diag::err_omp_unexpected_clause_value) 20534 << KindValue << getOpenMPClauseName(OMPC_defaultmap); 20535 } 20536 } else { 20537 StringRef ModifierValue = 20538 "'alloc', 'from', 'to', 'tofrom', " 20539 "'firstprivate', 'none', 'default', 'present'"; 20540 if (!isDefaultmapKind && isDefaultmapModifier) { 20541 Diag(KindLoc, diag::err_omp_unexpected_clause_value) 20542 << KindValue << getOpenMPClauseName(OMPC_defaultmap); 20543 } else if (isDefaultmapKind && !isDefaultmapModifier) { 20544 Diag(MLoc, diag::err_omp_unexpected_clause_value) 20545 << ModifierValue << getOpenMPClauseName(OMPC_defaultmap); 20546 } else { 20547 Diag(MLoc, diag::err_omp_unexpected_clause_value) 20548 << ModifierValue << getOpenMPClauseName(OMPC_defaultmap); 20549 Diag(KindLoc, diag::err_omp_unexpected_clause_value) 20550 << KindValue << getOpenMPClauseName(OMPC_defaultmap); 20551 } 20552 } 20553 return nullptr; 20554 } 20555 20556 // OpenMP [5.0, 2.12.5, Restrictions, p. 174] 20557 // At most one defaultmap clause for each category can appear on the 20558 // directive. 20559 if (DSAStack->checkDefaultmapCategory(Kind)) { 20560 Diag(StartLoc, diag::err_omp_one_defaultmap_each_category); 20561 return nullptr; 20562 } 20563 } 20564 if (Kind == OMPC_DEFAULTMAP_unknown) { 20565 // Variable category is not specified - mark all categories. 20566 DSAStack->setDefaultDMAAttr(M, OMPC_DEFAULTMAP_aggregate, StartLoc); 20567 DSAStack->setDefaultDMAAttr(M, OMPC_DEFAULTMAP_scalar, StartLoc); 20568 DSAStack->setDefaultDMAAttr(M, OMPC_DEFAULTMAP_pointer, StartLoc); 20569 } else { 20570 DSAStack->setDefaultDMAAttr(M, Kind, StartLoc); 20571 } 20572 20573 return new (Context) 20574 OMPDefaultmapClause(StartLoc, LParenLoc, MLoc, KindLoc, EndLoc, Kind, M); 20575 } 20576 20577 bool Sema::ActOnStartOpenMPDeclareTargetContext( 20578 DeclareTargetContextInfo &DTCI) { 20579 DeclContext *CurLexicalContext = getCurLexicalContext(); 20580 if (!CurLexicalContext->isFileContext() && 20581 !CurLexicalContext->isExternCContext() && 20582 !CurLexicalContext->isExternCXXContext() && 20583 !isa<CXXRecordDecl>(CurLexicalContext) && 20584 !isa<ClassTemplateDecl>(CurLexicalContext) && 20585 !isa<ClassTemplatePartialSpecializationDecl>(CurLexicalContext) && 20586 !isa<ClassTemplateSpecializationDecl>(CurLexicalContext)) { 20587 Diag(DTCI.Loc, diag::err_omp_region_not_file_context); 20588 return false; 20589 } 20590 DeclareTargetNesting.push_back(DTCI); 20591 return true; 20592 } 20593 20594 const Sema::DeclareTargetContextInfo 20595 Sema::ActOnOpenMPEndDeclareTargetDirective() { 20596 assert(!DeclareTargetNesting.empty() && 20597 "check isInOpenMPDeclareTargetContext() first!"); 20598 return DeclareTargetNesting.pop_back_val(); 20599 } 20600 20601 void Sema::ActOnFinishedOpenMPDeclareTargetContext( 20602 DeclareTargetContextInfo &DTCI) { 20603 for (auto &It : DTCI.ExplicitlyMapped) 20604 ActOnOpenMPDeclareTargetName(It.first, It.second.Loc, It.second.MT, 20605 DTCI.DT); 20606 } 20607 20608 NamedDecl *Sema::lookupOpenMPDeclareTargetName(Scope *CurScope, 20609 CXXScopeSpec &ScopeSpec, 20610 const DeclarationNameInfo &Id) { 20611 LookupResult Lookup(*this, Id, LookupOrdinaryName); 20612 LookupParsedName(Lookup, CurScope, &ScopeSpec, true); 20613 20614 if (Lookup.isAmbiguous()) 20615 return nullptr; 20616 Lookup.suppressDiagnostics(); 20617 20618 if (!Lookup.isSingleResult()) { 20619 VarOrFuncDeclFilterCCC CCC(*this); 20620 if (TypoCorrection Corrected = 20621 CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr, CCC, 20622 CTK_ErrorRecovery)) { 20623 diagnoseTypo(Corrected, PDiag(diag::err_undeclared_var_use_suggest) 20624 << Id.getName()); 20625 checkDeclIsAllowedInOpenMPTarget(nullptr, Corrected.getCorrectionDecl()); 20626 return nullptr; 20627 } 20628 20629 Diag(Id.getLoc(), diag::err_undeclared_var_use) << Id.getName(); 20630 return nullptr; 20631 } 20632 20633 NamedDecl *ND = Lookup.getAsSingle<NamedDecl>(); 20634 if (!isa<VarDecl>(ND) && !isa<FunctionDecl>(ND) && 20635 !isa<FunctionTemplateDecl>(ND)) { 20636 Diag(Id.getLoc(), diag::err_omp_invalid_target_decl) << Id.getName(); 20637 return nullptr; 20638 } 20639 return ND; 20640 } 20641 20642 void Sema::ActOnOpenMPDeclareTargetName( 20643 NamedDecl *ND, SourceLocation Loc, OMPDeclareTargetDeclAttr::MapTypeTy MT, 20644 OMPDeclareTargetDeclAttr::DevTypeTy DT) { 20645 assert((isa<VarDecl>(ND) || isa<FunctionDecl>(ND) || 20646 isa<FunctionTemplateDecl>(ND)) && 20647 "Expected variable, function or function template."); 20648 20649 // Diagnose marking after use as it may lead to incorrect diagnosis and 20650 // codegen. 20651 if (LangOpts.OpenMP >= 50 && 20652 (ND->isUsed(/*CheckUsedAttr=*/false) || ND->isReferenced())) 20653 Diag(Loc, diag::warn_omp_declare_target_after_first_use); 20654 20655 // Explicit declare target lists have precedence. 20656 const unsigned Level = -1; 20657 20658 auto *VD = cast<ValueDecl>(ND); 20659 llvm::Optional<OMPDeclareTargetDeclAttr *> ActiveAttr = 20660 OMPDeclareTargetDeclAttr::getActiveAttr(VD); 20661 if (ActiveAttr.hasValue() && ActiveAttr.getValue()->getDevType() != DT && 20662 ActiveAttr.getValue()->getLevel() == Level) { 20663 Diag(Loc, diag::err_omp_device_type_mismatch) 20664 << OMPDeclareTargetDeclAttr::ConvertDevTypeTyToStr(DT) 20665 << OMPDeclareTargetDeclAttr::ConvertDevTypeTyToStr( 20666 ActiveAttr.getValue()->getDevType()); 20667 return; 20668 } 20669 if (ActiveAttr.hasValue() && ActiveAttr.getValue()->getMapType() != MT && 20670 ActiveAttr.getValue()->getLevel() == Level) { 20671 Diag(Loc, diag::err_omp_declare_target_to_and_link) << ND; 20672 return; 20673 } 20674 20675 if (ActiveAttr.hasValue() && ActiveAttr.getValue()->getLevel() == Level) 20676 return; 20677 20678 auto *A = OMPDeclareTargetDeclAttr::CreateImplicit(Context, MT, DT, Level, 20679 SourceRange(Loc, Loc)); 20680 ND->addAttr(A); 20681 if (ASTMutationListener *ML = Context.getASTMutationListener()) 20682 ML->DeclarationMarkedOpenMPDeclareTarget(ND, A); 20683 checkDeclIsAllowedInOpenMPTarget(nullptr, ND, Loc); 20684 } 20685 20686 static void checkDeclInTargetContext(SourceLocation SL, SourceRange SR, 20687 Sema &SemaRef, Decl *D) { 20688 if (!D || !isa<VarDecl>(D)) 20689 return; 20690 auto *VD = cast<VarDecl>(D); 20691 Optional<OMPDeclareTargetDeclAttr::MapTypeTy> MapTy = 20692 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD); 20693 if (SemaRef.LangOpts.OpenMP >= 50 && 20694 (SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true) || 20695 SemaRef.getCurBlock() || SemaRef.getCurCapturedRegion()) && 20696 VD->hasGlobalStorage()) { 20697 if (!MapTy || *MapTy != OMPDeclareTargetDeclAttr::MT_To) { 20698 // OpenMP 5.0, 2.12.7 declare target Directive, Restrictions 20699 // If a lambda declaration and definition appears between a 20700 // declare target directive and the matching end declare target 20701 // directive, all variables that are captured by the lambda 20702 // expression must also appear in a to clause. 20703 SemaRef.Diag(VD->getLocation(), 20704 diag::err_omp_lambda_capture_in_declare_target_not_to); 20705 SemaRef.Diag(SL, diag::note_var_explicitly_captured_here) 20706 << VD << 0 << SR; 20707 return; 20708 } 20709 } 20710 if (MapTy.hasValue()) 20711 return; 20712 SemaRef.Diag(VD->getLocation(), diag::warn_omp_not_in_target_context); 20713 SemaRef.Diag(SL, diag::note_used_here) << SR; 20714 } 20715 20716 static bool checkValueDeclInTarget(SourceLocation SL, SourceRange SR, 20717 Sema &SemaRef, DSAStackTy *Stack, 20718 ValueDecl *VD) { 20719 return OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD) || 20720 checkTypeMappable(SL, SR, SemaRef, Stack, VD->getType(), 20721 /*FullCheck=*/false); 20722 } 20723 20724 void Sema::checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D, 20725 SourceLocation IdLoc) { 20726 if (!D || D->isInvalidDecl()) 20727 return; 20728 SourceRange SR = E ? E->getSourceRange() : D->getSourceRange(); 20729 SourceLocation SL = E ? E->getBeginLoc() : D->getLocation(); 20730 if (auto *VD = dyn_cast<VarDecl>(D)) { 20731 // Only global variables can be marked as declare target. 20732 if (!VD->isFileVarDecl() && !VD->isStaticLocal() && 20733 !VD->isStaticDataMember()) 20734 return; 20735 // 2.10.6: threadprivate variable cannot appear in a declare target 20736 // directive. 20737 if (DSAStack->isThreadPrivate(VD)) { 20738 Diag(SL, diag::err_omp_threadprivate_in_target); 20739 reportOriginalDsa(*this, DSAStack, VD, DSAStack->getTopDSA(VD, false)); 20740 return; 20741 } 20742 } 20743 if (const auto *FTD = dyn_cast<FunctionTemplateDecl>(D)) 20744 D = FTD->getTemplatedDecl(); 20745 if (auto *FD = dyn_cast<FunctionDecl>(D)) { 20746 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res = 20747 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(FD); 20748 if (IdLoc.isValid() && Res && *Res == OMPDeclareTargetDeclAttr::MT_Link) { 20749 Diag(IdLoc, diag::err_omp_function_in_link_clause); 20750 Diag(FD->getLocation(), diag::note_defined_here) << FD; 20751 return; 20752 } 20753 } 20754 if (auto *VD = dyn_cast<ValueDecl>(D)) { 20755 // Problem if any with var declared with incomplete type will be reported 20756 // as normal, so no need to check it here. 20757 if ((E || !VD->getType()->isIncompleteType()) && 20758 !checkValueDeclInTarget(SL, SR, *this, DSAStack, VD)) 20759 return; 20760 if (!E && isInOpenMPDeclareTargetContext()) { 20761 // Checking declaration inside declare target region. 20762 if (isa<VarDecl>(D) || isa<FunctionDecl>(D) || 20763 isa<FunctionTemplateDecl>(D)) { 20764 llvm::Optional<OMPDeclareTargetDeclAttr *> ActiveAttr = 20765 OMPDeclareTargetDeclAttr::getActiveAttr(VD); 20766 unsigned Level = DeclareTargetNesting.size(); 20767 if (ActiveAttr.hasValue() && ActiveAttr.getValue()->getLevel() >= Level) 20768 return; 20769 DeclareTargetContextInfo &DTCI = DeclareTargetNesting.back(); 20770 auto *A = OMPDeclareTargetDeclAttr::CreateImplicit( 20771 Context, OMPDeclareTargetDeclAttr::MT_To, DTCI.DT, Level, 20772 SourceRange(DTCI.Loc, DTCI.Loc)); 20773 D->addAttr(A); 20774 if (ASTMutationListener *ML = Context.getASTMutationListener()) 20775 ML->DeclarationMarkedOpenMPDeclareTarget(D, A); 20776 } 20777 return; 20778 } 20779 } 20780 if (!E) 20781 return; 20782 checkDeclInTargetContext(E->getExprLoc(), E->getSourceRange(), *this, D); 20783 } 20784 20785 OMPClause *Sema::ActOnOpenMPToClause( 20786 ArrayRef<OpenMPMotionModifierKind> MotionModifiers, 20787 ArrayRef<SourceLocation> MotionModifiersLoc, 20788 CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo &MapperId, 20789 SourceLocation ColonLoc, ArrayRef<Expr *> VarList, 20790 const OMPVarListLocTy &Locs, ArrayRef<Expr *> UnresolvedMappers) { 20791 OpenMPMotionModifierKind Modifiers[] = {OMPC_MOTION_MODIFIER_unknown, 20792 OMPC_MOTION_MODIFIER_unknown}; 20793 SourceLocation ModifiersLoc[NumberOfOMPMotionModifiers]; 20794 20795 // Process motion-modifiers, flag errors for duplicate modifiers. 20796 unsigned Count = 0; 20797 for (unsigned I = 0, E = MotionModifiers.size(); I < E; ++I) { 20798 if (MotionModifiers[I] != OMPC_MOTION_MODIFIER_unknown && 20799 llvm::is_contained(Modifiers, MotionModifiers[I])) { 20800 Diag(MotionModifiersLoc[I], diag::err_omp_duplicate_motion_modifier); 20801 continue; 20802 } 20803 assert(Count < NumberOfOMPMotionModifiers && 20804 "Modifiers exceed the allowed number of motion modifiers"); 20805 Modifiers[Count] = MotionModifiers[I]; 20806 ModifiersLoc[Count] = MotionModifiersLoc[I]; 20807 ++Count; 20808 } 20809 20810 MappableVarListInfo MVLI(VarList); 20811 checkMappableExpressionList(*this, DSAStack, OMPC_to, MVLI, Locs.StartLoc, 20812 MapperIdScopeSpec, MapperId, UnresolvedMappers); 20813 if (MVLI.ProcessedVarList.empty()) 20814 return nullptr; 20815 20816 return OMPToClause::Create( 20817 Context, Locs, MVLI.ProcessedVarList, MVLI.VarBaseDeclarations, 20818 MVLI.VarComponents, MVLI.UDMapperList, Modifiers, ModifiersLoc, 20819 MapperIdScopeSpec.getWithLocInContext(Context), MapperId); 20820 } 20821 20822 OMPClause *Sema::ActOnOpenMPFromClause( 20823 ArrayRef<OpenMPMotionModifierKind> MotionModifiers, 20824 ArrayRef<SourceLocation> MotionModifiersLoc, 20825 CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo &MapperId, 20826 SourceLocation ColonLoc, ArrayRef<Expr *> VarList, 20827 const OMPVarListLocTy &Locs, ArrayRef<Expr *> UnresolvedMappers) { 20828 OpenMPMotionModifierKind Modifiers[] = {OMPC_MOTION_MODIFIER_unknown, 20829 OMPC_MOTION_MODIFIER_unknown}; 20830 SourceLocation ModifiersLoc[NumberOfOMPMotionModifiers]; 20831 20832 // Process motion-modifiers, flag errors for duplicate modifiers. 20833 unsigned Count = 0; 20834 for (unsigned I = 0, E = MotionModifiers.size(); I < E; ++I) { 20835 if (MotionModifiers[I] != OMPC_MOTION_MODIFIER_unknown && 20836 llvm::is_contained(Modifiers, MotionModifiers[I])) { 20837 Diag(MotionModifiersLoc[I], diag::err_omp_duplicate_motion_modifier); 20838 continue; 20839 } 20840 assert(Count < NumberOfOMPMotionModifiers && 20841 "Modifiers exceed the allowed number of motion modifiers"); 20842 Modifiers[Count] = MotionModifiers[I]; 20843 ModifiersLoc[Count] = MotionModifiersLoc[I]; 20844 ++Count; 20845 } 20846 20847 MappableVarListInfo MVLI(VarList); 20848 checkMappableExpressionList(*this, DSAStack, OMPC_from, MVLI, Locs.StartLoc, 20849 MapperIdScopeSpec, MapperId, UnresolvedMappers); 20850 if (MVLI.ProcessedVarList.empty()) 20851 return nullptr; 20852 20853 return OMPFromClause::Create( 20854 Context, Locs, MVLI.ProcessedVarList, MVLI.VarBaseDeclarations, 20855 MVLI.VarComponents, MVLI.UDMapperList, Modifiers, ModifiersLoc, 20856 MapperIdScopeSpec.getWithLocInContext(Context), MapperId); 20857 } 20858 20859 OMPClause *Sema::ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList, 20860 const OMPVarListLocTy &Locs) { 20861 MappableVarListInfo MVLI(VarList); 20862 SmallVector<Expr *, 8> PrivateCopies; 20863 SmallVector<Expr *, 8> Inits; 20864 20865 for (Expr *RefExpr : VarList) { 20866 assert(RefExpr && "NULL expr in OpenMP use_device_ptr clause."); 20867 SourceLocation ELoc; 20868 SourceRange ERange; 20869 Expr *SimpleRefExpr = RefExpr; 20870 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 20871 if (Res.second) { 20872 // It will be analyzed later. 20873 MVLI.ProcessedVarList.push_back(RefExpr); 20874 PrivateCopies.push_back(nullptr); 20875 Inits.push_back(nullptr); 20876 } 20877 ValueDecl *D = Res.first; 20878 if (!D) 20879 continue; 20880 20881 QualType Type = D->getType(); 20882 Type = Type.getNonReferenceType().getUnqualifiedType(); 20883 20884 auto *VD = dyn_cast<VarDecl>(D); 20885 20886 // Item should be a pointer or reference to pointer. 20887 if (!Type->isPointerType()) { 20888 Diag(ELoc, diag::err_omp_usedeviceptr_not_a_pointer) 20889 << 0 << RefExpr->getSourceRange(); 20890 continue; 20891 } 20892 20893 // Build the private variable and the expression that refers to it. 20894 auto VDPrivate = 20895 buildVarDecl(*this, ELoc, Type, D->getName(), 20896 D->hasAttrs() ? &D->getAttrs() : nullptr, 20897 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr); 20898 if (VDPrivate->isInvalidDecl()) 20899 continue; 20900 20901 CurContext->addDecl(VDPrivate); 20902 DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr( 20903 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc); 20904 20905 // Add temporary variable to initialize the private copy of the pointer. 20906 VarDecl *VDInit = 20907 buildVarDecl(*this, RefExpr->getExprLoc(), Type, ".devptr.temp"); 20908 DeclRefExpr *VDInitRefExpr = buildDeclRefExpr( 20909 *this, VDInit, RefExpr->getType(), RefExpr->getExprLoc()); 20910 AddInitializerToDecl(VDPrivate, 20911 DefaultLvalueConversion(VDInitRefExpr).get(), 20912 /*DirectInit=*/false); 20913 20914 // If required, build a capture to implement the privatization initialized 20915 // with the current list item value. 20916 DeclRefExpr *Ref = nullptr; 20917 if (!VD) 20918 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true); 20919 MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref); 20920 PrivateCopies.push_back(VDPrivateRefExpr); 20921 Inits.push_back(VDInitRefExpr); 20922 20923 // We need to add a data sharing attribute for this variable to make sure it 20924 // is correctly captured. A variable that shows up in a use_device_ptr has 20925 // similar properties of a first private variable. 20926 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref); 20927 20928 // Create a mappable component for the list item. List items in this clause 20929 // only need a component. 20930 MVLI.VarBaseDeclarations.push_back(D); 20931 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1); 20932 MVLI.VarComponents.back().emplace_back(SimpleRefExpr, D, 20933 /*IsNonContiguous=*/false); 20934 } 20935 20936 if (MVLI.ProcessedVarList.empty()) 20937 return nullptr; 20938 20939 return OMPUseDevicePtrClause::Create( 20940 Context, Locs, MVLI.ProcessedVarList, PrivateCopies, Inits, 20941 MVLI.VarBaseDeclarations, MVLI.VarComponents); 20942 } 20943 20944 OMPClause *Sema::ActOnOpenMPUseDeviceAddrClause(ArrayRef<Expr *> VarList, 20945 const OMPVarListLocTy &Locs) { 20946 MappableVarListInfo MVLI(VarList); 20947 20948 for (Expr *RefExpr : VarList) { 20949 assert(RefExpr && "NULL expr in OpenMP use_device_addr clause."); 20950 SourceLocation ELoc; 20951 SourceRange ERange; 20952 Expr *SimpleRefExpr = RefExpr; 20953 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange, 20954 /*AllowArraySection=*/true); 20955 if (Res.second) { 20956 // It will be analyzed later. 20957 MVLI.ProcessedVarList.push_back(RefExpr); 20958 } 20959 ValueDecl *D = Res.first; 20960 if (!D) 20961 continue; 20962 auto *VD = dyn_cast<VarDecl>(D); 20963 20964 // If required, build a capture to implement the privatization initialized 20965 // with the current list item value. 20966 DeclRefExpr *Ref = nullptr; 20967 if (!VD) 20968 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true); 20969 MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref); 20970 20971 // We need to add a data sharing attribute for this variable to make sure it 20972 // is correctly captured. A variable that shows up in a use_device_addr has 20973 // similar properties of a first private variable. 20974 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref); 20975 20976 // Create a mappable component for the list item. List items in this clause 20977 // only need a component. 20978 MVLI.VarBaseDeclarations.push_back(D); 20979 MVLI.VarComponents.emplace_back(); 20980 Expr *Component = SimpleRefExpr; 20981 if (VD && (isa<OMPArraySectionExpr>(RefExpr->IgnoreParenImpCasts()) || 20982 isa<ArraySubscriptExpr>(RefExpr->IgnoreParenImpCasts()))) 20983 Component = DefaultFunctionArrayLvalueConversion(SimpleRefExpr).get(); 20984 MVLI.VarComponents.back().emplace_back(Component, D, 20985 /*IsNonContiguous=*/false); 20986 } 20987 20988 if (MVLI.ProcessedVarList.empty()) 20989 return nullptr; 20990 20991 return OMPUseDeviceAddrClause::Create(Context, Locs, MVLI.ProcessedVarList, 20992 MVLI.VarBaseDeclarations, 20993 MVLI.VarComponents); 20994 } 20995 20996 OMPClause *Sema::ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList, 20997 const OMPVarListLocTy &Locs) { 20998 MappableVarListInfo MVLI(VarList); 20999 for (Expr *RefExpr : VarList) { 21000 assert(RefExpr && "NULL expr in OpenMP is_device_ptr clause."); 21001 SourceLocation ELoc; 21002 SourceRange ERange; 21003 Expr *SimpleRefExpr = RefExpr; 21004 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 21005 if (Res.second) { 21006 // It will be analyzed later. 21007 MVLI.ProcessedVarList.push_back(RefExpr); 21008 } 21009 ValueDecl *D = Res.first; 21010 if (!D) 21011 continue; 21012 21013 QualType Type = D->getType(); 21014 // item should be a pointer or array or reference to pointer or array 21015 if (!Type.getNonReferenceType()->isPointerType() && 21016 !Type.getNonReferenceType()->isArrayType()) { 21017 Diag(ELoc, diag::err_omp_argument_type_isdeviceptr) 21018 << 0 << RefExpr->getSourceRange(); 21019 continue; 21020 } 21021 21022 // Check if the declaration in the clause does not show up in any data 21023 // sharing attribute. 21024 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false); 21025 if (isOpenMPPrivate(DVar.CKind)) { 21026 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa) 21027 << getOpenMPClauseName(DVar.CKind) 21028 << getOpenMPClauseName(OMPC_is_device_ptr) 21029 << getOpenMPDirectiveName(DSAStack->getCurrentDirective()); 21030 reportOriginalDsa(*this, DSAStack, D, DVar); 21031 continue; 21032 } 21033 21034 const Expr *ConflictExpr; 21035 if (DSAStack->checkMappableExprComponentListsForDecl( 21036 D, /*CurrentRegionOnly=*/true, 21037 [&ConflictExpr]( 21038 OMPClauseMappableExprCommon::MappableExprComponentListRef R, 21039 OpenMPClauseKind) -> bool { 21040 ConflictExpr = R.front().getAssociatedExpression(); 21041 return true; 21042 })) { 21043 Diag(ELoc, diag::err_omp_map_shared_storage) << RefExpr->getSourceRange(); 21044 Diag(ConflictExpr->getExprLoc(), diag::note_used_here) 21045 << ConflictExpr->getSourceRange(); 21046 continue; 21047 } 21048 21049 // Store the components in the stack so that they can be used to check 21050 // against other clauses later on. 21051 OMPClauseMappableExprCommon::MappableComponent MC( 21052 SimpleRefExpr, D, /*IsNonContiguous=*/false); 21053 DSAStack->addMappableExpressionComponents( 21054 D, MC, /*WhereFoundClauseKind=*/OMPC_is_device_ptr); 21055 21056 // Record the expression we've just processed. 21057 MVLI.ProcessedVarList.push_back(SimpleRefExpr); 21058 21059 // Create a mappable component for the list item. List items in this clause 21060 // only need a component. We use a null declaration to signal fields in 21061 // 'this'. 21062 assert((isa<DeclRefExpr>(SimpleRefExpr) || 21063 isa<CXXThisExpr>(cast<MemberExpr>(SimpleRefExpr)->getBase())) && 21064 "Unexpected device pointer expression!"); 21065 MVLI.VarBaseDeclarations.push_back( 21066 isa<DeclRefExpr>(SimpleRefExpr) ? D : nullptr); 21067 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1); 21068 MVLI.VarComponents.back().push_back(MC); 21069 } 21070 21071 if (MVLI.ProcessedVarList.empty()) 21072 return nullptr; 21073 21074 return OMPIsDevicePtrClause::Create(Context, Locs, MVLI.ProcessedVarList, 21075 MVLI.VarBaseDeclarations, 21076 MVLI.VarComponents); 21077 } 21078 21079 OMPClause *Sema::ActOnOpenMPAllocateClause( 21080 Expr *Allocator, ArrayRef<Expr *> VarList, SourceLocation StartLoc, 21081 SourceLocation ColonLoc, SourceLocation LParenLoc, SourceLocation EndLoc) { 21082 if (Allocator) { 21083 // OpenMP [2.11.4 allocate Clause, Description] 21084 // allocator is an expression of omp_allocator_handle_t type. 21085 if (!findOMPAllocatorHandleT(*this, Allocator->getExprLoc(), DSAStack)) 21086 return nullptr; 21087 21088 ExprResult AllocatorRes = DefaultLvalueConversion(Allocator); 21089 if (AllocatorRes.isInvalid()) 21090 return nullptr; 21091 AllocatorRes = PerformImplicitConversion(AllocatorRes.get(), 21092 DSAStack->getOMPAllocatorHandleT(), 21093 Sema::AA_Initializing, 21094 /*AllowExplicit=*/true); 21095 if (AllocatorRes.isInvalid()) 21096 return nullptr; 21097 Allocator = AllocatorRes.get(); 21098 } else { 21099 // OpenMP 5.0, 2.11.4 allocate Clause, Restrictions. 21100 // allocate clauses that appear on a target construct or on constructs in a 21101 // target region must specify an allocator expression unless a requires 21102 // directive with the dynamic_allocators clause is present in the same 21103 // compilation unit. 21104 if (LangOpts.OpenMPIsDevice && 21105 !DSAStack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>()) 21106 targetDiag(StartLoc, diag::err_expected_allocator_expression); 21107 } 21108 // Analyze and build list of variables. 21109 SmallVector<Expr *, 8> Vars; 21110 for (Expr *RefExpr : VarList) { 21111 assert(RefExpr && "NULL expr in OpenMP private clause."); 21112 SourceLocation ELoc; 21113 SourceRange ERange; 21114 Expr *SimpleRefExpr = RefExpr; 21115 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 21116 if (Res.second) { 21117 // It will be analyzed later. 21118 Vars.push_back(RefExpr); 21119 } 21120 ValueDecl *D = Res.first; 21121 if (!D) 21122 continue; 21123 21124 auto *VD = dyn_cast<VarDecl>(D); 21125 DeclRefExpr *Ref = nullptr; 21126 if (!VD && !CurContext->isDependentContext()) 21127 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false); 21128 Vars.push_back((VD || CurContext->isDependentContext()) 21129 ? RefExpr->IgnoreParens() 21130 : Ref); 21131 } 21132 21133 if (Vars.empty()) 21134 return nullptr; 21135 21136 if (Allocator) 21137 DSAStack->addInnerAllocatorExpr(Allocator); 21138 return OMPAllocateClause::Create(Context, StartLoc, LParenLoc, Allocator, 21139 ColonLoc, EndLoc, Vars); 21140 } 21141 21142 OMPClause *Sema::ActOnOpenMPNontemporalClause(ArrayRef<Expr *> VarList, 21143 SourceLocation StartLoc, 21144 SourceLocation LParenLoc, 21145 SourceLocation EndLoc) { 21146 SmallVector<Expr *, 8> Vars; 21147 for (Expr *RefExpr : VarList) { 21148 assert(RefExpr && "NULL expr in OpenMP nontemporal clause."); 21149 SourceLocation ELoc; 21150 SourceRange ERange; 21151 Expr *SimpleRefExpr = RefExpr; 21152 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 21153 if (Res.second) 21154 // It will be analyzed later. 21155 Vars.push_back(RefExpr); 21156 ValueDecl *D = Res.first; 21157 if (!D) 21158 continue; 21159 21160 // OpenMP 5.0, 2.9.3.1 simd Construct, Restrictions. 21161 // A list-item cannot appear in more than one nontemporal clause. 21162 if (const Expr *PrevRef = 21163 DSAStack->addUniqueNontemporal(D, SimpleRefExpr)) { 21164 Diag(ELoc, diag::err_omp_used_in_clause_twice) 21165 << 0 << getOpenMPClauseName(OMPC_nontemporal) << ERange; 21166 Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa) 21167 << getOpenMPClauseName(OMPC_nontemporal); 21168 continue; 21169 } 21170 21171 Vars.push_back(RefExpr); 21172 } 21173 21174 if (Vars.empty()) 21175 return nullptr; 21176 21177 return OMPNontemporalClause::Create(Context, StartLoc, LParenLoc, EndLoc, 21178 Vars); 21179 } 21180 21181 OMPClause *Sema::ActOnOpenMPInclusiveClause(ArrayRef<Expr *> VarList, 21182 SourceLocation StartLoc, 21183 SourceLocation LParenLoc, 21184 SourceLocation EndLoc) { 21185 SmallVector<Expr *, 8> Vars; 21186 for (Expr *RefExpr : VarList) { 21187 assert(RefExpr && "NULL expr in OpenMP nontemporal clause."); 21188 SourceLocation ELoc; 21189 SourceRange ERange; 21190 Expr *SimpleRefExpr = RefExpr; 21191 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange, 21192 /*AllowArraySection=*/true); 21193 if (Res.second) 21194 // It will be analyzed later. 21195 Vars.push_back(RefExpr); 21196 ValueDecl *D = Res.first; 21197 if (!D) 21198 continue; 21199 21200 const DSAStackTy::DSAVarData DVar = 21201 DSAStack->getTopDSA(D, /*FromParent=*/true); 21202 // OpenMP 5.0, 2.9.6, scan Directive, Restrictions. 21203 // A list item that appears in the inclusive or exclusive clause must appear 21204 // in a reduction clause with the inscan modifier on the enclosing 21205 // worksharing-loop, worksharing-loop SIMD, or simd construct. 21206 if (DVar.CKind != OMPC_reduction || 21207 DVar.Modifier != OMPC_REDUCTION_inscan) 21208 Diag(ELoc, diag::err_omp_inclusive_exclusive_not_reduction) 21209 << RefExpr->getSourceRange(); 21210 21211 if (DSAStack->getParentDirective() != OMPD_unknown) 21212 DSAStack->markDeclAsUsedInScanDirective(D); 21213 Vars.push_back(RefExpr); 21214 } 21215 21216 if (Vars.empty()) 21217 return nullptr; 21218 21219 return OMPInclusiveClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars); 21220 } 21221 21222 OMPClause *Sema::ActOnOpenMPExclusiveClause(ArrayRef<Expr *> VarList, 21223 SourceLocation StartLoc, 21224 SourceLocation LParenLoc, 21225 SourceLocation EndLoc) { 21226 SmallVector<Expr *, 8> Vars; 21227 for (Expr *RefExpr : VarList) { 21228 assert(RefExpr && "NULL expr in OpenMP nontemporal clause."); 21229 SourceLocation ELoc; 21230 SourceRange ERange; 21231 Expr *SimpleRefExpr = RefExpr; 21232 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange, 21233 /*AllowArraySection=*/true); 21234 if (Res.second) 21235 // It will be analyzed later. 21236 Vars.push_back(RefExpr); 21237 ValueDecl *D = Res.first; 21238 if (!D) 21239 continue; 21240 21241 OpenMPDirectiveKind ParentDirective = DSAStack->getParentDirective(); 21242 DSAStackTy::DSAVarData DVar; 21243 if (ParentDirective != OMPD_unknown) 21244 DVar = DSAStack->getTopDSA(D, /*FromParent=*/true); 21245 // OpenMP 5.0, 2.9.6, scan Directive, Restrictions. 21246 // A list item that appears in the inclusive or exclusive clause must appear 21247 // in a reduction clause with the inscan modifier on the enclosing 21248 // worksharing-loop, worksharing-loop SIMD, or simd construct. 21249 if (ParentDirective == OMPD_unknown || DVar.CKind != OMPC_reduction || 21250 DVar.Modifier != OMPC_REDUCTION_inscan) { 21251 Diag(ELoc, diag::err_omp_inclusive_exclusive_not_reduction) 21252 << RefExpr->getSourceRange(); 21253 } else { 21254 DSAStack->markDeclAsUsedInScanDirective(D); 21255 } 21256 Vars.push_back(RefExpr); 21257 } 21258 21259 if (Vars.empty()) 21260 return nullptr; 21261 21262 return OMPExclusiveClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars); 21263 } 21264 21265 /// Tries to find omp_alloctrait_t type. 21266 static bool findOMPAlloctraitT(Sema &S, SourceLocation Loc, DSAStackTy *Stack) { 21267 QualType OMPAlloctraitT = Stack->getOMPAlloctraitT(); 21268 if (!OMPAlloctraitT.isNull()) 21269 return true; 21270 IdentifierInfo &II = S.PP.getIdentifierTable().get("omp_alloctrait_t"); 21271 ParsedType PT = S.getTypeName(II, Loc, S.getCurScope()); 21272 if (!PT.getAsOpaquePtr() || PT.get().isNull()) { 21273 S.Diag(Loc, diag::err_omp_implied_type_not_found) << "omp_alloctrait_t"; 21274 return false; 21275 } 21276 Stack->setOMPAlloctraitT(PT.get()); 21277 return true; 21278 } 21279 21280 OMPClause *Sema::ActOnOpenMPUsesAllocatorClause( 21281 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc, 21282 ArrayRef<UsesAllocatorsData> Data) { 21283 // OpenMP [2.12.5, target Construct] 21284 // allocator is an identifier of omp_allocator_handle_t type. 21285 if (!findOMPAllocatorHandleT(*this, StartLoc, DSAStack)) 21286 return nullptr; 21287 // OpenMP [2.12.5, target Construct] 21288 // allocator-traits-array is an identifier of const omp_alloctrait_t * type. 21289 if (llvm::any_of( 21290 Data, 21291 [](const UsesAllocatorsData &D) { return D.AllocatorTraits; }) && 21292 !findOMPAlloctraitT(*this, StartLoc, DSAStack)) 21293 return nullptr; 21294 llvm::SmallPtrSet<CanonicalDeclPtr<Decl>, 4> PredefinedAllocators; 21295 for (int I = 0; I < OMPAllocateDeclAttr::OMPUserDefinedMemAlloc; ++I) { 21296 auto AllocatorKind = static_cast<OMPAllocateDeclAttr::AllocatorTypeTy>(I); 21297 StringRef Allocator = 21298 OMPAllocateDeclAttr::ConvertAllocatorTypeTyToStr(AllocatorKind); 21299 DeclarationName AllocatorName = &Context.Idents.get(Allocator); 21300 PredefinedAllocators.insert(LookupSingleName( 21301 TUScope, AllocatorName, StartLoc, Sema::LookupAnyName)); 21302 } 21303 21304 SmallVector<OMPUsesAllocatorsClause::Data, 4> NewData; 21305 for (const UsesAllocatorsData &D : Data) { 21306 Expr *AllocatorExpr = nullptr; 21307 // Check allocator expression. 21308 if (D.Allocator->isTypeDependent()) { 21309 AllocatorExpr = D.Allocator; 21310 } else { 21311 // Traits were specified - need to assign new allocator to the specified 21312 // allocator, so it must be an lvalue. 21313 AllocatorExpr = D.Allocator->IgnoreParenImpCasts(); 21314 auto *DRE = dyn_cast<DeclRefExpr>(AllocatorExpr); 21315 bool IsPredefinedAllocator = false; 21316 if (DRE) 21317 IsPredefinedAllocator = PredefinedAllocators.count(DRE->getDecl()); 21318 if (!DRE || 21319 !(Context.hasSameUnqualifiedType( 21320 AllocatorExpr->getType(), DSAStack->getOMPAllocatorHandleT()) || 21321 Context.typesAreCompatible(AllocatorExpr->getType(), 21322 DSAStack->getOMPAllocatorHandleT(), 21323 /*CompareUnqualified=*/true)) || 21324 (!IsPredefinedAllocator && 21325 (AllocatorExpr->getType().isConstant(Context) || 21326 !AllocatorExpr->isLValue()))) { 21327 Diag(D.Allocator->getExprLoc(), diag::err_omp_var_expected) 21328 << "omp_allocator_handle_t" << (DRE ? 1 : 0) 21329 << AllocatorExpr->getType() << D.Allocator->getSourceRange(); 21330 continue; 21331 } 21332 // OpenMP [2.12.5, target Construct] 21333 // Predefined allocators appearing in a uses_allocators clause cannot have 21334 // traits specified. 21335 if (IsPredefinedAllocator && D.AllocatorTraits) { 21336 Diag(D.AllocatorTraits->getExprLoc(), 21337 diag::err_omp_predefined_allocator_with_traits) 21338 << D.AllocatorTraits->getSourceRange(); 21339 Diag(D.Allocator->getExprLoc(), diag::note_omp_predefined_allocator) 21340 << cast<NamedDecl>(DRE->getDecl())->getName() 21341 << D.Allocator->getSourceRange(); 21342 continue; 21343 } 21344 // OpenMP [2.12.5, target Construct] 21345 // Non-predefined allocators appearing in a uses_allocators clause must 21346 // have traits specified. 21347 if (!IsPredefinedAllocator && !D.AllocatorTraits) { 21348 Diag(D.Allocator->getExprLoc(), 21349 diag::err_omp_nonpredefined_allocator_without_traits); 21350 continue; 21351 } 21352 // No allocator traits - just convert it to rvalue. 21353 if (!D.AllocatorTraits) 21354 AllocatorExpr = DefaultLvalueConversion(AllocatorExpr).get(); 21355 DSAStack->addUsesAllocatorsDecl( 21356 DRE->getDecl(), 21357 IsPredefinedAllocator 21358 ? DSAStackTy::UsesAllocatorsDeclKind::PredefinedAllocator 21359 : DSAStackTy::UsesAllocatorsDeclKind::UserDefinedAllocator); 21360 } 21361 Expr *AllocatorTraitsExpr = nullptr; 21362 if (D.AllocatorTraits) { 21363 if (D.AllocatorTraits->isTypeDependent()) { 21364 AllocatorTraitsExpr = D.AllocatorTraits; 21365 } else { 21366 // OpenMP [2.12.5, target Construct] 21367 // Arrays that contain allocator traits that appear in a uses_allocators 21368 // clause must be constant arrays, have constant values and be defined 21369 // in the same scope as the construct in which the clause appears. 21370 AllocatorTraitsExpr = D.AllocatorTraits->IgnoreParenImpCasts(); 21371 // Check that traits expr is a constant array. 21372 QualType TraitTy; 21373 if (const ArrayType *Ty = 21374 AllocatorTraitsExpr->getType()->getAsArrayTypeUnsafe()) 21375 if (const auto *ConstArrayTy = dyn_cast<ConstantArrayType>(Ty)) 21376 TraitTy = ConstArrayTy->getElementType(); 21377 if (TraitTy.isNull() || 21378 !(Context.hasSameUnqualifiedType(TraitTy, 21379 DSAStack->getOMPAlloctraitT()) || 21380 Context.typesAreCompatible(TraitTy, DSAStack->getOMPAlloctraitT(), 21381 /*CompareUnqualified=*/true))) { 21382 Diag(D.AllocatorTraits->getExprLoc(), 21383 diag::err_omp_expected_array_alloctraits) 21384 << AllocatorTraitsExpr->getType(); 21385 continue; 21386 } 21387 // Do not map by default allocator traits if it is a standalone 21388 // variable. 21389 if (auto *DRE = dyn_cast<DeclRefExpr>(AllocatorTraitsExpr)) 21390 DSAStack->addUsesAllocatorsDecl( 21391 DRE->getDecl(), 21392 DSAStackTy::UsesAllocatorsDeclKind::AllocatorTrait); 21393 } 21394 } 21395 OMPUsesAllocatorsClause::Data &NewD = NewData.emplace_back(); 21396 NewD.Allocator = AllocatorExpr; 21397 NewD.AllocatorTraits = AllocatorTraitsExpr; 21398 NewD.LParenLoc = D.LParenLoc; 21399 NewD.RParenLoc = D.RParenLoc; 21400 } 21401 return OMPUsesAllocatorsClause::Create(Context, StartLoc, LParenLoc, EndLoc, 21402 NewData); 21403 } 21404 21405 OMPClause *Sema::ActOnOpenMPAffinityClause( 21406 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc, 21407 SourceLocation EndLoc, Expr *Modifier, ArrayRef<Expr *> Locators) { 21408 SmallVector<Expr *, 8> Vars; 21409 for (Expr *RefExpr : Locators) { 21410 assert(RefExpr && "NULL expr in OpenMP shared clause."); 21411 if (isa<DependentScopeDeclRefExpr>(RefExpr) || RefExpr->isTypeDependent()) { 21412 // It will be analyzed later. 21413 Vars.push_back(RefExpr); 21414 continue; 21415 } 21416 21417 SourceLocation ELoc = RefExpr->getExprLoc(); 21418 Expr *SimpleExpr = RefExpr->IgnoreParenImpCasts(); 21419 21420 if (!SimpleExpr->isLValue()) { 21421 Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item) 21422 << 1 << 0 << RefExpr->getSourceRange(); 21423 continue; 21424 } 21425 21426 ExprResult Res; 21427 { 21428 Sema::TentativeAnalysisScope Trap(*this); 21429 Res = CreateBuiltinUnaryOp(ELoc, UO_AddrOf, SimpleExpr); 21430 } 21431 if (!Res.isUsable() && !isa<OMPArraySectionExpr>(SimpleExpr) && 21432 !isa<OMPArrayShapingExpr>(SimpleExpr)) { 21433 Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item) 21434 << 1 << 0 << RefExpr->getSourceRange(); 21435 continue; 21436 } 21437 Vars.push_back(SimpleExpr); 21438 } 21439 21440 return OMPAffinityClause::Create(Context, StartLoc, LParenLoc, ColonLoc, 21441 EndLoc, Modifier, Vars); 21442 } 21443