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/SmallSet.h" 39 #include "llvm/ADT/StringExtras.h" 40 #include "llvm/Frontend/OpenMP/OMPAssume.h" 41 #include "llvm/Frontend/OpenMP/OMPConstants.h" 42 #include <set> 43 44 using namespace clang; 45 using namespace llvm::omp; 46 47 //===----------------------------------------------------------------------===// 48 // Stack of data-sharing attributes for variables 49 //===----------------------------------------------------------------------===// 50 51 static const Expr *checkMapClauseExpressionBase( 52 Sema &SemaRef, Expr *E, 53 OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents, 54 OpenMPClauseKind CKind, OpenMPDirectiveKind DKind, bool NoDiagnose); 55 56 namespace { 57 /// Default data sharing attributes, which can be applied to directive. 58 enum DefaultDataSharingAttributes { 59 DSA_unspecified = 0, /// Data sharing attribute not specified. 60 DSA_none = 1 << 0, /// Default data sharing attribute 'none'. 61 DSA_shared = 1 << 1, /// Default data sharing attribute 'shared'. 62 DSA_firstprivate = 1 << 2, /// Default data sharing attribute 'firstprivate'. 63 }; 64 65 /// Stack for tracking declarations used in OpenMP directives and 66 /// clauses and their data-sharing attributes. 67 class DSAStackTy { 68 public: 69 struct DSAVarData { 70 OpenMPDirectiveKind DKind = OMPD_unknown; 71 OpenMPClauseKind CKind = OMPC_unknown; 72 unsigned Modifier = 0; 73 const Expr *RefExpr = nullptr; 74 DeclRefExpr *PrivateCopy = nullptr; 75 SourceLocation ImplicitDSALoc; 76 bool AppliedToPointee = false; 77 DSAVarData() = default; 78 DSAVarData(OpenMPDirectiveKind DKind, OpenMPClauseKind CKind, 79 const Expr *RefExpr, DeclRefExpr *PrivateCopy, 80 SourceLocation ImplicitDSALoc, unsigned Modifier, 81 bool AppliedToPointee) 82 : DKind(DKind), CKind(CKind), Modifier(Modifier), RefExpr(RefExpr), 83 PrivateCopy(PrivateCopy), ImplicitDSALoc(ImplicitDSALoc), 84 AppliedToPointee(AppliedToPointee) {} 85 }; 86 using OperatorOffsetTy = 87 llvm::SmallVector<std::pair<Expr *, OverloadedOperatorKind>, 4>; 88 using DoacrossDependMapTy = 89 llvm::DenseMap<OMPDependClause *, OperatorOffsetTy>; 90 /// Kind of the declaration used in the uses_allocators clauses. 91 enum class UsesAllocatorsDeclKind { 92 /// Predefined allocator 93 PredefinedAllocator, 94 /// User-defined allocator 95 UserDefinedAllocator, 96 /// The declaration that represent allocator trait 97 AllocatorTrait, 98 }; 99 100 private: 101 struct DSAInfo { 102 OpenMPClauseKind Attributes = OMPC_unknown; 103 unsigned Modifier = 0; 104 /// Pointer to a reference expression and a flag which shows that the 105 /// variable is marked as lastprivate(true) or not (false). 106 llvm::PointerIntPair<const Expr *, 1, bool> RefExpr; 107 DeclRefExpr *PrivateCopy = nullptr; 108 /// true if the attribute is applied to the pointee, not the variable 109 /// itself. 110 bool AppliedToPointee = false; 111 }; 112 using DeclSAMapTy = llvm::SmallDenseMap<const ValueDecl *, DSAInfo, 8>; 113 using UsedRefMapTy = llvm::SmallDenseMap<const ValueDecl *, const Expr *, 8>; 114 using LCDeclInfo = std::pair<unsigned, VarDecl *>; 115 using LoopControlVariablesMapTy = 116 llvm::SmallDenseMap<const ValueDecl *, LCDeclInfo, 8>; 117 /// Struct that associates a component with the clause kind where they are 118 /// found. 119 struct MappedExprComponentTy { 120 OMPClauseMappableExprCommon::MappableExprComponentLists Components; 121 OpenMPClauseKind Kind = OMPC_unknown; 122 }; 123 using MappedExprComponentsTy = 124 llvm::DenseMap<const ValueDecl *, MappedExprComponentTy>; 125 using CriticalsWithHintsTy = 126 llvm::StringMap<std::pair<const OMPCriticalDirective *, llvm::APSInt>>; 127 struct ReductionData { 128 using BOKPtrType = llvm::PointerEmbeddedInt<BinaryOperatorKind, 16>; 129 SourceRange ReductionRange; 130 llvm::PointerUnion<const Expr *, BOKPtrType> ReductionOp; 131 ReductionData() = default; 132 void set(BinaryOperatorKind BO, SourceRange RR) { 133 ReductionRange = RR; 134 ReductionOp = BO; 135 } 136 void set(const Expr *RefExpr, SourceRange RR) { 137 ReductionRange = RR; 138 ReductionOp = RefExpr; 139 } 140 }; 141 using DeclReductionMapTy = 142 llvm::SmallDenseMap<const ValueDecl *, ReductionData, 4>; 143 struct DefaultmapInfo { 144 OpenMPDefaultmapClauseModifier ImplicitBehavior = 145 OMPC_DEFAULTMAP_MODIFIER_unknown; 146 SourceLocation SLoc; 147 DefaultmapInfo() = default; 148 DefaultmapInfo(OpenMPDefaultmapClauseModifier M, SourceLocation Loc) 149 : ImplicitBehavior(M), SLoc(Loc) {} 150 }; 151 152 struct SharingMapTy { 153 DeclSAMapTy SharingMap; 154 DeclReductionMapTy ReductionMap; 155 UsedRefMapTy AlignedMap; 156 UsedRefMapTy NontemporalMap; 157 MappedExprComponentsTy MappedExprComponents; 158 LoopControlVariablesMapTy LCVMap; 159 DefaultDataSharingAttributes DefaultAttr = DSA_unspecified; 160 SourceLocation DefaultAttrLoc; 161 DefaultmapInfo DefaultmapMap[OMPC_DEFAULTMAP_unknown]; 162 OpenMPDirectiveKind Directive = OMPD_unknown; 163 DeclarationNameInfo DirectiveName; 164 Scope *CurScope = nullptr; 165 DeclContext *Context = nullptr; 166 SourceLocation ConstructLoc; 167 /// Set of 'depend' clauses with 'sink|source' dependence kind. Required to 168 /// get the data (loop counters etc.) about enclosing loop-based construct. 169 /// This data is required during codegen. 170 DoacrossDependMapTy DoacrossDepends; 171 /// First argument (Expr *) contains optional argument of the 172 /// 'ordered' clause, the second one is true if the regions has 'ordered' 173 /// clause, false otherwise. 174 llvm::Optional<std::pair<const Expr *, OMPOrderedClause *>> OrderedRegion; 175 unsigned AssociatedLoops = 1; 176 bool HasMutipleLoops = false; 177 const Decl *PossiblyLoopCounter = nullptr; 178 bool NowaitRegion = false; 179 bool CancelRegion = false; 180 bool LoopStart = false; 181 bool BodyComplete = false; 182 SourceLocation PrevScanLocation; 183 SourceLocation PrevOrderedLocation; 184 SourceLocation InnerTeamsRegionLoc; 185 /// Reference to the taskgroup task_reduction reference expression. 186 Expr *TaskgroupReductionRef = nullptr; 187 llvm::DenseSet<QualType> MappedClassesQualTypes; 188 SmallVector<Expr *, 4> InnerUsedAllocators; 189 llvm::DenseSet<CanonicalDeclPtr<Decl>> ImplicitTaskFirstprivates; 190 /// List of globals marked as declare target link in this target region 191 /// (isOpenMPTargetExecutionDirective(Directive) == true). 192 llvm::SmallVector<DeclRefExpr *, 4> DeclareTargetLinkVarDecls; 193 /// List of decls used in inclusive/exclusive clauses of the scan directive. 194 llvm::DenseSet<CanonicalDeclPtr<Decl>> UsedInScanDirective; 195 llvm::DenseMap<CanonicalDeclPtr<const Decl>, UsesAllocatorsDeclKind> 196 UsesAllocatorsDecls; 197 Expr *DeclareMapperVar = nullptr; 198 SharingMapTy(OpenMPDirectiveKind DKind, DeclarationNameInfo Name, 199 Scope *CurScope, SourceLocation Loc) 200 : Directive(DKind), DirectiveName(Name), CurScope(CurScope), 201 ConstructLoc(Loc) {} 202 SharingMapTy() = default; 203 }; 204 205 using StackTy = SmallVector<SharingMapTy, 4>; 206 207 /// Stack of used declaration and their data-sharing attributes. 208 DeclSAMapTy Threadprivates; 209 const FunctionScopeInfo *CurrentNonCapturingFunctionScope = nullptr; 210 SmallVector<std::pair<StackTy, const FunctionScopeInfo *>, 4> Stack; 211 /// true, if check for DSA must be from parent directive, false, if 212 /// from current directive. 213 OpenMPClauseKind ClauseKindMode = OMPC_unknown; 214 Sema &SemaRef; 215 bool ForceCapturing = false; 216 /// true if all the variables in the target executable directives must be 217 /// captured by reference. 218 bool ForceCaptureByReferenceInTargetExecutable = false; 219 CriticalsWithHintsTy Criticals; 220 unsigned IgnoredStackElements = 0; 221 222 /// Iterators over the stack iterate in order from innermost to outermost 223 /// directive. 224 using const_iterator = StackTy::const_reverse_iterator; 225 const_iterator begin() const { 226 return Stack.empty() ? const_iterator() 227 : Stack.back().first.rbegin() + IgnoredStackElements; 228 } 229 const_iterator end() const { 230 return Stack.empty() ? const_iterator() : Stack.back().first.rend(); 231 } 232 using iterator = StackTy::reverse_iterator; 233 iterator begin() { 234 return Stack.empty() ? iterator() 235 : Stack.back().first.rbegin() + IgnoredStackElements; 236 } 237 iterator end() { 238 return Stack.empty() ? iterator() : Stack.back().first.rend(); 239 } 240 241 // Convenience operations to get at the elements of the stack. 242 243 bool isStackEmpty() const { 244 return Stack.empty() || 245 Stack.back().second != CurrentNonCapturingFunctionScope || 246 Stack.back().first.size() <= IgnoredStackElements; 247 } 248 size_t getStackSize() const { 249 return isStackEmpty() ? 0 250 : Stack.back().first.size() - IgnoredStackElements; 251 } 252 253 SharingMapTy *getTopOfStackOrNull() { 254 size_t Size = getStackSize(); 255 if (Size == 0) 256 return nullptr; 257 return &Stack.back().first[Size - 1]; 258 } 259 const SharingMapTy *getTopOfStackOrNull() const { 260 return const_cast<DSAStackTy &>(*this).getTopOfStackOrNull(); 261 } 262 SharingMapTy &getTopOfStack() { 263 assert(!isStackEmpty() && "no current directive"); 264 return *getTopOfStackOrNull(); 265 } 266 const SharingMapTy &getTopOfStack() const { 267 return const_cast<DSAStackTy &>(*this).getTopOfStack(); 268 } 269 270 SharingMapTy *getSecondOnStackOrNull() { 271 size_t Size = getStackSize(); 272 if (Size <= 1) 273 return nullptr; 274 return &Stack.back().first[Size - 2]; 275 } 276 const SharingMapTy *getSecondOnStackOrNull() const { 277 return const_cast<DSAStackTy &>(*this).getSecondOnStackOrNull(); 278 } 279 280 /// Get the stack element at a certain level (previously returned by 281 /// \c getNestingLevel). 282 /// 283 /// Note that nesting levels count from outermost to innermost, and this is 284 /// the reverse of our iteration order where new inner levels are pushed at 285 /// the front of the stack. 286 SharingMapTy &getStackElemAtLevel(unsigned Level) { 287 assert(Level < getStackSize() && "no such stack element"); 288 return Stack.back().first[Level]; 289 } 290 const SharingMapTy &getStackElemAtLevel(unsigned Level) const { 291 return const_cast<DSAStackTy &>(*this).getStackElemAtLevel(Level); 292 } 293 294 DSAVarData getDSA(const_iterator &Iter, ValueDecl *D) const; 295 296 /// Checks if the variable is a local for OpenMP region. 297 bool isOpenMPLocal(VarDecl *D, const_iterator Iter) const; 298 299 /// Vector of previously declared requires directives 300 SmallVector<const OMPRequiresDecl *, 2> RequiresDecls; 301 /// omp_allocator_handle_t type. 302 QualType OMPAllocatorHandleT; 303 /// omp_depend_t type. 304 QualType OMPDependT; 305 /// omp_event_handle_t type. 306 QualType OMPEventHandleT; 307 /// omp_alloctrait_t type. 308 QualType OMPAlloctraitT; 309 /// Expression for the predefined allocators. 310 Expr *OMPPredefinedAllocators[OMPAllocateDeclAttr::OMPUserDefinedMemAlloc] = { 311 nullptr}; 312 /// Vector of previously encountered target directives 313 SmallVector<SourceLocation, 2> TargetLocations; 314 SourceLocation AtomicLocation; 315 /// Vector of declare variant construct traits. 316 SmallVector<llvm::omp::TraitProperty, 8> ConstructTraits; 317 318 public: 319 explicit DSAStackTy(Sema &S) : SemaRef(S) {} 320 321 /// Sets omp_allocator_handle_t type. 322 void setOMPAllocatorHandleT(QualType Ty) { OMPAllocatorHandleT = Ty; } 323 /// Gets omp_allocator_handle_t type. 324 QualType getOMPAllocatorHandleT() const { return OMPAllocatorHandleT; } 325 /// Sets omp_alloctrait_t type. 326 void setOMPAlloctraitT(QualType Ty) { OMPAlloctraitT = Ty; } 327 /// Gets omp_alloctrait_t type. 328 QualType getOMPAlloctraitT() const { return OMPAlloctraitT; } 329 /// Sets the given default allocator. 330 void setAllocator(OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind, 331 Expr *Allocator) { 332 OMPPredefinedAllocators[AllocatorKind] = Allocator; 333 } 334 /// Returns the specified default allocator. 335 Expr *getAllocator(OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind) const { 336 return OMPPredefinedAllocators[AllocatorKind]; 337 } 338 /// Sets omp_depend_t type. 339 void setOMPDependT(QualType Ty) { OMPDependT = Ty; } 340 /// Gets omp_depend_t type. 341 QualType getOMPDependT() const { return OMPDependT; } 342 343 /// Sets omp_event_handle_t type. 344 void setOMPEventHandleT(QualType Ty) { OMPEventHandleT = Ty; } 345 /// Gets omp_event_handle_t type. 346 QualType getOMPEventHandleT() const { return OMPEventHandleT; } 347 348 bool isClauseParsingMode() const { return ClauseKindMode != OMPC_unknown; } 349 OpenMPClauseKind getClauseParsingMode() const { 350 assert(isClauseParsingMode() && "Must be in clause parsing mode."); 351 return ClauseKindMode; 352 } 353 void setClauseParsingMode(OpenMPClauseKind K) { ClauseKindMode = K; } 354 355 bool isBodyComplete() const { 356 const SharingMapTy *Top = getTopOfStackOrNull(); 357 return Top && Top->BodyComplete; 358 } 359 void setBodyComplete() { getTopOfStack().BodyComplete = true; } 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 396 public: 397 ParentDirectiveScope(DSAStackTy &Self, bool Activate) 398 : Self(Self), Active(false) { 399 if (Activate) 400 enable(); 401 } 402 ~ParentDirectiveScope() { disable(); } 403 void disable() { 404 if (Active) { 405 --Self.IgnoredStackElements; 406 Active = false; 407 } 408 } 409 void enable() { 410 if (!Active) { 411 ++Self.IgnoredStackElements; 412 Active = true; 413 } 414 } 415 }; 416 417 /// Marks that we're started loop parsing. 418 void loopInit() { 419 assert(isOpenMPLoopDirective(getCurrentDirective()) && 420 "Expected loop-based directive."); 421 getTopOfStack().LoopStart = true; 422 } 423 /// Start capturing of the variables in the loop context. 424 void loopStart() { 425 assert(isOpenMPLoopDirective(getCurrentDirective()) && 426 "Expected loop-based directive."); 427 getTopOfStack().LoopStart = false; 428 } 429 /// true, if variables are captured, false otherwise. 430 bool isLoopStarted() const { 431 assert(isOpenMPLoopDirective(getCurrentDirective()) && 432 "Expected loop-based directive."); 433 return !getTopOfStack().LoopStart; 434 } 435 /// Marks (or clears) declaration as possibly loop counter. 436 void resetPossibleLoopCounter(const Decl *D = nullptr) { 437 getTopOfStack().PossiblyLoopCounter = 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.contains(D); 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) { RequiresDecls.push_back(RD); } 635 636 /// Checks if the defined 'requires' directive has specified type of clause. 637 template <typename ClauseType> bool hasRequiresDeclWithClause() const { 638 return llvm::any_of(RequiresDecls, [](const OMPRequiresDecl *D) { 639 return llvm::any_of(D->clauselists(), [](const OMPClause *C) { 640 return isa<ClauseType>(C); 641 }); 642 }); 643 } 644 645 /// Checks for a duplicate clause amongst previously declared requires 646 /// directives 647 bool hasDuplicateRequiresClause(ArrayRef<OMPClause *> ClauseList) const { 648 bool IsDuplicate = false; 649 for (OMPClause *CNew : ClauseList) { 650 for (const OMPRequiresDecl *D : RequiresDecls) { 651 for (const OMPClause *CPrev : D->clauselists()) { 652 if (CNew->getClauseKind() == CPrev->getClauseKind()) { 653 SemaRef.Diag(CNew->getBeginLoc(), 654 diag::err_omp_requires_clause_redeclaration) 655 << getOpenMPClauseName(CNew->getClauseKind()); 656 SemaRef.Diag(CPrev->getBeginLoc(), 657 diag::note_omp_requires_previous_clause) 658 << getOpenMPClauseName(CPrev->getClauseKind()); 659 IsDuplicate = true; 660 } 661 } 662 } 663 } 664 return IsDuplicate; 665 } 666 667 /// Add location of previously encountered target to internal vector 668 void addTargetDirLocation(SourceLocation LocStart) { 669 TargetLocations.push_back(LocStart); 670 } 671 672 /// Add location for the first encountered atomicc directive. 673 void addAtomicDirectiveLoc(SourceLocation Loc) { 674 if (AtomicLocation.isInvalid()) 675 AtomicLocation = Loc; 676 } 677 678 /// Returns the location of the first encountered atomic directive in the 679 /// module. 680 SourceLocation getAtomicDirectiveLoc() const { return AtomicLocation; } 681 682 // Return previously encountered target region locations. 683 ArrayRef<SourceLocation> getEncounteredTargetLocs() const { 684 return TargetLocations; 685 } 686 687 /// Set default data sharing attribute to none. 688 void setDefaultDSANone(SourceLocation Loc) { 689 getTopOfStack().DefaultAttr = DSA_none; 690 getTopOfStack().DefaultAttrLoc = Loc; 691 } 692 /// Set default data sharing attribute to shared. 693 void setDefaultDSAShared(SourceLocation Loc) { 694 getTopOfStack().DefaultAttr = DSA_shared; 695 getTopOfStack().DefaultAttrLoc = Loc; 696 } 697 /// Set default data sharing attribute to firstprivate. 698 void setDefaultDSAFirstPrivate(SourceLocation Loc) { 699 getTopOfStack().DefaultAttr = DSA_firstprivate; 700 getTopOfStack().DefaultAttrLoc = Loc; 701 } 702 /// Set default data mapping attribute to Modifier:Kind 703 void setDefaultDMAAttr(OpenMPDefaultmapClauseModifier M, 704 OpenMPDefaultmapClauseKind Kind, SourceLocation Loc) { 705 DefaultmapInfo &DMI = getTopOfStack().DefaultmapMap[Kind]; 706 DMI.ImplicitBehavior = M; 707 DMI.SLoc = Loc; 708 } 709 /// Check whether the implicit-behavior has been set in defaultmap 710 bool checkDefaultmapCategory(OpenMPDefaultmapClauseKind VariableCategory) { 711 if (VariableCategory == OMPC_DEFAULTMAP_unknown) 712 return getTopOfStack() 713 .DefaultmapMap[OMPC_DEFAULTMAP_aggregate] 714 .ImplicitBehavior != OMPC_DEFAULTMAP_MODIFIER_unknown || 715 getTopOfStack() 716 .DefaultmapMap[OMPC_DEFAULTMAP_scalar] 717 .ImplicitBehavior != OMPC_DEFAULTMAP_MODIFIER_unknown || 718 getTopOfStack() 719 .DefaultmapMap[OMPC_DEFAULTMAP_pointer] 720 .ImplicitBehavior != OMPC_DEFAULTMAP_MODIFIER_unknown; 721 return getTopOfStack().DefaultmapMap[VariableCategory].ImplicitBehavior != 722 OMPC_DEFAULTMAP_MODIFIER_unknown; 723 } 724 725 ArrayRef<llvm::omp::TraitProperty> getConstructTraits() { 726 return ConstructTraits; 727 } 728 void handleConstructTrait(ArrayRef<llvm::omp::TraitProperty> Traits, 729 bool ScopeEntry) { 730 if (ScopeEntry) 731 ConstructTraits.append(Traits.begin(), Traits.end()); 732 else 733 for (llvm::omp::TraitProperty Trait : llvm::reverse(Traits)) { 734 llvm::omp::TraitProperty Top = ConstructTraits.pop_back_val(); 735 assert(Top == Trait && "Something left a trait on the stack!"); 736 (void)Trait; 737 (void)Top; 738 } 739 } 740 741 DefaultDataSharingAttributes getDefaultDSA(unsigned Level) const { 742 return getStackSize() <= Level ? DSA_unspecified 743 : getStackElemAtLevel(Level).DefaultAttr; 744 } 745 DefaultDataSharingAttributes getDefaultDSA() const { 746 return isStackEmpty() ? DSA_unspecified : getTopOfStack().DefaultAttr; 747 } 748 SourceLocation getDefaultDSALocation() const { 749 return isStackEmpty() ? SourceLocation() : getTopOfStack().DefaultAttrLoc; 750 } 751 OpenMPDefaultmapClauseModifier 752 getDefaultmapModifier(OpenMPDefaultmapClauseKind Kind) const { 753 return isStackEmpty() 754 ? OMPC_DEFAULTMAP_MODIFIER_unknown 755 : getTopOfStack().DefaultmapMap[Kind].ImplicitBehavior; 756 } 757 OpenMPDefaultmapClauseModifier 758 getDefaultmapModifierAtLevel(unsigned Level, 759 OpenMPDefaultmapClauseKind Kind) const { 760 return getStackElemAtLevel(Level).DefaultmapMap[Kind].ImplicitBehavior; 761 } 762 bool isDefaultmapCapturedByRef(unsigned Level, 763 OpenMPDefaultmapClauseKind Kind) const { 764 OpenMPDefaultmapClauseModifier M = 765 getDefaultmapModifierAtLevel(Level, Kind); 766 if (Kind == OMPC_DEFAULTMAP_scalar || Kind == OMPC_DEFAULTMAP_pointer) { 767 return (M == OMPC_DEFAULTMAP_MODIFIER_alloc) || 768 (M == OMPC_DEFAULTMAP_MODIFIER_to) || 769 (M == OMPC_DEFAULTMAP_MODIFIER_from) || 770 (M == OMPC_DEFAULTMAP_MODIFIER_tofrom); 771 } 772 return true; 773 } 774 static bool mustBeFirstprivateBase(OpenMPDefaultmapClauseModifier M, 775 OpenMPDefaultmapClauseKind Kind) { 776 switch (Kind) { 777 case OMPC_DEFAULTMAP_scalar: 778 case OMPC_DEFAULTMAP_pointer: 779 return (M == OMPC_DEFAULTMAP_MODIFIER_unknown) || 780 (M == OMPC_DEFAULTMAP_MODIFIER_firstprivate) || 781 (M == OMPC_DEFAULTMAP_MODIFIER_default); 782 case OMPC_DEFAULTMAP_aggregate: 783 return M == OMPC_DEFAULTMAP_MODIFIER_firstprivate; 784 default: 785 break; 786 } 787 llvm_unreachable("Unexpected OpenMPDefaultmapClauseKind enum"); 788 } 789 bool mustBeFirstprivateAtLevel(unsigned Level, 790 OpenMPDefaultmapClauseKind Kind) const { 791 OpenMPDefaultmapClauseModifier M = 792 getDefaultmapModifierAtLevel(Level, Kind); 793 return mustBeFirstprivateBase(M, Kind); 794 } 795 bool mustBeFirstprivate(OpenMPDefaultmapClauseKind Kind) const { 796 OpenMPDefaultmapClauseModifier M = getDefaultmapModifier(Kind); 797 return mustBeFirstprivateBase(M, Kind); 798 } 799 800 /// Checks if the specified variable is a threadprivate. 801 bool isThreadPrivate(VarDecl *D) { 802 const DSAVarData DVar = getTopDSA(D, false); 803 return isOpenMPThreadPrivate(DVar.CKind); 804 } 805 806 /// Marks current region as ordered (it has an 'ordered' clause). 807 void setOrderedRegion(bool IsOrdered, const Expr *Param, 808 OMPOrderedClause *Clause) { 809 if (IsOrdered) 810 getTopOfStack().OrderedRegion.emplace(Param, Clause); 811 else 812 getTopOfStack().OrderedRegion.reset(); 813 } 814 /// Returns true, if region is ordered (has associated 'ordered' clause), 815 /// false - otherwise. 816 bool isOrderedRegion() const { 817 if (const SharingMapTy *Top = getTopOfStackOrNull()) 818 return Top->OrderedRegion.hasValue(); 819 return false; 820 } 821 /// Returns optional parameter for the ordered region. 822 std::pair<const Expr *, OMPOrderedClause *> getOrderedRegionParam() const { 823 if (const SharingMapTy *Top = getTopOfStackOrNull()) 824 if (Top->OrderedRegion.hasValue()) 825 return Top->OrderedRegion.getValue(); 826 return std::make_pair(nullptr, nullptr); 827 } 828 /// Returns true, if parent region is ordered (has associated 829 /// 'ordered' clause), false - otherwise. 830 bool isParentOrderedRegion() const { 831 if (const SharingMapTy *Parent = getSecondOnStackOrNull()) 832 return Parent->OrderedRegion.hasValue(); 833 return false; 834 } 835 /// Returns optional parameter for the ordered region. 836 std::pair<const Expr *, OMPOrderedClause *> 837 getParentOrderedRegionParam() const { 838 if (const SharingMapTy *Parent = getSecondOnStackOrNull()) 839 if (Parent->OrderedRegion.hasValue()) 840 return Parent->OrderedRegion.getValue(); 841 return std::make_pair(nullptr, nullptr); 842 } 843 /// Marks current region as nowait (it has a 'nowait' clause). 844 void setNowaitRegion(bool IsNowait = true) { 845 getTopOfStack().NowaitRegion = IsNowait; 846 } 847 /// Returns true, if parent region is nowait (has associated 848 /// 'nowait' clause), false - otherwise. 849 bool isParentNowaitRegion() const { 850 if (const SharingMapTy *Parent = getSecondOnStackOrNull()) 851 return Parent->NowaitRegion; 852 return false; 853 } 854 /// Marks parent region as cancel region. 855 void setParentCancelRegion(bool Cancel = true) { 856 if (SharingMapTy *Parent = getSecondOnStackOrNull()) 857 Parent->CancelRegion |= Cancel; 858 } 859 /// Return true if current region has inner cancel construct. 860 bool isCancelRegion() const { 861 const SharingMapTy *Top = getTopOfStackOrNull(); 862 return Top ? Top->CancelRegion : false; 863 } 864 865 /// Mark that parent region already has scan directive. 866 void setParentHasScanDirective(SourceLocation Loc) { 867 if (SharingMapTy *Parent = getSecondOnStackOrNull()) 868 Parent->PrevScanLocation = Loc; 869 } 870 /// Return true if current region has inner cancel construct. 871 bool doesParentHasScanDirective() const { 872 const SharingMapTy *Top = getSecondOnStackOrNull(); 873 return Top ? Top->PrevScanLocation.isValid() : false; 874 } 875 /// Return true if current region has inner cancel construct. 876 SourceLocation getParentScanDirectiveLoc() const { 877 const SharingMapTy *Top = getSecondOnStackOrNull(); 878 return Top ? Top->PrevScanLocation : SourceLocation(); 879 } 880 /// Mark that parent region already has ordered directive. 881 void setParentHasOrderedDirective(SourceLocation Loc) { 882 if (SharingMapTy *Parent = getSecondOnStackOrNull()) 883 Parent->PrevOrderedLocation = Loc; 884 } 885 /// Return true if current region has inner ordered construct. 886 bool doesParentHasOrderedDirective() const { 887 const SharingMapTy *Top = getSecondOnStackOrNull(); 888 return Top ? Top->PrevOrderedLocation.isValid() : false; 889 } 890 /// Returns the location of the previously specified ordered directive. 891 SourceLocation getParentOrderedDirectiveLoc() const { 892 const SharingMapTy *Top = getSecondOnStackOrNull(); 893 return Top ? Top->PrevOrderedLocation : SourceLocation(); 894 } 895 896 /// Set collapse value for the region. 897 void setAssociatedLoops(unsigned Val) { 898 getTopOfStack().AssociatedLoops = Val; 899 if (Val > 1) 900 getTopOfStack().HasMutipleLoops = true; 901 } 902 /// Return collapse value for region. 903 unsigned getAssociatedLoops() const { 904 const SharingMapTy *Top = getTopOfStackOrNull(); 905 return Top ? Top->AssociatedLoops : 0; 906 } 907 /// Returns true if the construct is associated with multiple loops. 908 bool hasMutipleLoops() const { 909 const SharingMapTy *Top = getTopOfStackOrNull(); 910 return Top ? Top->HasMutipleLoops : false; 911 } 912 913 /// Marks current target region as one with closely nested teams 914 /// region. 915 void setParentTeamsRegionLoc(SourceLocation TeamsRegionLoc) { 916 if (SharingMapTy *Parent = getSecondOnStackOrNull()) 917 Parent->InnerTeamsRegionLoc = TeamsRegionLoc; 918 } 919 /// Returns true, if current region has closely nested teams region. 920 bool hasInnerTeamsRegion() const { 921 return getInnerTeamsRegionLoc().isValid(); 922 } 923 /// Returns location of the nested teams region (if any). 924 SourceLocation getInnerTeamsRegionLoc() const { 925 const SharingMapTy *Top = getTopOfStackOrNull(); 926 return Top ? Top->InnerTeamsRegionLoc : SourceLocation(); 927 } 928 929 Scope *getCurScope() const { 930 const SharingMapTy *Top = getTopOfStackOrNull(); 931 return Top ? Top->CurScope : nullptr; 932 } 933 void setContext(DeclContext *DC) { getTopOfStack().Context = DC; } 934 SourceLocation getConstructLoc() const { 935 const SharingMapTy *Top = getTopOfStackOrNull(); 936 return Top ? Top->ConstructLoc : SourceLocation(); 937 } 938 939 /// Do the check specified in \a Check to all component lists and return true 940 /// if any issue is found. 941 bool checkMappableExprComponentListsForDecl( 942 const ValueDecl *VD, bool CurrentRegionOnly, 943 const llvm::function_ref< 944 bool(OMPClauseMappableExprCommon::MappableExprComponentListRef, 945 OpenMPClauseKind)> 946 Check) const { 947 if (isStackEmpty()) 948 return false; 949 auto SI = begin(); 950 auto SE = end(); 951 952 if (SI == SE) 953 return false; 954 955 if (CurrentRegionOnly) 956 SE = std::next(SI); 957 else 958 std::advance(SI, 1); 959 960 for (; SI != SE; ++SI) { 961 auto MI = SI->MappedExprComponents.find(VD); 962 if (MI != SI->MappedExprComponents.end()) 963 for (OMPClauseMappableExprCommon::MappableExprComponentListRef L : 964 MI->second.Components) 965 if (Check(L, MI->second.Kind)) 966 return true; 967 } 968 return false; 969 } 970 971 /// Do the check specified in \a Check to all component lists at a given level 972 /// and return true if any issue is found. 973 bool checkMappableExprComponentListsForDeclAtLevel( 974 const ValueDecl *VD, unsigned Level, 975 const llvm::function_ref< 976 bool(OMPClauseMappableExprCommon::MappableExprComponentListRef, 977 OpenMPClauseKind)> 978 Check) const { 979 if (getStackSize() <= Level) 980 return false; 981 982 const SharingMapTy &StackElem = getStackElemAtLevel(Level); 983 auto MI = StackElem.MappedExprComponents.find(VD); 984 if (MI != StackElem.MappedExprComponents.end()) 985 for (OMPClauseMappableExprCommon::MappableExprComponentListRef L : 986 MI->second.Components) 987 if (Check(L, MI->second.Kind)) 988 return true; 989 return false; 990 } 991 992 /// Create a new mappable expression component list associated with a given 993 /// declaration and initialize it with the provided list of components. 994 void addMappableExpressionComponents( 995 const ValueDecl *VD, 996 OMPClauseMappableExprCommon::MappableExprComponentListRef Components, 997 OpenMPClauseKind WhereFoundClauseKind) { 998 MappedExprComponentTy &MEC = getTopOfStack().MappedExprComponents[VD]; 999 // Create new entry and append the new components there. 1000 MEC.Components.resize(MEC.Components.size() + 1); 1001 MEC.Components.back().append(Components.begin(), Components.end()); 1002 MEC.Kind = WhereFoundClauseKind; 1003 } 1004 1005 unsigned getNestingLevel() const { 1006 assert(!isStackEmpty()); 1007 return getStackSize() - 1; 1008 } 1009 void addDoacrossDependClause(OMPDependClause *C, 1010 const OperatorOffsetTy &OpsOffs) { 1011 SharingMapTy *Parent = getSecondOnStackOrNull(); 1012 assert(Parent && isOpenMPWorksharingDirective(Parent->Directive)); 1013 Parent->DoacrossDepends.try_emplace(C, OpsOffs); 1014 } 1015 llvm::iterator_range<DoacrossDependMapTy::const_iterator> 1016 getDoacrossDependClauses() const { 1017 const SharingMapTy &StackElem = getTopOfStack(); 1018 if (isOpenMPWorksharingDirective(StackElem.Directive)) { 1019 const DoacrossDependMapTy &Ref = StackElem.DoacrossDepends; 1020 return llvm::make_range(Ref.begin(), Ref.end()); 1021 } 1022 return llvm::make_range(StackElem.DoacrossDepends.end(), 1023 StackElem.DoacrossDepends.end()); 1024 } 1025 1026 // Store types of classes which have been explicitly mapped 1027 void addMappedClassesQualTypes(QualType QT) { 1028 SharingMapTy &StackElem = getTopOfStack(); 1029 StackElem.MappedClassesQualTypes.insert(QT); 1030 } 1031 1032 // Return set of mapped classes types 1033 bool isClassPreviouslyMapped(QualType QT) const { 1034 const SharingMapTy &StackElem = getTopOfStack(); 1035 return StackElem.MappedClassesQualTypes.contains(QT); 1036 } 1037 1038 /// Adds global declare target to the parent target region. 1039 void addToParentTargetRegionLinkGlobals(DeclRefExpr *E) { 1040 assert(*OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration( 1041 E->getDecl()) == OMPDeclareTargetDeclAttr::MT_Link && 1042 "Expected declare target link global."); 1043 for (auto &Elem : *this) { 1044 if (isOpenMPTargetExecutionDirective(Elem.Directive)) { 1045 Elem.DeclareTargetLinkVarDecls.push_back(E); 1046 return; 1047 } 1048 } 1049 } 1050 1051 /// Returns the list of globals with declare target link if current directive 1052 /// is target. 1053 ArrayRef<DeclRefExpr *> getLinkGlobals() const { 1054 assert(isOpenMPTargetExecutionDirective(getCurrentDirective()) && 1055 "Expected target executable directive."); 1056 return getTopOfStack().DeclareTargetLinkVarDecls; 1057 } 1058 1059 /// Adds list of allocators expressions. 1060 void addInnerAllocatorExpr(Expr *E) { 1061 getTopOfStack().InnerUsedAllocators.push_back(E); 1062 } 1063 /// Return list of used allocators. 1064 ArrayRef<Expr *> getInnerAllocators() const { 1065 return getTopOfStack().InnerUsedAllocators; 1066 } 1067 /// Marks the declaration as implicitly firstprivate nin the task-based 1068 /// regions. 1069 void addImplicitTaskFirstprivate(unsigned Level, Decl *D) { 1070 getStackElemAtLevel(Level).ImplicitTaskFirstprivates.insert(D); 1071 } 1072 /// Checks if the decl is implicitly firstprivate in the task-based region. 1073 bool isImplicitTaskFirstprivate(Decl *D) const { 1074 return getTopOfStack().ImplicitTaskFirstprivates.contains(D); 1075 } 1076 1077 /// Marks decl as used in uses_allocators clause as the allocator. 1078 void addUsesAllocatorsDecl(const Decl *D, UsesAllocatorsDeclKind Kind) { 1079 getTopOfStack().UsesAllocatorsDecls.try_emplace(D, Kind); 1080 } 1081 /// Checks if specified decl is used in uses allocator clause as the 1082 /// allocator. 1083 Optional<UsesAllocatorsDeclKind> isUsesAllocatorsDecl(unsigned Level, 1084 const Decl *D) const { 1085 const SharingMapTy &StackElem = getTopOfStack(); 1086 auto I = StackElem.UsesAllocatorsDecls.find(D); 1087 if (I == StackElem.UsesAllocatorsDecls.end()) 1088 return None; 1089 return I->getSecond(); 1090 } 1091 Optional<UsesAllocatorsDeclKind> isUsesAllocatorsDecl(const Decl *D) const { 1092 const SharingMapTy &StackElem = getTopOfStack(); 1093 auto I = StackElem.UsesAllocatorsDecls.find(D); 1094 if (I == StackElem.UsesAllocatorsDecls.end()) 1095 return None; 1096 return I->getSecond(); 1097 } 1098 1099 void addDeclareMapperVarRef(Expr *Ref) { 1100 SharingMapTy &StackElem = getTopOfStack(); 1101 StackElem.DeclareMapperVar = Ref; 1102 } 1103 const Expr *getDeclareMapperVarRef() const { 1104 const SharingMapTy *Top = getTopOfStackOrNull(); 1105 return Top ? Top->DeclareMapperVar : nullptr; 1106 } 1107 }; 1108 1109 bool isImplicitTaskingRegion(OpenMPDirectiveKind DKind) { 1110 return isOpenMPParallelDirective(DKind) || isOpenMPTeamsDirective(DKind); 1111 } 1112 1113 bool isImplicitOrExplicitTaskingRegion(OpenMPDirectiveKind DKind) { 1114 return isImplicitTaskingRegion(DKind) || isOpenMPTaskingDirective(DKind) || 1115 DKind == OMPD_unknown; 1116 } 1117 1118 } // namespace 1119 1120 static const Expr *getExprAsWritten(const Expr *E) { 1121 if (const auto *FE = dyn_cast<FullExpr>(E)) 1122 E = FE->getSubExpr(); 1123 1124 if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) 1125 E = MTE->getSubExpr(); 1126 1127 while (const auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E)) 1128 E = Binder->getSubExpr(); 1129 1130 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 1131 E = ICE->getSubExprAsWritten(); 1132 return E->IgnoreParens(); 1133 } 1134 1135 static Expr *getExprAsWritten(Expr *E) { 1136 return const_cast<Expr *>(getExprAsWritten(const_cast<const Expr *>(E))); 1137 } 1138 1139 static const ValueDecl *getCanonicalDecl(const ValueDecl *D) { 1140 if (const auto *CED = dyn_cast<OMPCapturedExprDecl>(D)) 1141 if (const auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit()))) 1142 D = ME->getMemberDecl(); 1143 const auto *VD = dyn_cast<VarDecl>(D); 1144 const auto *FD = dyn_cast<FieldDecl>(D); 1145 if (VD != nullptr) { 1146 VD = VD->getCanonicalDecl(); 1147 D = VD; 1148 } else { 1149 assert(FD); 1150 FD = FD->getCanonicalDecl(); 1151 D = FD; 1152 } 1153 return D; 1154 } 1155 1156 static ValueDecl *getCanonicalDecl(ValueDecl *D) { 1157 return const_cast<ValueDecl *>( 1158 getCanonicalDecl(const_cast<const ValueDecl *>(D))); 1159 } 1160 1161 DSAStackTy::DSAVarData DSAStackTy::getDSA(const_iterator &Iter, 1162 ValueDecl *D) const { 1163 D = getCanonicalDecl(D); 1164 auto *VD = dyn_cast<VarDecl>(D); 1165 const auto *FD = dyn_cast<FieldDecl>(D); 1166 DSAVarData DVar; 1167 if (Iter == end()) { 1168 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 1169 // in a region but not in construct] 1170 // File-scope or namespace-scope variables referenced in called routines 1171 // in the region are shared unless they appear in a threadprivate 1172 // directive. 1173 if (VD && !VD->isFunctionOrMethodVarDecl() && !isa<ParmVarDecl>(VD)) 1174 DVar.CKind = OMPC_shared; 1175 1176 // OpenMP [2.9.1.2, Data-sharing Attribute Rules for Variables Referenced 1177 // in a region but not in construct] 1178 // Variables with static storage duration that are declared in called 1179 // routines in the region are shared. 1180 if (VD && VD->hasGlobalStorage()) 1181 DVar.CKind = OMPC_shared; 1182 1183 // Non-static data members are shared by default. 1184 if (FD) 1185 DVar.CKind = OMPC_shared; 1186 1187 return DVar; 1188 } 1189 1190 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 1191 // in a Construct, C/C++, predetermined, p.1] 1192 // Variables with automatic storage duration that are declared in a scope 1193 // inside the construct are private. 1194 if (VD && isOpenMPLocal(VD, Iter) && VD->isLocalVarDecl() && 1195 (VD->getStorageClass() == SC_Auto || VD->getStorageClass() == SC_None)) { 1196 DVar.CKind = OMPC_private; 1197 return DVar; 1198 } 1199 1200 DVar.DKind = Iter->Directive; 1201 // Explicitly specified attributes and local variables with predetermined 1202 // attributes. 1203 if (Iter->SharingMap.count(D)) { 1204 const DSAInfo &Data = Iter->SharingMap.lookup(D); 1205 DVar.RefExpr = Data.RefExpr.getPointer(); 1206 DVar.PrivateCopy = Data.PrivateCopy; 1207 DVar.CKind = Data.Attributes; 1208 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc; 1209 DVar.Modifier = Data.Modifier; 1210 DVar.AppliedToPointee = Data.AppliedToPointee; 1211 return DVar; 1212 } 1213 1214 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 1215 // in a Construct, C/C++, implicitly determined, p.1] 1216 // In a parallel or task construct, the data-sharing attributes of these 1217 // variables are determined by the default clause, if present. 1218 switch (Iter->DefaultAttr) { 1219 case DSA_shared: 1220 DVar.CKind = OMPC_shared; 1221 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc; 1222 return DVar; 1223 case DSA_none: 1224 return DVar; 1225 case DSA_firstprivate: 1226 if (VD->getStorageDuration() == SD_Static && 1227 VD->getDeclContext()->isFileContext()) { 1228 DVar.CKind = OMPC_unknown; 1229 } else { 1230 DVar.CKind = OMPC_firstprivate; 1231 } 1232 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc; 1233 return DVar; 1234 case DSA_unspecified: 1235 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 1236 // in a Construct, implicitly determined, p.2] 1237 // In a parallel construct, if no default clause is present, these 1238 // variables are shared. 1239 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc; 1240 if ((isOpenMPParallelDirective(DVar.DKind) && 1241 !isOpenMPTaskLoopDirective(DVar.DKind)) || 1242 isOpenMPTeamsDirective(DVar.DKind)) { 1243 DVar.CKind = OMPC_shared; 1244 return DVar; 1245 } 1246 1247 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 1248 // in a Construct, implicitly determined, p.4] 1249 // In a task construct, if no default clause is present, a variable that in 1250 // the enclosing context is determined to be shared by all implicit tasks 1251 // bound to the current team is shared. 1252 if (isOpenMPTaskingDirective(DVar.DKind)) { 1253 DSAVarData DVarTemp; 1254 const_iterator I = Iter, E = end(); 1255 do { 1256 ++I; 1257 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables 1258 // Referenced in a Construct, implicitly determined, p.6] 1259 // In a task construct, if no default clause is present, a variable 1260 // whose data-sharing attribute is not determined by the rules above is 1261 // firstprivate. 1262 DVarTemp = getDSA(I, D); 1263 if (DVarTemp.CKind != OMPC_shared) { 1264 DVar.RefExpr = nullptr; 1265 DVar.CKind = OMPC_firstprivate; 1266 return DVar; 1267 } 1268 } while (I != E && !isImplicitTaskingRegion(I->Directive)); 1269 DVar.CKind = 1270 (DVarTemp.CKind == OMPC_unknown) ? OMPC_firstprivate : OMPC_shared; 1271 return DVar; 1272 } 1273 } 1274 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 1275 // in a Construct, implicitly determined, p.3] 1276 // For constructs other than task, if no default clause is present, these 1277 // variables inherit their data-sharing attributes from the enclosing 1278 // context. 1279 return getDSA(++Iter, D); 1280 } 1281 1282 const Expr *DSAStackTy::addUniqueAligned(const ValueDecl *D, 1283 const Expr *NewDE) { 1284 assert(!isStackEmpty() && "Data sharing attributes stack is empty"); 1285 D = getCanonicalDecl(D); 1286 SharingMapTy &StackElem = getTopOfStack(); 1287 auto It = StackElem.AlignedMap.find(D); 1288 if (It == StackElem.AlignedMap.end()) { 1289 assert(NewDE && "Unexpected nullptr expr to be added into aligned map"); 1290 StackElem.AlignedMap[D] = NewDE; 1291 return nullptr; 1292 } 1293 assert(It->second && "Unexpected nullptr expr in the aligned map"); 1294 return It->second; 1295 } 1296 1297 const Expr *DSAStackTy::addUniqueNontemporal(const ValueDecl *D, 1298 const Expr *NewDE) { 1299 assert(!isStackEmpty() && "Data sharing attributes stack is empty"); 1300 D = getCanonicalDecl(D); 1301 SharingMapTy &StackElem = getTopOfStack(); 1302 auto It = StackElem.NontemporalMap.find(D); 1303 if (It == StackElem.NontemporalMap.end()) { 1304 assert(NewDE && "Unexpected nullptr expr to be added into aligned map"); 1305 StackElem.NontemporalMap[D] = NewDE; 1306 return nullptr; 1307 } 1308 assert(It->second && "Unexpected nullptr expr in the aligned map"); 1309 return It->second; 1310 } 1311 1312 void DSAStackTy::addLoopControlVariable(const ValueDecl *D, VarDecl *Capture) { 1313 assert(!isStackEmpty() && "Data-sharing attributes stack is empty"); 1314 D = getCanonicalDecl(D); 1315 SharingMapTy &StackElem = getTopOfStack(); 1316 StackElem.LCVMap.try_emplace( 1317 D, LCDeclInfo(StackElem.LCVMap.size() + 1, Capture)); 1318 } 1319 1320 const DSAStackTy::LCDeclInfo 1321 DSAStackTy::isLoopControlVariable(const ValueDecl *D) const { 1322 assert(!isStackEmpty() && "Data-sharing attributes stack is empty"); 1323 D = getCanonicalDecl(D); 1324 const SharingMapTy &StackElem = getTopOfStack(); 1325 auto It = StackElem.LCVMap.find(D); 1326 if (It != StackElem.LCVMap.end()) 1327 return It->second; 1328 return {0, nullptr}; 1329 } 1330 1331 const DSAStackTy::LCDeclInfo 1332 DSAStackTy::isLoopControlVariable(const ValueDecl *D, unsigned Level) const { 1333 assert(!isStackEmpty() && "Data-sharing attributes stack is empty"); 1334 D = getCanonicalDecl(D); 1335 for (unsigned I = Level + 1; I > 0; --I) { 1336 const SharingMapTy &StackElem = getStackElemAtLevel(I - 1); 1337 auto It = StackElem.LCVMap.find(D); 1338 if (It != StackElem.LCVMap.end()) 1339 return It->second; 1340 } 1341 return {0, nullptr}; 1342 } 1343 1344 const DSAStackTy::LCDeclInfo 1345 DSAStackTy::isParentLoopControlVariable(const ValueDecl *D) const { 1346 const SharingMapTy *Parent = getSecondOnStackOrNull(); 1347 assert(Parent && "Data-sharing attributes stack is empty"); 1348 D = getCanonicalDecl(D); 1349 auto It = Parent->LCVMap.find(D); 1350 if (It != Parent->LCVMap.end()) 1351 return It->second; 1352 return {0, nullptr}; 1353 } 1354 1355 const ValueDecl *DSAStackTy::getParentLoopControlVariable(unsigned I) const { 1356 const SharingMapTy *Parent = getSecondOnStackOrNull(); 1357 assert(Parent && "Data-sharing attributes stack is empty"); 1358 if (Parent->LCVMap.size() < I) 1359 return nullptr; 1360 for (const auto &Pair : Parent->LCVMap) 1361 if (Pair.second.first == I) 1362 return Pair.first; 1363 return nullptr; 1364 } 1365 1366 void DSAStackTy::addDSA(const ValueDecl *D, const Expr *E, OpenMPClauseKind A, 1367 DeclRefExpr *PrivateCopy, unsigned Modifier, 1368 bool AppliedToPointee) { 1369 D = getCanonicalDecl(D); 1370 if (A == OMPC_threadprivate) { 1371 DSAInfo &Data = Threadprivates[D]; 1372 Data.Attributes = A; 1373 Data.RefExpr.setPointer(E); 1374 Data.PrivateCopy = nullptr; 1375 Data.Modifier = Modifier; 1376 } else { 1377 DSAInfo &Data = getTopOfStack().SharingMap[D]; 1378 assert(Data.Attributes == OMPC_unknown || (A == Data.Attributes) || 1379 (A == OMPC_firstprivate && Data.Attributes == OMPC_lastprivate) || 1380 (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) || 1381 (isLoopControlVariable(D).first && A == OMPC_private)); 1382 Data.Modifier = Modifier; 1383 if (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) { 1384 Data.RefExpr.setInt(/*IntVal=*/true); 1385 return; 1386 } 1387 const bool IsLastprivate = 1388 A == OMPC_lastprivate || Data.Attributes == OMPC_lastprivate; 1389 Data.Attributes = A; 1390 Data.RefExpr.setPointerAndInt(E, IsLastprivate); 1391 Data.PrivateCopy = PrivateCopy; 1392 Data.AppliedToPointee = AppliedToPointee; 1393 if (PrivateCopy) { 1394 DSAInfo &Data = getTopOfStack().SharingMap[PrivateCopy->getDecl()]; 1395 Data.Modifier = Modifier; 1396 Data.Attributes = A; 1397 Data.RefExpr.setPointerAndInt(PrivateCopy, IsLastprivate); 1398 Data.PrivateCopy = nullptr; 1399 Data.AppliedToPointee = AppliedToPointee; 1400 } 1401 } 1402 } 1403 1404 /// Build a variable declaration for OpenMP loop iteration variable. 1405 static VarDecl *buildVarDecl(Sema &SemaRef, SourceLocation Loc, QualType Type, 1406 StringRef Name, const AttrVec *Attrs = nullptr, 1407 DeclRefExpr *OrigRef = nullptr) { 1408 DeclContext *DC = SemaRef.CurContext; 1409 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name); 1410 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc); 1411 auto *Decl = 1412 VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, TInfo, SC_None); 1413 if (Attrs) { 1414 for (specific_attr_iterator<AlignedAttr> I(Attrs->begin()), E(Attrs->end()); 1415 I != E; ++I) 1416 Decl->addAttr(*I); 1417 } 1418 Decl->setImplicit(); 1419 if (OrigRef) { 1420 Decl->addAttr( 1421 OMPReferencedVarAttr::CreateImplicit(SemaRef.Context, OrigRef)); 1422 } 1423 return Decl; 1424 } 1425 1426 static DeclRefExpr *buildDeclRefExpr(Sema &S, VarDecl *D, QualType Ty, 1427 SourceLocation Loc, 1428 bool RefersToCapture = false) { 1429 D->setReferenced(); 1430 D->markUsed(S.Context); 1431 return DeclRefExpr::Create(S.getASTContext(), NestedNameSpecifierLoc(), 1432 SourceLocation(), D, RefersToCapture, Loc, Ty, 1433 VK_LValue); 1434 } 1435 1436 void DSAStackTy::addTaskgroupReductionData(const ValueDecl *D, SourceRange SR, 1437 BinaryOperatorKind BOK) { 1438 D = getCanonicalDecl(D); 1439 assert(!isStackEmpty() && "Data-sharing attributes stack is empty"); 1440 assert( 1441 getTopOfStack().SharingMap[D].Attributes == OMPC_reduction && 1442 "Additional reduction info may be specified only for reduction items."); 1443 ReductionData &ReductionData = getTopOfStack().ReductionMap[D]; 1444 assert(ReductionData.ReductionRange.isInvalid() && 1445 (getTopOfStack().Directive == OMPD_taskgroup || 1446 ((isOpenMPParallelDirective(getTopOfStack().Directive) || 1447 isOpenMPWorksharingDirective(getTopOfStack().Directive)) && 1448 !isOpenMPSimdDirective(getTopOfStack().Directive))) && 1449 "Additional reduction info may be specified only once for reduction " 1450 "items."); 1451 ReductionData.set(BOK, SR); 1452 Expr *&TaskgroupReductionRef = getTopOfStack().TaskgroupReductionRef; 1453 if (!TaskgroupReductionRef) { 1454 VarDecl *VD = buildVarDecl(SemaRef, SR.getBegin(), 1455 SemaRef.Context.VoidPtrTy, ".task_red."); 1456 TaskgroupReductionRef = 1457 buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin()); 1458 } 1459 } 1460 1461 void DSAStackTy::addTaskgroupReductionData(const ValueDecl *D, SourceRange SR, 1462 const Expr *ReductionRef) { 1463 D = getCanonicalDecl(D); 1464 assert(!isStackEmpty() && "Data-sharing attributes stack is empty"); 1465 assert( 1466 getTopOfStack().SharingMap[D].Attributes == OMPC_reduction && 1467 "Additional reduction info may be specified only for reduction items."); 1468 ReductionData &ReductionData = getTopOfStack().ReductionMap[D]; 1469 assert(ReductionData.ReductionRange.isInvalid() && 1470 (getTopOfStack().Directive == OMPD_taskgroup || 1471 ((isOpenMPParallelDirective(getTopOfStack().Directive) || 1472 isOpenMPWorksharingDirective(getTopOfStack().Directive)) && 1473 !isOpenMPSimdDirective(getTopOfStack().Directive))) && 1474 "Additional reduction info may be specified only once for reduction " 1475 "items."); 1476 ReductionData.set(ReductionRef, SR); 1477 Expr *&TaskgroupReductionRef = getTopOfStack().TaskgroupReductionRef; 1478 if (!TaskgroupReductionRef) { 1479 VarDecl *VD = buildVarDecl(SemaRef, SR.getBegin(), 1480 SemaRef.Context.VoidPtrTy, ".task_red."); 1481 TaskgroupReductionRef = 1482 buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin()); 1483 } 1484 } 1485 1486 const DSAStackTy::DSAVarData DSAStackTy::getTopMostTaskgroupReductionData( 1487 const ValueDecl *D, SourceRange &SR, BinaryOperatorKind &BOK, 1488 Expr *&TaskgroupDescriptor) const { 1489 D = getCanonicalDecl(D); 1490 assert(!isStackEmpty() && "Data-sharing attributes stack is empty."); 1491 for (const_iterator I = begin() + 1, E = end(); I != E; ++I) { 1492 const DSAInfo &Data = I->SharingMap.lookup(D); 1493 if (Data.Attributes != OMPC_reduction || 1494 Data.Modifier != OMPC_REDUCTION_task) 1495 continue; 1496 const ReductionData &ReductionData = I->ReductionMap.lookup(D); 1497 if (!ReductionData.ReductionOp || 1498 ReductionData.ReductionOp.is<const Expr *>()) 1499 return DSAVarData(); 1500 SR = ReductionData.ReductionRange; 1501 BOK = ReductionData.ReductionOp.get<ReductionData::BOKPtrType>(); 1502 assert(I->TaskgroupReductionRef && "taskgroup reduction reference " 1503 "expression for the descriptor is not " 1504 "set."); 1505 TaskgroupDescriptor = I->TaskgroupReductionRef; 1506 return DSAVarData(I->Directive, OMPC_reduction, Data.RefExpr.getPointer(), 1507 Data.PrivateCopy, I->DefaultAttrLoc, OMPC_REDUCTION_task, 1508 /*AppliedToPointee=*/false); 1509 } 1510 return DSAVarData(); 1511 } 1512 1513 const DSAStackTy::DSAVarData DSAStackTy::getTopMostTaskgroupReductionData( 1514 const ValueDecl *D, SourceRange &SR, const Expr *&ReductionRef, 1515 Expr *&TaskgroupDescriptor) const { 1516 D = getCanonicalDecl(D); 1517 assert(!isStackEmpty() && "Data-sharing attributes stack is empty."); 1518 for (const_iterator I = begin() + 1, E = end(); I != E; ++I) { 1519 const DSAInfo &Data = I->SharingMap.lookup(D); 1520 if (Data.Attributes != OMPC_reduction || 1521 Data.Modifier != OMPC_REDUCTION_task) 1522 continue; 1523 const ReductionData &ReductionData = I->ReductionMap.lookup(D); 1524 if (!ReductionData.ReductionOp || 1525 !ReductionData.ReductionOp.is<const Expr *>()) 1526 return DSAVarData(); 1527 SR = ReductionData.ReductionRange; 1528 ReductionRef = ReductionData.ReductionOp.get<const Expr *>(); 1529 assert(I->TaskgroupReductionRef && "taskgroup reduction reference " 1530 "expression for the descriptor is not " 1531 "set."); 1532 TaskgroupDescriptor = I->TaskgroupReductionRef; 1533 return DSAVarData(I->Directive, OMPC_reduction, Data.RefExpr.getPointer(), 1534 Data.PrivateCopy, I->DefaultAttrLoc, OMPC_REDUCTION_task, 1535 /*AppliedToPointee=*/false); 1536 } 1537 return DSAVarData(); 1538 } 1539 1540 bool DSAStackTy::isOpenMPLocal(VarDecl *D, const_iterator I) const { 1541 D = D->getCanonicalDecl(); 1542 for (const_iterator E = end(); I != E; ++I) { 1543 if (isImplicitOrExplicitTaskingRegion(I->Directive) || 1544 isOpenMPTargetExecutionDirective(I->Directive)) { 1545 if (I->CurScope) { 1546 Scope *TopScope = I->CurScope->getParent(); 1547 Scope *CurScope = getCurScope(); 1548 while (CurScope && CurScope != TopScope && !CurScope->isDeclScope(D)) 1549 CurScope = CurScope->getParent(); 1550 return CurScope != TopScope; 1551 } 1552 for (DeclContext *DC = D->getDeclContext(); DC; DC = DC->getParent()) 1553 if (I->Context == DC) 1554 return true; 1555 return false; 1556 } 1557 } 1558 return false; 1559 } 1560 1561 static bool isConstNotMutableType(Sema &SemaRef, QualType Type, 1562 bool AcceptIfMutable = true, 1563 bool *IsClassType = nullptr) { 1564 ASTContext &Context = SemaRef.getASTContext(); 1565 Type = Type.getNonReferenceType().getCanonicalType(); 1566 bool IsConstant = Type.isConstant(Context); 1567 Type = Context.getBaseElementType(Type); 1568 const CXXRecordDecl *RD = AcceptIfMutable && SemaRef.getLangOpts().CPlusPlus 1569 ? Type->getAsCXXRecordDecl() 1570 : nullptr; 1571 if (const auto *CTSD = dyn_cast_or_null<ClassTemplateSpecializationDecl>(RD)) 1572 if (const ClassTemplateDecl *CTD = CTSD->getSpecializedTemplate()) 1573 RD = CTD->getTemplatedDecl(); 1574 if (IsClassType) 1575 *IsClassType = RD; 1576 return IsConstant && !(SemaRef.getLangOpts().CPlusPlus && RD && 1577 RD->hasDefinition() && RD->hasMutableFields()); 1578 } 1579 1580 static bool rejectConstNotMutableType(Sema &SemaRef, const ValueDecl *D, 1581 QualType Type, OpenMPClauseKind CKind, 1582 SourceLocation ELoc, 1583 bool AcceptIfMutable = true, 1584 bool ListItemNotVar = false) { 1585 ASTContext &Context = SemaRef.getASTContext(); 1586 bool IsClassType; 1587 if (isConstNotMutableType(SemaRef, Type, AcceptIfMutable, &IsClassType)) { 1588 unsigned Diag = ListItemNotVar ? diag::err_omp_const_list_item 1589 : IsClassType ? diag::err_omp_const_not_mutable_variable 1590 : diag::err_omp_const_variable; 1591 SemaRef.Diag(ELoc, Diag) << getOpenMPClauseName(CKind); 1592 if (!ListItemNotVar && D) { 1593 const VarDecl *VD = dyn_cast<VarDecl>(D); 1594 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) == 1595 VarDecl::DeclarationOnly; 1596 SemaRef.Diag(D->getLocation(), 1597 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 1598 << D; 1599 } 1600 return true; 1601 } 1602 return false; 1603 } 1604 1605 const DSAStackTy::DSAVarData DSAStackTy::getTopDSA(ValueDecl *D, 1606 bool FromParent) { 1607 D = getCanonicalDecl(D); 1608 DSAVarData DVar; 1609 1610 auto *VD = dyn_cast<VarDecl>(D); 1611 auto TI = Threadprivates.find(D); 1612 if (TI != Threadprivates.end()) { 1613 DVar.RefExpr = TI->getSecond().RefExpr.getPointer(); 1614 DVar.CKind = OMPC_threadprivate; 1615 DVar.Modifier = TI->getSecond().Modifier; 1616 return DVar; 1617 } 1618 if (VD && VD->hasAttr<OMPThreadPrivateDeclAttr>()) { 1619 DVar.RefExpr = buildDeclRefExpr( 1620 SemaRef, VD, D->getType().getNonReferenceType(), 1621 VD->getAttr<OMPThreadPrivateDeclAttr>()->getLocation()); 1622 DVar.CKind = OMPC_threadprivate; 1623 addDSA(D, DVar.RefExpr, OMPC_threadprivate); 1624 return DVar; 1625 } 1626 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 1627 // in a Construct, C/C++, predetermined, p.1] 1628 // Variables appearing in threadprivate directives are threadprivate. 1629 if ((VD && VD->getTLSKind() != VarDecl::TLS_None && 1630 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() && 1631 SemaRef.getLangOpts().OpenMPUseTLS && 1632 SemaRef.getASTContext().getTargetInfo().isTLSSupported())) || 1633 (VD && VD->getStorageClass() == SC_Register && 1634 VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())) { 1635 DVar.RefExpr = buildDeclRefExpr( 1636 SemaRef, VD, D->getType().getNonReferenceType(), D->getLocation()); 1637 DVar.CKind = OMPC_threadprivate; 1638 addDSA(D, DVar.RefExpr, OMPC_threadprivate); 1639 return DVar; 1640 } 1641 if (SemaRef.getLangOpts().OpenMPCUDAMode && VD && 1642 VD->isLocalVarDeclOrParm() && !isStackEmpty() && 1643 !isLoopControlVariable(D).first) { 1644 const_iterator IterTarget = 1645 std::find_if(begin(), end(), [](const SharingMapTy &Data) { 1646 return isOpenMPTargetExecutionDirective(Data.Directive); 1647 }); 1648 if (IterTarget != end()) { 1649 const_iterator ParentIterTarget = IterTarget + 1; 1650 for (const_iterator Iter = begin(); Iter != ParentIterTarget; ++Iter) { 1651 if (isOpenMPLocal(VD, Iter)) { 1652 DVar.RefExpr = 1653 buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(), 1654 D->getLocation()); 1655 DVar.CKind = OMPC_threadprivate; 1656 return DVar; 1657 } 1658 } 1659 if (!isClauseParsingMode() || IterTarget != begin()) { 1660 auto DSAIter = IterTarget->SharingMap.find(D); 1661 if (DSAIter != IterTarget->SharingMap.end() && 1662 isOpenMPPrivate(DSAIter->getSecond().Attributes)) { 1663 DVar.RefExpr = DSAIter->getSecond().RefExpr.getPointer(); 1664 DVar.CKind = OMPC_threadprivate; 1665 return DVar; 1666 } 1667 const_iterator End = end(); 1668 if (!SemaRef.isOpenMPCapturedByRef(D, 1669 std::distance(ParentIterTarget, End), 1670 /*OpenMPCaptureLevel=*/0)) { 1671 DVar.RefExpr = 1672 buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(), 1673 IterTarget->ConstructLoc); 1674 DVar.CKind = OMPC_threadprivate; 1675 return DVar; 1676 } 1677 } 1678 } 1679 } 1680 1681 if (isStackEmpty()) 1682 // Not in OpenMP execution region and top scope was already checked. 1683 return DVar; 1684 1685 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 1686 // in a Construct, C/C++, predetermined, p.4] 1687 // Static data members are shared. 1688 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 1689 // in a Construct, C/C++, predetermined, p.7] 1690 // Variables with static storage duration that are declared in a scope 1691 // inside the construct are shared. 1692 if (VD && VD->isStaticDataMember()) { 1693 // Check for explicitly specified attributes. 1694 const_iterator I = begin(); 1695 const_iterator EndI = end(); 1696 if (FromParent && I != EndI) 1697 ++I; 1698 if (I != EndI) { 1699 auto It = I->SharingMap.find(D); 1700 if (It != I->SharingMap.end()) { 1701 const DSAInfo &Data = It->getSecond(); 1702 DVar.RefExpr = Data.RefExpr.getPointer(); 1703 DVar.PrivateCopy = Data.PrivateCopy; 1704 DVar.CKind = Data.Attributes; 1705 DVar.ImplicitDSALoc = I->DefaultAttrLoc; 1706 DVar.DKind = I->Directive; 1707 DVar.Modifier = Data.Modifier; 1708 DVar.AppliedToPointee = Data.AppliedToPointee; 1709 return DVar; 1710 } 1711 } 1712 1713 DVar.CKind = OMPC_shared; 1714 return DVar; 1715 } 1716 1717 auto &&MatchesAlways = [](OpenMPDirectiveKind) { return true; }; 1718 // The predetermined shared attribute for const-qualified types having no 1719 // mutable members was removed after OpenMP 3.1. 1720 if (SemaRef.LangOpts.OpenMP <= 31) { 1721 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 1722 // in a Construct, C/C++, predetermined, p.6] 1723 // Variables with const qualified type having no mutable member are 1724 // shared. 1725 if (isConstNotMutableType(SemaRef, D->getType())) { 1726 // Variables with const-qualified type having no mutable member may be 1727 // listed in a firstprivate clause, even if they are static data members. 1728 DSAVarData DVarTemp = hasInnermostDSA( 1729 D, 1730 [](OpenMPClauseKind C, bool) { 1731 return C == OMPC_firstprivate || C == OMPC_shared; 1732 }, 1733 MatchesAlways, FromParent); 1734 if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr) 1735 return DVarTemp; 1736 1737 DVar.CKind = OMPC_shared; 1738 return DVar; 1739 } 1740 } 1741 1742 // Explicitly specified attributes and local variables with predetermined 1743 // attributes. 1744 const_iterator I = begin(); 1745 const_iterator EndI = end(); 1746 if (FromParent && I != EndI) 1747 ++I; 1748 if (I == EndI) 1749 return DVar; 1750 auto It = I->SharingMap.find(D); 1751 if (It != I->SharingMap.end()) { 1752 const DSAInfo &Data = It->getSecond(); 1753 DVar.RefExpr = Data.RefExpr.getPointer(); 1754 DVar.PrivateCopy = Data.PrivateCopy; 1755 DVar.CKind = Data.Attributes; 1756 DVar.ImplicitDSALoc = I->DefaultAttrLoc; 1757 DVar.DKind = I->Directive; 1758 DVar.Modifier = Data.Modifier; 1759 DVar.AppliedToPointee = Data.AppliedToPointee; 1760 } 1761 1762 return DVar; 1763 } 1764 1765 const DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(ValueDecl *D, 1766 bool FromParent) const { 1767 if (isStackEmpty()) { 1768 const_iterator I; 1769 return getDSA(I, D); 1770 } 1771 D = getCanonicalDecl(D); 1772 const_iterator StartI = begin(); 1773 const_iterator EndI = end(); 1774 if (FromParent && StartI != EndI) 1775 ++StartI; 1776 return getDSA(StartI, D); 1777 } 1778 1779 const DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(ValueDecl *D, 1780 unsigned Level) const { 1781 if (getStackSize() <= Level) 1782 return DSAVarData(); 1783 D = getCanonicalDecl(D); 1784 const_iterator StartI = std::next(begin(), getStackSize() - 1 - Level); 1785 return getDSA(StartI, D); 1786 } 1787 1788 const DSAStackTy::DSAVarData 1789 DSAStackTy::hasDSA(ValueDecl *D, 1790 const llvm::function_ref<bool(OpenMPClauseKind, bool)> CPred, 1791 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred, 1792 bool FromParent) const { 1793 if (isStackEmpty()) 1794 return {}; 1795 D = getCanonicalDecl(D); 1796 const_iterator I = begin(); 1797 const_iterator EndI = end(); 1798 if (FromParent && I != EndI) 1799 ++I; 1800 for (; I != EndI; ++I) { 1801 if (!DPred(I->Directive) && 1802 !isImplicitOrExplicitTaskingRegion(I->Directive)) 1803 continue; 1804 const_iterator NewI = I; 1805 DSAVarData DVar = getDSA(NewI, D); 1806 if (I == NewI && CPred(DVar.CKind, DVar.AppliedToPointee)) 1807 return DVar; 1808 } 1809 return {}; 1810 } 1811 1812 const DSAStackTy::DSAVarData DSAStackTy::hasInnermostDSA( 1813 ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind, bool)> CPred, 1814 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred, 1815 bool FromParent) const { 1816 if (isStackEmpty()) 1817 return {}; 1818 D = getCanonicalDecl(D); 1819 const_iterator StartI = begin(); 1820 const_iterator EndI = end(); 1821 if (FromParent && StartI != EndI) 1822 ++StartI; 1823 if (StartI == EndI || !DPred(StartI->Directive)) 1824 return {}; 1825 const_iterator NewI = StartI; 1826 DSAVarData DVar = getDSA(NewI, D); 1827 return (NewI == StartI && CPred(DVar.CKind, DVar.AppliedToPointee)) 1828 ? DVar 1829 : DSAVarData(); 1830 } 1831 1832 bool DSAStackTy::hasExplicitDSA( 1833 const ValueDecl *D, 1834 const llvm::function_ref<bool(OpenMPClauseKind, bool)> CPred, 1835 unsigned Level, bool NotLastprivate) const { 1836 if (getStackSize() <= Level) 1837 return false; 1838 D = getCanonicalDecl(D); 1839 const SharingMapTy &StackElem = getStackElemAtLevel(Level); 1840 auto I = StackElem.SharingMap.find(D); 1841 if (I != StackElem.SharingMap.end() && I->getSecond().RefExpr.getPointer() && 1842 CPred(I->getSecond().Attributes, I->getSecond().AppliedToPointee) && 1843 (!NotLastprivate || !I->getSecond().RefExpr.getInt())) 1844 return true; 1845 // Check predetermined rules for the loop control variables. 1846 auto LI = StackElem.LCVMap.find(D); 1847 if (LI != StackElem.LCVMap.end()) 1848 return CPred(OMPC_private, /*AppliedToPointee=*/false); 1849 return false; 1850 } 1851 1852 bool DSAStackTy::hasExplicitDirective( 1853 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred, 1854 unsigned Level) const { 1855 if (getStackSize() <= Level) 1856 return false; 1857 const SharingMapTy &StackElem = getStackElemAtLevel(Level); 1858 return DPred(StackElem.Directive); 1859 } 1860 1861 bool DSAStackTy::hasDirective( 1862 const llvm::function_ref<bool(OpenMPDirectiveKind, 1863 const DeclarationNameInfo &, SourceLocation)> 1864 DPred, 1865 bool FromParent) const { 1866 // We look only in the enclosing region. 1867 size_t Skip = FromParent ? 2 : 1; 1868 for (const_iterator I = begin() + std::min(Skip, getStackSize()), E = end(); 1869 I != E; ++I) { 1870 if (DPred(I->Directive, I->DirectiveName, I->ConstructLoc)) 1871 return true; 1872 } 1873 return false; 1874 } 1875 1876 void Sema::InitDataSharingAttributesStack() { 1877 VarDataSharingAttributesStack = new DSAStackTy(*this); 1878 } 1879 1880 #define DSAStack static_cast<DSAStackTy *>(VarDataSharingAttributesStack) 1881 1882 void Sema::pushOpenMPFunctionRegion() { DSAStack->pushFunction(); } 1883 1884 void Sema::popOpenMPFunctionRegion(const FunctionScopeInfo *OldFSI) { 1885 DSAStack->popFunction(OldFSI); 1886 } 1887 1888 static bool isOpenMPDeviceDelayedContext(Sema &S) { 1889 assert(S.LangOpts.OpenMP && S.LangOpts.OpenMPIsDevice && 1890 "Expected OpenMP device compilation."); 1891 return !S.isInOpenMPTargetExecutionDirective(); 1892 } 1893 1894 namespace { 1895 /// Status of the function emission on the host/device. 1896 enum class FunctionEmissionStatus { 1897 Emitted, 1898 Discarded, 1899 Unknown, 1900 }; 1901 } // anonymous namespace 1902 1903 Sema::SemaDiagnosticBuilder Sema::diagIfOpenMPDeviceCode(SourceLocation Loc, 1904 unsigned DiagID, 1905 FunctionDecl *FD) { 1906 assert(LangOpts.OpenMP && LangOpts.OpenMPIsDevice && 1907 "Expected OpenMP device compilation."); 1908 1909 SemaDiagnosticBuilder::Kind Kind = SemaDiagnosticBuilder::K_Nop; 1910 if (FD) { 1911 FunctionEmissionStatus FES = getEmissionStatus(FD); 1912 switch (FES) { 1913 case FunctionEmissionStatus::Emitted: 1914 Kind = SemaDiagnosticBuilder::K_Immediate; 1915 break; 1916 case FunctionEmissionStatus::Unknown: 1917 // TODO: We should always delay diagnostics here in case a target 1918 // region is in a function we do not emit. However, as the 1919 // current diagnostics are associated with the function containing 1920 // the target region and we do not emit that one, we would miss out 1921 // on diagnostics for the target region itself. We need to anchor 1922 // the diagnostics with the new generated function *or* ensure we 1923 // emit diagnostics associated with the surrounding function. 1924 Kind = isOpenMPDeviceDelayedContext(*this) 1925 ? SemaDiagnosticBuilder::K_Deferred 1926 : SemaDiagnosticBuilder::K_Immediate; 1927 break; 1928 case FunctionEmissionStatus::TemplateDiscarded: 1929 case FunctionEmissionStatus::OMPDiscarded: 1930 Kind = SemaDiagnosticBuilder::K_Nop; 1931 break; 1932 case FunctionEmissionStatus::CUDADiscarded: 1933 llvm_unreachable("CUDADiscarded unexpected in OpenMP device compilation"); 1934 break; 1935 } 1936 } 1937 1938 return SemaDiagnosticBuilder(Kind, Loc, DiagID, FD, *this); 1939 } 1940 1941 Sema::SemaDiagnosticBuilder Sema::diagIfOpenMPHostCode(SourceLocation Loc, 1942 unsigned DiagID, 1943 FunctionDecl *FD) { 1944 assert(LangOpts.OpenMP && !LangOpts.OpenMPIsDevice && 1945 "Expected OpenMP host compilation."); 1946 1947 SemaDiagnosticBuilder::Kind Kind = SemaDiagnosticBuilder::K_Nop; 1948 if (FD) { 1949 FunctionEmissionStatus FES = getEmissionStatus(FD); 1950 switch (FES) { 1951 case FunctionEmissionStatus::Emitted: 1952 Kind = SemaDiagnosticBuilder::K_Immediate; 1953 break; 1954 case FunctionEmissionStatus::Unknown: 1955 Kind = SemaDiagnosticBuilder::K_Deferred; 1956 break; 1957 case FunctionEmissionStatus::TemplateDiscarded: 1958 case FunctionEmissionStatus::OMPDiscarded: 1959 case FunctionEmissionStatus::CUDADiscarded: 1960 Kind = SemaDiagnosticBuilder::K_Nop; 1961 break; 1962 } 1963 } 1964 1965 return SemaDiagnosticBuilder(Kind, Loc, DiagID, FD, *this); 1966 } 1967 1968 static OpenMPDefaultmapClauseKind 1969 getVariableCategoryFromDecl(const LangOptions &LO, const ValueDecl *VD) { 1970 if (LO.OpenMP <= 45) { 1971 if (VD->getType().getNonReferenceType()->isScalarType()) 1972 return OMPC_DEFAULTMAP_scalar; 1973 return OMPC_DEFAULTMAP_aggregate; 1974 } 1975 if (VD->getType().getNonReferenceType()->isAnyPointerType()) 1976 return OMPC_DEFAULTMAP_pointer; 1977 if (VD->getType().getNonReferenceType()->isScalarType()) 1978 return OMPC_DEFAULTMAP_scalar; 1979 return OMPC_DEFAULTMAP_aggregate; 1980 } 1981 1982 bool Sema::isOpenMPCapturedByRef(const ValueDecl *D, unsigned Level, 1983 unsigned OpenMPCaptureLevel) const { 1984 assert(LangOpts.OpenMP && "OpenMP is not allowed"); 1985 1986 ASTContext &Ctx = getASTContext(); 1987 bool IsByRef = true; 1988 1989 // Find the directive that is associated with the provided scope. 1990 D = cast<ValueDecl>(D->getCanonicalDecl()); 1991 QualType Ty = D->getType(); 1992 1993 bool IsVariableUsedInMapClause = false; 1994 if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, Level)) { 1995 // This table summarizes how a given variable should be passed to the device 1996 // given its type and the clauses where it appears. This table is based on 1997 // the description in OpenMP 4.5 [2.10.4, target Construct] and 1998 // OpenMP 4.5 [2.15.5, Data-mapping Attribute Rules and Clauses]. 1999 // 2000 // ========================================================================= 2001 // | type | defaultmap | pvt | first | is_device_ptr | map | res. | 2002 // | |(tofrom:scalar)| | pvt | | | | 2003 // ========================================================================= 2004 // | scl | | | | - | | bycopy| 2005 // | scl | | - | x | - | - | bycopy| 2006 // | scl | | x | - | - | - | null | 2007 // | scl | x | | | - | | byref | 2008 // | scl | x | - | x | - | - | bycopy| 2009 // | scl | x | x | - | - | - | null | 2010 // | scl | | - | - | - | x | byref | 2011 // | scl | x | - | - | - | x | byref | 2012 // 2013 // | agg | n.a. | | | - | | byref | 2014 // | agg | n.a. | - | x | - | - | byref | 2015 // | agg | n.a. | x | - | - | - | null | 2016 // | agg | n.a. | - | - | - | x | byref | 2017 // | agg | n.a. | - | - | - | x[] | byref | 2018 // 2019 // | ptr | n.a. | | | - | | bycopy| 2020 // | ptr | n.a. | - | x | - | - | bycopy| 2021 // | ptr | n.a. | x | - | - | - | null | 2022 // | ptr | n.a. | - | - | - | x | byref | 2023 // | ptr | n.a. | - | - | - | x[] | bycopy| 2024 // | ptr | n.a. | - | - | x | | bycopy| 2025 // | ptr | n.a. | - | - | x | x | bycopy| 2026 // | ptr | n.a. | - | - | x | x[] | bycopy| 2027 // ========================================================================= 2028 // Legend: 2029 // scl - scalar 2030 // ptr - pointer 2031 // agg - aggregate 2032 // x - applies 2033 // - - invalid in this combination 2034 // [] - mapped with an array section 2035 // byref - should be mapped by reference 2036 // byval - should be mapped by value 2037 // null - initialize a local variable to null on the device 2038 // 2039 // Observations: 2040 // - All scalar declarations that show up in a map clause have to be passed 2041 // by reference, because they may have been mapped in the enclosing data 2042 // environment. 2043 // - If the scalar value does not fit the size of uintptr, it has to be 2044 // passed by reference, regardless the result in the table above. 2045 // - For pointers mapped by value that have either an implicit map or an 2046 // array section, the runtime library may pass the NULL value to the 2047 // device instead of the value passed to it by the compiler. 2048 2049 if (Ty->isReferenceType()) 2050 Ty = Ty->castAs<ReferenceType>()->getPointeeType(); 2051 2052 // Locate map clauses and see if the variable being captured is referred to 2053 // in any of those clauses. Here we only care about variables, not fields, 2054 // because fields are part of aggregates. 2055 bool IsVariableAssociatedWithSection = false; 2056 2057 DSAStack->checkMappableExprComponentListsForDeclAtLevel( 2058 D, Level, 2059 [&IsVariableUsedInMapClause, &IsVariableAssociatedWithSection, 2060 D](OMPClauseMappableExprCommon::MappableExprComponentListRef 2061 MapExprComponents, 2062 OpenMPClauseKind WhereFoundClauseKind) { 2063 // Only the map clause information influences how a variable is 2064 // captured. E.g. is_device_ptr does not require changing the default 2065 // behavior. 2066 if (WhereFoundClauseKind != OMPC_map) 2067 return false; 2068 2069 auto EI = MapExprComponents.rbegin(); 2070 auto EE = MapExprComponents.rend(); 2071 2072 assert(EI != EE && "Invalid map expression!"); 2073 2074 if (isa<DeclRefExpr>(EI->getAssociatedExpression())) 2075 IsVariableUsedInMapClause |= EI->getAssociatedDeclaration() == D; 2076 2077 ++EI; 2078 if (EI == EE) 2079 return false; 2080 2081 if (isa<ArraySubscriptExpr>(EI->getAssociatedExpression()) || 2082 isa<OMPArraySectionExpr>(EI->getAssociatedExpression()) || 2083 isa<MemberExpr>(EI->getAssociatedExpression()) || 2084 isa<OMPArrayShapingExpr>(EI->getAssociatedExpression())) { 2085 IsVariableAssociatedWithSection = true; 2086 // There is nothing more we need to know about this variable. 2087 return true; 2088 } 2089 2090 // Keep looking for more map info. 2091 return false; 2092 }); 2093 2094 if (IsVariableUsedInMapClause) { 2095 // If variable is identified in a map clause it is always captured by 2096 // reference except if it is a pointer that is dereferenced somehow. 2097 IsByRef = !(Ty->isPointerType() && IsVariableAssociatedWithSection); 2098 } else { 2099 // By default, all the data that has a scalar type is mapped by copy 2100 // (except for reduction variables). 2101 // Defaultmap scalar is mutual exclusive to defaultmap pointer 2102 IsByRef = (DSAStack->isForceCaptureByReferenceInTargetExecutable() && 2103 !Ty->isAnyPointerType()) || 2104 !Ty->isScalarType() || 2105 DSAStack->isDefaultmapCapturedByRef( 2106 Level, getVariableCategoryFromDecl(LangOpts, D)) || 2107 DSAStack->hasExplicitDSA( 2108 D, 2109 [](OpenMPClauseKind K, bool AppliedToPointee) { 2110 return K == OMPC_reduction && !AppliedToPointee; 2111 }, 2112 Level); 2113 } 2114 } 2115 2116 if (IsByRef && Ty.getNonReferenceType()->isScalarType()) { 2117 IsByRef = 2118 ((IsVariableUsedInMapClause && 2119 DSAStack->getCaptureRegion(Level, OpenMPCaptureLevel) == 2120 OMPD_target) || 2121 !(DSAStack->hasExplicitDSA( 2122 D, 2123 [](OpenMPClauseKind K, bool AppliedToPointee) -> bool { 2124 return K == OMPC_firstprivate || 2125 (K == OMPC_reduction && AppliedToPointee); 2126 }, 2127 Level, /*NotLastprivate=*/true) || 2128 DSAStack->isUsesAllocatorsDecl(Level, D))) && 2129 // If the variable is artificial and must be captured by value - try to 2130 // capture by value. 2131 !(isa<OMPCapturedExprDecl>(D) && !D->hasAttr<OMPCaptureNoInitAttr>() && 2132 !cast<OMPCapturedExprDecl>(D)->getInit()->isGLValue()) && 2133 // If the variable is implicitly firstprivate and scalar - capture by 2134 // copy 2135 !(DSAStack->getDefaultDSA() == DSA_firstprivate && 2136 !DSAStack->hasExplicitDSA( 2137 D, [](OpenMPClauseKind K, bool) { return K != OMPC_unknown; }, 2138 Level) && 2139 !DSAStack->isLoopControlVariable(D, Level).first); 2140 } 2141 2142 // When passing data by copy, we need to make sure it fits the uintptr size 2143 // and alignment, because the runtime library only deals with uintptr types. 2144 // If it does not fit the uintptr size, we need to pass the data by reference 2145 // instead. 2146 if (!IsByRef && 2147 (Ctx.getTypeSizeInChars(Ty) > 2148 Ctx.getTypeSizeInChars(Ctx.getUIntPtrType()) || 2149 Ctx.getDeclAlign(D) > Ctx.getTypeAlignInChars(Ctx.getUIntPtrType()))) { 2150 IsByRef = true; 2151 } 2152 2153 return IsByRef; 2154 } 2155 2156 unsigned Sema::getOpenMPNestingLevel() const { 2157 assert(getLangOpts().OpenMP); 2158 return DSAStack->getNestingLevel(); 2159 } 2160 2161 bool Sema::isInOpenMPTargetExecutionDirective() const { 2162 return (isOpenMPTargetExecutionDirective(DSAStack->getCurrentDirective()) && 2163 !DSAStack->isClauseParsingMode()) || 2164 DSAStack->hasDirective( 2165 [](OpenMPDirectiveKind K, const DeclarationNameInfo &, 2166 SourceLocation) -> bool { 2167 return isOpenMPTargetExecutionDirective(K); 2168 }, 2169 false); 2170 } 2171 2172 VarDecl *Sema::isOpenMPCapturedDecl(ValueDecl *D, bool CheckScopeInfo, 2173 unsigned StopAt) { 2174 assert(LangOpts.OpenMP && "OpenMP is not allowed"); 2175 D = getCanonicalDecl(D); 2176 2177 auto *VD = dyn_cast<VarDecl>(D); 2178 // Do not capture constexpr variables. 2179 if (VD && VD->isConstexpr()) 2180 return nullptr; 2181 2182 // If we want to determine whether the variable should be captured from the 2183 // perspective of the current capturing scope, and we've already left all the 2184 // capturing scopes of the top directive on the stack, check from the 2185 // perspective of its parent directive (if any) instead. 2186 DSAStackTy::ParentDirectiveScope InParentDirectiveRAII( 2187 *DSAStack, CheckScopeInfo && DSAStack->isBodyComplete()); 2188 2189 // If we are attempting to capture a global variable in a directive with 2190 // 'target' we return true so that this global is also mapped to the device. 2191 // 2192 if (VD && !VD->hasLocalStorage() && 2193 (getCurCapturedRegion() || getCurBlock() || getCurLambda())) { 2194 if (isInOpenMPTargetExecutionDirective()) { 2195 DSAStackTy::DSAVarData DVarTop = 2196 DSAStack->getTopDSA(D, DSAStack->isClauseParsingMode()); 2197 if (DVarTop.CKind != OMPC_unknown && DVarTop.RefExpr) 2198 return VD; 2199 // If the declaration is enclosed in a 'declare target' directive, 2200 // then it should not be captured. 2201 // 2202 if (OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) 2203 return nullptr; 2204 CapturedRegionScopeInfo *CSI = nullptr; 2205 for (FunctionScopeInfo *FSI : llvm::drop_begin( 2206 llvm::reverse(FunctionScopes), 2207 CheckScopeInfo ? (FunctionScopes.size() - (StopAt + 1)) : 0)) { 2208 if (!isa<CapturingScopeInfo>(FSI)) 2209 return nullptr; 2210 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(FSI)) 2211 if (RSI->CapRegionKind == CR_OpenMP) { 2212 CSI = RSI; 2213 break; 2214 } 2215 } 2216 assert(CSI && "Failed to find CapturedRegionScopeInfo"); 2217 SmallVector<OpenMPDirectiveKind, 4> Regions; 2218 getOpenMPCaptureRegions(Regions, 2219 DSAStack->getDirective(CSI->OpenMPLevel)); 2220 if (Regions[CSI->OpenMPCaptureLevel] != OMPD_task) 2221 return VD; 2222 } 2223 if (isInOpenMPDeclareTargetContext()) { 2224 // Try to mark variable as declare target if it is used in capturing 2225 // regions. 2226 if (LangOpts.OpenMP <= 45 && 2227 !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) 2228 checkDeclIsAllowedInOpenMPTarget(nullptr, VD); 2229 return nullptr; 2230 } 2231 } 2232 2233 if (CheckScopeInfo) { 2234 bool OpenMPFound = false; 2235 for (unsigned I = StopAt + 1; I > 0; --I) { 2236 FunctionScopeInfo *FSI = FunctionScopes[I - 1]; 2237 if (!isa<CapturingScopeInfo>(FSI)) 2238 return nullptr; 2239 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(FSI)) 2240 if (RSI->CapRegionKind == CR_OpenMP) { 2241 OpenMPFound = true; 2242 break; 2243 } 2244 } 2245 if (!OpenMPFound) 2246 return nullptr; 2247 } 2248 2249 if (DSAStack->getCurrentDirective() != OMPD_unknown && 2250 (!DSAStack->isClauseParsingMode() || 2251 DSAStack->getParentDirective() != OMPD_unknown)) { 2252 auto &&Info = DSAStack->isLoopControlVariable(D); 2253 if (Info.first || 2254 (VD && VD->hasLocalStorage() && 2255 isImplicitOrExplicitTaskingRegion(DSAStack->getCurrentDirective())) || 2256 (VD && DSAStack->isForceVarCapturing())) 2257 return VD ? VD : Info.second; 2258 DSAStackTy::DSAVarData DVarTop = 2259 DSAStack->getTopDSA(D, DSAStack->isClauseParsingMode()); 2260 if (DVarTop.CKind != OMPC_unknown && isOpenMPPrivate(DVarTop.CKind) && 2261 (!VD || VD->hasLocalStorage() || !DVarTop.AppliedToPointee)) 2262 return VD ? VD : cast<VarDecl>(DVarTop.PrivateCopy->getDecl()); 2263 // Threadprivate variables must not be captured. 2264 if (isOpenMPThreadPrivate(DVarTop.CKind)) 2265 return nullptr; 2266 // The variable is not private or it is the variable in the directive with 2267 // default(none) clause and not used in any clause. 2268 DSAStackTy::DSAVarData DVarPrivate = DSAStack->hasDSA( 2269 D, 2270 [](OpenMPClauseKind C, bool AppliedToPointee) { 2271 return isOpenMPPrivate(C) && !AppliedToPointee; 2272 }, 2273 [](OpenMPDirectiveKind) { return true; }, 2274 DSAStack->isClauseParsingMode()); 2275 // Global shared must not be captured. 2276 if (VD && !VD->hasLocalStorage() && DVarPrivate.CKind == OMPC_unknown && 2277 ((DSAStack->getDefaultDSA() != DSA_none && 2278 DSAStack->getDefaultDSA() != DSA_firstprivate) || 2279 DVarTop.CKind == OMPC_shared)) 2280 return nullptr; 2281 if (DVarPrivate.CKind != OMPC_unknown || 2282 (VD && (DSAStack->getDefaultDSA() == DSA_none || 2283 DSAStack->getDefaultDSA() == DSA_firstprivate))) 2284 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl()); 2285 } 2286 return nullptr; 2287 } 2288 2289 void Sema::adjustOpenMPTargetScopeIndex(unsigned &FunctionScopesIndex, 2290 unsigned Level) const { 2291 FunctionScopesIndex -= getOpenMPCaptureLevels(DSAStack->getDirective(Level)); 2292 } 2293 2294 void Sema::startOpenMPLoop() { 2295 assert(LangOpts.OpenMP && "OpenMP must be enabled."); 2296 if (isOpenMPLoopDirective(DSAStack->getCurrentDirective())) 2297 DSAStack->loopInit(); 2298 } 2299 2300 void Sema::startOpenMPCXXRangeFor() { 2301 assert(LangOpts.OpenMP && "OpenMP must be enabled."); 2302 if (isOpenMPLoopDirective(DSAStack->getCurrentDirective())) { 2303 DSAStack->resetPossibleLoopCounter(); 2304 DSAStack->loopStart(); 2305 } 2306 } 2307 2308 OpenMPClauseKind Sema::isOpenMPPrivateDecl(ValueDecl *D, unsigned Level, 2309 unsigned CapLevel) const { 2310 assert(LangOpts.OpenMP && "OpenMP is not allowed"); 2311 if (DSAStack->hasExplicitDirective(isOpenMPTaskingDirective, Level)) { 2312 bool IsTriviallyCopyable = 2313 D->getType().getNonReferenceType().isTriviallyCopyableType(Context) && 2314 !D->getType() 2315 .getNonReferenceType() 2316 .getCanonicalType() 2317 ->getAsCXXRecordDecl(); 2318 OpenMPDirectiveKind DKind = DSAStack->getDirective(Level); 2319 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions; 2320 getOpenMPCaptureRegions(CaptureRegions, DKind); 2321 if (isOpenMPTaskingDirective(CaptureRegions[CapLevel]) && 2322 (IsTriviallyCopyable || 2323 !isOpenMPTaskLoopDirective(CaptureRegions[CapLevel]))) { 2324 if (DSAStack->hasExplicitDSA( 2325 D, 2326 [](OpenMPClauseKind K, bool) { return K == OMPC_firstprivate; }, 2327 Level, /*NotLastprivate=*/true)) 2328 return OMPC_firstprivate; 2329 DSAStackTy::DSAVarData DVar = DSAStack->getImplicitDSA(D, Level); 2330 if (DVar.CKind != OMPC_shared && 2331 !DSAStack->isLoopControlVariable(D, Level).first && !DVar.RefExpr) { 2332 DSAStack->addImplicitTaskFirstprivate(Level, D); 2333 return OMPC_firstprivate; 2334 } 2335 } 2336 } 2337 if (isOpenMPLoopDirective(DSAStack->getCurrentDirective())) { 2338 if (DSAStack->getAssociatedLoops() > 0 && !DSAStack->isLoopStarted()) { 2339 DSAStack->resetPossibleLoopCounter(D); 2340 DSAStack->loopStart(); 2341 return OMPC_private; 2342 } 2343 if ((DSAStack->getPossiblyLoopCunter() == D->getCanonicalDecl() || 2344 DSAStack->isLoopControlVariable(D).first) && 2345 !DSAStack->hasExplicitDSA( 2346 D, [](OpenMPClauseKind K, bool) { return K != OMPC_private; }, 2347 Level) && 2348 !isOpenMPSimdDirective(DSAStack->getCurrentDirective())) 2349 return OMPC_private; 2350 } 2351 if (const auto *VD = dyn_cast<VarDecl>(D)) { 2352 if (DSAStack->isThreadPrivate(const_cast<VarDecl *>(VD)) && 2353 DSAStack->isForceVarCapturing() && 2354 !DSAStack->hasExplicitDSA( 2355 D, [](OpenMPClauseKind K, bool) { return K == OMPC_copyin; }, 2356 Level)) 2357 return OMPC_private; 2358 } 2359 // User-defined allocators are private since they must be defined in the 2360 // context of target region. 2361 if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, Level) && 2362 DSAStack->isUsesAllocatorsDecl(Level, D).getValueOr( 2363 DSAStackTy::UsesAllocatorsDeclKind::AllocatorTrait) == 2364 DSAStackTy::UsesAllocatorsDeclKind::UserDefinedAllocator) 2365 return OMPC_private; 2366 return (DSAStack->hasExplicitDSA( 2367 D, [](OpenMPClauseKind K, bool) { return K == OMPC_private; }, 2368 Level) || 2369 (DSAStack->isClauseParsingMode() && 2370 DSAStack->getClauseParsingMode() == OMPC_private) || 2371 // Consider taskgroup reduction descriptor variable a private 2372 // to avoid possible capture in the region. 2373 (DSAStack->hasExplicitDirective( 2374 [](OpenMPDirectiveKind K) { 2375 return K == OMPD_taskgroup || 2376 ((isOpenMPParallelDirective(K) || 2377 isOpenMPWorksharingDirective(K)) && 2378 !isOpenMPSimdDirective(K)); 2379 }, 2380 Level) && 2381 DSAStack->isTaskgroupReductionRef(D, Level))) 2382 ? OMPC_private 2383 : OMPC_unknown; 2384 } 2385 2386 void Sema::setOpenMPCaptureKind(FieldDecl *FD, const ValueDecl *D, 2387 unsigned Level) { 2388 assert(LangOpts.OpenMP && "OpenMP is not allowed"); 2389 D = getCanonicalDecl(D); 2390 OpenMPClauseKind OMPC = OMPC_unknown; 2391 for (unsigned I = DSAStack->getNestingLevel() + 1; I > Level; --I) { 2392 const unsigned NewLevel = I - 1; 2393 if (DSAStack->hasExplicitDSA( 2394 D, 2395 [&OMPC](const OpenMPClauseKind K, bool AppliedToPointee) { 2396 if (isOpenMPPrivate(K) && !AppliedToPointee) { 2397 OMPC = K; 2398 return true; 2399 } 2400 return false; 2401 }, 2402 NewLevel)) 2403 break; 2404 if (DSAStack->checkMappableExprComponentListsForDeclAtLevel( 2405 D, NewLevel, 2406 [](OMPClauseMappableExprCommon::MappableExprComponentListRef, 2407 OpenMPClauseKind) { return true; })) { 2408 OMPC = OMPC_map; 2409 break; 2410 } 2411 if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, 2412 NewLevel)) { 2413 OMPC = OMPC_map; 2414 if (DSAStack->mustBeFirstprivateAtLevel( 2415 NewLevel, getVariableCategoryFromDecl(LangOpts, D))) 2416 OMPC = OMPC_firstprivate; 2417 break; 2418 } 2419 } 2420 if (OMPC != OMPC_unknown) 2421 FD->addAttr(OMPCaptureKindAttr::CreateImplicit(Context, unsigned(OMPC))); 2422 } 2423 2424 bool Sema::isOpenMPTargetCapturedDecl(const ValueDecl *D, unsigned Level, 2425 unsigned CaptureLevel) const { 2426 assert(LangOpts.OpenMP && "OpenMP is not allowed"); 2427 // Return true if the current level is no longer enclosed in a target region. 2428 2429 SmallVector<OpenMPDirectiveKind, 4> Regions; 2430 getOpenMPCaptureRegions(Regions, DSAStack->getDirective(Level)); 2431 const auto *VD = dyn_cast<VarDecl>(D); 2432 return VD && !VD->hasLocalStorage() && 2433 DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, 2434 Level) && 2435 Regions[CaptureLevel] != OMPD_task; 2436 } 2437 2438 bool Sema::isOpenMPGlobalCapturedDecl(ValueDecl *D, unsigned Level, 2439 unsigned CaptureLevel) const { 2440 assert(LangOpts.OpenMP && "OpenMP is not allowed"); 2441 // Return true if the current level is no longer enclosed in a target region. 2442 2443 if (const auto *VD = dyn_cast<VarDecl>(D)) { 2444 if (!VD->hasLocalStorage()) { 2445 if (isInOpenMPTargetExecutionDirective()) 2446 return true; 2447 DSAStackTy::DSAVarData TopDVar = 2448 DSAStack->getTopDSA(D, /*FromParent=*/false); 2449 unsigned NumLevels = 2450 getOpenMPCaptureLevels(DSAStack->getDirective(Level)); 2451 if (Level == 0) 2452 return (NumLevels == CaptureLevel + 1) && TopDVar.CKind != OMPC_shared; 2453 do { 2454 --Level; 2455 DSAStackTy::DSAVarData DVar = DSAStack->getImplicitDSA(D, Level); 2456 if (DVar.CKind != OMPC_shared) 2457 return true; 2458 } while (Level > 0); 2459 } 2460 } 2461 return true; 2462 } 2463 2464 void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; } 2465 2466 void Sema::ActOnOpenMPBeginDeclareVariant(SourceLocation Loc, 2467 OMPTraitInfo &TI) { 2468 OMPDeclareVariantScopes.push_back(OMPDeclareVariantScope(TI)); 2469 } 2470 2471 void Sema::ActOnOpenMPEndDeclareVariant() { 2472 assert(isInOpenMPDeclareVariantScope() && 2473 "Not in OpenMP declare variant scope!"); 2474 2475 OMPDeclareVariantScopes.pop_back(); 2476 } 2477 2478 void Sema::finalizeOpenMPDelayedAnalysis(const FunctionDecl *Caller, 2479 const FunctionDecl *Callee, 2480 SourceLocation Loc) { 2481 assert(LangOpts.OpenMP && "Expected OpenMP compilation mode."); 2482 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy = 2483 OMPDeclareTargetDeclAttr::getDeviceType(Caller->getMostRecentDecl()); 2484 // Ignore host functions during device analyzis. 2485 if (LangOpts.OpenMPIsDevice && 2486 (!DevTy || *DevTy == OMPDeclareTargetDeclAttr::DT_Host)) 2487 return; 2488 // Ignore nohost functions during host analyzis. 2489 if (!LangOpts.OpenMPIsDevice && DevTy && 2490 *DevTy == OMPDeclareTargetDeclAttr::DT_NoHost) 2491 return; 2492 const FunctionDecl *FD = Callee->getMostRecentDecl(); 2493 DevTy = OMPDeclareTargetDeclAttr::getDeviceType(FD); 2494 if (LangOpts.OpenMPIsDevice && DevTy && 2495 *DevTy == OMPDeclareTargetDeclAttr::DT_Host) { 2496 // Diagnose host function called during device codegen. 2497 StringRef HostDevTy = 2498 getOpenMPSimpleClauseTypeName(OMPC_device_type, OMPC_DEVICE_TYPE_host); 2499 Diag(Loc, diag::err_omp_wrong_device_function_call) << HostDevTy << 0; 2500 Diag(*OMPDeclareTargetDeclAttr::getLocation(FD), 2501 diag::note_omp_marked_device_type_here) 2502 << HostDevTy; 2503 return; 2504 } 2505 if (!LangOpts.OpenMPIsDevice && DevTy && 2506 *DevTy == OMPDeclareTargetDeclAttr::DT_NoHost) { 2507 // Diagnose nohost function called during host codegen. 2508 StringRef NoHostDevTy = getOpenMPSimpleClauseTypeName( 2509 OMPC_device_type, OMPC_DEVICE_TYPE_nohost); 2510 Diag(Loc, diag::err_omp_wrong_device_function_call) << NoHostDevTy << 1; 2511 Diag(*OMPDeclareTargetDeclAttr::getLocation(FD), 2512 diag::note_omp_marked_device_type_here) 2513 << NoHostDevTy; 2514 } 2515 } 2516 2517 void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind, 2518 const DeclarationNameInfo &DirName, 2519 Scope *CurScope, SourceLocation Loc) { 2520 DSAStack->push(DKind, DirName, CurScope, Loc); 2521 PushExpressionEvaluationContext( 2522 ExpressionEvaluationContext::PotentiallyEvaluated); 2523 } 2524 2525 void Sema::StartOpenMPClause(OpenMPClauseKind K) { 2526 DSAStack->setClauseParsingMode(K); 2527 } 2528 2529 void Sema::EndOpenMPClause() { 2530 DSAStack->setClauseParsingMode(/*K=*/OMPC_unknown); 2531 CleanupVarDeclMarking(); 2532 } 2533 2534 static std::pair<ValueDecl *, bool> 2535 getPrivateItem(Sema &S, Expr *&RefExpr, SourceLocation &ELoc, 2536 SourceRange &ERange, bool AllowArraySection = false); 2537 2538 /// Check consistency of the reduction clauses. 2539 static void checkReductionClauses(Sema &S, DSAStackTy *Stack, 2540 ArrayRef<OMPClause *> Clauses) { 2541 bool InscanFound = false; 2542 SourceLocation InscanLoc; 2543 // OpenMP 5.0, 2.19.5.4 reduction Clause, Restrictions. 2544 // A reduction clause without the inscan reduction-modifier may not appear on 2545 // a construct on which a reduction clause with the inscan reduction-modifier 2546 // appears. 2547 for (OMPClause *C : Clauses) { 2548 if (C->getClauseKind() != OMPC_reduction) 2549 continue; 2550 auto *RC = cast<OMPReductionClause>(C); 2551 if (RC->getModifier() == OMPC_REDUCTION_inscan) { 2552 InscanFound = true; 2553 InscanLoc = RC->getModifierLoc(); 2554 continue; 2555 } 2556 if (RC->getModifier() == OMPC_REDUCTION_task) { 2557 // OpenMP 5.0, 2.19.5.4 reduction Clause. 2558 // A reduction clause with the task reduction-modifier may only appear on 2559 // a parallel construct, a worksharing construct or a combined or 2560 // composite construct for which any of the aforementioned constructs is a 2561 // constituent construct and simd or loop are not constituent constructs. 2562 OpenMPDirectiveKind CurDir = Stack->getCurrentDirective(); 2563 if (!(isOpenMPParallelDirective(CurDir) || 2564 isOpenMPWorksharingDirective(CurDir)) || 2565 isOpenMPSimdDirective(CurDir)) 2566 S.Diag(RC->getModifierLoc(), 2567 diag::err_omp_reduction_task_not_parallel_or_worksharing); 2568 continue; 2569 } 2570 } 2571 if (InscanFound) { 2572 for (OMPClause *C : Clauses) { 2573 if (C->getClauseKind() != OMPC_reduction) 2574 continue; 2575 auto *RC = cast<OMPReductionClause>(C); 2576 if (RC->getModifier() != OMPC_REDUCTION_inscan) { 2577 S.Diag(RC->getModifier() == OMPC_REDUCTION_unknown 2578 ? RC->getBeginLoc() 2579 : RC->getModifierLoc(), 2580 diag::err_omp_inscan_reduction_expected); 2581 S.Diag(InscanLoc, diag::note_omp_previous_inscan_reduction); 2582 continue; 2583 } 2584 for (Expr *Ref : RC->varlists()) { 2585 assert(Ref && "NULL expr in OpenMP nontemporal clause."); 2586 SourceLocation ELoc; 2587 SourceRange ERange; 2588 Expr *SimpleRefExpr = Ref; 2589 auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange, 2590 /*AllowArraySection=*/true); 2591 ValueDecl *D = Res.first; 2592 if (!D) 2593 continue; 2594 if (!Stack->isUsedInScanDirective(getCanonicalDecl(D))) { 2595 S.Diag(Ref->getExprLoc(), 2596 diag::err_omp_reduction_not_inclusive_exclusive) 2597 << Ref->getSourceRange(); 2598 } 2599 } 2600 } 2601 } 2602 } 2603 2604 static void checkAllocateClauses(Sema &S, DSAStackTy *Stack, 2605 ArrayRef<OMPClause *> Clauses); 2606 static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr, 2607 bool WithInit); 2608 2609 static void reportOriginalDsa(Sema &SemaRef, const DSAStackTy *Stack, 2610 const ValueDecl *D, 2611 const DSAStackTy::DSAVarData &DVar, 2612 bool IsLoopIterVar = false); 2613 2614 void Sema::EndOpenMPDSABlock(Stmt *CurDirective) { 2615 // OpenMP [2.14.3.5, Restrictions, C/C++, p.1] 2616 // A variable of class type (or array thereof) that appears in a lastprivate 2617 // clause requires an accessible, unambiguous default constructor for the 2618 // class type, unless the list item is also specified in a firstprivate 2619 // clause. 2620 if (const auto *D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) { 2621 for (OMPClause *C : D->clauses()) { 2622 if (auto *Clause = dyn_cast<OMPLastprivateClause>(C)) { 2623 SmallVector<Expr *, 8> PrivateCopies; 2624 for (Expr *DE : Clause->varlists()) { 2625 if (DE->isValueDependent() || DE->isTypeDependent()) { 2626 PrivateCopies.push_back(nullptr); 2627 continue; 2628 } 2629 auto *DRE = cast<DeclRefExpr>(DE->IgnoreParens()); 2630 auto *VD = cast<VarDecl>(DRE->getDecl()); 2631 QualType Type = VD->getType().getNonReferenceType(); 2632 const DSAStackTy::DSAVarData DVar = 2633 DSAStack->getTopDSA(VD, /*FromParent=*/false); 2634 if (DVar.CKind == OMPC_lastprivate) { 2635 // Generate helper private variable and initialize it with the 2636 // default value. The address of the original variable is replaced 2637 // by the address of the new private variable in CodeGen. This new 2638 // variable is not added to IdResolver, so the code in the OpenMP 2639 // region uses original variable for proper diagnostics. 2640 VarDecl *VDPrivate = buildVarDecl( 2641 *this, DE->getExprLoc(), Type.getUnqualifiedType(), 2642 VD->getName(), VD->hasAttrs() ? &VD->getAttrs() : nullptr, DRE); 2643 ActOnUninitializedDecl(VDPrivate); 2644 if (VDPrivate->isInvalidDecl()) { 2645 PrivateCopies.push_back(nullptr); 2646 continue; 2647 } 2648 PrivateCopies.push_back(buildDeclRefExpr( 2649 *this, VDPrivate, DE->getType(), DE->getExprLoc())); 2650 } else { 2651 // The variable is also a firstprivate, so initialization sequence 2652 // for private copy is generated already. 2653 PrivateCopies.push_back(nullptr); 2654 } 2655 } 2656 Clause->setPrivateCopies(PrivateCopies); 2657 continue; 2658 } 2659 // Finalize nontemporal clause by handling private copies, if any. 2660 if (auto *Clause = dyn_cast<OMPNontemporalClause>(C)) { 2661 SmallVector<Expr *, 8> PrivateRefs; 2662 for (Expr *RefExpr : Clause->varlists()) { 2663 assert(RefExpr && "NULL expr in OpenMP nontemporal clause."); 2664 SourceLocation ELoc; 2665 SourceRange ERange; 2666 Expr *SimpleRefExpr = RefExpr; 2667 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 2668 if (Res.second) 2669 // It will be analyzed later. 2670 PrivateRefs.push_back(RefExpr); 2671 ValueDecl *D = Res.first; 2672 if (!D) 2673 continue; 2674 2675 const DSAStackTy::DSAVarData DVar = 2676 DSAStack->getTopDSA(D, /*FromParent=*/false); 2677 PrivateRefs.push_back(DVar.PrivateCopy ? DVar.PrivateCopy 2678 : SimpleRefExpr); 2679 } 2680 Clause->setPrivateRefs(PrivateRefs); 2681 continue; 2682 } 2683 if (auto *Clause = dyn_cast<OMPUsesAllocatorsClause>(C)) { 2684 for (unsigned I = 0, E = Clause->getNumberOfAllocators(); I < E; ++I) { 2685 OMPUsesAllocatorsClause::Data D = Clause->getAllocatorData(I); 2686 auto *DRE = dyn_cast<DeclRefExpr>(D.Allocator->IgnoreParenImpCasts()); 2687 if (!DRE) 2688 continue; 2689 ValueDecl *VD = DRE->getDecl(); 2690 if (!VD || !isa<VarDecl>(VD)) 2691 continue; 2692 DSAStackTy::DSAVarData DVar = 2693 DSAStack->getTopDSA(VD, /*FromParent=*/false); 2694 // OpenMP [2.12.5, target Construct] 2695 // Memory allocators that appear in a uses_allocators clause cannot 2696 // appear in other data-sharing attribute clauses or data-mapping 2697 // attribute clauses in the same construct. 2698 Expr *MapExpr = nullptr; 2699 if (DVar.RefExpr || 2700 DSAStack->checkMappableExprComponentListsForDecl( 2701 VD, /*CurrentRegionOnly=*/true, 2702 [VD, &MapExpr]( 2703 OMPClauseMappableExprCommon::MappableExprComponentListRef 2704 MapExprComponents, 2705 OpenMPClauseKind C) { 2706 auto MI = MapExprComponents.rbegin(); 2707 auto ME = MapExprComponents.rend(); 2708 if (MI != ME && 2709 MI->getAssociatedDeclaration()->getCanonicalDecl() == 2710 VD->getCanonicalDecl()) { 2711 MapExpr = MI->getAssociatedExpression(); 2712 return true; 2713 } 2714 return false; 2715 })) { 2716 Diag(D.Allocator->getExprLoc(), 2717 diag::err_omp_allocator_used_in_clauses) 2718 << D.Allocator->getSourceRange(); 2719 if (DVar.RefExpr) 2720 reportOriginalDsa(*this, DSAStack, VD, DVar); 2721 else 2722 Diag(MapExpr->getExprLoc(), diag::note_used_here) 2723 << MapExpr->getSourceRange(); 2724 } 2725 } 2726 continue; 2727 } 2728 } 2729 // Check allocate clauses. 2730 if (!CurContext->isDependentContext()) 2731 checkAllocateClauses(*this, DSAStack, D->clauses()); 2732 checkReductionClauses(*this, DSAStack, D->clauses()); 2733 } 2734 2735 DSAStack->pop(); 2736 DiscardCleanupsInEvaluationContext(); 2737 PopExpressionEvaluationContext(); 2738 } 2739 2740 static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV, 2741 Expr *NumIterations, Sema &SemaRef, 2742 Scope *S, DSAStackTy *Stack); 2743 2744 namespace { 2745 2746 class VarDeclFilterCCC final : public CorrectionCandidateCallback { 2747 private: 2748 Sema &SemaRef; 2749 2750 public: 2751 explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {} 2752 bool ValidateCandidate(const TypoCorrection &Candidate) override { 2753 NamedDecl *ND = Candidate.getCorrectionDecl(); 2754 if (const auto *VD = dyn_cast_or_null<VarDecl>(ND)) { 2755 return VD->hasGlobalStorage() && 2756 SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(), 2757 SemaRef.getCurScope()); 2758 } 2759 return false; 2760 } 2761 2762 std::unique_ptr<CorrectionCandidateCallback> clone() override { 2763 return std::make_unique<VarDeclFilterCCC>(*this); 2764 } 2765 }; 2766 2767 class VarOrFuncDeclFilterCCC final : public CorrectionCandidateCallback { 2768 private: 2769 Sema &SemaRef; 2770 2771 public: 2772 explicit VarOrFuncDeclFilterCCC(Sema &S) : SemaRef(S) {} 2773 bool ValidateCandidate(const TypoCorrection &Candidate) override { 2774 NamedDecl *ND = Candidate.getCorrectionDecl(); 2775 if (ND && ((isa<VarDecl>(ND) && ND->getKind() == Decl::Var) || 2776 isa<FunctionDecl>(ND))) { 2777 return SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(), 2778 SemaRef.getCurScope()); 2779 } 2780 return false; 2781 } 2782 2783 std::unique_ptr<CorrectionCandidateCallback> clone() override { 2784 return std::make_unique<VarOrFuncDeclFilterCCC>(*this); 2785 } 2786 }; 2787 2788 } // namespace 2789 2790 ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope, 2791 CXXScopeSpec &ScopeSpec, 2792 const DeclarationNameInfo &Id, 2793 OpenMPDirectiveKind Kind) { 2794 LookupResult Lookup(*this, Id, LookupOrdinaryName); 2795 LookupParsedName(Lookup, CurScope, &ScopeSpec, true); 2796 2797 if (Lookup.isAmbiguous()) 2798 return ExprError(); 2799 2800 VarDecl *VD; 2801 if (!Lookup.isSingleResult()) { 2802 VarDeclFilterCCC CCC(*this); 2803 if (TypoCorrection Corrected = 2804 CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr, CCC, 2805 CTK_ErrorRecovery)) { 2806 diagnoseTypo(Corrected, 2807 PDiag(Lookup.empty() 2808 ? diag::err_undeclared_var_use_suggest 2809 : diag::err_omp_expected_var_arg_suggest) 2810 << Id.getName()); 2811 VD = Corrected.getCorrectionDeclAs<VarDecl>(); 2812 } else { 2813 Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use 2814 : diag::err_omp_expected_var_arg) 2815 << Id.getName(); 2816 return ExprError(); 2817 } 2818 } else if (!(VD = Lookup.getAsSingle<VarDecl>())) { 2819 Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName(); 2820 Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at); 2821 return ExprError(); 2822 } 2823 Lookup.suppressDiagnostics(); 2824 2825 // OpenMP [2.9.2, Syntax, C/C++] 2826 // Variables must be file-scope, namespace-scope, or static block-scope. 2827 if (Kind == OMPD_threadprivate && !VD->hasGlobalStorage()) { 2828 Diag(Id.getLoc(), diag::err_omp_global_var_arg) 2829 << getOpenMPDirectiveName(Kind) << !VD->isStaticLocal(); 2830 bool IsDecl = 2831 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 2832 Diag(VD->getLocation(), 2833 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 2834 << VD; 2835 return ExprError(); 2836 } 2837 2838 VarDecl *CanonicalVD = VD->getCanonicalDecl(); 2839 NamedDecl *ND = CanonicalVD; 2840 // OpenMP [2.9.2, Restrictions, C/C++, p.2] 2841 // A threadprivate directive for file-scope variables must appear outside 2842 // any definition or declaration. 2843 if (CanonicalVD->getDeclContext()->isTranslationUnit() && 2844 !getCurLexicalContext()->isTranslationUnit()) { 2845 Diag(Id.getLoc(), diag::err_omp_var_scope) 2846 << getOpenMPDirectiveName(Kind) << VD; 2847 bool IsDecl = 2848 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 2849 Diag(VD->getLocation(), 2850 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 2851 << VD; 2852 return ExprError(); 2853 } 2854 // OpenMP [2.9.2, Restrictions, C/C++, p.3] 2855 // A threadprivate directive for static class member variables must appear 2856 // in the class definition, in the same scope in which the member 2857 // variables are declared. 2858 if (CanonicalVD->isStaticDataMember() && 2859 !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) { 2860 Diag(Id.getLoc(), diag::err_omp_var_scope) 2861 << getOpenMPDirectiveName(Kind) << VD; 2862 bool IsDecl = 2863 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 2864 Diag(VD->getLocation(), 2865 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 2866 << VD; 2867 return ExprError(); 2868 } 2869 // OpenMP [2.9.2, Restrictions, C/C++, p.4] 2870 // A threadprivate directive for namespace-scope variables must appear 2871 // outside any definition or declaration other than the namespace 2872 // definition itself. 2873 if (CanonicalVD->getDeclContext()->isNamespace() && 2874 (!getCurLexicalContext()->isFileContext() || 2875 !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) { 2876 Diag(Id.getLoc(), diag::err_omp_var_scope) 2877 << getOpenMPDirectiveName(Kind) << VD; 2878 bool IsDecl = 2879 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 2880 Diag(VD->getLocation(), 2881 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 2882 << VD; 2883 return ExprError(); 2884 } 2885 // OpenMP [2.9.2, Restrictions, C/C++, p.6] 2886 // A threadprivate directive for static block-scope variables must appear 2887 // in the scope of the variable and not in a nested scope. 2888 if (CanonicalVD->isLocalVarDecl() && CurScope && 2889 !isDeclInScope(ND, getCurLexicalContext(), CurScope)) { 2890 Diag(Id.getLoc(), diag::err_omp_var_scope) 2891 << getOpenMPDirectiveName(Kind) << VD; 2892 bool IsDecl = 2893 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 2894 Diag(VD->getLocation(), 2895 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 2896 << VD; 2897 return ExprError(); 2898 } 2899 2900 // OpenMP [2.9.2, Restrictions, C/C++, p.2-6] 2901 // A threadprivate directive must lexically precede all references to any 2902 // of the variables in its list. 2903 if (Kind == OMPD_threadprivate && VD->isUsed() && 2904 !DSAStack->isThreadPrivate(VD)) { 2905 Diag(Id.getLoc(), diag::err_omp_var_used) 2906 << getOpenMPDirectiveName(Kind) << VD; 2907 return ExprError(); 2908 } 2909 2910 QualType ExprType = VD->getType().getNonReferenceType(); 2911 return DeclRefExpr::Create(Context, NestedNameSpecifierLoc(), 2912 SourceLocation(), VD, 2913 /*RefersToEnclosingVariableOrCapture=*/false, 2914 Id.getLoc(), ExprType, VK_LValue); 2915 } 2916 2917 Sema::DeclGroupPtrTy 2918 Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc, 2919 ArrayRef<Expr *> VarList) { 2920 if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) { 2921 CurContext->addDecl(D); 2922 return DeclGroupPtrTy::make(DeclGroupRef(D)); 2923 } 2924 return nullptr; 2925 } 2926 2927 namespace { 2928 class LocalVarRefChecker final 2929 : public ConstStmtVisitor<LocalVarRefChecker, bool> { 2930 Sema &SemaRef; 2931 2932 public: 2933 bool VisitDeclRefExpr(const DeclRefExpr *E) { 2934 if (const auto *VD = dyn_cast<VarDecl>(E->getDecl())) { 2935 if (VD->hasLocalStorage()) { 2936 SemaRef.Diag(E->getBeginLoc(), 2937 diag::err_omp_local_var_in_threadprivate_init) 2938 << E->getSourceRange(); 2939 SemaRef.Diag(VD->getLocation(), diag::note_defined_here) 2940 << VD << VD->getSourceRange(); 2941 return true; 2942 } 2943 } 2944 return false; 2945 } 2946 bool VisitStmt(const Stmt *S) { 2947 for (const Stmt *Child : S->children()) { 2948 if (Child && Visit(Child)) 2949 return true; 2950 } 2951 return false; 2952 } 2953 explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {} 2954 }; 2955 } // namespace 2956 2957 OMPThreadPrivateDecl * 2958 Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) { 2959 SmallVector<Expr *, 8> Vars; 2960 for (Expr *RefExpr : VarList) { 2961 auto *DE = cast<DeclRefExpr>(RefExpr); 2962 auto *VD = cast<VarDecl>(DE->getDecl()); 2963 SourceLocation ILoc = DE->getExprLoc(); 2964 2965 // Mark variable as used. 2966 VD->setReferenced(); 2967 VD->markUsed(Context); 2968 2969 QualType QType = VD->getType(); 2970 if (QType->isDependentType() || QType->isInstantiationDependentType()) { 2971 // It will be analyzed later. 2972 Vars.push_back(DE); 2973 continue; 2974 } 2975 2976 // OpenMP [2.9.2, Restrictions, C/C++, p.10] 2977 // A threadprivate variable must not have an incomplete type. 2978 if (RequireCompleteType(ILoc, VD->getType(), 2979 diag::err_omp_threadprivate_incomplete_type)) { 2980 continue; 2981 } 2982 2983 // OpenMP [2.9.2, Restrictions, C/C++, p.10] 2984 // A threadprivate variable must not have a reference type. 2985 if (VD->getType()->isReferenceType()) { 2986 Diag(ILoc, diag::err_omp_ref_type_arg) 2987 << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType(); 2988 bool IsDecl = 2989 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 2990 Diag(VD->getLocation(), 2991 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 2992 << VD; 2993 continue; 2994 } 2995 2996 // Check if this is a TLS variable. If TLS is not being supported, produce 2997 // the corresponding diagnostic. 2998 if ((VD->getTLSKind() != VarDecl::TLS_None && 2999 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() && 3000 getLangOpts().OpenMPUseTLS && 3001 getASTContext().getTargetInfo().isTLSSupported())) || 3002 (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() && 3003 !VD->isLocalVarDecl())) { 3004 Diag(ILoc, diag::err_omp_var_thread_local) 3005 << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1); 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 initial value of threadprivate variable reference variable with 3015 // local storage (it is not supported by runtime). 3016 if (const Expr *Init = VD->getAnyInitializer()) { 3017 LocalVarRefChecker Checker(*this); 3018 if (Checker.Visit(Init)) 3019 continue; 3020 } 3021 3022 Vars.push_back(RefExpr); 3023 DSAStack->addDSA(VD, DE, OMPC_threadprivate); 3024 VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit( 3025 Context, SourceRange(Loc, Loc))); 3026 if (ASTMutationListener *ML = Context.getASTMutationListener()) 3027 ML->DeclarationMarkedOpenMPThreadPrivate(VD); 3028 } 3029 OMPThreadPrivateDecl *D = nullptr; 3030 if (!Vars.empty()) { 3031 D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc, 3032 Vars); 3033 D->setAccess(AS_public); 3034 } 3035 return D; 3036 } 3037 3038 static OMPAllocateDeclAttr::AllocatorTypeTy 3039 getAllocatorKind(Sema &S, DSAStackTy *Stack, Expr *Allocator) { 3040 if (!Allocator) 3041 return OMPAllocateDeclAttr::OMPNullMemAlloc; 3042 if (Allocator->isTypeDependent() || Allocator->isValueDependent() || 3043 Allocator->isInstantiationDependent() || 3044 Allocator->containsUnexpandedParameterPack()) 3045 return OMPAllocateDeclAttr::OMPUserDefinedMemAlloc; 3046 auto AllocatorKindRes = OMPAllocateDeclAttr::OMPUserDefinedMemAlloc; 3047 const Expr *AE = Allocator->IgnoreParenImpCasts(); 3048 for (int I = 0; I < OMPAllocateDeclAttr::OMPUserDefinedMemAlloc; ++I) { 3049 auto AllocatorKind = static_cast<OMPAllocateDeclAttr::AllocatorTypeTy>(I); 3050 const Expr *DefAllocator = Stack->getAllocator(AllocatorKind); 3051 llvm::FoldingSetNodeID AEId, DAEId; 3052 AE->Profile(AEId, S.getASTContext(), /*Canonical=*/true); 3053 DefAllocator->Profile(DAEId, S.getASTContext(), /*Canonical=*/true); 3054 if (AEId == DAEId) { 3055 AllocatorKindRes = AllocatorKind; 3056 break; 3057 } 3058 } 3059 return AllocatorKindRes; 3060 } 3061 3062 static bool checkPreviousOMPAllocateAttribute( 3063 Sema &S, DSAStackTy *Stack, Expr *RefExpr, VarDecl *VD, 3064 OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind, Expr *Allocator) { 3065 if (!VD->hasAttr<OMPAllocateDeclAttr>()) 3066 return false; 3067 const auto *A = VD->getAttr<OMPAllocateDeclAttr>(); 3068 Expr *PrevAllocator = A->getAllocator(); 3069 OMPAllocateDeclAttr::AllocatorTypeTy PrevAllocatorKind = 3070 getAllocatorKind(S, Stack, PrevAllocator); 3071 bool AllocatorsMatch = AllocatorKind == PrevAllocatorKind; 3072 if (AllocatorsMatch && 3073 AllocatorKind == OMPAllocateDeclAttr::OMPUserDefinedMemAlloc && 3074 Allocator && PrevAllocator) { 3075 const Expr *AE = Allocator->IgnoreParenImpCasts(); 3076 const Expr *PAE = PrevAllocator->IgnoreParenImpCasts(); 3077 llvm::FoldingSetNodeID AEId, PAEId; 3078 AE->Profile(AEId, S.Context, /*Canonical=*/true); 3079 PAE->Profile(PAEId, S.Context, /*Canonical=*/true); 3080 AllocatorsMatch = AEId == PAEId; 3081 } 3082 if (!AllocatorsMatch) { 3083 SmallString<256> AllocatorBuffer; 3084 llvm::raw_svector_ostream AllocatorStream(AllocatorBuffer); 3085 if (Allocator) 3086 Allocator->printPretty(AllocatorStream, nullptr, S.getPrintingPolicy()); 3087 SmallString<256> PrevAllocatorBuffer; 3088 llvm::raw_svector_ostream PrevAllocatorStream(PrevAllocatorBuffer); 3089 if (PrevAllocator) 3090 PrevAllocator->printPretty(PrevAllocatorStream, nullptr, 3091 S.getPrintingPolicy()); 3092 3093 SourceLocation AllocatorLoc = 3094 Allocator ? Allocator->getExprLoc() : RefExpr->getExprLoc(); 3095 SourceRange AllocatorRange = 3096 Allocator ? Allocator->getSourceRange() : RefExpr->getSourceRange(); 3097 SourceLocation PrevAllocatorLoc = 3098 PrevAllocator ? PrevAllocator->getExprLoc() : A->getLocation(); 3099 SourceRange PrevAllocatorRange = 3100 PrevAllocator ? PrevAllocator->getSourceRange() : A->getRange(); 3101 S.Diag(AllocatorLoc, diag::warn_omp_used_different_allocator) 3102 << (Allocator ? 1 : 0) << AllocatorStream.str() 3103 << (PrevAllocator ? 1 : 0) << PrevAllocatorStream.str() 3104 << AllocatorRange; 3105 S.Diag(PrevAllocatorLoc, diag::note_omp_previous_allocator) 3106 << PrevAllocatorRange; 3107 return true; 3108 } 3109 return false; 3110 } 3111 3112 static void 3113 applyOMPAllocateAttribute(Sema &S, VarDecl *VD, 3114 OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind, 3115 Expr *Allocator, Expr *Alignment, SourceRange SR) { 3116 if (VD->hasAttr<OMPAllocateDeclAttr>()) 3117 return; 3118 if (Alignment && 3119 (Alignment->isTypeDependent() || Alignment->isValueDependent() || 3120 Alignment->isInstantiationDependent() || 3121 Alignment->containsUnexpandedParameterPack())) 3122 // Apply later when we have a usable value. 3123 return; 3124 if (Allocator && 3125 (Allocator->isTypeDependent() || Allocator->isValueDependent() || 3126 Allocator->isInstantiationDependent() || 3127 Allocator->containsUnexpandedParameterPack())) 3128 return; 3129 auto *A = OMPAllocateDeclAttr::CreateImplicit(S.Context, AllocatorKind, 3130 Allocator, Alignment, SR); 3131 VD->addAttr(A); 3132 if (ASTMutationListener *ML = S.Context.getASTMutationListener()) 3133 ML->DeclarationMarkedOpenMPAllocate(VD, A); 3134 } 3135 3136 Sema::DeclGroupPtrTy 3137 Sema::ActOnOpenMPAllocateDirective(SourceLocation Loc, ArrayRef<Expr *> VarList, 3138 ArrayRef<OMPClause *> Clauses, 3139 DeclContext *Owner) { 3140 assert(Clauses.size() <= 2 && "Expected at most two clauses."); 3141 Expr *Alignment = nullptr; 3142 Expr *Allocator = nullptr; 3143 if (Clauses.empty()) { 3144 // OpenMP 5.0, 2.11.3 allocate Directive, Restrictions. 3145 // allocate directives that appear in a target region must specify an 3146 // allocator clause unless a requires directive with the dynamic_allocators 3147 // clause is present in the same compilation unit. 3148 if (LangOpts.OpenMPIsDevice && 3149 !DSAStack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>()) 3150 targetDiag(Loc, diag::err_expected_allocator_clause); 3151 } else { 3152 for (const OMPClause *C : Clauses) 3153 if (const auto *AC = dyn_cast<OMPAllocatorClause>(C)) 3154 Allocator = AC->getAllocator(); 3155 else if (const auto *AC = dyn_cast<OMPAlignClause>(C)) 3156 Alignment = AC->getAlignment(); 3157 else 3158 llvm_unreachable("Unexpected clause on allocate directive"); 3159 } 3160 OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind = 3161 getAllocatorKind(*this, DSAStack, Allocator); 3162 SmallVector<Expr *, 8> Vars; 3163 for (Expr *RefExpr : VarList) { 3164 auto *DE = cast<DeclRefExpr>(RefExpr); 3165 auto *VD = cast<VarDecl>(DE->getDecl()); 3166 3167 // Check if this is a TLS variable or global register. 3168 if (VD->getTLSKind() != VarDecl::TLS_None || 3169 VD->hasAttr<OMPThreadPrivateDeclAttr>() || 3170 (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() && 3171 !VD->isLocalVarDecl())) 3172 continue; 3173 3174 // If the used several times in the allocate directive, the same allocator 3175 // must be used. 3176 if (checkPreviousOMPAllocateAttribute(*this, DSAStack, RefExpr, VD, 3177 AllocatorKind, Allocator)) 3178 continue; 3179 3180 // OpenMP, 2.11.3 allocate Directive, Restrictions, C / C++ 3181 // If a list item has a static storage type, the allocator expression in the 3182 // allocator clause must be a constant expression that evaluates to one of 3183 // the predefined memory allocator values. 3184 if (Allocator && VD->hasGlobalStorage()) { 3185 if (AllocatorKind == OMPAllocateDeclAttr::OMPUserDefinedMemAlloc) { 3186 Diag(Allocator->getExprLoc(), 3187 diag::err_omp_expected_predefined_allocator) 3188 << Allocator->getSourceRange(); 3189 bool IsDecl = VD->isThisDeclarationADefinition(Context) == 3190 VarDecl::DeclarationOnly; 3191 Diag(VD->getLocation(), 3192 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 3193 << VD; 3194 continue; 3195 } 3196 } 3197 3198 Vars.push_back(RefExpr); 3199 applyOMPAllocateAttribute(*this, VD, AllocatorKind, Allocator, Alignment, 3200 DE->getSourceRange()); 3201 } 3202 if (Vars.empty()) 3203 return nullptr; 3204 if (!Owner) 3205 Owner = getCurLexicalContext(); 3206 auto *D = OMPAllocateDecl::Create(Context, Owner, Loc, Vars, Clauses); 3207 D->setAccess(AS_public); 3208 Owner->addDecl(D); 3209 return DeclGroupPtrTy::make(DeclGroupRef(D)); 3210 } 3211 3212 Sema::DeclGroupPtrTy 3213 Sema::ActOnOpenMPRequiresDirective(SourceLocation Loc, 3214 ArrayRef<OMPClause *> ClauseList) { 3215 OMPRequiresDecl *D = nullptr; 3216 if (!CurContext->isFileContext()) { 3217 Diag(Loc, diag::err_omp_invalid_scope) << "requires"; 3218 } else { 3219 D = CheckOMPRequiresDecl(Loc, ClauseList); 3220 if (D) { 3221 CurContext->addDecl(D); 3222 DSAStack->addRequiresDecl(D); 3223 } 3224 } 3225 return DeclGroupPtrTy::make(DeclGroupRef(D)); 3226 } 3227 3228 void Sema::ActOnOpenMPAssumesDirective(SourceLocation Loc, 3229 OpenMPDirectiveKind DKind, 3230 ArrayRef<std::string> Assumptions, 3231 bool SkippedClauses) { 3232 if (!SkippedClauses && Assumptions.empty()) 3233 Diag(Loc, diag::err_omp_no_clause_for_directive) 3234 << llvm::omp::getAllAssumeClauseOptions() 3235 << llvm::omp::getOpenMPDirectiveName(DKind); 3236 3237 auto *AA = AssumptionAttr::Create(Context, llvm::join(Assumptions, ","), Loc); 3238 if (DKind == llvm::omp::Directive::OMPD_begin_assumes) { 3239 OMPAssumeScoped.push_back(AA); 3240 return; 3241 } 3242 3243 // Global assumes without assumption clauses are ignored. 3244 if (Assumptions.empty()) 3245 return; 3246 3247 assert(DKind == llvm::omp::Directive::OMPD_assumes && 3248 "Unexpected omp assumption directive!"); 3249 OMPAssumeGlobal.push_back(AA); 3250 3251 // The OMPAssumeGlobal scope above will take care of new declarations but 3252 // we also want to apply the assumption to existing ones, e.g., to 3253 // declarations in included headers. To this end, we traverse all existing 3254 // declaration contexts and annotate function declarations here. 3255 SmallVector<DeclContext *, 8> DeclContexts; 3256 auto *Ctx = CurContext; 3257 while (Ctx->getLexicalParent()) 3258 Ctx = Ctx->getLexicalParent(); 3259 DeclContexts.push_back(Ctx); 3260 while (!DeclContexts.empty()) { 3261 DeclContext *DC = DeclContexts.pop_back_val(); 3262 for (auto *SubDC : DC->decls()) { 3263 if (SubDC->isInvalidDecl()) 3264 continue; 3265 if (auto *CTD = dyn_cast<ClassTemplateDecl>(SubDC)) { 3266 DeclContexts.push_back(CTD->getTemplatedDecl()); 3267 for (auto *S : CTD->specializations()) 3268 DeclContexts.push_back(S); 3269 continue; 3270 } 3271 if (auto *DC = dyn_cast<DeclContext>(SubDC)) 3272 DeclContexts.push_back(DC); 3273 if (auto *F = dyn_cast<FunctionDecl>(SubDC)) { 3274 F->addAttr(AA); 3275 continue; 3276 } 3277 } 3278 } 3279 } 3280 3281 void Sema::ActOnOpenMPEndAssumesDirective() { 3282 assert(isInOpenMPAssumeScope() && "Not in OpenMP assumes scope!"); 3283 OMPAssumeScoped.pop_back(); 3284 } 3285 3286 OMPRequiresDecl *Sema::CheckOMPRequiresDecl(SourceLocation Loc, 3287 ArrayRef<OMPClause *> ClauseList) { 3288 /// For target specific clauses, the requires directive cannot be 3289 /// specified after the handling of any of the target regions in the 3290 /// current compilation unit. 3291 ArrayRef<SourceLocation> TargetLocations = 3292 DSAStack->getEncounteredTargetLocs(); 3293 SourceLocation AtomicLoc = DSAStack->getAtomicDirectiveLoc(); 3294 if (!TargetLocations.empty() || !AtomicLoc.isInvalid()) { 3295 for (const OMPClause *CNew : ClauseList) { 3296 // Check if any of the requires clauses affect target regions. 3297 if (isa<OMPUnifiedSharedMemoryClause>(CNew) || 3298 isa<OMPUnifiedAddressClause>(CNew) || 3299 isa<OMPReverseOffloadClause>(CNew) || 3300 isa<OMPDynamicAllocatorsClause>(CNew)) { 3301 Diag(Loc, diag::err_omp_directive_before_requires) 3302 << "target" << getOpenMPClauseName(CNew->getClauseKind()); 3303 for (SourceLocation TargetLoc : TargetLocations) { 3304 Diag(TargetLoc, diag::note_omp_requires_encountered_directive) 3305 << "target"; 3306 } 3307 } else if (!AtomicLoc.isInvalid() && 3308 isa<OMPAtomicDefaultMemOrderClause>(CNew)) { 3309 Diag(Loc, diag::err_omp_directive_before_requires) 3310 << "atomic" << getOpenMPClauseName(CNew->getClauseKind()); 3311 Diag(AtomicLoc, diag::note_omp_requires_encountered_directive) 3312 << "atomic"; 3313 } 3314 } 3315 } 3316 3317 if (!DSAStack->hasDuplicateRequiresClause(ClauseList)) 3318 return OMPRequiresDecl::Create(Context, getCurLexicalContext(), Loc, 3319 ClauseList); 3320 return nullptr; 3321 } 3322 3323 static void reportOriginalDsa(Sema &SemaRef, const DSAStackTy *Stack, 3324 const ValueDecl *D, 3325 const DSAStackTy::DSAVarData &DVar, 3326 bool IsLoopIterVar) { 3327 if (DVar.RefExpr) { 3328 SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa) 3329 << getOpenMPClauseName(DVar.CKind); 3330 return; 3331 } 3332 enum { 3333 PDSA_StaticMemberShared, 3334 PDSA_StaticLocalVarShared, 3335 PDSA_LoopIterVarPrivate, 3336 PDSA_LoopIterVarLinear, 3337 PDSA_LoopIterVarLastprivate, 3338 PDSA_ConstVarShared, 3339 PDSA_GlobalVarShared, 3340 PDSA_TaskVarFirstprivate, 3341 PDSA_LocalVarPrivate, 3342 PDSA_Implicit 3343 } Reason = PDSA_Implicit; 3344 bool ReportHint = false; 3345 auto ReportLoc = D->getLocation(); 3346 auto *VD = dyn_cast<VarDecl>(D); 3347 if (IsLoopIterVar) { 3348 if (DVar.CKind == OMPC_private) 3349 Reason = PDSA_LoopIterVarPrivate; 3350 else if (DVar.CKind == OMPC_lastprivate) 3351 Reason = PDSA_LoopIterVarLastprivate; 3352 else 3353 Reason = PDSA_LoopIterVarLinear; 3354 } else if (isOpenMPTaskingDirective(DVar.DKind) && 3355 DVar.CKind == OMPC_firstprivate) { 3356 Reason = PDSA_TaskVarFirstprivate; 3357 ReportLoc = DVar.ImplicitDSALoc; 3358 } else if (VD && VD->isStaticLocal()) 3359 Reason = PDSA_StaticLocalVarShared; 3360 else if (VD && VD->isStaticDataMember()) 3361 Reason = PDSA_StaticMemberShared; 3362 else if (VD && VD->isFileVarDecl()) 3363 Reason = PDSA_GlobalVarShared; 3364 else if (D->getType().isConstant(SemaRef.getASTContext())) 3365 Reason = PDSA_ConstVarShared; 3366 else if (VD && VD->isLocalVarDecl() && DVar.CKind == OMPC_private) { 3367 ReportHint = true; 3368 Reason = PDSA_LocalVarPrivate; 3369 } 3370 if (Reason != PDSA_Implicit) { 3371 SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa) 3372 << Reason << ReportHint 3373 << getOpenMPDirectiveName(Stack->getCurrentDirective()); 3374 } else if (DVar.ImplicitDSALoc.isValid()) { 3375 SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa) 3376 << getOpenMPClauseName(DVar.CKind); 3377 } 3378 } 3379 3380 static OpenMPMapClauseKind 3381 getMapClauseKindFromModifier(OpenMPDefaultmapClauseModifier M, 3382 bool IsAggregateOrDeclareTarget) { 3383 OpenMPMapClauseKind Kind = OMPC_MAP_unknown; 3384 switch (M) { 3385 case OMPC_DEFAULTMAP_MODIFIER_alloc: 3386 Kind = OMPC_MAP_alloc; 3387 break; 3388 case OMPC_DEFAULTMAP_MODIFIER_to: 3389 Kind = OMPC_MAP_to; 3390 break; 3391 case OMPC_DEFAULTMAP_MODIFIER_from: 3392 Kind = OMPC_MAP_from; 3393 break; 3394 case OMPC_DEFAULTMAP_MODIFIER_tofrom: 3395 Kind = OMPC_MAP_tofrom; 3396 break; 3397 case OMPC_DEFAULTMAP_MODIFIER_present: 3398 // OpenMP 5.1 [2.21.7.3] defaultmap clause, Description] 3399 // If implicit-behavior is present, each variable referenced in the 3400 // construct in the category specified by variable-category is treated as if 3401 // it had been listed in a map clause with the map-type of alloc and 3402 // map-type-modifier of present. 3403 Kind = OMPC_MAP_alloc; 3404 break; 3405 case OMPC_DEFAULTMAP_MODIFIER_firstprivate: 3406 case OMPC_DEFAULTMAP_MODIFIER_last: 3407 llvm_unreachable("Unexpected defaultmap implicit behavior"); 3408 case OMPC_DEFAULTMAP_MODIFIER_none: 3409 case OMPC_DEFAULTMAP_MODIFIER_default: 3410 case OMPC_DEFAULTMAP_MODIFIER_unknown: 3411 // IsAggregateOrDeclareTarget could be true if: 3412 // 1. the implicit behavior for aggregate is tofrom 3413 // 2. it's a declare target link 3414 if (IsAggregateOrDeclareTarget) { 3415 Kind = OMPC_MAP_tofrom; 3416 break; 3417 } 3418 llvm_unreachable("Unexpected defaultmap implicit behavior"); 3419 } 3420 assert(Kind != OMPC_MAP_unknown && "Expect map kind to be known"); 3421 return Kind; 3422 } 3423 3424 namespace { 3425 class DSAAttrChecker final : public StmtVisitor<DSAAttrChecker, void> { 3426 DSAStackTy *Stack; 3427 Sema &SemaRef; 3428 bool ErrorFound = false; 3429 bool TryCaptureCXXThisMembers = false; 3430 CapturedStmt *CS = nullptr; 3431 const static unsigned DefaultmapKindNum = OMPC_DEFAULTMAP_pointer + 1; 3432 llvm::SmallVector<Expr *, 4> ImplicitFirstprivate; 3433 llvm::SmallVector<Expr *, 4> ImplicitMap[DefaultmapKindNum][OMPC_MAP_delete]; 3434 llvm::SmallVector<OpenMPMapModifierKind, NumberOfOMPMapClauseModifiers> 3435 ImplicitMapModifier[DefaultmapKindNum]; 3436 Sema::VarsWithInheritedDSAType VarsWithInheritedDSA; 3437 llvm::SmallDenseSet<const ValueDecl *, 4> ImplicitDeclarations; 3438 3439 void VisitSubCaptures(OMPExecutableDirective *S) { 3440 // Check implicitly captured variables. 3441 if (!S->hasAssociatedStmt() || !S->getAssociatedStmt()) 3442 return; 3443 if (S->getDirectiveKind() == OMPD_atomic || 3444 S->getDirectiveKind() == OMPD_critical || 3445 S->getDirectiveKind() == OMPD_section || 3446 S->getDirectiveKind() == OMPD_master || 3447 S->getDirectiveKind() == OMPD_masked || 3448 isOpenMPLoopTransformationDirective(S->getDirectiveKind())) { 3449 Visit(S->getAssociatedStmt()); 3450 return; 3451 } 3452 visitSubCaptures(S->getInnermostCapturedStmt()); 3453 // Try to capture inner this->member references to generate correct mappings 3454 // and diagnostics. 3455 if (TryCaptureCXXThisMembers || 3456 (isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()) && 3457 llvm::any_of(S->getInnermostCapturedStmt()->captures(), 3458 [](const CapturedStmt::Capture &C) { 3459 return C.capturesThis(); 3460 }))) { 3461 bool SavedTryCaptureCXXThisMembers = TryCaptureCXXThisMembers; 3462 TryCaptureCXXThisMembers = true; 3463 Visit(S->getInnermostCapturedStmt()->getCapturedStmt()); 3464 TryCaptureCXXThisMembers = SavedTryCaptureCXXThisMembers; 3465 } 3466 // In tasks firstprivates are not captured anymore, need to analyze them 3467 // explicitly. 3468 if (isOpenMPTaskingDirective(S->getDirectiveKind()) && 3469 !isOpenMPTaskLoopDirective(S->getDirectiveKind())) { 3470 for (OMPClause *C : S->clauses()) 3471 if (auto *FC = dyn_cast<OMPFirstprivateClause>(C)) { 3472 for (Expr *Ref : FC->varlists()) 3473 Visit(Ref); 3474 } 3475 } 3476 } 3477 3478 public: 3479 void VisitDeclRefExpr(DeclRefExpr *E) { 3480 if (TryCaptureCXXThisMembers || E->isTypeDependent() || 3481 E->isValueDependent() || E->containsUnexpandedParameterPack() || 3482 E->isInstantiationDependent()) 3483 return; 3484 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) { 3485 // Check the datasharing rules for the expressions in the clauses. 3486 if (!CS || (isa<OMPCapturedExprDecl>(VD) && !CS->capturesVariable(VD) && 3487 !Stack->getTopDSA(VD, /*FromParent=*/false).RefExpr)) { 3488 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(VD)) 3489 if (!CED->hasAttr<OMPCaptureNoInitAttr>()) { 3490 Visit(CED->getInit()); 3491 return; 3492 } 3493 } else if (VD->isImplicit() || isa<OMPCapturedExprDecl>(VD)) 3494 // Do not analyze internal variables and do not enclose them into 3495 // implicit clauses. 3496 return; 3497 VD = VD->getCanonicalDecl(); 3498 // Skip internally declared variables. 3499 if (VD->hasLocalStorage() && CS && !CS->capturesVariable(VD) && 3500 !Stack->isImplicitTaskFirstprivate(VD)) 3501 return; 3502 // Skip allocators in uses_allocators clauses. 3503 if (Stack->isUsesAllocatorsDecl(VD).hasValue()) 3504 return; 3505 3506 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, /*FromParent=*/false); 3507 // Check if the variable has explicit DSA set and stop analysis if it so. 3508 if (DVar.RefExpr || !ImplicitDeclarations.insert(VD).second) 3509 return; 3510 3511 // Skip internally declared static variables. 3512 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res = 3513 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD); 3514 if (VD->hasGlobalStorage() && CS && !CS->capturesVariable(VD) && 3515 (Stack->hasRequiresDeclWithClause<OMPUnifiedSharedMemoryClause>() || 3516 !Res || *Res != OMPDeclareTargetDeclAttr::MT_Link) && 3517 !Stack->isImplicitTaskFirstprivate(VD)) 3518 return; 3519 3520 SourceLocation ELoc = E->getExprLoc(); 3521 OpenMPDirectiveKind DKind = Stack->getCurrentDirective(); 3522 // The default(none) clause requires that each variable that is referenced 3523 // in the construct, and does not have a predetermined data-sharing 3524 // attribute, must have its data-sharing attribute explicitly determined 3525 // by being listed in a data-sharing attribute clause. 3526 if (DVar.CKind == OMPC_unknown && 3527 (Stack->getDefaultDSA() == DSA_none || 3528 Stack->getDefaultDSA() == DSA_firstprivate) && 3529 isImplicitOrExplicitTaskingRegion(DKind) && 3530 VarsWithInheritedDSA.count(VD) == 0) { 3531 bool InheritedDSA = Stack->getDefaultDSA() == DSA_none; 3532 if (!InheritedDSA && Stack->getDefaultDSA() == DSA_firstprivate) { 3533 DSAStackTy::DSAVarData DVar = 3534 Stack->getImplicitDSA(VD, /*FromParent=*/false); 3535 InheritedDSA = DVar.CKind == OMPC_unknown; 3536 } 3537 if (InheritedDSA) 3538 VarsWithInheritedDSA[VD] = E; 3539 return; 3540 } 3541 3542 // OpenMP 5.0 [2.19.7.2, defaultmap clause, Description] 3543 // If implicit-behavior is none, each variable referenced in the 3544 // construct that does not have a predetermined data-sharing attribute 3545 // and does not appear in a to or link clause on a declare target 3546 // directive must be listed in a data-mapping attribute clause, a 3547 // data-haring attribute clause (including a data-sharing attribute 3548 // clause on a combined construct where target. is one of the 3549 // constituent constructs), or an is_device_ptr clause. 3550 OpenMPDefaultmapClauseKind ClauseKind = 3551 getVariableCategoryFromDecl(SemaRef.getLangOpts(), VD); 3552 if (SemaRef.getLangOpts().OpenMP >= 50) { 3553 bool IsModifierNone = Stack->getDefaultmapModifier(ClauseKind) == 3554 OMPC_DEFAULTMAP_MODIFIER_none; 3555 if (DVar.CKind == OMPC_unknown && IsModifierNone && 3556 VarsWithInheritedDSA.count(VD) == 0 && !Res) { 3557 // Only check for data-mapping attribute and is_device_ptr here 3558 // since we have already make sure that the declaration does not 3559 // have a data-sharing attribute above 3560 if (!Stack->checkMappableExprComponentListsForDecl( 3561 VD, /*CurrentRegionOnly=*/true, 3562 [VD](OMPClauseMappableExprCommon::MappableExprComponentListRef 3563 MapExprComponents, 3564 OpenMPClauseKind) { 3565 auto MI = MapExprComponents.rbegin(); 3566 auto ME = MapExprComponents.rend(); 3567 return MI != ME && MI->getAssociatedDeclaration() == VD; 3568 })) { 3569 VarsWithInheritedDSA[VD] = E; 3570 return; 3571 } 3572 } 3573 } 3574 if (SemaRef.getLangOpts().OpenMP > 50) { 3575 bool IsModifierPresent = Stack->getDefaultmapModifier(ClauseKind) == 3576 OMPC_DEFAULTMAP_MODIFIER_present; 3577 if (IsModifierPresent) { 3578 if (llvm::find(ImplicitMapModifier[ClauseKind], 3579 OMPC_MAP_MODIFIER_present) == 3580 std::end(ImplicitMapModifier[ClauseKind])) { 3581 ImplicitMapModifier[ClauseKind].push_back( 3582 OMPC_MAP_MODIFIER_present); 3583 } 3584 } 3585 } 3586 3587 if (isOpenMPTargetExecutionDirective(DKind) && 3588 !Stack->isLoopControlVariable(VD).first) { 3589 if (!Stack->checkMappableExprComponentListsForDecl( 3590 VD, /*CurrentRegionOnly=*/true, 3591 [this](OMPClauseMappableExprCommon::MappableExprComponentListRef 3592 StackComponents, 3593 OpenMPClauseKind) { 3594 if (SemaRef.LangOpts.OpenMP >= 50) 3595 return !StackComponents.empty(); 3596 // Variable is used if it has been marked as an array, array 3597 // section, array shaping or the variable iself. 3598 return StackComponents.size() == 1 || 3599 std::all_of( 3600 std::next(StackComponents.rbegin()), 3601 StackComponents.rend(), 3602 [](const OMPClauseMappableExprCommon:: 3603 MappableComponent &MC) { 3604 return MC.getAssociatedDeclaration() == 3605 nullptr && 3606 (isa<OMPArraySectionExpr>( 3607 MC.getAssociatedExpression()) || 3608 isa<OMPArrayShapingExpr>( 3609 MC.getAssociatedExpression()) || 3610 isa<ArraySubscriptExpr>( 3611 MC.getAssociatedExpression())); 3612 }); 3613 })) { 3614 bool IsFirstprivate = false; 3615 // By default lambdas are captured as firstprivates. 3616 if (const auto *RD = 3617 VD->getType().getNonReferenceType()->getAsCXXRecordDecl()) 3618 IsFirstprivate = RD->isLambda(); 3619 IsFirstprivate = 3620 IsFirstprivate || (Stack->mustBeFirstprivate(ClauseKind) && !Res); 3621 if (IsFirstprivate) { 3622 ImplicitFirstprivate.emplace_back(E); 3623 } else { 3624 OpenMPDefaultmapClauseModifier M = 3625 Stack->getDefaultmapModifier(ClauseKind); 3626 OpenMPMapClauseKind Kind = getMapClauseKindFromModifier( 3627 M, ClauseKind == OMPC_DEFAULTMAP_aggregate || Res); 3628 ImplicitMap[ClauseKind][Kind].emplace_back(E); 3629 } 3630 return; 3631 } 3632 } 3633 3634 // OpenMP [2.9.3.6, Restrictions, p.2] 3635 // A list item that appears in a reduction clause of the innermost 3636 // enclosing worksharing or parallel construct may not be accessed in an 3637 // explicit task. 3638 DVar = Stack->hasInnermostDSA( 3639 VD, 3640 [](OpenMPClauseKind C, bool AppliedToPointee) { 3641 return C == OMPC_reduction && !AppliedToPointee; 3642 }, 3643 [](OpenMPDirectiveKind K) { 3644 return isOpenMPParallelDirective(K) || 3645 isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K); 3646 }, 3647 /*FromParent=*/true); 3648 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) { 3649 ErrorFound = true; 3650 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task); 3651 reportOriginalDsa(SemaRef, Stack, VD, DVar); 3652 return; 3653 } 3654 3655 // Define implicit data-sharing attributes for task. 3656 DVar = Stack->getImplicitDSA(VD, /*FromParent=*/false); 3657 if (((isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared) || 3658 (Stack->getDefaultDSA() == DSA_firstprivate && 3659 DVar.CKind == OMPC_firstprivate && !DVar.RefExpr)) && 3660 !Stack->isLoopControlVariable(VD).first) { 3661 ImplicitFirstprivate.push_back(E); 3662 return; 3663 } 3664 3665 // Store implicitly used globals with declare target link for parent 3666 // target. 3667 if (!isOpenMPTargetExecutionDirective(DKind) && Res && 3668 *Res == OMPDeclareTargetDeclAttr::MT_Link) { 3669 Stack->addToParentTargetRegionLinkGlobals(E); 3670 return; 3671 } 3672 } 3673 } 3674 void VisitMemberExpr(MemberExpr *E) { 3675 if (E->isTypeDependent() || E->isValueDependent() || 3676 E->containsUnexpandedParameterPack() || E->isInstantiationDependent()) 3677 return; 3678 auto *FD = dyn_cast<FieldDecl>(E->getMemberDecl()); 3679 OpenMPDirectiveKind DKind = Stack->getCurrentDirective(); 3680 if (auto *TE = dyn_cast<CXXThisExpr>(E->getBase()->IgnoreParenCasts())) { 3681 if (!FD) 3682 return; 3683 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(FD, /*FromParent=*/false); 3684 // Check if the variable has explicit DSA set and stop analysis if it 3685 // so. 3686 if (DVar.RefExpr || !ImplicitDeclarations.insert(FD).second) 3687 return; 3688 3689 if (isOpenMPTargetExecutionDirective(DKind) && 3690 !Stack->isLoopControlVariable(FD).first && 3691 !Stack->checkMappableExprComponentListsForDecl( 3692 FD, /*CurrentRegionOnly=*/true, 3693 [](OMPClauseMappableExprCommon::MappableExprComponentListRef 3694 StackComponents, 3695 OpenMPClauseKind) { 3696 return isa<CXXThisExpr>( 3697 cast<MemberExpr>( 3698 StackComponents.back().getAssociatedExpression()) 3699 ->getBase() 3700 ->IgnoreParens()); 3701 })) { 3702 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3] 3703 // A bit-field cannot appear in a map clause. 3704 // 3705 if (FD->isBitField()) 3706 return; 3707 3708 // Check to see if the member expression is referencing a class that 3709 // has already been explicitly mapped 3710 if (Stack->isClassPreviouslyMapped(TE->getType())) 3711 return; 3712 3713 OpenMPDefaultmapClauseModifier Modifier = 3714 Stack->getDefaultmapModifier(OMPC_DEFAULTMAP_aggregate); 3715 OpenMPDefaultmapClauseKind ClauseKind = 3716 getVariableCategoryFromDecl(SemaRef.getLangOpts(), FD); 3717 OpenMPMapClauseKind Kind = getMapClauseKindFromModifier( 3718 Modifier, /*IsAggregateOrDeclareTarget*/ true); 3719 ImplicitMap[ClauseKind][Kind].emplace_back(E); 3720 return; 3721 } 3722 3723 SourceLocation ELoc = E->getExprLoc(); 3724 // OpenMP [2.9.3.6, Restrictions, p.2] 3725 // A list item that appears in a reduction clause of the innermost 3726 // enclosing worksharing or parallel construct may not be accessed in 3727 // an explicit task. 3728 DVar = Stack->hasInnermostDSA( 3729 FD, 3730 [](OpenMPClauseKind C, bool AppliedToPointee) { 3731 return C == OMPC_reduction && !AppliedToPointee; 3732 }, 3733 [](OpenMPDirectiveKind K) { 3734 return isOpenMPParallelDirective(K) || 3735 isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K); 3736 }, 3737 /*FromParent=*/true); 3738 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) { 3739 ErrorFound = true; 3740 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task); 3741 reportOriginalDsa(SemaRef, Stack, FD, DVar); 3742 return; 3743 } 3744 3745 // Define implicit data-sharing attributes for task. 3746 DVar = Stack->getImplicitDSA(FD, /*FromParent=*/false); 3747 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared && 3748 !Stack->isLoopControlVariable(FD).first) { 3749 // Check if there is a captured expression for the current field in the 3750 // region. Do not mark it as firstprivate unless there is no captured 3751 // expression. 3752 // TODO: try to make it firstprivate. 3753 if (DVar.CKind != OMPC_unknown) 3754 ImplicitFirstprivate.push_back(E); 3755 } 3756 return; 3757 } 3758 if (isOpenMPTargetExecutionDirective(DKind)) { 3759 OMPClauseMappableExprCommon::MappableExprComponentList CurComponents; 3760 if (!checkMapClauseExpressionBase(SemaRef, E, CurComponents, OMPC_map, 3761 Stack->getCurrentDirective(), 3762 /*NoDiagnose=*/true)) 3763 return; 3764 const auto *VD = cast<ValueDecl>( 3765 CurComponents.back().getAssociatedDeclaration()->getCanonicalDecl()); 3766 if (!Stack->checkMappableExprComponentListsForDecl( 3767 VD, /*CurrentRegionOnly=*/true, 3768 [&CurComponents]( 3769 OMPClauseMappableExprCommon::MappableExprComponentListRef 3770 StackComponents, 3771 OpenMPClauseKind) { 3772 auto CCI = CurComponents.rbegin(); 3773 auto CCE = CurComponents.rend(); 3774 for (const auto &SC : llvm::reverse(StackComponents)) { 3775 // Do both expressions have the same kind? 3776 if (CCI->getAssociatedExpression()->getStmtClass() != 3777 SC.getAssociatedExpression()->getStmtClass()) 3778 if (!((isa<OMPArraySectionExpr>( 3779 SC.getAssociatedExpression()) || 3780 isa<OMPArrayShapingExpr>( 3781 SC.getAssociatedExpression())) && 3782 isa<ArraySubscriptExpr>( 3783 CCI->getAssociatedExpression()))) 3784 return false; 3785 3786 const Decl *CCD = CCI->getAssociatedDeclaration(); 3787 const Decl *SCD = SC.getAssociatedDeclaration(); 3788 CCD = CCD ? CCD->getCanonicalDecl() : nullptr; 3789 SCD = SCD ? SCD->getCanonicalDecl() : nullptr; 3790 if (SCD != CCD) 3791 return false; 3792 std::advance(CCI, 1); 3793 if (CCI == CCE) 3794 break; 3795 } 3796 return true; 3797 })) { 3798 Visit(E->getBase()); 3799 } 3800 } else if (!TryCaptureCXXThisMembers) { 3801 Visit(E->getBase()); 3802 } 3803 } 3804 void VisitOMPExecutableDirective(OMPExecutableDirective *S) { 3805 for (OMPClause *C : S->clauses()) { 3806 // Skip analysis of arguments of private clauses for task|target 3807 // directives. 3808 if (isa_and_nonnull<OMPPrivateClause>(C)) 3809 continue; 3810 // Skip analysis of arguments of implicitly defined firstprivate clause 3811 // for task|target directives. 3812 // Skip analysis of arguments of implicitly defined map clause for target 3813 // directives. 3814 if (C && !((isa<OMPFirstprivateClause>(C) || isa<OMPMapClause>(C)) && 3815 C->isImplicit() && 3816 !isOpenMPTaskingDirective(Stack->getCurrentDirective()))) { 3817 for (Stmt *CC : C->children()) { 3818 if (CC) 3819 Visit(CC); 3820 } 3821 } 3822 } 3823 // Check implicitly captured variables. 3824 VisitSubCaptures(S); 3825 } 3826 3827 void VisitOMPLoopTransformationDirective(OMPLoopTransformationDirective *S) { 3828 // Loop transformation directives do not introduce data sharing 3829 VisitStmt(S); 3830 } 3831 3832 void VisitCallExpr(CallExpr *S) { 3833 for (Stmt *C : S->arguments()) { 3834 if (C) { 3835 // Check implicitly captured variables in the task-based directives to 3836 // check if they must be firstprivatized. 3837 Visit(C); 3838 } 3839 } 3840 if (Expr *Callee = S->getCallee()) 3841 if (auto *CE = dyn_cast<MemberExpr>(Callee->IgnoreParenImpCasts())) 3842 Visit(CE->getBase()); 3843 } 3844 void VisitStmt(Stmt *S) { 3845 for (Stmt *C : S->children()) { 3846 if (C) { 3847 // Check implicitly captured variables in the task-based directives to 3848 // check if they must be firstprivatized. 3849 Visit(C); 3850 } 3851 } 3852 } 3853 3854 void visitSubCaptures(CapturedStmt *S) { 3855 for (const CapturedStmt::Capture &Cap : S->captures()) { 3856 if (!Cap.capturesVariable() && !Cap.capturesVariableByCopy()) 3857 continue; 3858 VarDecl *VD = Cap.getCapturedVar(); 3859 // Do not try to map the variable if it or its sub-component was mapped 3860 // already. 3861 if (isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()) && 3862 Stack->checkMappableExprComponentListsForDecl( 3863 VD, /*CurrentRegionOnly=*/true, 3864 [](OMPClauseMappableExprCommon::MappableExprComponentListRef, 3865 OpenMPClauseKind) { return true; })) 3866 continue; 3867 DeclRefExpr *DRE = buildDeclRefExpr( 3868 SemaRef, VD, VD->getType().getNonLValueExprType(SemaRef.Context), 3869 Cap.getLocation(), /*RefersToCapture=*/true); 3870 Visit(DRE); 3871 } 3872 } 3873 bool isErrorFound() const { return ErrorFound; } 3874 ArrayRef<Expr *> getImplicitFirstprivate() const { 3875 return ImplicitFirstprivate; 3876 } 3877 ArrayRef<Expr *> getImplicitMap(OpenMPDefaultmapClauseKind DK, 3878 OpenMPMapClauseKind MK) const { 3879 return ImplicitMap[DK][MK]; 3880 } 3881 ArrayRef<OpenMPMapModifierKind> 3882 getImplicitMapModifier(OpenMPDefaultmapClauseKind Kind) const { 3883 return ImplicitMapModifier[Kind]; 3884 } 3885 const Sema::VarsWithInheritedDSAType &getVarsWithInheritedDSA() const { 3886 return VarsWithInheritedDSA; 3887 } 3888 3889 DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS) 3890 : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) { 3891 // Process declare target link variables for the target directives. 3892 if (isOpenMPTargetExecutionDirective(S->getCurrentDirective())) { 3893 for (DeclRefExpr *E : Stack->getLinkGlobals()) 3894 Visit(E); 3895 } 3896 } 3897 }; 3898 } // namespace 3899 3900 static void handleDeclareVariantConstructTrait(DSAStackTy *Stack, 3901 OpenMPDirectiveKind DKind, 3902 bool ScopeEntry) { 3903 SmallVector<llvm::omp::TraitProperty, 8> Traits; 3904 if (isOpenMPTargetExecutionDirective(DKind)) 3905 Traits.emplace_back(llvm::omp::TraitProperty::construct_target_target); 3906 if (isOpenMPTeamsDirective(DKind)) 3907 Traits.emplace_back(llvm::omp::TraitProperty::construct_teams_teams); 3908 if (isOpenMPParallelDirective(DKind)) 3909 Traits.emplace_back(llvm::omp::TraitProperty::construct_parallel_parallel); 3910 if (isOpenMPWorksharingDirective(DKind)) 3911 Traits.emplace_back(llvm::omp::TraitProperty::construct_for_for); 3912 if (isOpenMPSimdDirective(DKind)) 3913 Traits.emplace_back(llvm::omp::TraitProperty::construct_simd_simd); 3914 Stack->handleConstructTrait(Traits, ScopeEntry); 3915 } 3916 3917 void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) { 3918 switch (DKind) { 3919 case OMPD_parallel: 3920 case OMPD_parallel_for: 3921 case OMPD_parallel_for_simd: 3922 case OMPD_parallel_sections: 3923 case OMPD_parallel_master: 3924 case OMPD_teams: 3925 case OMPD_teams_distribute: 3926 case OMPD_teams_distribute_simd: { 3927 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst(); 3928 QualType KmpInt32PtrTy = 3929 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 3930 Sema::CapturedParamNameType Params[] = { 3931 std::make_pair(".global_tid.", KmpInt32PtrTy), 3932 std::make_pair(".bound_tid.", KmpInt32PtrTy), 3933 std::make_pair(StringRef(), QualType()) // __context with shared vars 3934 }; 3935 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 3936 Params); 3937 break; 3938 } 3939 case OMPD_target_teams: 3940 case OMPD_target_parallel: 3941 case OMPD_target_parallel_for: 3942 case OMPD_target_parallel_for_simd: 3943 case OMPD_target_teams_distribute: 3944 case OMPD_target_teams_distribute_simd: { 3945 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst(); 3946 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict(); 3947 QualType KmpInt32PtrTy = 3948 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 3949 QualType Args[] = {VoidPtrTy}; 3950 FunctionProtoType::ExtProtoInfo EPI; 3951 EPI.Variadic = true; 3952 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI); 3953 Sema::CapturedParamNameType Params[] = { 3954 std::make_pair(".global_tid.", KmpInt32Ty), 3955 std::make_pair(".part_id.", KmpInt32PtrTy), 3956 std::make_pair(".privates.", VoidPtrTy), 3957 std::make_pair( 3958 ".copy_fn.", 3959 Context.getPointerType(CopyFnType).withConst().withRestrict()), 3960 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()), 3961 std::make_pair(StringRef(), QualType()) // __context with shared vars 3962 }; 3963 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 3964 Params, /*OpenMPCaptureLevel=*/0); 3965 // Mark this captured region as inlined, because we don't use outlined 3966 // function directly. 3967 getCurCapturedRegion()->TheCapturedDecl->addAttr( 3968 AlwaysInlineAttr::CreateImplicit( 3969 Context, {}, AttributeCommonInfo::AS_Keyword, 3970 AlwaysInlineAttr::Keyword_forceinline)); 3971 Sema::CapturedParamNameType ParamsTarget[] = { 3972 std::make_pair(StringRef(), QualType()) // __context with shared vars 3973 }; 3974 // Start a captured region for 'target' with no implicit parameters. 3975 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 3976 ParamsTarget, /*OpenMPCaptureLevel=*/1); 3977 Sema::CapturedParamNameType ParamsTeamsOrParallel[] = { 3978 std::make_pair(".global_tid.", KmpInt32PtrTy), 3979 std::make_pair(".bound_tid.", KmpInt32PtrTy), 3980 std::make_pair(StringRef(), QualType()) // __context with shared vars 3981 }; 3982 // Start a captured region for 'teams' or 'parallel'. Both regions have 3983 // the same implicit parameters. 3984 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 3985 ParamsTeamsOrParallel, /*OpenMPCaptureLevel=*/2); 3986 break; 3987 } 3988 case OMPD_target: 3989 case OMPD_target_simd: { 3990 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst(); 3991 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict(); 3992 QualType KmpInt32PtrTy = 3993 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 3994 QualType Args[] = {VoidPtrTy}; 3995 FunctionProtoType::ExtProtoInfo EPI; 3996 EPI.Variadic = true; 3997 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI); 3998 Sema::CapturedParamNameType Params[] = { 3999 std::make_pair(".global_tid.", KmpInt32Ty), 4000 std::make_pair(".part_id.", KmpInt32PtrTy), 4001 std::make_pair(".privates.", VoidPtrTy), 4002 std::make_pair( 4003 ".copy_fn.", 4004 Context.getPointerType(CopyFnType).withConst().withRestrict()), 4005 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()), 4006 std::make_pair(StringRef(), QualType()) // __context with shared vars 4007 }; 4008 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 4009 Params, /*OpenMPCaptureLevel=*/0); 4010 // Mark this captured region as inlined, because we don't use outlined 4011 // function directly. 4012 getCurCapturedRegion()->TheCapturedDecl->addAttr( 4013 AlwaysInlineAttr::CreateImplicit( 4014 Context, {}, AttributeCommonInfo::AS_Keyword, 4015 AlwaysInlineAttr::Keyword_forceinline)); 4016 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 4017 std::make_pair(StringRef(), QualType()), 4018 /*OpenMPCaptureLevel=*/1); 4019 break; 4020 } 4021 case OMPD_atomic: 4022 case OMPD_critical: 4023 case OMPD_section: 4024 case OMPD_master: 4025 case OMPD_masked: 4026 case OMPD_tile: 4027 case OMPD_unroll: 4028 break; 4029 case OMPD_loop: 4030 // TODO: 'loop' may require additional parameters depending on the binding. 4031 // Treat similar to OMPD_simd/OMPD_for for now. 4032 case OMPD_simd: 4033 case OMPD_for: 4034 case OMPD_for_simd: 4035 case OMPD_sections: 4036 case OMPD_single: 4037 case OMPD_taskgroup: 4038 case OMPD_distribute: 4039 case OMPD_distribute_simd: 4040 case OMPD_ordered: 4041 case OMPD_target_data: 4042 case OMPD_dispatch: { 4043 Sema::CapturedParamNameType Params[] = { 4044 std::make_pair(StringRef(), QualType()) // __context with shared vars 4045 }; 4046 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 4047 Params); 4048 break; 4049 } 4050 case OMPD_task: { 4051 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst(); 4052 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict(); 4053 QualType KmpInt32PtrTy = 4054 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 4055 QualType Args[] = {VoidPtrTy}; 4056 FunctionProtoType::ExtProtoInfo EPI; 4057 EPI.Variadic = true; 4058 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI); 4059 Sema::CapturedParamNameType Params[] = { 4060 std::make_pair(".global_tid.", KmpInt32Ty), 4061 std::make_pair(".part_id.", KmpInt32PtrTy), 4062 std::make_pair(".privates.", VoidPtrTy), 4063 std::make_pair( 4064 ".copy_fn.", 4065 Context.getPointerType(CopyFnType).withConst().withRestrict()), 4066 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()), 4067 std::make_pair(StringRef(), QualType()) // __context with shared vars 4068 }; 4069 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 4070 Params); 4071 // Mark this captured region as inlined, because we don't use outlined 4072 // function directly. 4073 getCurCapturedRegion()->TheCapturedDecl->addAttr( 4074 AlwaysInlineAttr::CreateImplicit( 4075 Context, {}, AttributeCommonInfo::AS_Keyword, 4076 AlwaysInlineAttr::Keyword_forceinline)); 4077 break; 4078 } 4079 case OMPD_taskloop: 4080 case OMPD_taskloop_simd: 4081 case OMPD_master_taskloop: 4082 case OMPD_master_taskloop_simd: { 4083 QualType KmpInt32Ty = 4084 Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1) 4085 .withConst(); 4086 QualType KmpUInt64Ty = 4087 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0) 4088 .withConst(); 4089 QualType KmpInt64Ty = 4090 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1) 4091 .withConst(); 4092 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict(); 4093 QualType KmpInt32PtrTy = 4094 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 4095 QualType Args[] = {VoidPtrTy}; 4096 FunctionProtoType::ExtProtoInfo EPI; 4097 EPI.Variadic = true; 4098 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI); 4099 Sema::CapturedParamNameType Params[] = { 4100 std::make_pair(".global_tid.", KmpInt32Ty), 4101 std::make_pair(".part_id.", KmpInt32PtrTy), 4102 std::make_pair(".privates.", VoidPtrTy), 4103 std::make_pair( 4104 ".copy_fn.", 4105 Context.getPointerType(CopyFnType).withConst().withRestrict()), 4106 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()), 4107 std::make_pair(".lb.", KmpUInt64Ty), 4108 std::make_pair(".ub.", KmpUInt64Ty), 4109 std::make_pair(".st.", KmpInt64Ty), 4110 std::make_pair(".liter.", KmpInt32Ty), 4111 std::make_pair(".reductions.", VoidPtrTy), 4112 std::make_pair(StringRef(), QualType()) // __context with shared vars 4113 }; 4114 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 4115 Params); 4116 // Mark this captured region as inlined, because we don't use outlined 4117 // function directly. 4118 getCurCapturedRegion()->TheCapturedDecl->addAttr( 4119 AlwaysInlineAttr::CreateImplicit( 4120 Context, {}, AttributeCommonInfo::AS_Keyword, 4121 AlwaysInlineAttr::Keyword_forceinline)); 4122 break; 4123 } 4124 case OMPD_parallel_master_taskloop: 4125 case OMPD_parallel_master_taskloop_simd: { 4126 QualType KmpInt32Ty = 4127 Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1) 4128 .withConst(); 4129 QualType KmpUInt64Ty = 4130 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0) 4131 .withConst(); 4132 QualType KmpInt64Ty = 4133 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1) 4134 .withConst(); 4135 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict(); 4136 QualType KmpInt32PtrTy = 4137 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 4138 Sema::CapturedParamNameType ParamsParallel[] = { 4139 std::make_pair(".global_tid.", KmpInt32PtrTy), 4140 std::make_pair(".bound_tid.", KmpInt32PtrTy), 4141 std::make_pair(StringRef(), QualType()) // __context with shared vars 4142 }; 4143 // Start a captured region for 'parallel'. 4144 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 4145 ParamsParallel, /*OpenMPCaptureLevel=*/0); 4146 QualType Args[] = {VoidPtrTy}; 4147 FunctionProtoType::ExtProtoInfo EPI; 4148 EPI.Variadic = true; 4149 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI); 4150 Sema::CapturedParamNameType Params[] = { 4151 std::make_pair(".global_tid.", KmpInt32Ty), 4152 std::make_pair(".part_id.", KmpInt32PtrTy), 4153 std::make_pair(".privates.", VoidPtrTy), 4154 std::make_pair( 4155 ".copy_fn.", 4156 Context.getPointerType(CopyFnType).withConst().withRestrict()), 4157 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()), 4158 std::make_pair(".lb.", KmpUInt64Ty), 4159 std::make_pair(".ub.", KmpUInt64Ty), 4160 std::make_pair(".st.", KmpInt64Ty), 4161 std::make_pair(".liter.", KmpInt32Ty), 4162 std::make_pair(".reductions.", VoidPtrTy), 4163 std::make_pair(StringRef(), QualType()) // __context with shared vars 4164 }; 4165 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 4166 Params, /*OpenMPCaptureLevel=*/1); 4167 // Mark this captured region as inlined, because we don't use outlined 4168 // function directly. 4169 getCurCapturedRegion()->TheCapturedDecl->addAttr( 4170 AlwaysInlineAttr::CreateImplicit( 4171 Context, {}, AttributeCommonInfo::AS_Keyword, 4172 AlwaysInlineAttr::Keyword_forceinline)); 4173 break; 4174 } 4175 case OMPD_distribute_parallel_for_simd: 4176 case OMPD_distribute_parallel_for: { 4177 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst(); 4178 QualType KmpInt32PtrTy = 4179 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 4180 Sema::CapturedParamNameType Params[] = { 4181 std::make_pair(".global_tid.", KmpInt32PtrTy), 4182 std::make_pair(".bound_tid.", KmpInt32PtrTy), 4183 std::make_pair(".previous.lb.", Context.getSizeType().withConst()), 4184 std::make_pair(".previous.ub.", Context.getSizeType().withConst()), 4185 std::make_pair(StringRef(), QualType()) // __context with shared vars 4186 }; 4187 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 4188 Params); 4189 break; 4190 } 4191 case OMPD_target_teams_distribute_parallel_for: 4192 case OMPD_target_teams_distribute_parallel_for_simd: { 4193 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst(); 4194 QualType KmpInt32PtrTy = 4195 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 4196 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict(); 4197 4198 QualType Args[] = {VoidPtrTy}; 4199 FunctionProtoType::ExtProtoInfo EPI; 4200 EPI.Variadic = true; 4201 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI); 4202 Sema::CapturedParamNameType Params[] = { 4203 std::make_pair(".global_tid.", KmpInt32Ty), 4204 std::make_pair(".part_id.", KmpInt32PtrTy), 4205 std::make_pair(".privates.", VoidPtrTy), 4206 std::make_pair( 4207 ".copy_fn.", 4208 Context.getPointerType(CopyFnType).withConst().withRestrict()), 4209 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()), 4210 std::make_pair(StringRef(), QualType()) // __context with shared vars 4211 }; 4212 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 4213 Params, /*OpenMPCaptureLevel=*/0); 4214 // Mark this captured region as inlined, because we don't use outlined 4215 // function directly. 4216 getCurCapturedRegion()->TheCapturedDecl->addAttr( 4217 AlwaysInlineAttr::CreateImplicit( 4218 Context, {}, AttributeCommonInfo::AS_Keyword, 4219 AlwaysInlineAttr::Keyword_forceinline)); 4220 Sema::CapturedParamNameType ParamsTarget[] = { 4221 std::make_pair(StringRef(), QualType()) // __context with shared vars 4222 }; 4223 // Start a captured region for 'target' with no implicit parameters. 4224 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 4225 ParamsTarget, /*OpenMPCaptureLevel=*/1); 4226 4227 Sema::CapturedParamNameType ParamsTeams[] = { 4228 std::make_pair(".global_tid.", KmpInt32PtrTy), 4229 std::make_pair(".bound_tid.", KmpInt32PtrTy), 4230 std::make_pair(StringRef(), QualType()) // __context with shared vars 4231 }; 4232 // Start a captured region for 'target' with no implicit parameters. 4233 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 4234 ParamsTeams, /*OpenMPCaptureLevel=*/2); 4235 4236 Sema::CapturedParamNameType ParamsParallel[] = { 4237 std::make_pair(".global_tid.", KmpInt32PtrTy), 4238 std::make_pair(".bound_tid.", KmpInt32PtrTy), 4239 std::make_pair(".previous.lb.", Context.getSizeType().withConst()), 4240 std::make_pair(".previous.ub.", Context.getSizeType().withConst()), 4241 std::make_pair(StringRef(), QualType()) // __context with shared vars 4242 }; 4243 // Start a captured region for 'teams' or 'parallel'. Both regions have 4244 // the same implicit parameters. 4245 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 4246 ParamsParallel, /*OpenMPCaptureLevel=*/3); 4247 break; 4248 } 4249 4250 case OMPD_teams_distribute_parallel_for: 4251 case OMPD_teams_distribute_parallel_for_simd: { 4252 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst(); 4253 QualType KmpInt32PtrTy = 4254 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 4255 4256 Sema::CapturedParamNameType ParamsTeams[] = { 4257 std::make_pair(".global_tid.", KmpInt32PtrTy), 4258 std::make_pair(".bound_tid.", KmpInt32PtrTy), 4259 std::make_pair(StringRef(), QualType()) // __context with shared vars 4260 }; 4261 // Start a captured region for 'target' with no implicit parameters. 4262 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 4263 ParamsTeams, /*OpenMPCaptureLevel=*/0); 4264 4265 Sema::CapturedParamNameType ParamsParallel[] = { 4266 std::make_pair(".global_tid.", KmpInt32PtrTy), 4267 std::make_pair(".bound_tid.", KmpInt32PtrTy), 4268 std::make_pair(".previous.lb.", Context.getSizeType().withConst()), 4269 std::make_pair(".previous.ub.", Context.getSizeType().withConst()), 4270 std::make_pair(StringRef(), QualType()) // __context with shared vars 4271 }; 4272 // Start a captured region for 'teams' or 'parallel'. Both regions have 4273 // the same implicit parameters. 4274 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 4275 ParamsParallel, /*OpenMPCaptureLevel=*/1); 4276 break; 4277 } 4278 case OMPD_target_update: 4279 case OMPD_target_enter_data: 4280 case OMPD_target_exit_data: { 4281 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst(); 4282 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict(); 4283 QualType KmpInt32PtrTy = 4284 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 4285 QualType Args[] = {VoidPtrTy}; 4286 FunctionProtoType::ExtProtoInfo EPI; 4287 EPI.Variadic = true; 4288 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI); 4289 Sema::CapturedParamNameType Params[] = { 4290 std::make_pair(".global_tid.", KmpInt32Ty), 4291 std::make_pair(".part_id.", KmpInt32PtrTy), 4292 std::make_pair(".privates.", VoidPtrTy), 4293 std::make_pair( 4294 ".copy_fn.", 4295 Context.getPointerType(CopyFnType).withConst().withRestrict()), 4296 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()), 4297 std::make_pair(StringRef(), QualType()) // __context with shared vars 4298 }; 4299 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 4300 Params); 4301 // Mark this captured region as inlined, because we don't use outlined 4302 // function directly. 4303 getCurCapturedRegion()->TheCapturedDecl->addAttr( 4304 AlwaysInlineAttr::CreateImplicit( 4305 Context, {}, AttributeCommonInfo::AS_Keyword, 4306 AlwaysInlineAttr::Keyword_forceinline)); 4307 break; 4308 } 4309 case OMPD_threadprivate: 4310 case OMPD_allocate: 4311 case OMPD_taskyield: 4312 case OMPD_barrier: 4313 case OMPD_taskwait: 4314 case OMPD_cancellation_point: 4315 case OMPD_cancel: 4316 case OMPD_flush: 4317 case OMPD_depobj: 4318 case OMPD_scan: 4319 case OMPD_declare_reduction: 4320 case OMPD_declare_mapper: 4321 case OMPD_declare_simd: 4322 case OMPD_declare_target: 4323 case OMPD_end_declare_target: 4324 case OMPD_requires: 4325 case OMPD_declare_variant: 4326 case OMPD_begin_declare_variant: 4327 case OMPD_end_declare_variant: 4328 case OMPD_metadirective: 4329 llvm_unreachable("OpenMP Directive is not allowed"); 4330 case OMPD_unknown: 4331 default: 4332 llvm_unreachable("Unknown OpenMP directive"); 4333 } 4334 DSAStack->setContext(CurContext); 4335 handleDeclareVariantConstructTrait(DSAStack, DKind, /* ScopeEntry */ true); 4336 } 4337 4338 int Sema::getNumberOfConstructScopes(unsigned Level) const { 4339 return getOpenMPCaptureLevels(DSAStack->getDirective(Level)); 4340 } 4341 4342 int Sema::getOpenMPCaptureLevels(OpenMPDirectiveKind DKind) { 4343 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions; 4344 getOpenMPCaptureRegions(CaptureRegions, DKind); 4345 return CaptureRegions.size(); 4346 } 4347 4348 static OMPCapturedExprDecl *buildCaptureDecl(Sema &S, IdentifierInfo *Id, 4349 Expr *CaptureExpr, bool WithInit, 4350 bool AsExpression) { 4351 assert(CaptureExpr); 4352 ASTContext &C = S.getASTContext(); 4353 Expr *Init = AsExpression ? CaptureExpr : CaptureExpr->IgnoreImpCasts(); 4354 QualType Ty = Init->getType(); 4355 if (CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue()) { 4356 if (S.getLangOpts().CPlusPlus) { 4357 Ty = C.getLValueReferenceType(Ty); 4358 } else { 4359 Ty = C.getPointerType(Ty); 4360 ExprResult Res = 4361 S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_AddrOf, Init); 4362 if (!Res.isUsable()) 4363 return nullptr; 4364 Init = Res.get(); 4365 } 4366 WithInit = true; 4367 } 4368 auto *CED = OMPCapturedExprDecl::Create(C, S.CurContext, Id, Ty, 4369 CaptureExpr->getBeginLoc()); 4370 if (!WithInit) 4371 CED->addAttr(OMPCaptureNoInitAttr::CreateImplicit(C)); 4372 S.CurContext->addHiddenDecl(CED); 4373 Sema::TentativeAnalysisScope Trap(S); 4374 S.AddInitializerToDecl(CED, Init, /*DirectInit=*/false); 4375 return CED; 4376 } 4377 4378 static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr, 4379 bool WithInit) { 4380 OMPCapturedExprDecl *CD; 4381 if (VarDecl *VD = S.isOpenMPCapturedDecl(D)) 4382 CD = cast<OMPCapturedExprDecl>(VD); 4383 else 4384 CD = buildCaptureDecl(S, D->getIdentifier(), CaptureExpr, WithInit, 4385 /*AsExpression=*/false); 4386 return buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(), 4387 CaptureExpr->getExprLoc()); 4388 } 4389 4390 static ExprResult buildCapture(Sema &S, Expr *CaptureExpr, DeclRefExpr *&Ref) { 4391 CaptureExpr = S.DefaultLvalueConversion(CaptureExpr).get(); 4392 if (!Ref) { 4393 OMPCapturedExprDecl *CD = buildCaptureDecl( 4394 S, &S.getASTContext().Idents.get(".capture_expr."), CaptureExpr, 4395 /*WithInit=*/true, /*AsExpression=*/true); 4396 Ref = buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(), 4397 CaptureExpr->getExprLoc()); 4398 } 4399 ExprResult Res = Ref; 4400 if (!S.getLangOpts().CPlusPlus && 4401 CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue() && 4402 Ref->getType()->isPointerType()) { 4403 Res = S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_Deref, Ref); 4404 if (!Res.isUsable()) 4405 return ExprError(); 4406 } 4407 return S.DefaultLvalueConversion(Res.get()); 4408 } 4409 4410 namespace { 4411 // OpenMP directives parsed in this section are represented as a 4412 // CapturedStatement with an associated statement. If a syntax error 4413 // is detected during the parsing of the associated statement, the 4414 // compiler must abort processing and close the CapturedStatement. 4415 // 4416 // Combined directives such as 'target parallel' have more than one 4417 // nested CapturedStatements. This RAII ensures that we unwind out 4418 // of all the nested CapturedStatements when an error is found. 4419 class CaptureRegionUnwinderRAII { 4420 private: 4421 Sema &S; 4422 bool &ErrorFound; 4423 OpenMPDirectiveKind DKind = OMPD_unknown; 4424 4425 public: 4426 CaptureRegionUnwinderRAII(Sema &S, bool &ErrorFound, 4427 OpenMPDirectiveKind DKind) 4428 : S(S), ErrorFound(ErrorFound), DKind(DKind) {} 4429 ~CaptureRegionUnwinderRAII() { 4430 if (ErrorFound) { 4431 int ThisCaptureLevel = S.getOpenMPCaptureLevels(DKind); 4432 while (--ThisCaptureLevel >= 0) 4433 S.ActOnCapturedRegionError(); 4434 } 4435 } 4436 }; 4437 } // namespace 4438 4439 void Sema::tryCaptureOpenMPLambdas(ValueDecl *V) { 4440 // Capture variables captured by reference in lambdas for target-based 4441 // directives. 4442 if (!CurContext->isDependentContext() && 4443 (isOpenMPTargetExecutionDirective(DSAStack->getCurrentDirective()) || 4444 isOpenMPTargetDataManagementDirective( 4445 DSAStack->getCurrentDirective()))) { 4446 QualType Type = V->getType(); 4447 if (const auto *RD = Type.getCanonicalType() 4448 .getNonReferenceType() 4449 ->getAsCXXRecordDecl()) { 4450 bool SavedForceCaptureByReferenceInTargetExecutable = 4451 DSAStack->isForceCaptureByReferenceInTargetExecutable(); 4452 DSAStack->setForceCaptureByReferenceInTargetExecutable( 4453 /*V=*/true); 4454 if (RD->isLambda()) { 4455 llvm::DenseMap<const VarDecl *, FieldDecl *> Captures; 4456 FieldDecl *ThisCapture; 4457 RD->getCaptureFields(Captures, ThisCapture); 4458 for (const LambdaCapture &LC : RD->captures()) { 4459 if (LC.getCaptureKind() == LCK_ByRef) { 4460 VarDecl *VD = LC.getCapturedVar(); 4461 DeclContext *VDC = VD->getDeclContext(); 4462 if (!VDC->Encloses(CurContext)) 4463 continue; 4464 MarkVariableReferenced(LC.getLocation(), VD); 4465 } else if (LC.getCaptureKind() == LCK_This) { 4466 QualType ThisTy = getCurrentThisType(); 4467 if (!ThisTy.isNull() && 4468 Context.typesAreCompatible(ThisTy, ThisCapture->getType())) 4469 CheckCXXThisCapture(LC.getLocation()); 4470 } 4471 } 4472 } 4473 DSAStack->setForceCaptureByReferenceInTargetExecutable( 4474 SavedForceCaptureByReferenceInTargetExecutable); 4475 } 4476 } 4477 } 4478 4479 static bool checkOrderedOrderSpecified(Sema &S, 4480 const ArrayRef<OMPClause *> Clauses) { 4481 const OMPOrderedClause *Ordered = nullptr; 4482 const OMPOrderClause *Order = nullptr; 4483 4484 for (const OMPClause *Clause : Clauses) { 4485 if (Clause->getClauseKind() == OMPC_ordered) 4486 Ordered = cast<OMPOrderedClause>(Clause); 4487 else if (Clause->getClauseKind() == OMPC_order) { 4488 Order = cast<OMPOrderClause>(Clause); 4489 if (Order->getKind() != OMPC_ORDER_concurrent) 4490 Order = nullptr; 4491 } 4492 if (Ordered && Order) 4493 break; 4494 } 4495 4496 if (Ordered && Order) { 4497 S.Diag(Order->getKindKwLoc(), 4498 diag::err_omp_simple_clause_incompatible_with_ordered) 4499 << getOpenMPClauseName(OMPC_order) 4500 << getOpenMPSimpleClauseTypeName(OMPC_order, OMPC_ORDER_concurrent) 4501 << SourceRange(Order->getBeginLoc(), Order->getEndLoc()); 4502 S.Diag(Ordered->getBeginLoc(), diag::note_omp_ordered_param) 4503 << 0 << SourceRange(Ordered->getBeginLoc(), Ordered->getEndLoc()); 4504 return true; 4505 } 4506 return false; 4507 } 4508 4509 StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S, 4510 ArrayRef<OMPClause *> Clauses) { 4511 handleDeclareVariantConstructTrait(DSAStack, DSAStack->getCurrentDirective(), 4512 /* ScopeEntry */ false); 4513 if (DSAStack->getCurrentDirective() == OMPD_atomic || 4514 DSAStack->getCurrentDirective() == OMPD_critical || 4515 DSAStack->getCurrentDirective() == OMPD_section || 4516 DSAStack->getCurrentDirective() == OMPD_master || 4517 DSAStack->getCurrentDirective() == OMPD_masked) 4518 return S; 4519 4520 bool ErrorFound = false; 4521 CaptureRegionUnwinderRAII CaptureRegionUnwinder( 4522 *this, ErrorFound, DSAStack->getCurrentDirective()); 4523 if (!S.isUsable()) { 4524 ErrorFound = true; 4525 return StmtError(); 4526 } 4527 4528 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions; 4529 getOpenMPCaptureRegions(CaptureRegions, DSAStack->getCurrentDirective()); 4530 OMPOrderedClause *OC = nullptr; 4531 OMPScheduleClause *SC = nullptr; 4532 SmallVector<const OMPLinearClause *, 4> LCs; 4533 SmallVector<const OMPClauseWithPreInit *, 4> PICs; 4534 // This is required for proper codegen. 4535 for (OMPClause *Clause : Clauses) { 4536 if (!LangOpts.OpenMPSimd && 4537 isOpenMPTaskingDirective(DSAStack->getCurrentDirective()) && 4538 Clause->getClauseKind() == OMPC_in_reduction) { 4539 // Capture taskgroup task_reduction descriptors inside the tasking regions 4540 // with the corresponding in_reduction items. 4541 auto *IRC = cast<OMPInReductionClause>(Clause); 4542 for (Expr *E : IRC->taskgroup_descriptors()) 4543 if (E) 4544 MarkDeclarationsReferencedInExpr(E); 4545 } 4546 if (isOpenMPPrivate(Clause->getClauseKind()) || 4547 Clause->getClauseKind() == OMPC_copyprivate || 4548 (getLangOpts().OpenMPUseTLS && 4549 getASTContext().getTargetInfo().isTLSSupported() && 4550 Clause->getClauseKind() == OMPC_copyin)) { 4551 DSAStack->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin); 4552 // Mark all variables in private list clauses as used in inner region. 4553 for (Stmt *VarRef : Clause->children()) { 4554 if (auto *E = cast_or_null<Expr>(VarRef)) { 4555 MarkDeclarationsReferencedInExpr(E); 4556 } 4557 } 4558 DSAStack->setForceVarCapturing(/*V=*/false); 4559 } else if (isOpenMPLoopTransformationDirective( 4560 DSAStack->getCurrentDirective())) { 4561 assert(CaptureRegions.empty() && 4562 "No captured regions in loop transformation directives."); 4563 } else if (CaptureRegions.size() > 1 || 4564 CaptureRegions.back() != OMPD_unknown) { 4565 if (auto *C = OMPClauseWithPreInit::get(Clause)) 4566 PICs.push_back(C); 4567 if (auto *C = OMPClauseWithPostUpdate::get(Clause)) { 4568 if (Expr *E = C->getPostUpdateExpr()) 4569 MarkDeclarationsReferencedInExpr(E); 4570 } 4571 } 4572 if (Clause->getClauseKind() == OMPC_schedule) 4573 SC = cast<OMPScheduleClause>(Clause); 4574 else if (Clause->getClauseKind() == OMPC_ordered) 4575 OC = cast<OMPOrderedClause>(Clause); 4576 else if (Clause->getClauseKind() == OMPC_linear) 4577 LCs.push_back(cast<OMPLinearClause>(Clause)); 4578 } 4579 // Capture allocator expressions if used. 4580 for (Expr *E : DSAStack->getInnerAllocators()) 4581 MarkDeclarationsReferencedInExpr(E); 4582 // OpenMP, 2.7.1 Loop Construct, Restrictions 4583 // The nonmonotonic modifier cannot be specified if an ordered clause is 4584 // specified. 4585 if (SC && 4586 (SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic || 4587 SC->getSecondScheduleModifier() == 4588 OMPC_SCHEDULE_MODIFIER_nonmonotonic) && 4589 OC) { 4590 Diag(SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic 4591 ? SC->getFirstScheduleModifierLoc() 4592 : SC->getSecondScheduleModifierLoc(), 4593 diag::err_omp_simple_clause_incompatible_with_ordered) 4594 << getOpenMPClauseName(OMPC_schedule) 4595 << getOpenMPSimpleClauseTypeName(OMPC_schedule, 4596 OMPC_SCHEDULE_MODIFIER_nonmonotonic) 4597 << SourceRange(OC->getBeginLoc(), OC->getEndLoc()); 4598 ErrorFound = true; 4599 } 4600 // OpenMP 5.0, 2.9.2 Worksharing-Loop Construct, Restrictions. 4601 // If an order(concurrent) clause is present, an ordered clause may not appear 4602 // on the same directive. 4603 if (checkOrderedOrderSpecified(*this, Clauses)) 4604 ErrorFound = true; 4605 if (!LCs.empty() && OC && OC->getNumForLoops()) { 4606 for (const OMPLinearClause *C : LCs) { 4607 Diag(C->getBeginLoc(), diag::err_omp_linear_ordered) 4608 << SourceRange(OC->getBeginLoc(), OC->getEndLoc()); 4609 } 4610 ErrorFound = true; 4611 } 4612 if (isOpenMPWorksharingDirective(DSAStack->getCurrentDirective()) && 4613 isOpenMPSimdDirective(DSAStack->getCurrentDirective()) && OC && 4614 OC->getNumForLoops()) { 4615 Diag(OC->getBeginLoc(), diag::err_omp_ordered_simd) 4616 << getOpenMPDirectiveName(DSAStack->getCurrentDirective()); 4617 ErrorFound = true; 4618 } 4619 if (ErrorFound) { 4620 return StmtError(); 4621 } 4622 StmtResult SR = S; 4623 unsigned CompletedRegions = 0; 4624 for (OpenMPDirectiveKind ThisCaptureRegion : llvm::reverse(CaptureRegions)) { 4625 // Mark all variables in private list clauses as used in inner region. 4626 // Required for proper codegen of combined directives. 4627 // TODO: add processing for other clauses. 4628 if (ThisCaptureRegion != OMPD_unknown) { 4629 for (const clang::OMPClauseWithPreInit *C : PICs) { 4630 OpenMPDirectiveKind CaptureRegion = C->getCaptureRegion(); 4631 // Find the particular capture region for the clause if the 4632 // directive is a combined one with multiple capture regions. 4633 // If the directive is not a combined one, the capture region 4634 // associated with the clause is OMPD_unknown and is generated 4635 // only once. 4636 if (CaptureRegion == ThisCaptureRegion || 4637 CaptureRegion == OMPD_unknown) { 4638 if (auto *DS = cast_or_null<DeclStmt>(C->getPreInitStmt())) { 4639 for (Decl *D : DS->decls()) 4640 MarkVariableReferenced(D->getLocation(), cast<VarDecl>(D)); 4641 } 4642 } 4643 } 4644 } 4645 if (ThisCaptureRegion == OMPD_target) { 4646 // Capture allocator traits in the target region. They are used implicitly 4647 // and, thus, are not captured by default. 4648 for (OMPClause *C : Clauses) { 4649 if (const auto *UAC = dyn_cast<OMPUsesAllocatorsClause>(C)) { 4650 for (unsigned I = 0, End = UAC->getNumberOfAllocators(); I < End; 4651 ++I) { 4652 OMPUsesAllocatorsClause::Data D = UAC->getAllocatorData(I); 4653 if (Expr *E = D.AllocatorTraits) 4654 MarkDeclarationsReferencedInExpr(E); 4655 } 4656 continue; 4657 } 4658 } 4659 } 4660 if (ThisCaptureRegion == OMPD_parallel) { 4661 // Capture temp arrays for inscan reductions and locals in aligned 4662 // clauses. 4663 for (OMPClause *C : Clauses) { 4664 if (auto *RC = dyn_cast<OMPReductionClause>(C)) { 4665 if (RC->getModifier() != OMPC_REDUCTION_inscan) 4666 continue; 4667 for (Expr *E : RC->copy_array_temps()) 4668 MarkDeclarationsReferencedInExpr(E); 4669 } 4670 if (auto *AC = dyn_cast<OMPAlignedClause>(C)) { 4671 for (Expr *E : AC->varlists()) 4672 MarkDeclarationsReferencedInExpr(E); 4673 } 4674 } 4675 } 4676 if (++CompletedRegions == CaptureRegions.size()) 4677 DSAStack->setBodyComplete(); 4678 SR = ActOnCapturedRegionEnd(SR.get()); 4679 } 4680 return SR; 4681 } 4682 4683 static bool checkCancelRegion(Sema &SemaRef, OpenMPDirectiveKind CurrentRegion, 4684 OpenMPDirectiveKind CancelRegion, 4685 SourceLocation StartLoc) { 4686 // CancelRegion is only needed for cancel and cancellation_point. 4687 if (CurrentRegion != OMPD_cancel && CurrentRegion != OMPD_cancellation_point) 4688 return false; 4689 4690 if (CancelRegion == OMPD_parallel || CancelRegion == OMPD_for || 4691 CancelRegion == OMPD_sections || CancelRegion == OMPD_taskgroup) 4692 return false; 4693 4694 SemaRef.Diag(StartLoc, diag::err_omp_wrong_cancel_region) 4695 << getOpenMPDirectiveName(CancelRegion); 4696 return true; 4697 } 4698 4699 static bool checkNestingOfRegions(Sema &SemaRef, const DSAStackTy *Stack, 4700 OpenMPDirectiveKind CurrentRegion, 4701 const DeclarationNameInfo &CurrentName, 4702 OpenMPDirectiveKind CancelRegion, 4703 OpenMPBindClauseKind BindKind, 4704 SourceLocation StartLoc) { 4705 if (Stack->getCurScope()) { 4706 OpenMPDirectiveKind ParentRegion = Stack->getParentDirective(); 4707 OpenMPDirectiveKind OffendingRegion = ParentRegion; 4708 bool NestingProhibited = false; 4709 bool CloseNesting = true; 4710 bool OrphanSeen = false; 4711 enum { 4712 NoRecommend, 4713 ShouldBeInParallelRegion, 4714 ShouldBeInOrderedRegion, 4715 ShouldBeInTargetRegion, 4716 ShouldBeInTeamsRegion, 4717 ShouldBeInLoopSimdRegion, 4718 } Recommend = NoRecommend; 4719 if (isOpenMPSimdDirective(ParentRegion) && 4720 ((SemaRef.LangOpts.OpenMP <= 45 && CurrentRegion != OMPD_ordered) || 4721 (SemaRef.LangOpts.OpenMP >= 50 && CurrentRegion != OMPD_ordered && 4722 CurrentRegion != OMPD_simd && CurrentRegion != OMPD_atomic && 4723 CurrentRegion != OMPD_scan))) { 4724 // OpenMP [2.16, Nesting of Regions] 4725 // OpenMP constructs may not be nested inside a simd region. 4726 // OpenMP [2.8.1,simd Construct, Restrictions] 4727 // An ordered construct with the simd clause is the only OpenMP 4728 // construct that can appear in the simd region. 4729 // Allowing a SIMD construct nested in another SIMD construct is an 4730 // extension. The OpenMP 4.5 spec does not allow it. Issue a warning 4731 // message. 4732 // OpenMP 5.0 [2.9.3.1, simd Construct, Restrictions] 4733 // The only OpenMP constructs that can be encountered during execution of 4734 // a simd region are the atomic construct, the loop construct, the simd 4735 // construct and the ordered construct with the simd clause. 4736 SemaRef.Diag(StartLoc, (CurrentRegion != OMPD_simd) 4737 ? diag::err_omp_prohibited_region_simd 4738 : diag::warn_omp_nesting_simd) 4739 << (SemaRef.LangOpts.OpenMP >= 50 ? 1 : 0); 4740 return CurrentRegion != OMPD_simd; 4741 } 4742 if (ParentRegion == OMPD_atomic) { 4743 // OpenMP [2.16, Nesting of Regions] 4744 // OpenMP constructs may not be nested inside an atomic region. 4745 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic); 4746 return true; 4747 } 4748 if (CurrentRegion == OMPD_section) { 4749 // OpenMP [2.7.2, sections Construct, Restrictions] 4750 // Orphaned section directives are prohibited. That is, the section 4751 // directives must appear within the sections construct and must not be 4752 // encountered elsewhere in the sections region. 4753 if (ParentRegion != OMPD_sections && 4754 ParentRegion != OMPD_parallel_sections) { 4755 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive) 4756 << (ParentRegion != OMPD_unknown) 4757 << getOpenMPDirectiveName(ParentRegion); 4758 return true; 4759 } 4760 return false; 4761 } 4762 // Allow some constructs (except teams and cancellation constructs) to be 4763 // orphaned (they could be used in functions, called from OpenMP regions 4764 // with the required preconditions). 4765 if (ParentRegion == OMPD_unknown && 4766 !isOpenMPNestingTeamsDirective(CurrentRegion) && 4767 CurrentRegion != OMPD_cancellation_point && 4768 CurrentRegion != OMPD_cancel && CurrentRegion != OMPD_scan) 4769 return false; 4770 if (CurrentRegion == OMPD_cancellation_point || 4771 CurrentRegion == OMPD_cancel) { 4772 // OpenMP [2.16, Nesting of Regions] 4773 // A cancellation point construct for which construct-type-clause is 4774 // taskgroup must be nested inside a task construct. A cancellation 4775 // point construct for which construct-type-clause is not taskgroup must 4776 // be closely nested inside an OpenMP construct that matches the type 4777 // specified in construct-type-clause. 4778 // A cancel construct for which construct-type-clause is taskgroup must be 4779 // nested inside a task construct. A cancel construct for which 4780 // construct-type-clause is not taskgroup must be closely nested inside an 4781 // OpenMP construct that matches the type specified in 4782 // construct-type-clause. 4783 NestingProhibited = 4784 !((CancelRegion == OMPD_parallel && 4785 (ParentRegion == OMPD_parallel || 4786 ParentRegion == OMPD_target_parallel)) || 4787 (CancelRegion == OMPD_for && 4788 (ParentRegion == OMPD_for || ParentRegion == OMPD_parallel_for || 4789 ParentRegion == OMPD_target_parallel_for || 4790 ParentRegion == OMPD_distribute_parallel_for || 4791 ParentRegion == OMPD_teams_distribute_parallel_for || 4792 ParentRegion == OMPD_target_teams_distribute_parallel_for)) || 4793 (CancelRegion == OMPD_taskgroup && 4794 (ParentRegion == OMPD_task || 4795 (SemaRef.getLangOpts().OpenMP >= 50 && 4796 (ParentRegion == OMPD_taskloop || 4797 ParentRegion == OMPD_master_taskloop || 4798 ParentRegion == OMPD_parallel_master_taskloop)))) || 4799 (CancelRegion == OMPD_sections && 4800 (ParentRegion == OMPD_section || ParentRegion == OMPD_sections || 4801 ParentRegion == OMPD_parallel_sections))); 4802 OrphanSeen = ParentRegion == OMPD_unknown; 4803 } else if (CurrentRegion == OMPD_master || CurrentRegion == OMPD_masked) { 4804 // OpenMP 5.1 [2.22, Nesting of Regions] 4805 // A masked region may not be closely nested inside a worksharing, loop, 4806 // atomic, task, or taskloop region. 4807 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) || 4808 isOpenMPGenericLoopDirective(ParentRegion) || 4809 isOpenMPTaskingDirective(ParentRegion); 4810 } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) { 4811 // OpenMP [2.16, Nesting of Regions] 4812 // A critical region may not be nested (closely or otherwise) inside a 4813 // critical region with the same name. Note that this restriction is not 4814 // sufficient to prevent deadlock. 4815 SourceLocation PreviousCriticalLoc; 4816 bool DeadLock = Stack->hasDirective( 4817 [CurrentName, &PreviousCriticalLoc](OpenMPDirectiveKind K, 4818 const DeclarationNameInfo &DNI, 4819 SourceLocation Loc) { 4820 if (K == OMPD_critical && DNI.getName() == CurrentName.getName()) { 4821 PreviousCriticalLoc = Loc; 4822 return true; 4823 } 4824 return false; 4825 }, 4826 false /* skip top directive */); 4827 if (DeadLock) { 4828 SemaRef.Diag(StartLoc, 4829 diag::err_omp_prohibited_region_critical_same_name) 4830 << CurrentName.getName(); 4831 if (PreviousCriticalLoc.isValid()) 4832 SemaRef.Diag(PreviousCriticalLoc, 4833 diag::note_omp_previous_critical_region); 4834 return true; 4835 } 4836 } else if (CurrentRegion == OMPD_barrier) { 4837 // OpenMP 5.1 [2.22, Nesting of Regions] 4838 // A barrier region may not be closely nested inside a worksharing, loop, 4839 // task, taskloop, critical, ordered, atomic, or masked region. 4840 NestingProhibited = 4841 isOpenMPWorksharingDirective(ParentRegion) || 4842 isOpenMPGenericLoopDirective(ParentRegion) || 4843 isOpenMPTaskingDirective(ParentRegion) || 4844 ParentRegion == OMPD_master || ParentRegion == OMPD_masked || 4845 ParentRegion == OMPD_parallel_master || 4846 ParentRegion == OMPD_critical || ParentRegion == OMPD_ordered; 4847 } else if (isOpenMPWorksharingDirective(CurrentRegion) && 4848 !isOpenMPParallelDirective(CurrentRegion) && 4849 !isOpenMPTeamsDirective(CurrentRegion)) { 4850 // OpenMP 5.1 [2.22, Nesting of Regions] 4851 // A loop region that binds to a parallel region or a worksharing region 4852 // may not be closely nested inside a worksharing, loop, task, taskloop, 4853 // critical, ordered, atomic, or masked region. 4854 NestingProhibited = 4855 isOpenMPWorksharingDirective(ParentRegion) || 4856 isOpenMPGenericLoopDirective(ParentRegion) || 4857 isOpenMPTaskingDirective(ParentRegion) || 4858 ParentRegion == OMPD_master || ParentRegion == OMPD_masked || 4859 ParentRegion == OMPD_parallel_master || 4860 ParentRegion == OMPD_critical || ParentRegion == OMPD_ordered; 4861 Recommend = ShouldBeInParallelRegion; 4862 } else if (CurrentRegion == OMPD_ordered) { 4863 // OpenMP [2.16, Nesting of Regions] 4864 // An ordered region may not be closely nested inside a critical, 4865 // atomic, or explicit task region. 4866 // An ordered region must be closely nested inside a loop region (or 4867 // parallel loop region) with an ordered clause. 4868 // OpenMP [2.8.1,simd Construct, Restrictions] 4869 // An ordered construct with the simd clause is the only OpenMP construct 4870 // that can appear in the simd region. 4871 NestingProhibited = ParentRegion == OMPD_critical || 4872 isOpenMPTaskingDirective(ParentRegion) || 4873 !(isOpenMPSimdDirective(ParentRegion) || 4874 Stack->isParentOrderedRegion()); 4875 Recommend = ShouldBeInOrderedRegion; 4876 } else if (isOpenMPNestingTeamsDirective(CurrentRegion)) { 4877 // OpenMP [2.16, Nesting of Regions] 4878 // If specified, a teams construct must be contained within a target 4879 // construct. 4880 NestingProhibited = 4881 (SemaRef.LangOpts.OpenMP <= 45 && ParentRegion != OMPD_target) || 4882 (SemaRef.LangOpts.OpenMP >= 50 && ParentRegion != OMPD_unknown && 4883 ParentRegion != OMPD_target); 4884 OrphanSeen = ParentRegion == OMPD_unknown; 4885 Recommend = ShouldBeInTargetRegion; 4886 } else if (CurrentRegion == OMPD_scan) { 4887 // OpenMP [2.16, Nesting of Regions] 4888 // If specified, a teams construct must be contained within a target 4889 // construct. 4890 NestingProhibited = 4891 SemaRef.LangOpts.OpenMP < 50 || 4892 (ParentRegion != OMPD_simd && ParentRegion != OMPD_for && 4893 ParentRegion != OMPD_for_simd && ParentRegion != OMPD_parallel_for && 4894 ParentRegion != OMPD_parallel_for_simd); 4895 OrphanSeen = ParentRegion == OMPD_unknown; 4896 Recommend = ShouldBeInLoopSimdRegion; 4897 } 4898 if (!NestingProhibited && 4899 !isOpenMPTargetExecutionDirective(CurrentRegion) && 4900 !isOpenMPTargetDataManagementDirective(CurrentRegion) && 4901 (ParentRegion == OMPD_teams || ParentRegion == OMPD_target_teams)) { 4902 // OpenMP [5.1, 2.22, Nesting of Regions] 4903 // distribute, distribute simd, distribute parallel worksharing-loop, 4904 // distribute parallel worksharing-loop SIMD, loop, parallel regions, 4905 // including any parallel regions arising from combined constructs, 4906 // omp_get_num_teams() regions, and omp_get_team_num() regions are the 4907 // only OpenMP regions that may be strictly nested inside the teams 4908 // region. 4909 NestingProhibited = !isOpenMPParallelDirective(CurrentRegion) && 4910 !isOpenMPDistributeDirective(CurrentRegion) && 4911 CurrentRegion != OMPD_loop; 4912 Recommend = ShouldBeInParallelRegion; 4913 } 4914 if (!NestingProhibited && CurrentRegion == OMPD_loop) { 4915 // OpenMP [5.1, 2.11.7, loop Construct, Restrictions] 4916 // If the bind clause is present on the loop construct and binding is 4917 // teams then the corresponding loop region must be strictly nested inside 4918 // a teams region. 4919 NestingProhibited = BindKind == OMPC_BIND_teams && 4920 ParentRegion != OMPD_teams && 4921 ParentRegion != OMPD_target_teams; 4922 Recommend = ShouldBeInTeamsRegion; 4923 } 4924 if (!NestingProhibited && 4925 isOpenMPNestingDistributeDirective(CurrentRegion)) { 4926 // OpenMP 4.5 [2.17 Nesting of Regions] 4927 // The region associated with the distribute construct must be strictly 4928 // nested inside a teams region 4929 NestingProhibited = 4930 (ParentRegion != OMPD_teams && ParentRegion != OMPD_target_teams); 4931 Recommend = ShouldBeInTeamsRegion; 4932 } 4933 if (!NestingProhibited && 4934 (isOpenMPTargetExecutionDirective(CurrentRegion) || 4935 isOpenMPTargetDataManagementDirective(CurrentRegion))) { 4936 // OpenMP 4.5 [2.17 Nesting of Regions] 4937 // If a target, target update, target data, target enter data, or 4938 // target exit data construct is encountered during execution of a 4939 // target region, the behavior is unspecified. 4940 NestingProhibited = Stack->hasDirective( 4941 [&OffendingRegion](OpenMPDirectiveKind K, const DeclarationNameInfo &, 4942 SourceLocation) { 4943 if (isOpenMPTargetExecutionDirective(K)) { 4944 OffendingRegion = K; 4945 return true; 4946 } 4947 return false; 4948 }, 4949 false /* don't skip top directive */); 4950 CloseNesting = false; 4951 } 4952 if (NestingProhibited) { 4953 if (OrphanSeen) { 4954 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_device_directive) 4955 << getOpenMPDirectiveName(CurrentRegion) << Recommend; 4956 } else { 4957 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region) 4958 << CloseNesting << getOpenMPDirectiveName(OffendingRegion) 4959 << Recommend << getOpenMPDirectiveName(CurrentRegion); 4960 } 4961 return true; 4962 } 4963 } 4964 return false; 4965 } 4966 4967 struct Kind2Unsigned { 4968 using argument_type = OpenMPDirectiveKind; 4969 unsigned operator()(argument_type DK) { return unsigned(DK); } 4970 }; 4971 static bool checkIfClauses(Sema &S, OpenMPDirectiveKind Kind, 4972 ArrayRef<OMPClause *> Clauses, 4973 ArrayRef<OpenMPDirectiveKind> AllowedNameModifiers) { 4974 bool ErrorFound = false; 4975 unsigned NamedModifiersNumber = 0; 4976 llvm::IndexedMap<const OMPIfClause *, Kind2Unsigned> FoundNameModifiers; 4977 FoundNameModifiers.resize(llvm::omp::Directive_enumSize + 1); 4978 SmallVector<SourceLocation, 4> NameModifierLoc; 4979 for (const OMPClause *C : Clauses) { 4980 if (const auto *IC = dyn_cast_or_null<OMPIfClause>(C)) { 4981 // At most one if clause without a directive-name-modifier can appear on 4982 // the directive. 4983 OpenMPDirectiveKind CurNM = IC->getNameModifier(); 4984 if (FoundNameModifiers[CurNM]) { 4985 S.Diag(C->getBeginLoc(), diag::err_omp_more_one_clause) 4986 << getOpenMPDirectiveName(Kind) << getOpenMPClauseName(OMPC_if) 4987 << (CurNM != OMPD_unknown) << getOpenMPDirectiveName(CurNM); 4988 ErrorFound = true; 4989 } else if (CurNM != OMPD_unknown) { 4990 NameModifierLoc.push_back(IC->getNameModifierLoc()); 4991 ++NamedModifiersNumber; 4992 } 4993 FoundNameModifiers[CurNM] = IC; 4994 if (CurNM == OMPD_unknown) 4995 continue; 4996 // Check if the specified name modifier is allowed for the current 4997 // directive. 4998 // At most one if clause with the particular directive-name-modifier can 4999 // appear on the directive. 5000 if (!llvm::is_contained(AllowedNameModifiers, CurNM)) { 5001 S.Diag(IC->getNameModifierLoc(), 5002 diag::err_omp_wrong_if_directive_name_modifier) 5003 << getOpenMPDirectiveName(CurNM) << getOpenMPDirectiveName(Kind); 5004 ErrorFound = true; 5005 } 5006 } 5007 } 5008 // If any if clause on the directive includes a directive-name-modifier then 5009 // all if clauses on the directive must include a directive-name-modifier. 5010 if (FoundNameModifiers[OMPD_unknown] && NamedModifiersNumber > 0) { 5011 if (NamedModifiersNumber == AllowedNameModifiers.size()) { 5012 S.Diag(FoundNameModifiers[OMPD_unknown]->getBeginLoc(), 5013 diag::err_omp_no_more_if_clause); 5014 } else { 5015 std::string Values; 5016 std::string Sep(", "); 5017 unsigned AllowedCnt = 0; 5018 unsigned TotalAllowedNum = 5019 AllowedNameModifiers.size() - NamedModifiersNumber; 5020 for (unsigned Cnt = 0, End = AllowedNameModifiers.size(); Cnt < End; 5021 ++Cnt) { 5022 OpenMPDirectiveKind NM = AllowedNameModifiers[Cnt]; 5023 if (!FoundNameModifiers[NM]) { 5024 Values += "'"; 5025 Values += getOpenMPDirectiveName(NM); 5026 Values += "'"; 5027 if (AllowedCnt + 2 == TotalAllowedNum) 5028 Values += " or "; 5029 else if (AllowedCnt + 1 != TotalAllowedNum) 5030 Values += Sep; 5031 ++AllowedCnt; 5032 } 5033 } 5034 S.Diag(FoundNameModifiers[OMPD_unknown]->getCondition()->getBeginLoc(), 5035 diag::err_omp_unnamed_if_clause) 5036 << (TotalAllowedNum > 1) << Values; 5037 } 5038 for (SourceLocation Loc : NameModifierLoc) { 5039 S.Diag(Loc, diag::note_omp_previous_named_if_clause); 5040 } 5041 ErrorFound = true; 5042 } 5043 return ErrorFound; 5044 } 5045 5046 static std::pair<ValueDecl *, bool> getPrivateItem(Sema &S, Expr *&RefExpr, 5047 SourceLocation &ELoc, 5048 SourceRange &ERange, 5049 bool AllowArraySection) { 5050 if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() || 5051 RefExpr->containsUnexpandedParameterPack()) 5052 return std::make_pair(nullptr, true); 5053 5054 // OpenMP [3.1, C/C++] 5055 // A list item is a variable name. 5056 // OpenMP [2.9.3.3, Restrictions, p.1] 5057 // A variable that is part of another variable (as an array or 5058 // structure element) cannot appear in a private clause. 5059 RefExpr = RefExpr->IgnoreParens(); 5060 enum { 5061 NoArrayExpr = -1, 5062 ArraySubscript = 0, 5063 OMPArraySection = 1 5064 } IsArrayExpr = NoArrayExpr; 5065 if (AllowArraySection) { 5066 if (auto *ASE = dyn_cast_or_null<ArraySubscriptExpr>(RefExpr)) { 5067 Expr *Base = ASE->getBase()->IgnoreParenImpCasts(); 5068 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) 5069 Base = TempASE->getBase()->IgnoreParenImpCasts(); 5070 RefExpr = Base; 5071 IsArrayExpr = ArraySubscript; 5072 } else if (auto *OASE = dyn_cast_or_null<OMPArraySectionExpr>(RefExpr)) { 5073 Expr *Base = OASE->getBase()->IgnoreParenImpCasts(); 5074 while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base)) 5075 Base = TempOASE->getBase()->IgnoreParenImpCasts(); 5076 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) 5077 Base = TempASE->getBase()->IgnoreParenImpCasts(); 5078 RefExpr = Base; 5079 IsArrayExpr = OMPArraySection; 5080 } 5081 } 5082 ELoc = RefExpr->getExprLoc(); 5083 ERange = RefExpr->getSourceRange(); 5084 RefExpr = RefExpr->IgnoreParenImpCasts(); 5085 auto *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr); 5086 auto *ME = dyn_cast_or_null<MemberExpr>(RefExpr); 5087 if ((!DE || !isa<VarDecl>(DE->getDecl())) && 5088 (S.getCurrentThisType().isNull() || !ME || 5089 !isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()) || 5090 !isa<FieldDecl>(ME->getMemberDecl()))) { 5091 if (IsArrayExpr != NoArrayExpr) { 5092 S.Diag(ELoc, diag::err_omp_expected_base_var_name) 5093 << IsArrayExpr << ERange; 5094 } else { 5095 S.Diag(ELoc, 5096 AllowArraySection 5097 ? diag::err_omp_expected_var_name_member_expr_or_array_item 5098 : diag::err_omp_expected_var_name_member_expr) 5099 << (S.getCurrentThisType().isNull() ? 0 : 1) << ERange; 5100 } 5101 return std::make_pair(nullptr, false); 5102 } 5103 return std::make_pair( 5104 getCanonicalDecl(DE ? DE->getDecl() : ME->getMemberDecl()), false); 5105 } 5106 5107 namespace { 5108 /// Checks if the allocator is used in uses_allocators clause to be allowed in 5109 /// target regions. 5110 class AllocatorChecker final : public ConstStmtVisitor<AllocatorChecker, bool> { 5111 DSAStackTy *S = nullptr; 5112 5113 public: 5114 bool VisitDeclRefExpr(const DeclRefExpr *E) { 5115 return S->isUsesAllocatorsDecl(E->getDecl()) 5116 .getValueOr( 5117 DSAStackTy::UsesAllocatorsDeclKind::AllocatorTrait) == 5118 DSAStackTy::UsesAllocatorsDeclKind::AllocatorTrait; 5119 } 5120 bool VisitStmt(const Stmt *S) { 5121 for (const Stmt *Child : S->children()) { 5122 if (Child && Visit(Child)) 5123 return true; 5124 } 5125 return false; 5126 } 5127 explicit AllocatorChecker(DSAStackTy *S) : S(S) {} 5128 }; 5129 } // namespace 5130 5131 static void checkAllocateClauses(Sema &S, DSAStackTy *Stack, 5132 ArrayRef<OMPClause *> Clauses) { 5133 assert(!S.CurContext->isDependentContext() && 5134 "Expected non-dependent context."); 5135 auto AllocateRange = 5136 llvm::make_filter_range(Clauses, OMPAllocateClause::classof); 5137 llvm::DenseMap<CanonicalDeclPtr<Decl>, CanonicalDeclPtr<VarDecl>> DeclToCopy; 5138 auto PrivateRange = llvm::make_filter_range(Clauses, [](const OMPClause *C) { 5139 return isOpenMPPrivate(C->getClauseKind()); 5140 }); 5141 for (OMPClause *Cl : PrivateRange) { 5142 MutableArrayRef<Expr *>::iterator I, It, Et; 5143 if (Cl->getClauseKind() == OMPC_private) { 5144 auto *PC = cast<OMPPrivateClause>(Cl); 5145 I = PC->private_copies().begin(); 5146 It = PC->varlist_begin(); 5147 Et = PC->varlist_end(); 5148 } else if (Cl->getClauseKind() == OMPC_firstprivate) { 5149 auto *PC = cast<OMPFirstprivateClause>(Cl); 5150 I = PC->private_copies().begin(); 5151 It = PC->varlist_begin(); 5152 Et = PC->varlist_end(); 5153 } else if (Cl->getClauseKind() == OMPC_lastprivate) { 5154 auto *PC = cast<OMPLastprivateClause>(Cl); 5155 I = PC->private_copies().begin(); 5156 It = PC->varlist_begin(); 5157 Et = PC->varlist_end(); 5158 } else if (Cl->getClauseKind() == OMPC_linear) { 5159 auto *PC = cast<OMPLinearClause>(Cl); 5160 I = PC->privates().begin(); 5161 It = PC->varlist_begin(); 5162 Et = PC->varlist_end(); 5163 } else if (Cl->getClauseKind() == OMPC_reduction) { 5164 auto *PC = cast<OMPReductionClause>(Cl); 5165 I = PC->privates().begin(); 5166 It = PC->varlist_begin(); 5167 Et = PC->varlist_end(); 5168 } else if (Cl->getClauseKind() == OMPC_task_reduction) { 5169 auto *PC = cast<OMPTaskReductionClause>(Cl); 5170 I = PC->privates().begin(); 5171 It = PC->varlist_begin(); 5172 Et = PC->varlist_end(); 5173 } else if (Cl->getClauseKind() == OMPC_in_reduction) { 5174 auto *PC = cast<OMPInReductionClause>(Cl); 5175 I = PC->privates().begin(); 5176 It = PC->varlist_begin(); 5177 Et = PC->varlist_end(); 5178 } else { 5179 llvm_unreachable("Expected private clause."); 5180 } 5181 for (Expr *E : llvm::make_range(It, Et)) { 5182 if (!*I) { 5183 ++I; 5184 continue; 5185 } 5186 SourceLocation ELoc; 5187 SourceRange ERange; 5188 Expr *SimpleRefExpr = E; 5189 auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange, 5190 /*AllowArraySection=*/true); 5191 DeclToCopy.try_emplace(Res.first, 5192 cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl())); 5193 ++I; 5194 } 5195 } 5196 for (OMPClause *C : AllocateRange) { 5197 auto *AC = cast<OMPAllocateClause>(C); 5198 if (S.getLangOpts().OpenMP >= 50 && 5199 !Stack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>() && 5200 isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()) && 5201 AC->getAllocator()) { 5202 Expr *Allocator = AC->getAllocator(); 5203 // OpenMP, 2.12.5 target Construct 5204 // Memory allocators that do not appear in a uses_allocators clause cannot 5205 // appear as an allocator in an allocate clause or be used in the target 5206 // region unless a requires directive with the dynamic_allocators clause 5207 // is present in the same compilation unit. 5208 AllocatorChecker Checker(Stack); 5209 if (Checker.Visit(Allocator)) 5210 S.Diag(Allocator->getExprLoc(), 5211 diag::err_omp_allocator_not_in_uses_allocators) 5212 << Allocator->getSourceRange(); 5213 } 5214 OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind = 5215 getAllocatorKind(S, Stack, AC->getAllocator()); 5216 // OpenMP, 2.11.4 allocate Clause, Restrictions. 5217 // For task, taskloop or target directives, allocation requests to memory 5218 // allocators with the trait access set to thread result in unspecified 5219 // behavior. 5220 if (AllocatorKind == OMPAllocateDeclAttr::OMPThreadMemAlloc && 5221 (isOpenMPTaskingDirective(Stack->getCurrentDirective()) || 5222 isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()))) { 5223 S.Diag(AC->getAllocator()->getExprLoc(), 5224 diag::warn_omp_allocate_thread_on_task_target_directive) 5225 << getOpenMPDirectiveName(Stack->getCurrentDirective()); 5226 } 5227 for (Expr *E : AC->varlists()) { 5228 SourceLocation ELoc; 5229 SourceRange ERange; 5230 Expr *SimpleRefExpr = E; 5231 auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange); 5232 ValueDecl *VD = Res.first; 5233 DSAStackTy::DSAVarData Data = Stack->getTopDSA(VD, /*FromParent=*/false); 5234 if (!isOpenMPPrivate(Data.CKind)) { 5235 S.Diag(E->getExprLoc(), 5236 diag::err_omp_expected_private_copy_for_allocate); 5237 continue; 5238 } 5239 VarDecl *PrivateVD = DeclToCopy[VD]; 5240 if (checkPreviousOMPAllocateAttribute(S, Stack, E, PrivateVD, 5241 AllocatorKind, AC->getAllocator())) 5242 continue; 5243 // Placeholder until allocate clause supports align modifier. 5244 Expr *Alignment = nullptr; 5245 applyOMPAllocateAttribute(S, PrivateVD, AllocatorKind, AC->getAllocator(), 5246 Alignment, E->getSourceRange()); 5247 } 5248 } 5249 } 5250 5251 namespace { 5252 /// Rewrite statements and expressions for Sema \p Actions CurContext. 5253 /// 5254 /// Used to wrap already parsed statements/expressions into a new CapturedStmt 5255 /// context. DeclRefExpr used inside the new context are changed to refer to the 5256 /// captured variable instead. 5257 class CaptureVars : public TreeTransform<CaptureVars> { 5258 using BaseTransform = TreeTransform<CaptureVars>; 5259 5260 public: 5261 CaptureVars(Sema &Actions) : BaseTransform(Actions) {} 5262 5263 bool AlwaysRebuild() { return true; } 5264 }; 5265 } // namespace 5266 5267 static VarDecl *precomputeExpr(Sema &Actions, 5268 SmallVectorImpl<Stmt *> &BodyStmts, Expr *E, 5269 StringRef Name) { 5270 Expr *NewE = AssertSuccess(CaptureVars(Actions).TransformExpr(E)); 5271 VarDecl *NewVar = buildVarDecl(Actions, {}, NewE->getType(), Name, nullptr, 5272 dyn_cast<DeclRefExpr>(E->IgnoreImplicit())); 5273 auto *NewDeclStmt = cast<DeclStmt>(AssertSuccess( 5274 Actions.ActOnDeclStmt(Actions.ConvertDeclToDeclGroup(NewVar), {}, {}))); 5275 Actions.AddInitializerToDecl(NewDeclStmt->getSingleDecl(), NewE, false); 5276 BodyStmts.push_back(NewDeclStmt); 5277 return NewVar; 5278 } 5279 5280 /// Create a closure that computes the number of iterations of a loop. 5281 /// 5282 /// \param Actions The Sema object. 5283 /// \param LogicalTy Type for the logical iteration number. 5284 /// \param Rel Comparison operator of the loop condition. 5285 /// \param StartExpr Value of the loop counter at the first iteration. 5286 /// \param StopExpr Expression the loop counter is compared against in the loop 5287 /// condition. \param StepExpr Amount of increment after each iteration. 5288 /// 5289 /// \return Closure (CapturedStmt) of the distance calculation. 5290 static CapturedStmt *buildDistanceFunc(Sema &Actions, QualType LogicalTy, 5291 BinaryOperator::Opcode Rel, 5292 Expr *StartExpr, Expr *StopExpr, 5293 Expr *StepExpr) { 5294 ASTContext &Ctx = Actions.getASTContext(); 5295 TypeSourceInfo *LogicalTSI = Ctx.getTrivialTypeSourceInfo(LogicalTy); 5296 5297 // Captured regions currently don't support return values, we use an 5298 // out-parameter instead. All inputs are implicit captures. 5299 // TODO: Instead of capturing each DeclRefExpr occurring in 5300 // StartExpr/StopExpr/Step, these could also be passed as a value capture. 5301 QualType ResultTy = Ctx.getLValueReferenceType(LogicalTy); 5302 Sema::CapturedParamNameType Params[] = {{"Distance", ResultTy}, 5303 {StringRef(), QualType()}}; 5304 Actions.ActOnCapturedRegionStart({}, nullptr, CR_Default, Params); 5305 5306 Stmt *Body; 5307 { 5308 Sema::CompoundScopeRAII CompoundScope(Actions); 5309 CapturedDecl *CS = cast<CapturedDecl>(Actions.CurContext); 5310 5311 // Get the LValue expression for the result. 5312 ImplicitParamDecl *DistParam = CS->getParam(0); 5313 DeclRefExpr *DistRef = Actions.BuildDeclRefExpr( 5314 DistParam, LogicalTy, VK_LValue, {}, nullptr, nullptr, {}, nullptr); 5315 5316 SmallVector<Stmt *, 4> BodyStmts; 5317 5318 // Capture all referenced variable references. 5319 // TODO: Instead of computing NewStart/NewStop/NewStep inside the 5320 // CapturedStmt, we could compute them before and capture the result, to be 5321 // used jointly with the LoopVar function. 5322 VarDecl *NewStart = precomputeExpr(Actions, BodyStmts, StartExpr, ".start"); 5323 VarDecl *NewStop = precomputeExpr(Actions, BodyStmts, StopExpr, ".stop"); 5324 VarDecl *NewStep = precomputeExpr(Actions, BodyStmts, StepExpr, ".step"); 5325 auto BuildVarRef = [&](VarDecl *VD) { 5326 return buildDeclRefExpr(Actions, VD, VD->getType(), {}); 5327 }; 5328 5329 IntegerLiteral *Zero = IntegerLiteral::Create( 5330 Ctx, llvm::APInt(Ctx.getIntWidth(LogicalTy), 0), LogicalTy, {}); 5331 IntegerLiteral *One = IntegerLiteral::Create( 5332 Ctx, llvm::APInt(Ctx.getIntWidth(LogicalTy), 1), LogicalTy, {}); 5333 Expr *Dist; 5334 if (Rel == BO_NE) { 5335 // When using a != comparison, the increment can be +1 or -1. This can be 5336 // dynamic at runtime, so we need to check for the direction. 5337 Expr *IsNegStep = AssertSuccess( 5338 Actions.BuildBinOp(nullptr, {}, BO_LT, BuildVarRef(NewStep), Zero)); 5339 5340 // Positive increment. 5341 Expr *ForwardRange = AssertSuccess(Actions.BuildBinOp( 5342 nullptr, {}, BO_Sub, BuildVarRef(NewStop), BuildVarRef(NewStart))); 5343 ForwardRange = AssertSuccess( 5344 Actions.BuildCStyleCastExpr({}, LogicalTSI, {}, ForwardRange)); 5345 Expr *ForwardDist = AssertSuccess(Actions.BuildBinOp( 5346 nullptr, {}, BO_Div, ForwardRange, BuildVarRef(NewStep))); 5347 5348 // Negative increment. 5349 Expr *BackwardRange = AssertSuccess(Actions.BuildBinOp( 5350 nullptr, {}, BO_Sub, BuildVarRef(NewStart), BuildVarRef(NewStop))); 5351 BackwardRange = AssertSuccess( 5352 Actions.BuildCStyleCastExpr({}, LogicalTSI, {}, BackwardRange)); 5353 Expr *NegIncAmount = AssertSuccess( 5354 Actions.BuildUnaryOp(nullptr, {}, UO_Minus, BuildVarRef(NewStep))); 5355 Expr *BackwardDist = AssertSuccess( 5356 Actions.BuildBinOp(nullptr, {}, BO_Div, BackwardRange, NegIncAmount)); 5357 5358 // Use the appropriate case. 5359 Dist = AssertSuccess(Actions.ActOnConditionalOp( 5360 {}, {}, IsNegStep, BackwardDist, ForwardDist)); 5361 } else { 5362 assert((Rel == BO_LT || Rel == BO_LE || Rel == BO_GE || Rel == BO_GT) && 5363 "Expected one of these relational operators"); 5364 5365 // We can derive the direction from any other comparison operator. It is 5366 // non well-formed OpenMP if Step increments/decrements in the other 5367 // directions. Whether at least the first iteration passes the loop 5368 // condition. 5369 Expr *HasAnyIteration = AssertSuccess(Actions.BuildBinOp( 5370 nullptr, {}, Rel, BuildVarRef(NewStart), BuildVarRef(NewStop))); 5371 5372 // Compute the range between first and last counter value. 5373 Expr *Range; 5374 if (Rel == BO_GE || Rel == BO_GT) 5375 Range = AssertSuccess(Actions.BuildBinOp( 5376 nullptr, {}, BO_Sub, BuildVarRef(NewStart), BuildVarRef(NewStop))); 5377 else 5378 Range = AssertSuccess(Actions.BuildBinOp( 5379 nullptr, {}, BO_Sub, BuildVarRef(NewStop), BuildVarRef(NewStart))); 5380 5381 // Ensure unsigned range space. 5382 Range = 5383 AssertSuccess(Actions.BuildCStyleCastExpr({}, LogicalTSI, {}, Range)); 5384 5385 if (Rel == BO_LE || Rel == BO_GE) { 5386 // Add one to the range if the relational operator is inclusive. 5387 Range = 5388 AssertSuccess(Actions.BuildBinOp(nullptr, {}, BO_Add, Range, One)); 5389 } 5390 5391 // Divide by the absolute step amount. If the range is not a multiple of 5392 // the step size, rounding-up the effective upper bound ensures that the 5393 // last iteration is included. 5394 // Note that the rounding-up may cause an overflow in a temporry that 5395 // could be avoided, but would have occurred in a C-style for-loop as well. 5396 Expr *Divisor = BuildVarRef(NewStep); 5397 if (Rel == BO_GE || Rel == BO_GT) 5398 Divisor = 5399 AssertSuccess(Actions.BuildUnaryOp(nullptr, {}, UO_Minus, Divisor)); 5400 Expr *DivisorMinusOne = 5401 AssertSuccess(Actions.BuildBinOp(nullptr, {}, BO_Sub, Divisor, One)); 5402 Expr *RangeRoundUp = AssertSuccess( 5403 Actions.BuildBinOp(nullptr, {}, BO_Add, Range, DivisorMinusOne)); 5404 Dist = AssertSuccess( 5405 Actions.BuildBinOp(nullptr, {}, BO_Div, RangeRoundUp, Divisor)); 5406 5407 // If there is not at least one iteration, the range contains garbage. Fix 5408 // to zero in this case. 5409 Dist = AssertSuccess( 5410 Actions.ActOnConditionalOp({}, {}, HasAnyIteration, Dist, Zero)); 5411 } 5412 5413 // Assign the result to the out-parameter. 5414 Stmt *ResultAssign = AssertSuccess(Actions.BuildBinOp( 5415 Actions.getCurScope(), {}, BO_Assign, DistRef, Dist)); 5416 BodyStmts.push_back(ResultAssign); 5417 5418 Body = AssertSuccess(Actions.ActOnCompoundStmt({}, {}, BodyStmts, false)); 5419 } 5420 5421 return cast<CapturedStmt>( 5422 AssertSuccess(Actions.ActOnCapturedRegionEnd(Body))); 5423 } 5424 5425 /// Create a closure that computes the loop variable from the logical iteration 5426 /// number. 5427 /// 5428 /// \param Actions The Sema object. 5429 /// \param LoopVarTy Type for the loop variable used for result value. 5430 /// \param LogicalTy Type for the logical iteration number. 5431 /// \param StartExpr Value of the loop counter at the first iteration. 5432 /// \param Step Amount of increment after each iteration. 5433 /// \param Deref Whether the loop variable is a dereference of the loop 5434 /// counter variable. 5435 /// 5436 /// \return Closure (CapturedStmt) of the loop value calculation. 5437 static CapturedStmt *buildLoopVarFunc(Sema &Actions, QualType LoopVarTy, 5438 QualType LogicalTy, 5439 DeclRefExpr *StartExpr, Expr *Step, 5440 bool Deref) { 5441 ASTContext &Ctx = Actions.getASTContext(); 5442 5443 // Pass the result as an out-parameter. Passing as return value would require 5444 // the OpenMPIRBuilder to know additional C/C++ semantics, such as how to 5445 // invoke a copy constructor. 5446 QualType TargetParamTy = Ctx.getLValueReferenceType(LoopVarTy); 5447 Sema::CapturedParamNameType Params[] = {{"LoopVar", TargetParamTy}, 5448 {"Logical", LogicalTy}, 5449 {StringRef(), QualType()}}; 5450 Actions.ActOnCapturedRegionStart({}, nullptr, CR_Default, Params); 5451 5452 // Capture the initial iterator which represents the LoopVar value at the 5453 // zero's logical iteration. Since the original ForStmt/CXXForRangeStmt update 5454 // it in every iteration, capture it by value before it is modified. 5455 VarDecl *StartVar = cast<VarDecl>(StartExpr->getDecl()); 5456 bool Invalid = Actions.tryCaptureVariable(StartVar, {}, 5457 Sema::TryCapture_ExplicitByVal, {}); 5458 (void)Invalid; 5459 assert(!Invalid && "Expecting capture-by-value to work."); 5460 5461 Expr *Body; 5462 { 5463 Sema::CompoundScopeRAII CompoundScope(Actions); 5464 auto *CS = cast<CapturedDecl>(Actions.CurContext); 5465 5466 ImplicitParamDecl *TargetParam = CS->getParam(0); 5467 DeclRefExpr *TargetRef = Actions.BuildDeclRefExpr( 5468 TargetParam, LoopVarTy, VK_LValue, {}, nullptr, nullptr, {}, nullptr); 5469 ImplicitParamDecl *IndvarParam = CS->getParam(1); 5470 DeclRefExpr *LogicalRef = Actions.BuildDeclRefExpr( 5471 IndvarParam, LogicalTy, VK_LValue, {}, nullptr, nullptr, {}, nullptr); 5472 5473 // Capture the Start expression. 5474 CaptureVars Recap(Actions); 5475 Expr *NewStart = AssertSuccess(Recap.TransformExpr(StartExpr)); 5476 Expr *NewStep = AssertSuccess(Recap.TransformExpr(Step)); 5477 5478 Expr *Skip = AssertSuccess( 5479 Actions.BuildBinOp(nullptr, {}, BO_Mul, NewStep, LogicalRef)); 5480 // TODO: Explicitly cast to the iterator's difference_type instead of 5481 // relying on implicit conversion. 5482 Expr *Advanced = 5483 AssertSuccess(Actions.BuildBinOp(nullptr, {}, BO_Add, NewStart, Skip)); 5484 5485 if (Deref) { 5486 // For range-based for-loops convert the loop counter value to a concrete 5487 // loop variable value by dereferencing the iterator. 5488 Advanced = 5489 AssertSuccess(Actions.BuildUnaryOp(nullptr, {}, UO_Deref, Advanced)); 5490 } 5491 5492 // Assign the result to the output parameter. 5493 Body = AssertSuccess(Actions.BuildBinOp(Actions.getCurScope(), {}, 5494 BO_Assign, TargetRef, Advanced)); 5495 } 5496 return cast<CapturedStmt>( 5497 AssertSuccess(Actions.ActOnCapturedRegionEnd(Body))); 5498 } 5499 5500 StmtResult Sema::ActOnOpenMPCanonicalLoop(Stmt *AStmt) { 5501 ASTContext &Ctx = getASTContext(); 5502 5503 // Extract the common elements of ForStmt and CXXForRangeStmt: 5504 // Loop variable, repeat condition, increment 5505 Expr *Cond, *Inc; 5506 VarDecl *LIVDecl, *LUVDecl; 5507 if (auto *For = dyn_cast<ForStmt>(AStmt)) { 5508 Stmt *Init = For->getInit(); 5509 if (auto *LCVarDeclStmt = dyn_cast<DeclStmt>(Init)) { 5510 // For statement declares loop variable. 5511 LIVDecl = cast<VarDecl>(LCVarDeclStmt->getSingleDecl()); 5512 } else if (auto *LCAssign = dyn_cast<BinaryOperator>(Init)) { 5513 // For statement reuses variable. 5514 assert(LCAssign->getOpcode() == BO_Assign && 5515 "init part must be a loop variable assignment"); 5516 auto *CounterRef = cast<DeclRefExpr>(LCAssign->getLHS()); 5517 LIVDecl = cast<VarDecl>(CounterRef->getDecl()); 5518 } else 5519 llvm_unreachable("Cannot determine loop variable"); 5520 LUVDecl = LIVDecl; 5521 5522 Cond = For->getCond(); 5523 Inc = For->getInc(); 5524 } else if (auto *RangeFor = dyn_cast<CXXForRangeStmt>(AStmt)) { 5525 DeclStmt *BeginStmt = RangeFor->getBeginStmt(); 5526 LIVDecl = cast<VarDecl>(BeginStmt->getSingleDecl()); 5527 LUVDecl = RangeFor->getLoopVariable(); 5528 5529 Cond = RangeFor->getCond(); 5530 Inc = RangeFor->getInc(); 5531 } else 5532 llvm_unreachable("unhandled kind of loop"); 5533 5534 QualType CounterTy = LIVDecl->getType(); 5535 QualType LVTy = LUVDecl->getType(); 5536 5537 // Analyze the loop condition. 5538 Expr *LHS, *RHS; 5539 BinaryOperator::Opcode CondRel; 5540 Cond = Cond->IgnoreImplicit(); 5541 if (auto *CondBinExpr = dyn_cast<BinaryOperator>(Cond)) { 5542 LHS = CondBinExpr->getLHS(); 5543 RHS = CondBinExpr->getRHS(); 5544 CondRel = CondBinExpr->getOpcode(); 5545 } else if (auto *CondCXXOp = dyn_cast<CXXOperatorCallExpr>(Cond)) { 5546 assert(CondCXXOp->getNumArgs() == 2 && "Comparison should have 2 operands"); 5547 LHS = CondCXXOp->getArg(0); 5548 RHS = CondCXXOp->getArg(1); 5549 switch (CondCXXOp->getOperator()) { 5550 case OO_ExclaimEqual: 5551 CondRel = BO_NE; 5552 break; 5553 case OO_Less: 5554 CondRel = BO_LT; 5555 break; 5556 case OO_LessEqual: 5557 CondRel = BO_LE; 5558 break; 5559 case OO_Greater: 5560 CondRel = BO_GT; 5561 break; 5562 case OO_GreaterEqual: 5563 CondRel = BO_GE; 5564 break; 5565 default: 5566 llvm_unreachable("unexpected iterator operator"); 5567 } 5568 } else 5569 llvm_unreachable("unexpected loop condition"); 5570 5571 // Normalize such that the loop counter is on the LHS. 5572 if (!isa<DeclRefExpr>(LHS->IgnoreImplicit()) || 5573 cast<DeclRefExpr>(LHS->IgnoreImplicit())->getDecl() != LIVDecl) { 5574 std::swap(LHS, RHS); 5575 CondRel = BinaryOperator::reverseComparisonOp(CondRel); 5576 } 5577 auto *CounterRef = cast<DeclRefExpr>(LHS->IgnoreImplicit()); 5578 5579 // Decide the bit width for the logical iteration counter. By default use the 5580 // unsigned ptrdiff_t integer size (for iterators and pointers). 5581 // TODO: For iterators, use iterator::difference_type, 5582 // std::iterator_traits<>::difference_type or decltype(it - end). 5583 QualType LogicalTy = Ctx.getUnsignedPointerDiffType(); 5584 if (CounterTy->isIntegerType()) { 5585 unsigned BitWidth = Ctx.getIntWidth(CounterTy); 5586 LogicalTy = Ctx.getIntTypeForBitwidth(BitWidth, false); 5587 } 5588 5589 // Analyze the loop increment. 5590 Expr *Step; 5591 if (auto *IncUn = dyn_cast<UnaryOperator>(Inc)) { 5592 int Direction; 5593 switch (IncUn->getOpcode()) { 5594 case UO_PreInc: 5595 case UO_PostInc: 5596 Direction = 1; 5597 break; 5598 case UO_PreDec: 5599 case UO_PostDec: 5600 Direction = -1; 5601 break; 5602 default: 5603 llvm_unreachable("unhandled unary increment operator"); 5604 } 5605 Step = IntegerLiteral::Create( 5606 Ctx, llvm::APInt(Ctx.getIntWidth(LogicalTy), Direction), LogicalTy, {}); 5607 } else if (auto *IncBin = dyn_cast<BinaryOperator>(Inc)) { 5608 if (IncBin->getOpcode() == BO_AddAssign) { 5609 Step = IncBin->getRHS(); 5610 } else if (IncBin->getOpcode() == BO_SubAssign) { 5611 Step = 5612 AssertSuccess(BuildUnaryOp(nullptr, {}, UO_Minus, IncBin->getRHS())); 5613 } else 5614 llvm_unreachable("unhandled binary increment operator"); 5615 } else if (auto *CondCXXOp = dyn_cast<CXXOperatorCallExpr>(Inc)) { 5616 switch (CondCXXOp->getOperator()) { 5617 case OO_PlusPlus: 5618 Step = IntegerLiteral::Create( 5619 Ctx, llvm::APInt(Ctx.getIntWidth(LogicalTy), 1), LogicalTy, {}); 5620 break; 5621 case OO_MinusMinus: 5622 Step = IntegerLiteral::Create( 5623 Ctx, llvm::APInt(Ctx.getIntWidth(LogicalTy), -1), LogicalTy, {}); 5624 break; 5625 case OO_PlusEqual: 5626 Step = CondCXXOp->getArg(1); 5627 break; 5628 case OO_MinusEqual: 5629 Step = AssertSuccess( 5630 BuildUnaryOp(nullptr, {}, UO_Minus, CondCXXOp->getArg(1))); 5631 break; 5632 default: 5633 llvm_unreachable("unhandled overloaded increment operator"); 5634 } 5635 } else 5636 llvm_unreachable("unknown increment expression"); 5637 5638 CapturedStmt *DistanceFunc = 5639 buildDistanceFunc(*this, LogicalTy, CondRel, LHS, RHS, Step); 5640 CapturedStmt *LoopVarFunc = buildLoopVarFunc( 5641 *this, LVTy, LogicalTy, CounterRef, Step, isa<CXXForRangeStmt>(AStmt)); 5642 DeclRefExpr *LVRef = BuildDeclRefExpr(LUVDecl, LUVDecl->getType(), VK_LValue, 5643 {}, nullptr, nullptr, {}, nullptr); 5644 return OMPCanonicalLoop::create(getASTContext(), AStmt, DistanceFunc, 5645 LoopVarFunc, LVRef); 5646 } 5647 5648 StmtResult Sema::ActOnOpenMPLoopnest(Stmt *AStmt) { 5649 // Handle a literal loop. 5650 if (isa<ForStmt>(AStmt) || isa<CXXForRangeStmt>(AStmt)) 5651 return ActOnOpenMPCanonicalLoop(AStmt); 5652 5653 // If not a literal loop, it must be the result of a loop transformation. 5654 OMPExecutableDirective *LoopTransform = cast<OMPExecutableDirective>(AStmt); 5655 assert( 5656 isOpenMPLoopTransformationDirective(LoopTransform->getDirectiveKind()) && 5657 "Loop transformation directive expected"); 5658 return LoopTransform; 5659 } 5660 5661 static ExprResult buildUserDefinedMapperRef(Sema &SemaRef, Scope *S, 5662 CXXScopeSpec &MapperIdScopeSpec, 5663 const DeclarationNameInfo &MapperId, 5664 QualType Type, 5665 Expr *UnresolvedMapper); 5666 5667 /// Perform DFS through the structure/class data members trying to find 5668 /// member(s) with user-defined 'default' mapper and generate implicit map 5669 /// clauses for such members with the found 'default' mapper. 5670 static void 5671 processImplicitMapsWithDefaultMappers(Sema &S, DSAStackTy *Stack, 5672 SmallVectorImpl<OMPClause *> &Clauses) { 5673 // Check for the deault mapper for data members. 5674 if (S.getLangOpts().OpenMP < 50) 5675 return; 5676 SmallVector<OMPClause *, 4> ImplicitMaps; 5677 for (int Cnt = 0, EndCnt = Clauses.size(); Cnt < EndCnt; ++Cnt) { 5678 auto *C = dyn_cast<OMPMapClause>(Clauses[Cnt]); 5679 if (!C) 5680 continue; 5681 SmallVector<Expr *, 4> SubExprs; 5682 auto *MI = C->mapperlist_begin(); 5683 for (auto I = C->varlist_begin(), End = C->varlist_end(); I != End; 5684 ++I, ++MI) { 5685 // Expression is mapped using mapper - skip it. 5686 if (*MI) 5687 continue; 5688 Expr *E = *I; 5689 // Expression is dependent - skip it, build the mapper when it gets 5690 // instantiated. 5691 if (E->isTypeDependent() || E->isValueDependent() || 5692 E->containsUnexpandedParameterPack()) 5693 continue; 5694 // Array section - need to check for the mapping of the array section 5695 // element. 5696 QualType CanonType = E->getType().getCanonicalType(); 5697 if (CanonType->isSpecificBuiltinType(BuiltinType::OMPArraySection)) { 5698 const auto *OASE = cast<OMPArraySectionExpr>(E->IgnoreParenImpCasts()); 5699 QualType BaseType = 5700 OMPArraySectionExpr::getBaseOriginalType(OASE->getBase()); 5701 QualType ElemType; 5702 if (const auto *ATy = BaseType->getAsArrayTypeUnsafe()) 5703 ElemType = ATy->getElementType(); 5704 else 5705 ElemType = BaseType->getPointeeType(); 5706 CanonType = ElemType; 5707 } 5708 5709 // DFS over data members in structures/classes. 5710 SmallVector<std::pair<QualType, FieldDecl *>, 4> Types( 5711 1, {CanonType, nullptr}); 5712 llvm::DenseMap<const Type *, Expr *> Visited; 5713 SmallVector<std::pair<FieldDecl *, unsigned>, 4> ParentChain( 5714 1, {nullptr, 1}); 5715 while (!Types.empty()) { 5716 QualType BaseType; 5717 FieldDecl *CurFD; 5718 std::tie(BaseType, CurFD) = Types.pop_back_val(); 5719 while (ParentChain.back().second == 0) 5720 ParentChain.pop_back(); 5721 --ParentChain.back().second; 5722 if (BaseType.isNull()) 5723 continue; 5724 // Only structs/classes are allowed to have mappers. 5725 const RecordDecl *RD = BaseType.getCanonicalType()->getAsRecordDecl(); 5726 if (!RD) 5727 continue; 5728 auto It = Visited.find(BaseType.getTypePtr()); 5729 if (It == Visited.end()) { 5730 // Try to find the associated user-defined mapper. 5731 CXXScopeSpec MapperIdScopeSpec; 5732 DeclarationNameInfo DefaultMapperId; 5733 DefaultMapperId.setName(S.Context.DeclarationNames.getIdentifier( 5734 &S.Context.Idents.get("default"))); 5735 DefaultMapperId.setLoc(E->getExprLoc()); 5736 ExprResult ER = buildUserDefinedMapperRef( 5737 S, Stack->getCurScope(), MapperIdScopeSpec, DefaultMapperId, 5738 BaseType, /*UnresolvedMapper=*/nullptr); 5739 if (ER.isInvalid()) 5740 continue; 5741 It = Visited.try_emplace(BaseType.getTypePtr(), ER.get()).first; 5742 } 5743 // Found default mapper. 5744 if (It->second) { 5745 auto *OE = new (S.Context) OpaqueValueExpr(E->getExprLoc(), CanonType, 5746 VK_LValue, OK_Ordinary, E); 5747 OE->setIsUnique(/*V=*/true); 5748 Expr *BaseExpr = OE; 5749 for (const auto &P : ParentChain) { 5750 if (P.first) { 5751 BaseExpr = S.BuildMemberExpr( 5752 BaseExpr, /*IsArrow=*/false, E->getExprLoc(), 5753 NestedNameSpecifierLoc(), SourceLocation(), P.first, 5754 DeclAccessPair::make(P.first, P.first->getAccess()), 5755 /*HadMultipleCandidates=*/false, DeclarationNameInfo(), 5756 P.first->getType(), VK_LValue, OK_Ordinary); 5757 BaseExpr = S.DefaultLvalueConversion(BaseExpr).get(); 5758 } 5759 } 5760 if (CurFD) 5761 BaseExpr = S.BuildMemberExpr( 5762 BaseExpr, /*IsArrow=*/false, E->getExprLoc(), 5763 NestedNameSpecifierLoc(), SourceLocation(), CurFD, 5764 DeclAccessPair::make(CurFD, CurFD->getAccess()), 5765 /*HadMultipleCandidates=*/false, DeclarationNameInfo(), 5766 CurFD->getType(), VK_LValue, OK_Ordinary); 5767 SubExprs.push_back(BaseExpr); 5768 continue; 5769 } 5770 // Check for the "default" mapper for data members. 5771 bool FirstIter = true; 5772 for (FieldDecl *FD : RD->fields()) { 5773 if (!FD) 5774 continue; 5775 QualType FieldTy = FD->getType(); 5776 if (FieldTy.isNull() || 5777 !(FieldTy->isStructureOrClassType() || FieldTy->isUnionType())) 5778 continue; 5779 if (FirstIter) { 5780 FirstIter = false; 5781 ParentChain.emplace_back(CurFD, 1); 5782 } else { 5783 ++ParentChain.back().second; 5784 } 5785 Types.emplace_back(FieldTy, FD); 5786 } 5787 } 5788 } 5789 if (SubExprs.empty()) 5790 continue; 5791 CXXScopeSpec MapperIdScopeSpec; 5792 DeclarationNameInfo MapperId; 5793 if (OMPClause *NewClause = S.ActOnOpenMPMapClause( 5794 C->getMapTypeModifiers(), C->getMapTypeModifiersLoc(), 5795 MapperIdScopeSpec, MapperId, C->getMapType(), 5796 /*IsMapTypeImplicit=*/true, SourceLocation(), SourceLocation(), 5797 SubExprs, OMPVarListLocTy())) 5798 Clauses.push_back(NewClause); 5799 } 5800 } 5801 5802 StmtResult Sema::ActOnOpenMPExecutableDirective( 5803 OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName, 5804 OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses, 5805 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) { 5806 StmtResult Res = StmtError(); 5807 OpenMPBindClauseKind BindKind = OMPC_BIND_unknown; 5808 if (const OMPBindClause *BC = 5809 OMPExecutableDirective::getSingleClause<OMPBindClause>(Clauses)) 5810 BindKind = BC->getBindKind(); 5811 // First check CancelRegion which is then used in checkNestingOfRegions. 5812 if (checkCancelRegion(*this, Kind, CancelRegion, StartLoc) || 5813 checkNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion, 5814 BindKind, StartLoc)) 5815 return StmtError(); 5816 5817 llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit; 5818 VarsWithInheritedDSAType VarsWithInheritedDSA; 5819 bool ErrorFound = false; 5820 ClausesWithImplicit.append(Clauses.begin(), Clauses.end()); 5821 if (AStmt && !CurContext->isDependentContext() && Kind != OMPD_atomic && 5822 Kind != OMPD_critical && Kind != OMPD_section && Kind != OMPD_master && 5823 Kind != OMPD_masked && !isOpenMPLoopTransformationDirective(Kind)) { 5824 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 5825 5826 // Check default data sharing attributes for referenced variables. 5827 DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt)); 5828 int ThisCaptureLevel = getOpenMPCaptureLevels(Kind); 5829 Stmt *S = AStmt; 5830 while (--ThisCaptureLevel >= 0) 5831 S = cast<CapturedStmt>(S)->getCapturedStmt(); 5832 DSAChecker.Visit(S); 5833 if (!isOpenMPTargetDataManagementDirective(Kind) && 5834 !isOpenMPTaskingDirective(Kind)) { 5835 // Visit subcaptures to generate implicit clauses for captured vars. 5836 auto *CS = cast<CapturedStmt>(AStmt); 5837 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions; 5838 getOpenMPCaptureRegions(CaptureRegions, Kind); 5839 // Ignore outer tasking regions for target directives. 5840 if (CaptureRegions.size() > 1 && CaptureRegions.front() == OMPD_task) 5841 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 5842 DSAChecker.visitSubCaptures(CS); 5843 } 5844 if (DSAChecker.isErrorFound()) 5845 return StmtError(); 5846 // Generate list of implicitly defined firstprivate variables. 5847 VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA(); 5848 5849 SmallVector<Expr *, 4> ImplicitFirstprivates( 5850 DSAChecker.getImplicitFirstprivate().begin(), 5851 DSAChecker.getImplicitFirstprivate().end()); 5852 const unsigned DefaultmapKindNum = OMPC_DEFAULTMAP_pointer + 1; 5853 SmallVector<Expr *, 4> ImplicitMaps[DefaultmapKindNum][OMPC_MAP_delete]; 5854 SmallVector<OpenMPMapModifierKind, NumberOfOMPMapClauseModifiers> 5855 ImplicitMapModifiers[DefaultmapKindNum]; 5856 SmallVector<SourceLocation, NumberOfOMPMapClauseModifiers> 5857 ImplicitMapModifiersLoc[DefaultmapKindNum]; 5858 // Get the original location of present modifier from Defaultmap clause. 5859 SourceLocation PresentModifierLocs[DefaultmapKindNum]; 5860 for (OMPClause *C : Clauses) { 5861 if (auto *DMC = dyn_cast<OMPDefaultmapClause>(C)) 5862 if (DMC->getDefaultmapModifier() == OMPC_DEFAULTMAP_MODIFIER_present) 5863 PresentModifierLocs[DMC->getDefaultmapKind()] = 5864 DMC->getDefaultmapModifierLoc(); 5865 } 5866 for (unsigned VC = 0; VC < DefaultmapKindNum; ++VC) { 5867 auto Kind = static_cast<OpenMPDefaultmapClauseKind>(VC); 5868 for (unsigned I = 0; I < OMPC_MAP_delete; ++I) { 5869 ArrayRef<Expr *> ImplicitMap = DSAChecker.getImplicitMap( 5870 Kind, static_cast<OpenMPMapClauseKind>(I)); 5871 ImplicitMaps[VC][I].append(ImplicitMap.begin(), ImplicitMap.end()); 5872 } 5873 ArrayRef<OpenMPMapModifierKind> ImplicitModifier = 5874 DSAChecker.getImplicitMapModifier(Kind); 5875 ImplicitMapModifiers[VC].append(ImplicitModifier.begin(), 5876 ImplicitModifier.end()); 5877 std::fill_n(std::back_inserter(ImplicitMapModifiersLoc[VC]), 5878 ImplicitModifier.size(), PresentModifierLocs[VC]); 5879 } 5880 // Mark taskgroup task_reduction descriptors as implicitly firstprivate. 5881 for (OMPClause *C : Clauses) { 5882 if (auto *IRC = dyn_cast<OMPInReductionClause>(C)) { 5883 for (Expr *E : IRC->taskgroup_descriptors()) 5884 if (E) 5885 ImplicitFirstprivates.emplace_back(E); 5886 } 5887 // OpenMP 5.0, 2.10.1 task Construct 5888 // [detach clause]... The event-handle will be considered as if it was 5889 // specified on a firstprivate clause. 5890 if (auto *DC = dyn_cast<OMPDetachClause>(C)) 5891 ImplicitFirstprivates.push_back(DC->getEventHandler()); 5892 } 5893 if (!ImplicitFirstprivates.empty()) { 5894 if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause( 5895 ImplicitFirstprivates, SourceLocation(), SourceLocation(), 5896 SourceLocation())) { 5897 ClausesWithImplicit.push_back(Implicit); 5898 ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() != 5899 ImplicitFirstprivates.size(); 5900 } else { 5901 ErrorFound = true; 5902 } 5903 } 5904 // OpenMP 5.0 [2.19.7] 5905 // If a list item appears in a reduction, lastprivate or linear 5906 // clause on a combined target construct then it is treated as 5907 // if it also appears in a map clause with a map-type of tofrom 5908 if (getLangOpts().OpenMP >= 50 && Kind != OMPD_target && 5909 isOpenMPTargetExecutionDirective(Kind)) { 5910 SmallVector<Expr *, 4> ImplicitExprs; 5911 for (OMPClause *C : Clauses) { 5912 if (auto *RC = dyn_cast<OMPReductionClause>(C)) 5913 for (Expr *E : RC->varlists()) 5914 if (!isa<DeclRefExpr>(E->IgnoreParenImpCasts())) 5915 ImplicitExprs.emplace_back(E); 5916 } 5917 if (!ImplicitExprs.empty()) { 5918 ArrayRef<Expr *> Exprs = ImplicitExprs; 5919 CXXScopeSpec MapperIdScopeSpec; 5920 DeclarationNameInfo MapperId; 5921 if (OMPClause *Implicit = ActOnOpenMPMapClause( 5922 OMPC_MAP_MODIFIER_unknown, SourceLocation(), MapperIdScopeSpec, 5923 MapperId, OMPC_MAP_tofrom, 5924 /*IsMapTypeImplicit=*/true, SourceLocation(), SourceLocation(), 5925 Exprs, OMPVarListLocTy(), /*NoDiagnose=*/true)) 5926 ClausesWithImplicit.emplace_back(Implicit); 5927 } 5928 } 5929 for (unsigned I = 0, E = DefaultmapKindNum; I < E; ++I) { 5930 int ClauseKindCnt = -1; 5931 for (ArrayRef<Expr *> ImplicitMap : ImplicitMaps[I]) { 5932 ++ClauseKindCnt; 5933 if (ImplicitMap.empty()) 5934 continue; 5935 CXXScopeSpec MapperIdScopeSpec; 5936 DeclarationNameInfo MapperId; 5937 auto Kind = static_cast<OpenMPMapClauseKind>(ClauseKindCnt); 5938 if (OMPClause *Implicit = ActOnOpenMPMapClause( 5939 ImplicitMapModifiers[I], ImplicitMapModifiersLoc[I], 5940 MapperIdScopeSpec, MapperId, Kind, /*IsMapTypeImplicit=*/true, 5941 SourceLocation(), SourceLocation(), ImplicitMap, 5942 OMPVarListLocTy())) { 5943 ClausesWithImplicit.emplace_back(Implicit); 5944 ErrorFound |= cast<OMPMapClause>(Implicit)->varlist_size() != 5945 ImplicitMap.size(); 5946 } else { 5947 ErrorFound = true; 5948 } 5949 } 5950 } 5951 // Build expressions for implicit maps of data members with 'default' 5952 // mappers. 5953 if (LangOpts.OpenMP >= 50) 5954 processImplicitMapsWithDefaultMappers(*this, DSAStack, 5955 ClausesWithImplicit); 5956 } 5957 5958 llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers; 5959 switch (Kind) { 5960 case OMPD_parallel: 5961 Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc, 5962 EndLoc); 5963 AllowedNameModifiers.push_back(OMPD_parallel); 5964 break; 5965 case OMPD_simd: 5966 Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc, 5967 VarsWithInheritedDSA); 5968 if (LangOpts.OpenMP >= 50) 5969 AllowedNameModifiers.push_back(OMPD_simd); 5970 break; 5971 case OMPD_tile: 5972 Res = 5973 ActOnOpenMPTileDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc); 5974 break; 5975 case OMPD_unroll: 5976 Res = ActOnOpenMPUnrollDirective(ClausesWithImplicit, AStmt, StartLoc, 5977 EndLoc); 5978 break; 5979 case OMPD_for: 5980 Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc, 5981 VarsWithInheritedDSA); 5982 break; 5983 case OMPD_for_simd: 5984 Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc, 5985 EndLoc, VarsWithInheritedDSA); 5986 if (LangOpts.OpenMP >= 50) 5987 AllowedNameModifiers.push_back(OMPD_simd); 5988 break; 5989 case OMPD_sections: 5990 Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc, 5991 EndLoc); 5992 break; 5993 case OMPD_section: 5994 assert(ClausesWithImplicit.empty() && 5995 "No clauses are allowed for 'omp section' directive"); 5996 Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc); 5997 break; 5998 case OMPD_single: 5999 Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc, 6000 EndLoc); 6001 break; 6002 case OMPD_master: 6003 assert(ClausesWithImplicit.empty() && 6004 "No clauses are allowed for 'omp master' directive"); 6005 Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc); 6006 break; 6007 case OMPD_masked: 6008 Res = ActOnOpenMPMaskedDirective(ClausesWithImplicit, AStmt, StartLoc, 6009 EndLoc); 6010 break; 6011 case OMPD_critical: 6012 Res = ActOnOpenMPCriticalDirective(DirName, ClausesWithImplicit, AStmt, 6013 StartLoc, EndLoc); 6014 break; 6015 case OMPD_parallel_for: 6016 Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc, 6017 EndLoc, VarsWithInheritedDSA); 6018 AllowedNameModifiers.push_back(OMPD_parallel); 6019 break; 6020 case OMPD_parallel_for_simd: 6021 Res = ActOnOpenMPParallelForSimdDirective( 6022 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 6023 AllowedNameModifiers.push_back(OMPD_parallel); 6024 if (LangOpts.OpenMP >= 50) 6025 AllowedNameModifiers.push_back(OMPD_simd); 6026 break; 6027 case OMPD_parallel_master: 6028 Res = ActOnOpenMPParallelMasterDirective(ClausesWithImplicit, AStmt, 6029 StartLoc, EndLoc); 6030 AllowedNameModifiers.push_back(OMPD_parallel); 6031 break; 6032 case OMPD_parallel_sections: 6033 Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt, 6034 StartLoc, EndLoc); 6035 AllowedNameModifiers.push_back(OMPD_parallel); 6036 break; 6037 case OMPD_task: 6038 Res = 6039 ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc); 6040 AllowedNameModifiers.push_back(OMPD_task); 6041 break; 6042 case OMPD_taskyield: 6043 assert(ClausesWithImplicit.empty() && 6044 "No clauses are allowed for 'omp taskyield' directive"); 6045 assert(AStmt == nullptr && 6046 "No associated statement allowed for 'omp taskyield' directive"); 6047 Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc); 6048 break; 6049 case OMPD_barrier: 6050 assert(ClausesWithImplicit.empty() && 6051 "No clauses are allowed for 'omp barrier' directive"); 6052 assert(AStmt == nullptr && 6053 "No associated statement allowed for 'omp barrier' directive"); 6054 Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc); 6055 break; 6056 case OMPD_taskwait: 6057 assert(AStmt == nullptr && 6058 "No associated statement allowed for 'omp taskwait' directive"); 6059 Res = ActOnOpenMPTaskwaitDirective(ClausesWithImplicit, StartLoc, EndLoc); 6060 break; 6061 case OMPD_taskgroup: 6062 Res = ActOnOpenMPTaskgroupDirective(ClausesWithImplicit, AStmt, StartLoc, 6063 EndLoc); 6064 break; 6065 case OMPD_flush: 6066 assert(AStmt == nullptr && 6067 "No associated statement allowed for 'omp flush' directive"); 6068 Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc); 6069 break; 6070 case OMPD_depobj: 6071 assert(AStmt == nullptr && 6072 "No associated statement allowed for 'omp depobj' directive"); 6073 Res = ActOnOpenMPDepobjDirective(ClausesWithImplicit, StartLoc, EndLoc); 6074 break; 6075 case OMPD_scan: 6076 assert(AStmt == nullptr && 6077 "No associated statement allowed for 'omp scan' directive"); 6078 Res = ActOnOpenMPScanDirective(ClausesWithImplicit, StartLoc, EndLoc); 6079 break; 6080 case OMPD_ordered: 6081 Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc, 6082 EndLoc); 6083 break; 6084 case OMPD_atomic: 6085 Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc, 6086 EndLoc); 6087 break; 6088 case OMPD_teams: 6089 Res = 6090 ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc); 6091 break; 6092 case OMPD_target: 6093 Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc, 6094 EndLoc); 6095 AllowedNameModifiers.push_back(OMPD_target); 6096 break; 6097 case OMPD_target_parallel: 6098 Res = ActOnOpenMPTargetParallelDirective(ClausesWithImplicit, AStmt, 6099 StartLoc, EndLoc); 6100 AllowedNameModifiers.push_back(OMPD_target); 6101 AllowedNameModifiers.push_back(OMPD_parallel); 6102 break; 6103 case OMPD_target_parallel_for: 6104 Res = ActOnOpenMPTargetParallelForDirective( 6105 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 6106 AllowedNameModifiers.push_back(OMPD_target); 6107 AllowedNameModifiers.push_back(OMPD_parallel); 6108 break; 6109 case OMPD_cancellation_point: 6110 assert(ClausesWithImplicit.empty() && 6111 "No clauses are allowed for 'omp cancellation point' directive"); 6112 assert(AStmt == nullptr && "No associated statement allowed for 'omp " 6113 "cancellation point' directive"); 6114 Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion); 6115 break; 6116 case OMPD_cancel: 6117 assert(AStmt == nullptr && 6118 "No associated statement allowed for 'omp cancel' directive"); 6119 Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc, 6120 CancelRegion); 6121 AllowedNameModifiers.push_back(OMPD_cancel); 6122 break; 6123 case OMPD_target_data: 6124 Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc, 6125 EndLoc); 6126 AllowedNameModifiers.push_back(OMPD_target_data); 6127 break; 6128 case OMPD_target_enter_data: 6129 Res = ActOnOpenMPTargetEnterDataDirective(ClausesWithImplicit, StartLoc, 6130 EndLoc, AStmt); 6131 AllowedNameModifiers.push_back(OMPD_target_enter_data); 6132 break; 6133 case OMPD_target_exit_data: 6134 Res = ActOnOpenMPTargetExitDataDirective(ClausesWithImplicit, StartLoc, 6135 EndLoc, AStmt); 6136 AllowedNameModifiers.push_back(OMPD_target_exit_data); 6137 break; 6138 case OMPD_taskloop: 6139 Res = ActOnOpenMPTaskLoopDirective(ClausesWithImplicit, AStmt, StartLoc, 6140 EndLoc, VarsWithInheritedDSA); 6141 AllowedNameModifiers.push_back(OMPD_taskloop); 6142 break; 6143 case OMPD_taskloop_simd: 6144 Res = ActOnOpenMPTaskLoopSimdDirective(ClausesWithImplicit, AStmt, StartLoc, 6145 EndLoc, VarsWithInheritedDSA); 6146 AllowedNameModifiers.push_back(OMPD_taskloop); 6147 if (LangOpts.OpenMP >= 50) 6148 AllowedNameModifiers.push_back(OMPD_simd); 6149 break; 6150 case OMPD_master_taskloop: 6151 Res = ActOnOpenMPMasterTaskLoopDirective( 6152 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 6153 AllowedNameModifiers.push_back(OMPD_taskloop); 6154 break; 6155 case OMPD_master_taskloop_simd: 6156 Res = ActOnOpenMPMasterTaskLoopSimdDirective( 6157 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 6158 AllowedNameModifiers.push_back(OMPD_taskloop); 6159 if (LangOpts.OpenMP >= 50) 6160 AllowedNameModifiers.push_back(OMPD_simd); 6161 break; 6162 case OMPD_parallel_master_taskloop: 6163 Res = ActOnOpenMPParallelMasterTaskLoopDirective( 6164 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 6165 AllowedNameModifiers.push_back(OMPD_taskloop); 6166 AllowedNameModifiers.push_back(OMPD_parallel); 6167 break; 6168 case OMPD_parallel_master_taskloop_simd: 6169 Res = ActOnOpenMPParallelMasterTaskLoopSimdDirective( 6170 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 6171 AllowedNameModifiers.push_back(OMPD_taskloop); 6172 AllowedNameModifiers.push_back(OMPD_parallel); 6173 if (LangOpts.OpenMP >= 50) 6174 AllowedNameModifiers.push_back(OMPD_simd); 6175 break; 6176 case OMPD_distribute: 6177 Res = ActOnOpenMPDistributeDirective(ClausesWithImplicit, AStmt, StartLoc, 6178 EndLoc, VarsWithInheritedDSA); 6179 break; 6180 case OMPD_target_update: 6181 Res = ActOnOpenMPTargetUpdateDirective(ClausesWithImplicit, StartLoc, 6182 EndLoc, AStmt); 6183 AllowedNameModifiers.push_back(OMPD_target_update); 6184 break; 6185 case OMPD_distribute_parallel_for: 6186 Res = ActOnOpenMPDistributeParallelForDirective( 6187 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 6188 AllowedNameModifiers.push_back(OMPD_parallel); 6189 break; 6190 case OMPD_distribute_parallel_for_simd: 6191 Res = ActOnOpenMPDistributeParallelForSimdDirective( 6192 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 6193 AllowedNameModifiers.push_back(OMPD_parallel); 6194 if (LangOpts.OpenMP >= 50) 6195 AllowedNameModifiers.push_back(OMPD_simd); 6196 break; 6197 case OMPD_distribute_simd: 6198 Res = ActOnOpenMPDistributeSimdDirective( 6199 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 6200 if (LangOpts.OpenMP >= 50) 6201 AllowedNameModifiers.push_back(OMPD_simd); 6202 break; 6203 case OMPD_target_parallel_for_simd: 6204 Res = ActOnOpenMPTargetParallelForSimdDirective( 6205 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 6206 AllowedNameModifiers.push_back(OMPD_target); 6207 AllowedNameModifiers.push_back(OMPD_parallel); 6208 if (LangOpts.OpenMP >= 50) 6209 AllowedNameModifiers.push_back(OMPD_simd); 6210 break; 6211 case OMPD_target_simd: 6212 Res = ActOnOpenMPTargetSimdDirective(ClausesWithImplicit, AStmt, StartLoc, 6213 EndLoc, VarsWithInheritedDSA); 6214 AllowedNameModifiers.push_back(OMPD_target); 6215 if (LangOpts.OpenMP >= 50) 6216 AllowedNameModifiers.push_back(OMPD_simd); 6217 break; 6218 case OMPD_teams_distribute: 6219 Res = ActOnOpenMPTeamsDistributeDirective( 6220 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 6221 break; 6222 case OMPD_teams_distribute_simd: 6223 Res = ActOnOpenMPTeamsDistributeSimdDirective( 6224 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 6225 if (LangOpts.OpenMP >= 50) 6226 AllowedNameModifiers.push_back(OMPD_simd); 6227 break; 6228 case OMPD_teams_distribute_parallel_for_simd: 6229 Res = ActOnOpenMPTeamsDistributeParallelForSimdDirective( 6230 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 6231 AllowedNameModifiers.push_back(OMPD_parallel); 6232 if (LangOpts.OpenMP >= 50) 6233 AllowedNameModifiers.push_back(OMPD_simd); 6234 break; 6235 case OMPD_teams_distribute_parallel_for: 6236 Res = ActOnOpenMPTeamsDistributeParallelForDirective( 6237 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 6238 AllowedNameModifiers.push_back(OMPD_parallel); 6239 break; 6240 case OMPD_target_teams: 6241 Res = ActOnOpenMPTargetTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, 6242 EndLoc); 6243 AllowedNameModifiers.push_back(OMPD_target); 6244 break; 6245 case OMPD_target_teams_distribute: 6246 Res = ActOnOpenMPTargetTeamsDistributeDirective( 6247 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 6248 AllowedNameModifiers.push_back(OMPD_target); 6249 break; 6250 case OMPD_target_teams_distribute_parallel_for: 6251 Res = ActOnOpenMPTargetTeamsDistributeParallelForDirective( 6252 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 6253 AllowedNameModifiers.push_back(OMPD_target); 6254 AllowedNameModifiers.push_back(OMPD_parallel); 6255 break; 6256 case OMPD_target_teams_distribute_parallel_for_simd: 6257 Res = ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective( 6258 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 6259 AllowedNameModifiers.push_back(OMPD_target); 6260 AllowedNameModifiers.push_back(OMPD_parallel); 6261 if (LangOpts.OpenMP >= 50) 6262 AllowedNameModifiers.push_back(OMPD_simd); 6263 break; 6264 case OMPD_target_teams_distribute_simd: 6265 Res = ActOnOpenMPTargetTeamsDistributeSimdDirective( 6266 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 6267 AllowedNameModifiers.push_back(OMPD_target); 6268 if (LangOpts.OpenMP >= 50) 6269 AllowedNameModifiers.push_back(OMPD_simd); 6270 break; 6271 case OMPD_interop: 6272 assert(AStmt == nullptr && 6273 "No associated statement allowed for 'omp interop' directive"); 6274 Res = ActOnOpenMPInteropDirective(ClausesWithImplicit, StartLoc, EndLoc); 6275 break; 6276 case OMPD_dispatch: 6277 Res = ActOnOpenMPDispatchDirective(ClausesWithImplicit, AStmt, StartLoc, 6278 EndLoc); 6279 break; 6280 case OMPD_loop: 6281 Res = ActOnOpenMPGenericLoopDirective(ClausesWithImplicit, AStmt, StartLoc, 6282 EndLoc, VarsWithInheritedDSA); 6283 break; 6284 case OMPD_declare_target: 6285 case OMPD_end_declare_target: 6286 case OMPD_threadprivate: 6287 case OMPD_allocate: 6288 case OMPD_declare_reduction: 6289 case OMPD_declare_mapper: 6290 case OMPD_declare_simd: 6291 case OMPD_requires: 6292 case OMPD_declare_variant: 6293 case OMPD_begin_declare_variant: 6294 case OMPD_end_declare_variant: 6295 llvm_unreachable("OpenMP Directive is not allowed"); 6296 case OMPD_unknown: 6297 default: 6298 llvm_unreachable("Unknown OpenMP directive"); 6299 } 6300 6301 ErrorFound = Res.isInvalid() || ErrorFound; 6302 6303 // Check variables in the clauses if default(none) or 6304 // default(firstprivate) was specified. 6305 if (DSAStack->getDefaultDSA() == DSA_none || 6306 DSAStack->getDefaultDSA() == DSA_firstprivate) { 6307 DSAAttrChecker DSAChecker(DSAStack, *this, nullptr); 6308 for (OMPClause *C : Clauses) { 6309 switch (C->getClauseKind()) { 6310 case OMPC_num_threads: 6311 case OMPC_dist_schedule: 6312 // Do not analyse if no parent teams directive. 6313 if (isOpenMPTeamsDirective(Kind)) 6314 break; 6315 continue; 6316 case OMPC_if: 6317 if (isOpenMPTeamsDirective(Kind) && 6318 cast<OMPIfClause>(C)->getNameModifier() != OMPD_target) 6319 break; 6320 if (isOpenMPParallelDirective(Kind) && 6321 isOpenMPTaskLoopDirective(Kind) && 6322 cast<OMPIfClause>(C)->getNameModifier() != OMPD_parallel) 6323 break; 6324 continue; 6325 case OMPC_schedule: 6326 case OMPC_detach: 6327 break; 6328 case OMPC_grainsize: 6329 case OMPC_num_tasks: 6330 case OMPC_final: 6331 case OMPC_priority: 6332 case OMPC_novariants: 6333 case OMPC_nocontext: 6334 // Do not analyze if no parent parallel directive. 6335 if (isOpenMPParallelDirective(Kind)) 6336 break; 6337 continue; 6338 case OMPC_ordered: 6339 case OMPC_device: 6340 case OMPC_num_teams: 6341 case OMPC_thread_limit: 6342 case OMPC_hint: 6343 case OMPC_collapse: 6344 case OMPC_safelen: 6345 case OMPC_simdlen: 6346 case OMPC_sizes: 6347 case OMPC_default: 6348 case OMPC_proc_bind: 6349 case OMPC_private: 6350 case OMPC_firstprivate: 6351 case OMPC_lastprivate: 6352 case OMPC_shared: 6353 case OMPC_reduction: 6354 case OMPC_task_reduction: 6355 case OMPC_in_reduction: 6356 case OMPC_linear: 6357 case OMPC_aligned: 6358 case OMPC_copyin: 6359 case OMPC_copyprivate: 6360 case OMPC_nowait: 6361 case OMPC_untied: 6362 case OMPC_mergeable: 6363 case OMPC_allocate: 6364 case OMPC_read: 6365 case OMPC_write: 6366 case OMPC_update: 6367 case OMPC_capture: 6368 case OMPC_compare: 6369 case OMPC_seq_cst: 6370 case OMPC_acq_rel: 6371 case OMPC_acquire: 6372 case OMPC_release: 6373 case OMPC_relaxed: 6374 case OMPC_depend: 6375 case OMPC_threads: 6376 case OMPC_simd: 6377 case OMPC_map: 6378 case OMPC_nogroup: 6379 case OMPC_defaultmap: 6380 case OMPC_to: 6381 case OMPC_from: 6382 case OMPC_use_device_ptr: 6383 case OMPC_use_device_addr: 6384 case OMPC_is_device_ptr: 6385 case OMPC_nontemporal: 6386 case OMPC_order: 6387 case OMPC_destroy: 6388 case OMPC_inclusive: 6389 case OMPC_exclusive: 6390 case OMPC_uses_allocators: 6391 case OMPC_affinity: 6392 case OMPC_bind: 6393 continue; 6394 case OMPC_allocator: 6395 case OMPC_flush: 6396 case OMPC_depobj: 6397 case OMPC_threadprivate: 6398 case OMPC_uniform: 6399 case OMPC_unknown: 6400 case OMPC_unified_address: 6401 case OMPC_unified_shared_memory: 6402 case OMPC_reverse_offload: 6403 case OMPC_dynamic_allocators: 6404 case OMPC_atomic_default_mem_order: 6405 case OMPC_device_type: 6406 case OMPC_match: 6407 case OMPC_when: 6408 default: 6409 llvm_unreachable("Unexpected clause"); 6410 } 6411 for (Stmt *CC : C->children()) { 6412 if (CC) 6413 DSAChecker.Visit(CC); 6414 } 6415 } 6416 for (const auto &P : DSAChecker.getVarsWithInheritedDSA()) 6417 VarsWithInheritedDSA[P.getFirst()] = P.getSecond(); 6418 } 6419 for (const auto &P : VarsWithInheritedDSA) { 6420 if (P.getFirst()->isImplicit() || isa<OMPCapturedExprDecl>(P.getFirst())) 6421 continue; 6422 ErrorFound = true; 6423 if (DSAStack->getDefaultDSA() == DSA_none || 6424 DSAStack->getDefaultDSA() == DSA_firstprivate) { 6425 Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable) 6426 << P.first << P.second->getSourceRange(); 6427 Diag(DSAStack->getDefaultDSALocation(), diag::note_omp_default_dsa_none); 6428 } else if (getLangOpts().OpenMP >= 50) { 6429 Diag(P.second->getExprLoc(), 6430 diag::err_omp_defaultmap_no_attr_for_variable) 6431 << P.first << P.second->getSourceRange(); 6432 Diag(DSAStack->getDefaultDSALocation(), 6433 diag::note_omp_defaultmap_attr_none); 6434 } 6435 } 6436 6437 if (!AllowedNameModifiers.empty()) 6438 ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) || 6439 ErrorFound; 6440 6441 if (ErrorFound) 6442 return StmtError(); 6443 6444 if (!CurContext->isDependentContext() && 6445 isOpenMPTargetExecutionDirective(Kind) && 6446 !(DSAStack->hasRequiresDeclWithClause<OMPUnifiedSharedMemoryClause>() || 6447 DSAStack->hasRequiresDeclWithClause<OMPUnifiedAddressClause>() || 6448 DSAStack->hasRequiresDeclWithClause<OMPReverseOffloadClause>() || 6449 DSAStack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>())) { 6450 // Register target to DSA Stack. 6451 DSAStack->addTargetDirLocation(StartLoc); 6452 } 6453 6454 return Res; 6455 } 6456 6457 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareSimdDirective( 6458 DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen, 6459 ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds, 6460 ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears, 6461 ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR) { 6462 assert(Aligneds.size() == Alignments.size()); 6463 assert(Linears.size() == LinModifiers.size()); 6464 assert(Linears.size() == Steps.size()); 6465 if (!DG || DG.get().isNull()) 6466 return DeclGroupPtrTy(); 6467 6468 const int SimdId = 0; 6469 if (!DG.get().isSingleDecl()) { 6470 Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd_variant) 6471 << SimdId; 6472 return DG; 6473 } 6474 Decl *ADecl = DG.get().getSingleDecl(); 6475 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl)) 6476 ADecl = FTD->getTemplatedDecl(); 6477 6478 auto *FD = dyn_cast<FunctionDecl>(ADecl); 6479 if (!FD) { 6480 Diag(ADecl->getLocation(), diag::err_omp_function_expected) << SimdId; 6481 return DeclGroupPtrTy(); 6482 } 6483 6484 // OpenMP [2.8.2, declare simd construct, Description] 6485 // The parameter of the simdlen clause must be a constant positive integer 6486 // expression. 6487 ExprResult SL; 6488 if (Simdlen) 6489 SL = VerifyPositiveIntegerConstantInClause(Simdlen, OMPC_simdlen); 6490 // OpenMP [2.8.2, declare simd construct, Description] 6491 // The special this pointer can be used as if was one of the arguments to the 6492 // function in any of the linear, aligned, or uniform clauses. 6493 // The uniform clause declares one or more arguments to have an invariant 6494 // value for all concurrent invocations of the function in the execution of a 6495 // single SIMD loop. 6496 llvm::DenseMap<const Decl *, const Expr *> UniformedArgs; 6497 const Expr *UniformedLinearThis = nullptr; 6498 for (const Expr *E : Uniforms) { 6499 E = E->IgnoreParenImpCasts(); 6500 if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) 6501 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) 6502 if (FD->getNumParams() > PVD->getFunctionScopeIndex() && 6503 FD->getParamDecl(PVD->getFunctionScopeIndex()) 6504 ->getCanonicalDecl() == PVD->getCanonicalDecl()) { 6505 UniformedArgs.try_emplace(PVD->getCanonicalDecl(), E); 6506 continue; 6507 } 6508 if (isa<CXXThisExpr>(E)) { 6509 UniformedLinearThis = E; 6510 continue; 6511 } 6512 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause) 6513 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0); 6514 } 6515 // OpenMP [2.8.2, declare simd construct, Description] 6516 // The aligned clause declares that the object to which each list item points 6517 // is aligned to the number of bytes expressed in the optional parameter of 6518 // the aligned clause. 6519 // The special this pointer can be used as if was one of the arguments to the 6520 // function in any of the linear, aligned, or uniform clauses. 6521 // The type of list items appearing in the aligned clause must be array, 6522 // pointer, reference to array, or reference to pointer. 6523 llvm::DenseMap<const Decl *, const Expr *> AlignedArgs; 6524 const Expr *AlignedThis = nullptr; 6525 for (const Expr *E : Aligneds) { 6526 E = E->IgnoreParenImpCasts(); 6527 if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) 6528 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) { 6529 const VarDecl *CanonPVD = PVD->getCanonicalDecl(); 6530 if (FD->getNumParams() > PVD->getFunctionScopeIndex() && 6531 FD->getParamDecl(PVD->getFunctionScopeIndex()) 6532 ->getCanonicalDecl() == CanonPVD) { 6533 // OpenMP [2.8.1, simd construct, Restrictions] 6534 // A list-item cannot appear in more than one aligned clause. 6535 if (AlignedArgs.count(CanonPVD) > 0) { 6536 Diag(E->getExprLoc(), diag::err_omp_used_in_clause_twice) 6537 << 1 << getOpenMPClauseName(OMPC_aligned) 6538 << E->getSourceRange(); 6539 Diag(AlignedArgs[CanonPVD]->getExprLoc(), 6540 diag::note_omp_explicit_dsa) 6541 << getOpenMPClauseName(OMPC_aligned); 6542 continue; 6543 } 6544 AlignedArgs[CanonPVD] = E; 6545 QualType QTy = PVD->getType() 6546 .getNonReferenceType() 6547 .getUnqualifiedType() 6548 .getCanonicalType(); 6549 const Type *Ty = QTy.getTypePtrOrNull(); 6550 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) { 6551 Diag(E->getExprLoc(), diag::err_omp_aligned_expected_array_or_ptr) 6552 << QTy << getLangOpts().CPlusPlus << E->getSourceRange(); 6553 Diag(PVD->getLocation(), diag::note_previous_decl) << PVD; 6554 } 6555 continue; 6556 } 6557 } 6558 if (isa<CXXThisExpr>(E)) { 6559 if (AlignedThis) { 6560 Diag(E->getExprLoc(), diag::err_omp_used_in_clause_twice) 6561 << 2 << getOpenMPClauseName(OMPC_aligned) << E->getSourceRange(); 6562 Diag(AlignedThis->getExprLoc(), diag::note_omp_explicit_dsa) 6563 << getOpenMPClauseName(OMPC_aligned); 6564 } 6565 AlignedThis = E; 6566 continue; 6567 } 6568 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause) 6569 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0); 6570 } 6571 // The optional parameter of the aligned clause, alignment, must be a constant 6572 // positive integer expression. If no optional parameter is specified, 6573 // implementation-defined default alignments for SIMD instructions on the 6574 // target platforms are assumed. 6575 SmallVector<const Expr *, 4> NewAligns; 6576 for (Expr *E : Alignments) { 6577 ExprResult Align; 6578 if (E) 6579 Align = VerifyPositiveIntegerConstantInClause(E, OMPC_aligned); 6580 NewAligns.push_back(Align.get()); 6581 } 6582 // OpenMP [2.8.2, declare simd construct, Description] 6583 // The linear clause declares one or more list items to be private to a SIMD 6584 // lane and to have a linear relationship with respect to the iteration space 6585 // of a loop. 6586 // The special this pointer can be used as if was one of the arguments to the 6587 // function in any of the linear, aligned, or uniform clauses. 6588 // When a linear-step expression is specified in a linear clause it must be 6589 // either a constant integer expression or an integer-typed parameter that is 6590 // specified in a uniform clause on the directive. 6591 llvm::DenseMap<const Decl *, const Expr *> LinearArgs; 6592 const bool IsUniformedThis = UniformedLinearThis != nullptr; 6593 auto MI = LinModifiers.begin(); 6594 for (const Expr *E : Linears) { 6595 auto LinKind = static_cast<OpenMPLinearClauseKind>(*MI); 6596 ++MI; 6597 E = E->IgnoreParenImpCasts(); 6598 if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) 6599 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) { 6600 const VarDecl *CanonPVD = PVD->getCanonicalDecl(); 6601 if (FD->getNumParams() > PVD->getFunctionScopeIndex() && 6602 FD->getParamDecl(PVD->getFunctionScopeIndex()) 6603 ->getCanonicalDecl() == CanonPVD) { 6604 // OpenMP [2.15.3.7, linear Clause, Restrictions] 6605 // A list-item cannot appear in more than one linear clause. 6606 if (LinearArgs.count(CanonPVD) > 0) { 6607 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa) 6608 << getOpenMPClauseName(OMPC_linear) 6609 << getOpenMPClauseName(OMPC_linear) << E->getSourceRange(); 6610 Diag(LinearArgs[CanonPVD]->getExprLoc(), 6611 diag::note_omp_explicit_dsa) 6612 << getOpenMPClauseName(OMPC_linear); 6613 continue; 6614 } 6615 // Each argument can appear in at most one uniform or linear clause. 6616 if (UniformedArgs.count(CanonPVD) > 0) { 6617 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa) 6618 << getOpenMPClauseName(OMPC_linear) 6619 << getOpenMPClauseName(OMPC_uniform) << E->getSourceRange(); 6620 Diag(UniformedArgs[CanonPVD]->getExprLoc(), 6621 diag::note_omp_explicit_dsa) 6622 << getOpenMPClauseName(OMPC_uniform); 6623 continue; 6624 } 6625 LinearArgs[CanonPVD] = E; 6626 if (E->isValueDependent() || E->isTypeDependent() || 6627 E->isInstantiationDependent() || 6628 E->containsUnexpandedParameterPack()) 6629 continue; 6630 (void)CheckOpenMPLinearDecl(CanonPVD, E->getExprLoc(), LinKind, 6631 PVD->getOriginalType(), 6632 /*IsDeclareSimd=*/true); 6633 continue; 6634 } 6635 } 6636 if (isa<CXXThisExpr>(E)) { 6637 if (UniformedLinearThis) { 6638 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa) 6639 << getOpenMPClauseName(OMPC_linear) 6640 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform : OMPC_linear) 6641 << E->getSourceRange(); 6642 Diag(UniformedLinearThis->getExprLoc(), diag::note_omp_explicit_dsa) 6643 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform 6644 : OMPC_linear); 6645 continue; 6646 } 6647 UniformedLinearThis = E; 6648 if (E->isValueDependent() || E->isTypeDependent() || 6649 E->isInstantiationDependent() || E->containsUnexpandedParameterPack()) 6650 continue; 6651 (void)CheckOpenMPLinearDecl(/*D=*/nullptr, E->getExprLoc(), LinKind, 6652 E->getType(), /*IsDeclareSimd=*/true); 6653 continue; 6654 } 6655 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause) 6656 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0); 6657 } 6658 Expr *Step = nullptr; 6659 Expr *NewStep = nullptr; 6660 SmallVector<Expr *, 4> NewSteps; 6661 for (Expr *E : Steps) { 6662 // Skip the same step expression, it was checked already. 6663 if (Step == E || !E) { 6664 NewSteps.push_back(E ? NewStep : nullptr); 6665 continue; 6666 } 6667 Step = E; 6668 if (const auto *DRE = dyn_cast<DeclRefExpr>(Step)) 6669 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) { 6670 const VarDecl *CanonPVD = PVD->getCanonicalDecl(); 6671 if (UniformedArgs.count(CanonPVD) == 0) { 6672 Diag(Step->getExprLoc(), diag::err_omp_expected_uniform_param) 6673 << Step->getSourceRange(); 6674 } else if (E->isValueDependent() || E->isTypeDependent() || 6675 E->isInstantiationDependent() || 6676 E->containsUnexpandedParameterPack() || 6677 CanonPVD->getType()->hasIntegerRepresentation()) { 6678 NewSteps.push_back(Step); 6679 } else { 6680 Diag(Step->getExprLoc(), diag::err_omp_expected_int_param) 6681 << Step->getSourceRange(); 6682 } 6683 continue; 6684 } 6685 NewStep = Step; 6686 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() && 6687 !Step->isInstantiationDependent() && 6688 !Step->containsUnexpandedParameterPack()) { 6689 NewStep = PerformOpenMPImplicitIntegerConversion(Step->getExprLoc(), Step) 6690 .get(); 6691 if (NewStep) 6692 NewStep = 6693 VerifyIntegerConstantExpression(NewStep, /*FIXME*/ AllowFold).get(); 6694 } 6695 NewSteps.push_back(NewStep); 6696 } 6697 auto *NewAttr = OMPDeclareSimdDeclAttr::CreateImplicit( 6698 Context, BS, SL.get(), const_cast<Expr **>(Uniforms.data()), 6699 Uniforms.size(), const_cast<Expr **>(Aligneds.data()), Aligneds.size(), 6700 const_cast<Expr **>(NewAligns.data()), NewAligns.size(), 6701 const_cast<Expr **>(Linears.data()), Linears.size(), 6702 const_cast<unsigned *>(LinModifiers.data()), LinModifiers.size(), 6703 NewSteps.data(), NewSteps.size(), SR); 6704 ADecl->addAttr(NewAttr); 6705 return DG; 6706 } 6707 6708 static void setPrototype(Sema &S, FunctionDecl *FD, FunctionDecl *FDWithProto, 6709 QualType NewType) { 6710 assert(NewType->isFunctionProtoType() && 6711 "Expected function type with prototype."); 6712 assert(FD->getType()->isFunctionNoProtoType() && 6713 "Expected function with type with no prototype."); 6714 assert(FDWithProto->getType()->isFunctionProtoType() && 6715 "Expected function with prototype."); 6716 // Synthesize parameters with the same types. 6717 FD->setType(NewType); 6718 SmallVector<ParmVarDecl *, 16> Params; 6719 for (const ParmVarDecl *P : FDWithProto->parameters()) { 6720 auto *Param = ParmVarDecl::Create(S.getASTContext(), FD, SourceLocation(), 6721 SourceLocation(), nullptr, P->getType(), 6722 /*TInfo=*/nullptr, SC_None, nullptr); 6723 Param->setScopeInfo(0, Params.size()); 6724 Param->setImplicit(); 6725 Params.push_back(Param); 6726 } 6727 6728 FD->setParams(Params); 6729 } 6730 6731 void Sema::ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(Decl *D) { 6732 if (D->isInvalidDecl()) 6733 return; 6734 FunctionDecl *FD = nullptr; 6735 if (auto *UTemplDecl = dyn_cast<FunctionTemplateDecl>(D)) 6736 FD = UTemplDecl->getTemplatedDecl(); 6737 else 6738 FD = cast<FunctionDecl>(D); 6739 assert(FD && "Expected a function declaration!"); 6740 6741 // If we are instantiating templates we do *not* apply scoped assumptions but 6742 // only global ones. We apply scoped assumption to the template definition 6743 // though. 6744 if (!inTemplateInstantiation()) { 6745 for (AssumptionAttr *AA : OMPAssumeScoped) 6746 FD->addAttr(AA); 6747 } 6748 for (AssumptionAttr *AA : OMPAssumeGlobal) 6749 FD->addAttr(AA); 6750 } 6751 6752 Sema::OMPDeclareVariantScope::OMPDeclareVariantScope(OMPTraitInfo &TI) 6753 : TI(&TI), NameSuffix(TI.getMangledName()) {} 6754 6755 void Sema::ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope( 6756 Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParamLists, 6757 SmallVectorImpl<FunctionDecl *> &Bases) { 6758 if (!D.getIdentifier()) 6759 return; 6760 6761 OMPDeclareVariantScope &DVScope = OMPDeclareVariantScopes.back(); 6762 6763 // Template specialization is an extension, check if we do it. 6764 bool IsTemplated = !TemplateParamLists.empty(); 6765 if (IsTemplated & 6766 !DVScope.TI->isExtensionActive( 6767 llvm::omp::TraitProperty::implementation_extension_allow_templates)) 6768 return; 6769 6770 IdentifierInfo *BaseII = D.getIdentifier(); 6771 LookupResult Lookup(*this, DeclarationName(BaseII), D.getIdentifierLoc(), 6772 LookupOrdinaryName); 6773 LookupParsedName(Lookup, S, &D.getCXXScopeSpec()); 6774 6775 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 6776 QualType FType = TInfo->getType(); 6777 6778 bool IsConstexpr = 6779 D.getDeclSpec().getConstexprSpecifier() == ConstexprSpecKind::Constexpr; 6780 bool IsConsteval = 6781 D.getDeclSpec().getConstexprSpecifier() == ConstexprSpecKind::Consteval; 6782 6783 for (auto *Candidate : Lookup) { 6784 auto *CandidateDecl = Candidate->getUnderlyingDecl(); 6785 FunctionDecl *UDecl = nullptr; 6786 if (IsTemplated && isa<FunctionTemplateDecl>(CandidateDecl)) { 6787 auto *FTD = cast<FunctionTemplateDecl>(CandidateDecl); 6788 if (FTD->getTemplateParameters()->size() == TemplateParamLists.size()) 6789 UDecl = FTD->getTemplatedDecl(); 6790 } else if (!IsTemplated) 6791 UDecl = dyn_cast<FunctionDecl>(CandidateDecl); 6792 if (!UDecl) 6793 continue; 6794 6795 // Don't specialize constexpr/consteval functions with 6796 // non-constexpr/consteval functions. 6797 if (UDecl->isConstexpr() && !IsConstexpr) 6798 continue; 6799 if (UDecl->isConsteval() && !IsConsteval) 6800 continue; 6801 6802 QualType UDeclTy = UDecl->getType(); 6803 if (!UDeclTy->isDependentType()) { 6804 QualType NewType = Context.mergeFunctionTypes( 6805 FType, UDeclTy, /* OfBlockPointer */ false, 6806 /* Unqualified */ false, /* AllowCXX */ true); 6807 if (NewType.isNull()) 6808 continue; 6809 } 6810 6811 // Found a base! 6812 Bases.push_back(UDecl); 6813 } 6814 6815 bool UseImplicitBase = !DVScope.TI->isExtensionActive( 6816 llvm::omp::TraitProperty::implementation_extension_disable_implicit_base); 6817 // If no base was found we create a declaration that we use as base. 6818 if (Bases.empty() && UseImplicitBase) { 6819 D.setFunctionDefinitionKind(FunctionDefinitionKind::Declaration); 6820 Decl *BaseD = HandleDeclarator(S, D, TemplateParamLists); 6821 BaseD->setImplicit(true); 6822 if (auto *BaseTemplD = dyn_cast<FunctionTemplateDecl>(BaseD)) 6823 Bases.push_back(BaseTemplD->getTemplatedDecl()); 6824 else 6825 Bases.push_back(cast<FunctionDecl>(BaseD)); 6826 } 6827 6828 std::string MangledName; 6829 MangledName += D.getIdentifier()->getName(); 6830 MangledName += getOpenMPVariantManglingSeparatorStr(); 6831 MangledName += DVScope.NameSuffix; 6832 IdentifierInfo &VariantII = Context.Idents.get(MangledName); 6833 6834 VariantII.setMangledOpenMPVariantName(true); 6835 D.SetIdentifier(&VariantII, D.getBeginLoc()); 6836 } 6837 6838 void Sema::ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope( 6839 Decl *D, SmallVectorImpl<FunctionDecl *> &Bases) { 6840 // Do not mark function as is used to prevent its emission if this is the 6841 // only place where it is used. 6842 EnterExpressionEvaluationContext Unevaluated( 6843 *this, Sema::ExpressionEvaluationContext::Unevaluated); 6844 6845 FunctionDecl *FD = nullptr; 6846 if (auto *UTemplDecl = dyn_cast<FunctionTemplateDecl>(D)) 6847 FD = UTemplDecl->getTemplatedDecl(); 6848 else 6849 FD = cast<FunctionDecl>(D); 6850 auto *VariantFuncRef = DeclRefExpr::Create( 6851 Context, NestedNameSpecifierLoc(), SourceLocation(), FD, 6852 /* RefersToEnclosingVariableOrCapture */ false, 6853 /* NameLoc */ FD->getLocation(), FD->getType(), 6854 ExprValueKind::VK_PRValue); 6855 6856 OMPDeclareVariantScope &DVScope = OMPDeclareVariantScopes.back(); 6857 auto *OMPDeclareVariantA = OMPDeclareVariantAttr::CreateImplicit( 6858 Context, VariantFuncRef, DVScope.TI, 6859 /*NothingArgs=*/nullptr, /*NothingArgsSize=*/0, 6860 /*NeedDevicePtrArgs=*/nullptr, /*NeedDevicePtrArgsSize=*/0, 6861 /*AppendArgs=*/nullptr, /*AppendArgsSize=*/0); 6862 for (FunctionDecl *BaseFD : Bases) 6863 BaseFD->addAttr(OMPDeclareVariantA); 6864 } 6865 6866 ExprResult Sema::ActOnOpenMPCall(ExprResult Call, Scope *Scope, 6867 SourceLocation LParenLoc, 6868 MultiExprArg ArgExprs, 6869 SourceLocation RParenLoc, Expr *ExecConfig) { 6870 // The common case is a regular call we do not want to specialize at all. Try 6871 // to make that case fast by bailing early. 6872 CallExpr *CE = dyn_cast<CallExpr>(Call.get()); 6873 if (!CE) 6874 return Call; 6875 6876 FunctionDecl *CalleeFnDecl = CE->getDirectCallee(); 6877 if (!CalleeFnDecl) 6878 return Call; 6879 6880 if (!CalleeFnDecl->hasAttr<OMPDeclareVariantAttr>()) 6881 return Call; 6882 6883 ASTContext &Context = getASTContext(); 6884 std::function<void(StringRef)> DiagUnknownTrait = [this, 6885 CE](StringRef ISATrait) { 6886 // TODO Track the selector locations in a way that is accessible here to 6887 // improve the diagnostic location. 6888 Diag(CE->getBeginLoc(), diag::warn_unknown_declare_variant_isa_trait) 6889 << ISATrait; 6890 }; 6891 TargetOMPContext OMPCtx(Context, std::move(DiagUnknownTrait), 6892 getCurFunctionDecl(), DSAStack->getConstructTraits()); 6893 6894 QualType CalleeFnType = CalleeFnDecl->getType(); 6895 6896 SmallVector<Expr *, 4> Exprs; 6897 SmallVector<VariantMatchInfo, 4> VMIs; 6898 while (CalleeFnDecl) { 6899 for (OMPDeclareVariantAttr *A : 6900 CalleeFnDecl->specific_attrs<OMPDeclareVariantAttr>()) { 6901 Expr *VariantRef = A->getVariantFuncRef(); 6902 6903 VariantMatchInfo VMI; 6904 OMPTraitInfo &TI = A->getTraitInfo(); 6905 TI.getAsVariantMatchInfo(Context, VMI); 6906 if (!isVariantApplicableInContext(VMI, OMPCtx, 6907 /* DeviceSetOnly */ false)) 6908 continue; 6909 6910 VMIs.push_back(VMI); 6911 Exprs.push_back(VariantRef); 6912 } 6913 6914 CalleeFnDecl = CalleeFnDecl->getPreviousDecl(); 6915 } 6916 6917 ExprResult NewCall; 6918 do { 6919 int BestIdx = getBestVariantMatchForContext(VMIs, OMPCtx); 6920 if (BestIdx < 0) 6921 return Call; 6922 Expr *BestExpr = cast<DeclRefExpr>(Exprs[BestIdx]); 6923 Decl *BestDecl = cast<DeclRefExpr>(BestExpr)->getDecl(); 6924 6925 { 6926 // Try to build a (member) call expression for the current best applicable 6927 // variant expression. We allow this to fail in which case we continue 6928 // with the next best variant expression. The fail case is part of the 6929 // implementation defined behavior in the OpenMP standard when it talks 6930 // about what differences in the function prototypes: "Any differences 6931 // that the specific OpenMP context requires in the prototype of the 6932 // variant from the base function prototype are implementation defined." 6933 // This wording is there to allow the specialized variant to have a 6934 // different type than the base function. This is intended and OK but if 6935 // we cannot create a call the difference is not in the "implementation 6936 // defined range" we allow. 6937 Sema::TentativeAnalysisScope Trap(*this); 6938 6939 if (auto *SpecializedMethod = dyn_cast<CXXMethodDecl>(BestDecl)) { 6940 auto *MemberCall = dyn_cast<CXXMemberCallExpr>(CE); 6941 BestExpr = MemberExpr::CreateImplicit( 6942 Context, MemberCall->getImplicitObjectArgument(), 6943 /* IsArrow */ false, SpecializedMethod, Context.BoundMemberTy, 6944 MemberCall->getValueKind(), MemberCall->getObjectKind()); 6945 } 6946 NewCall = BuildCallExpr(Scope, BestExpr, LParenLoc, ArgExprs, RParenLoc, 6947 ExecConfig); 6948 if (NewCall.isUsable()) { 6949 if (CallExpr *NCE = dyn_cast<CallExpr>(NewCall.get())) { 6950 FunctionDecl *NewCalleeFnDecl = NCE->getDirectCallee(); 6951 QualType NewType = Context.mergeFunctionTypes( 6952 CalleeFnType, NewCalleeFnDecl->getType(), 6953 /* OfBlockPointer */ false, 6954 /* Unqualified */ false, /* AllowCXX */ true); 6955 if (!NewType.isNull()) 6956 break; 6957 // Don't use the call if the function type was not compatible. 6958 NewCall = nullptr; 6959 } 6960 } 6961 } 6962 6963 VMIs.erase(VMIs.begin() + BestIdx); 6964 Exprs.erase(Exprs.begin() + BestIdx); 6965 } while (!VMIs.empty()); 6966 6967 if (!NewCall.isUsable()) 6968 return Call; 6969 return PseudoObjectExpr::Create(Context, CE, {NewCall.get()}, 0); 6970 } 6971 6972 Optional<std::pair<FunctionDecl *, Expr *>> 6973 Sema::checkOpenMPDeclareVariantFunction(Sema::DeclGroupPtrTy DG, 6974 Expr *VariantRef, OMPTraitInfo &TI, 6975 unsigned NumAppendArgs, 6976 SourceRange SR) { 6977 if (!DG || DG.get().isNull()) 6978 return None; 6979 6980 const int VariantId = 1; 6981 // Must be applied only to single decl. 6982 if (!DG.get().isSingleDecl()) { 6983 Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd_variant) 6984 << VariantId << SR; 6985 return None; 6986 } 6987 Decl *ADecl = DG.get().getSingleDecl(); 6988 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl)) 6989 ADecl = FTD->getTemplatedDecl(); 6990 6991 // Decl must be a function. 6992 auto *FD = dyn_cast<FunctionDecl>(ADecl); 6993 if (!FD) { 6994 Diag(ADecl->getLocation(), diag::err_omp_function_expected) 6995 << VariantId << SR; 6996 return None; 6997 } 6998 6999 auto &&HasMultiVersionAttributes = [](const FunctionDecl *FD) { 7000 return FD->hasAttrs() && 7001 (FD->hasAttr<CPUDispatchAttr>() || FD->hasAttr<CPUSpecificAttr>() || 7002 FD->hasAttr<TargetAttr>()); 7003 }; 7004 // OpenMP is not compatible with CPU-specific attributes. 7005 if (HasMultiVersionAttributes(FD)) { 7006 Diag(FD->getLocation(), diag::err_omp_declare_variant_incompat_attributes) 7007 << SR; 7008 return None; 7009 } 7010 7011 // Allow #pragma omp declare variant only if the function is not used. 7012 if (FD->isUsed(false)) 7013 Diag(SR.getBegin(), diag::warn_omp_declare_variant_after_used) 7014 << FD->getLocation(); 7015 7016 // Check if the function was emitted already. 7017 const FunctionDecl *Definition; 7018 if (!FD->isThisDeclarationADefinition() && FD->isDefined(Definition) && 7019 (LangOpts.EmitAllDecls || Context.DeclMustBeEmitted(Definition))) 7020 Diag(SR.getBegin(), diag::warn_omp_declare_variant_after_emitted) 7021 << FD->getLocation(); 7022 7023 // The VariantRef must point to function. 7024 if (!VariantRef) { 7025 Diag(SR.getBegin(), diag::err_omp_function_expected) << VariantId; 7026 return None; 7027 } 7028 7029 auto ShouldDelayChecks = [](Expr *&E, bool) { 7030 return E && (E->isTypeDependent() || E->isValueDependent() || 7031 E->containsUnexpandedParameterPack() || 7032 E->isInstantiationDependent()); 7033 }; 7034 // Do not check templates, wait until instantiation. 7035 if (FD->isDependentContext() || ShouldDelayChecks(VariantRef, false) || 7036 TI.anyScoreOrCondition(ShouldDelayChecks)) 7037 return std::make_pair(FD, VariantRef); 7038 7039 // Deal with non-constant score and user condition expressions. 7040 auto HandleNonConstantScoresAndConditions = [this](Expr *&E, 7041 bool IsScore) -> bool { 7042 if (!E || E->isIntegerConstantExpr(Context)) 7043 return false; 7044 7045 if (IsScore) { 7046 // We warn on non-constant scores and pretend they were not present. 7047 Diag(E->getExprLoc(), diag::warn_omp_declare_variant_score_not_constant) 7048 << E; 7049 E = nullptr; 7050 } else { 7051 // We could replace a non-constant user condition with "false" but we 7052 // will soon need to handle these anyway for the dynamic version of 7053 // OpenMP context selectors. 7054 Diag(E->getExprLoc(), 7055 diag::err_omp_declare_variant_user_condition_not_constant) 7056 << E; 7057 } 7058 return true; 7059 }; 7060 if (TI.anyScoreOrCondition(HandleNonConstantScoresAndConditions)) 7061 return None; 7062 7063 QualType AdjustedFnType = FD->getType(); 7064 if (NumAppendArgs) { 7065 const auto *PTy = AdjustedFnType->getAsAdjusted<FunctionProtoType>(); 7066 if (!PTy) { 7067 Diag(FD->getLocation(), diag::err_omp_declare_variant_prototype_required) 7068 << SR; 7069 return None; 7070 } 7071 // Adjust the function type to account for an extra omp_interop_t for each 7072 // specified in the append_args clause. 7073 const TypeDecl *TD = nullptr; 7074 LookupResult Result(*this, &Context.Idents.get("omp_interop_t"), 7075 SR.getBegin(), Sema::LookupOrdinaryName); 7076 if (LookupName(Result, getCurScope())) { 7077 NamedDecl *ND = Result.getFoundDecl(); 7078 TD = dyn_cast_or_null<TypeDecl>(ND); 7079 } 7080 if (!TD) { 7081 Diag(SR.getBegin(), diag::err_omp_interop_type_not_found) << SR; 7082 return None; 7083 } 7084 QualType InteropType = Context.getTypeDeclType(TD); 7085 if (PTy->isVariadic()) { 7086 Diag(FD->getLocation(), diag::err_omp_append_args_with_varargs) << SR; 7087 return None; 7088 } 7089 llvm::SmallVector<QualType, 8> Params; 7090 Params.append(PTy->param_type_begin(), PTy->param_type_end()); 7091 Params.insert(Params.end(), NumAppendArgs, InteropType); 7092 AdjustedFnType = Context.getFunctionType(PTy->getReturnType(), Params, 7093 PTy->getExtProtoInfo()); 7094 } 7095 7096 // Convert VariantRef expression to the type of the original function to 7097 // resolve possible conflicts. 7098 ExprResult VariantRefCast = VariantRef; 7099 if (LangOpts.CPlusPlus) { 7100 QualType FnPtrType; 7101 auto *Method = dyn_cast<CXXMethodDecl>(FD); 7102 if (Method && !Method->isStatic()) { 7103 const Type *ClassType = 7104 Context.getTypeDeclType(Method->getParent()).getTypePtr(); 7105 FnPtrType = Context.getMemberPointerType(AdjustedFnType, ClassType); 7106 ExprResult ER; 7107 { 7108 // Build adrr_of unary op to correctly handle type checks for member 7109 // functions. 7110 Sema::TentativeAnalysisScope Trap(*this); 7111 ER = CreateBuiltinUnaryOp(VariantRef->getBeginLoc(), UO_AddrOf, 7112 VariantRef); 7113 } 7114 if (!ER.isUsable()) { 7115 Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected) 7116 << VariantId << VariantRef->getSourceRange(); 7117 return None; 7118 } 7119 VariantRef = ER.get(); 7120 } else { 7121 FnPtrType = Context.getPointerType(AdjustedFnType); 7122 } 7123 QualType VarianPtrType = Context.getPointerType(VariantRef->getType()); 7124 if (VarianPtrType.getUnqualifiedType() != FnPtrType.getUnqualifiedType()) { 7125 ImplicitConversionSequence ICS = TryImplicitConversion( 7126 VariantRef, FnPtrType.getUnqualifiedType(), 7127 /*SuppressUserConversions=*/false, AllowedExplicit::None, 7128 /*InOverloadResolution=*/false, 7129 /*CStyle=*/false, 7130 /*AllowObjCWritebackConversion=*/false); 7131 if (ICS.isFailure()) { 7132 Diag(VariantRef->getExprLoc(), 7133 diag::err_omp_declare_variant_incompat_types) 7134 << VariantRef->getType() 7135 << ((Method && !Method->isStatic()) ? FnPtrType : FD->getType()) 7136 << (NumAppendArgs ? 1 : 0) << VariantRef->getSourceRange(); 7137 return None; 7138 } 7139 VariantRefCast = PerformImplicitConversion( 7140 VariantRef, FnPtrType.getUnqualifiedType(), AA_Converting); 7141 if (!VariantRefCast.isUsable()) 7142 return None; 7143 } 7144 // Drop previously built artificial addr_of unary op for member functions. 7145 if (Method && !Method->isStatic()) { 7146 Expr *PossibleAddrOfVariantRef = VariantRefCast.get(); 7147 if (auto *UO = dyn_cast<UnaryOperator>( 7148 PossibleAddrOfVariantRef->IgnoreImplicit())) 7149 VariantRefCast = UO->getSubExpr(); 7150 } 7151 } 7152 7153 ExprResult ER = CheckPlaceholderExpr(VariantRefCast.get()); 7154 if (!ER.isUsable() || 7155 !ER.get()->IgnoreParenImpCasts()->getType()->isFunctionType()) { 7156 Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected) 7157 << VariantId << VariantRef->getSourceRange(); 7158 return None; 7159 } 7160 7161 // The VariantRef must point to function. 7162 auto *DRE = dyn_cast<DeclRefExpr>(ER.get()->IgnoreParenImpCasts()); 7163 if (!DRE) { 7164 Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected) 7165 << VariantId << VariantRef->getSourceRange(); 7166 return None; 7167 } 7168 auto *NewFD = dyn_cast_or_null<FunctionDecl>(DRE->getDecl()); 7169 if (!NewFD) { 7170 Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected) 7171 << VariantId << VariantRef->getSourceRange(); 7172 return None; 7173 } 7174 7175 if (FD->getCanonicalDecl() == NewFD->getCanonicalDecl()) { 7176 Diag(VariantRef->getExprLoc(), 7177 diag::err_omp_declare_variant_same_base_function) 7178 << VariantRef->getSourceRange(); 7179 return None; 7180 } 7181 7182 // Check if function types are compatible in C. 7183 if (!LangOpts.CPlusPlus) { 7184 QualType NewType = 7185 Context.mergeFunctionTypes(AdjustedFnType, NewFD->getType()); 7186 if (NewType.isNull()) { 7187 Diag(VariantRef->getExprLoc(), 7188 diag::err_omp_declare_variant_incompat_types) 7189 << NewFD->getType() << FD->getType() << (NumAppendArgs ? 1 : 0) 7190 << VariantRef->getSourceRange(); 7191 return None; 7192 } 7193 if (NewType->isFunctionProtoType()) { 7194 if (FD->getType()->isFunctionNoProtoType()) 7195 setPrototype(*this, FD, NewFD, NewType); 7196 else if (NewFD->getType()->isFunctionNoProtoType()) 7197 setPrototype(*this, NewFD, FD, NewType); 7198 } 7199 } 7200 7201 // Check if variant function is not marked with declare variant directive. 7202 if (NewFD->hasAttrs() && NewFD->hasAttr<OMPDeclareVariantAttr>()) { 7203 Diag(VariantRef->getExprLoc(), 7204 diag::warn_omp_declare_variant_marked_as_declare_variant) 7205 << VariantRef->getSourceRange(); 7206 SourceRange SR = 7207 NewFD->specific_attr_begin<OMPDeclareVariantAttr>()->getRange(); 7208 Diag(SR.getBegin(), diag::note_omp_marked_declare_variant_here) << SR; 7209 return None; 7210 } 7211 7212 enum DoesntSupport { 7213 VirtFuncs = 1, 7214 Constructors = 3, 7215 Destructors = 4, 7216 DeletedFuncs = 5, 7217 DefaultedFuncs = 6, 7218 ConstexprFuncs = 7, 7219 ConstevalFuncs = 8, 7220 }; 7221 if (const auto *CXXFD = dyn_cast<CXXMethodDecl>(FD)) { 7222 if (CXXFD->isVirtual()) { 7223 Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support) 7224 << VirtFuncs; 7225 return None; 7226 } 7227 7228 if (isa<CXXConstructorDecl>(FD)) { 7229 Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support) 7230 << Constructors; 7231 return None; 7232 } 7233 7234 if (isa<CXXDestructorDecl>(FD)) { 7235 Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support) 7236 << Destructors; 7237 return None; 7238 } 7239 } 7240 7241 if (FD->isDeleted()) { 7242 Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support) 7243 << DeletedFuncs; 7244 return None; 7245 } 7246 7247 if (FD->isDefaulted()) { 7248 Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support) 7249 << DefaultedFuncs; 7250 return None; 7251 } 7252 7253 if (FD->isConstexpr()) { 7254 Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support) 7255 << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs); 7256 return None; 7257 } 7258 7259 // Check general compatibility. 7260 if (areMultiversionVariantFunctionsCompatible( 7261 FD, NewFD, PartialDiagnostic::NullDiagnostic(), 7262 PartialDiagnosticAt(SourceLocation(), 7263 PartialDiagnostic::NullDiagnostic()), 7264 PartialDiagnosticAt( 7265 VariantRef->getExprLoc(), 7266 PDiag(diag::err_omp_declare_variant_doesnt_support)), 7267 PartialDiagnosticAt(VariantRef->getExprLoc(), 7268 PDiag(diag::err_omp_declare_variant_diff) 7269 << FD->getLocation()), 7270 /*TemplatesSupported=*/true, /*ConstexprSupported=*/false, 7271 /*CLinkageMayDiffer=*/true)) 7272 return None; 7273 return std::make_pair(FD, cast<Expr>(DRE)); 7274 } 7275 7276 void Sema::ActOnOpenMPDeclareVariantDirective( 7277 FunctionDecl *FD, Expr *VariantRef, OMPTraitInfo &TI, 7278 ArrayRef<Expr *> AdjustArgsNothing, 7279 ArrayRef<Expr *> AdjustArgsNeedDevicePtr, 7280 ArrayRef<OMPDeclareVariantAttr::InteropType> AppendArgs, 7281 SourceLocation AdjustArgsLoc, SourceLocation AppendArgsLoc, 7282 SourceRange SR) { 7283 7284 // OpenMP 5.1 [2.3.5, declare variant directive, Restrictions] 7285 // An adjust_args clause or append_args clause can only be specified if the 7286 // dispatch selector of the construct selector set appears in the match 7287 // clause. 7288 7289 SmallVector<Expr *, 8> AllAdjustArgs; 7290 llvm::append_range(AllAdjustArgs, AdjustArgsNothing); 7291 llvm::append_range(AllAdjustArgs, AdjustArgsNeedDevicePtr); 7292 7293 if (!AllAdjustArgs.empty() || !AppendArgs.empty()) { 7294 VariantMatchInfo VMI; 7295 TI.getAsVariantMatchInfo(Context, VMI); 7296 if (!llvm::is_contained( 7297 VMI.ConstructTraits, 7298 llvm::omp::TraitProperty::construct_dispatch_dispatch)) { 7299 if (!AllAdjustArgs.empty()) 7300 Diag(AdjustArgsLoc, diag::err_omp_clause_requires_dispatch_construct) 7301 << getOpenMPClauseName(OMPC_adjust_args); 7302 if (!AppendArgs.empty()) 7303 Diag(AppendArgsLoc, diag::err_omp_clause_requires_dispatch_construct) 7304 << getOpenMPClauseName(OMPC_append_args); 7305 return; 7306 } 7307 } 7308 7309 // OpenMP 5.1 [2.3.5, declare variant directive, Restrictions] 7310 // Each argument can only appear in a single adjust_args clause for each 7311 // declare variant directive. 7312 llvm::SmallPtrSet<const VarDecl *, 4> AdjustVars; 7313 7314 for (Expr *E : AllAdjustArgs) { 7315 E = E->IgnoreParenImpCasts(); 7316 if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) { 7317 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) { 7318 const VarDecl *CanonPVD = PVD->getCanonicalDecl(); 7319 if (FD->getNumParams() > PVD->getFunctionScopeIndex() && 7320 FD->getParamDecl(PVD->getFunctionScopeIndex()) 7321 ->getCanonicalDecl() == CanonPVD) { 7322 // It's a parameter of the function, check duplicates. 7323 if (!AdjustVars.insert(CanonPVD).second) { 7324 Diag(DRE->getLocation(), diag::err_omp_adjust_arg_multiple_clauses) 7325 << PVD; 7326 return; 7327 } 7328 continue; 7329 } 7330 } 7331 } 7332 // Anything that is not a function parameter is an error. 7333 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause) << FD << 0; 7334 return; 7335 } 7336 7337 auto *NewAttr = OMPDeclareVariantAttr::CreateImplicit( 7338 Context, VariantRef, &TI, const_cast<Expr **>(AdjustArgsNothing.data()), 7339 AdjustArgsNothing.size(), 7340 const_cast<Expr **>(AdjustArgsNeedDevicePtr.data()), 7341 AdjustArgsNeedDevicePtr.size(), 7342 const_cast<OMPDeclareVariantAttr::InteropType *>(AppendArgs.data()), 7343 AppendArgs.size(), SR); 7344 FD->addAttr(NewAttr); 7345 } 7346 7347 StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses, 7348 Stmt *AStmt, 7349 SourceLocation StartLoc, 7350 SourceLocation EndLoc) { 7351 if (!AStmt) 7352 return StmtError(); 7353 7354 auto *CS = cast<CapturedStmt>(AStmt); 7355 // 1.2.2 OpenMP Language Terminology 7356 // Structured block - An executable statement with a single entry at the 7357 // top and a single exit at the bottom. 7358 // The point of exit cannot be a branch out of the structured block. 7359 // longjmp() and throw() must not violate the entry/exit criteria. 7360 CS->getCapturedDecl()->setNothrow(); 7361 7362 setFunctionHasBranchProtectedScope(); 7363 7364 return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt, 7365 DSAStack->getTaskgroupReductionRef(), 7366 DSAStack->isCancelRegion()); 7367 } 7368 7369 namespace { 7370 /// Iteration space of a single for loop. 7371 struct LoopIterationSpace final { 7372 /// True if the condition operator is the strict compare operator (<, > or 7373 /// !=). 7374 bool IsStrictCompare = false; 7375 /// Condition of the loop. 7376 Expr *PreCond = nullptr; 7377 /// This expression calculates the number of iterations in the loop. 7378 /// It is always possible to calculate it before starting the loop. 7379 Expr *NumIterations = nullptr; 7380 /// The loop counter variable. 7381 Expr *CounterVar = nullptr; 7382 /// Private loop counter variable. 7383 Expr *PrivateCounterVar = nullptr; 7384 /// This is initializer for the initial value of #CounterVar. 7385 Expr *CounterInit = nullptr; 7386 /// This is step for the #CounterVar used to generate its update: 7387 /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration. 7388 Expr *CounterStep = nullptr; 7389 /// Should step be subtracted? 7390 bool Subtract = false; 7391 /// Source range of the loop init. 7392 SourceRange InitSrcRange; 7393 /// Source range of the loop condition. 7394 SourceRange CondSrcRange; 7395 /// Source range of the loop increment. 7396 SourceRange IncSrcRange; 7397 /// Minimum value that can have the loop control variable. Used to support 7398 /// non-rectangular loops. Applied only for LCV with the non-iterator types, 7399 /// since only such variables can be used in non-loop invariant expressions. 7400 Expr *MinValue = nullptr; 7401 /// Maximum value that can have the loop control variable. Used to support 7402 /// non-rectangular loops. Applied only for LCV with the non-iterator type, 7403 /// since only such variables can be used in non-loop invariant expressions. 7404 Expr *MaxValue = nullptr; 7405 /// true, if the lower bound depends on the outer loop control var. 7406 bool IsNonRectangularLB = false; 7407 /// true, if the upper bound depends on the outer loop control var. 7408 bool IsNonRectangularUB = false; 7409 /// Index of the loop this loop depends on and forms non-rectangular loop 7410 /// nest. 7411 unsigned LoopDependentIdx = 0; 7412 /// Final condition for the non-rectangular loop nest support. It is used to 7413 /// check that the number of iterations for this particular counter must be 7414 /// finished. 7415 Expr *FinalCondition = nullptr; 7416 }; 7417 7418 /// Helper class for checking canonical form of the OpenMP loops and 7419 /// extracting iteration space of each loop in the loop nest, that will be used 7420 /// for IR generation. 7421 class OpenMPIterationSpaceChecker { 7422 /// Reference to Sema. 7423 Sema &SemaRef; 7424 /// Does the loop associated directive support non-rectangular loops? 7425 bool SupportsNonRectangular; 7426 /// Data-sharing stack. 7427 DSAStackTy &Stack; 7428 /// A location for diagnostics (when there is no some better location). 7429 SourceLocation DefaultLoc; 7430 /// A location for diagnostics (when increment is not compatible). 7431 SourceLocation ConditionLoc; 7432 /// A source location for referring to loop init later. 7433 SourceRange InitSrcRange; 7434 /// A source location for referring to condition later. 7435 SourceRange ConditionSrcRange; 7436 /// A source location for referring to increment later. 7437 SourceRange IncrementSrcRange; 7438 /// Loop variable. 7439 ValueDecl *LCDecl = nullptr; 7440 /// Reference to loop variable. 7441 Expr *LCRef = nullptr; 7442 /// Lower bound (initializer for the var). 7443 Expr *LB = nullptr; 7444 /// Upper bound. 7445 Expr *UB = nullptr; 7446 /// Loop step (increment). 7447 Expr *Step = nullptr; 7448 /// This flag is true when condition is one of: 7449 /// Var < UB 7450 /// Var <= UB 7451 /// UB > Var 7452 /// UB >= Var 7453 /// This will have no value when the condition is != 7454 llvm::Optional<bool> TestIsLessOp; 7455 /// This flag is true when condition is strict ( < or > ). 7456 bool TestIsStrictOp = false; 7457 /// This flag is true when step is subtracted on each iteration. 7458 bool SubtractStep = false; 7459 /// The outer loop counter this loop depends on (if any). 7460 const ValueDecl *DepDecl = nullptr; 7461 /// Contains number of loop (starts from 1) on which loop counter init 7462 /// expression of this loop depends on. 7463 Optional<unsigned> InitDependOnLC; 7464 /// Contains number of loop (starts from 1) on which loop counter condition 7465 /// expression of this loop depends on. 7466 Optional<unsigned> CondDependOnLC; 7467 /// Checks if the provide statement depends on the loop counter. 7468 Optional<unsigned> doesDependOnLoopCounter(const Stmt *S, bool IsInitializer); 7469 /// Original condition required for checking of the exit condition for 7470 /// non-rectangular loop. 7471 Expr *Condition = nullptr; 7472 7473 public: 7474 OpenMPIterationSpaceChecker(Sema &SemaRef, bool SupportsNonRectangular, 7475 DSAStackTy &Stack, SourceLocation DefaultLoc) 7476 : SemaRef(SemaRef), SupportsNonRectangular(SupportsNonRectangular), 7477 Stack(Stack), DefaultLoc(DefaultLoc), ConditionLoc(DefaultLoc) {} 7478 /// Check init-expr for canonical loop form and save loop counter 7479 /// variable - #Var and its initialization value - #LB. 7480 bool checkAndSetInit(Stmt *S, bool EmitDiags = true); 7481 /// Check test-expr for canonical form, save upper-bound (#UB), flags 7482 /// for less/greater and for strict/non-strict comparison. 7483 bool checkAndSetCond(Expr *S); 7484 /// Check incr-expr for canonical loop form and return true if it 7485 /// does not conform, otherwise save loop step (#Step). 7486 bool checkAndSetInc(Expr *S); 7487 /// Return the loop counter variable. 7488 ValueDecl *getLoopDecl() const { return LCDecl; } 7489 /// Return the reference expression to loop counter variable. 7490 Expr *getLoopDeclRefExpr() const { return LCRef; } 7491 /// Source range of the loop init. 7492 SourceRange getInitSrcRange() const { return InitSrcRange; } 7493 /// Source range of the loop condition. 7494 SourceRange getConditionSrcRange() const { return ConditionSrcRange; } 7495 /// Source range of the loop increment. 7496 SourceRange getIncrementSrcRange() const { return IncrementSrcRange; } 7497 /// True if the step should be subtracted. 7498 bool shouldSubtractStep() const { return SubtractStep; } 7499 /// True, if the compare operator is strict (<, > or !=). 7500 bool isStrictTestOp() const { return TestIsStrictOp; } 7501 /// Build the expression to calculate the number of iterations. 7502 Expr *buildNumIterations( 7503 Scope *S, ArrayRef<LoopIterationSpace> ResultIterSpaces, bool LimitedType, 7504 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const; 7505 /// Build the precondition expression for the loops. 7506 Expr * 7507 buildPreCond(Scope *S, Expr *Cond, 7508 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const; 7509 /// Build reference expression to the counter be used for codegen. 7510 DeclRefExpr * 7511 buildCounterVar(llvm::MapVector<const Expr *, DeclRefExpr *> &Captures, 7512 DSAStackTy &DSA) const; 7513 /// Build reference expression to the private counter be used for 7514 /// codegen. 7515 Expr *buildPrivateCounterVar() const; 7516 /// Build initialization of the counter be used for codegen. 7517 Expr *buildCounterInit() const; 7518 /// Build step of the counter be used for codegen. 7519 Expr *buildCounterStep() const; 7520 /// Build loop data with counter value for depend clauses in ordered 7521 /// directives. 7522 Expr * 7523 buildOrderedLoopData(Scope *S, Expr *Counter, 7524 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures, 7525 SourceLocation Loc, Expr *Inc = nullptr, 7526 OverloadedOperatorKind OOK = OO_Amp); 7527 /// Builds the minimum value for the loop counter. 7528 std::pair<Expr *, Expr *> buildMinMaxValues( 7529 Scope *S, llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const; 7530 /// Builds final condition for the non-rectangular loops. 7531 Expr *buildFinalCondition(Scope *S) const; 7532 /// Return true if any expression is dependent. 7533 bool dependent() const; 7534 /// Returns true if the initializer forms non-rectangular loop. 7535 bool doesInitDependOnLC() const { return InitDependOnLC.hasValue(); } 7536 /// Returns true if the condition forms non-rectangular loop. 7537 bool doesCondDependOnLC() const { return CondDependOnLC.hasValue(); } 7538 /// Returns index of the loop we depend on (starting from 1), or 0 otherwise. 7539 unsigned getLoopDependentIdx() const { 7540 return InitDependOnLC.getValueOr(CondDependOnLC.getValueOr(0)); 7541 } 7542 7543 private: 7544 /// Check the right-hand side of an assignment in the increment 7545 /// expression. 7546 bool checkAndSetIncRHS(Expr *RHS); 7547 /// Helper to set loop counter variable and its initializer. 7548 bool setLCDeclAndLB(ValueDecl *NewLCDecl, Expr *NewDeclRefExpr, Expr *NewLB, 7549 bool EmitDiags); 7550 /// Helper to set upper bound. 7551 bool setUB(Expr *NewUB, llvm::Optional<bool> LessOp, bool StrictOp, 7552 SourceRange SR, SourceLocation SL); 7553 /// Helper to set loop increment. 7554 bool setStep(Expr *NewStep, bool Subtract); 7555 }; 7556 7557 bool OpenMPIterationSpaceChecker::dependent() const { 7558 if (!LCDecl) { 7559 assert(!LB && !UB && !Step); 7560 return false; 7561 } 7562 return LCDecl->getType()->isDependentType() || 7563 (LB && LB->isValueDependent()) || (UB && UB->isValueDependent()) || 7564 (Step && Step->isValueDependent()); 7565 } 7566 7567 bool OpenMPIterationSpaceChecker::setLCDeclAndLB(ValueDecl *NewLCDecl, 7568 Expr *NewLCRefExpr, 7569 Expr *NewLB, bool EmitDiags) { 7570 // State consistency checking to ensure correct usage. 7571 assert(LCDecl == nullptr && LB == nullptr && LCRef == nullptr && 7572 UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp); 7573 if (!NewLCDecl || !NewLB || NewLB->containsErrors()) 7574 return true; 7575 LCDecl = getCanonicalDecl(NewLCDecl); 7576 LCRef = NewLCRefExpr; 7577 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB)) 7578 if (const CXXConstructorDecl *Ctor = CE->getConstructor()) 7579 if ((Ctor->isCopyOrMoveConstructor() || 7580 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) && 7581 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr) 7582 NewLB = CE->getArg(0)->IgnoreParenImpCasts(); 7583 LB = NewLB; 7584 if (EmitDiags) 7585 InitDependOnLC = doesDependOnLoopCounter(LB, /*IsInitializer=*/true); 7586 return false; 7587 } 7588 7589 bool OpenMPIterationSpaceChecker::setUB(Expr *NewUB, 7590 llvm::Optional<bool> LessOp, 7591 bool StrictOp, SourceRange SR, 7592 SourceLocation SL) { 7593 // State consistency checking to ensure correct usage. 7594 assert(LCDecl != nullptr && LB != nullptr && UB == nullptr && 7595 Step == nullptr && !TestIsLessOp && !TestIsStrictOp); 7596 if (!NewUB || NewUB->containsErrors()) 7597 return true; 7598 UB = NewUB; 7599 if (LessOp) 7600 TestIsLessOp = LessOp; 7601 TestIsStrictOp = StrictOp; 7602 ConditionSrcRange = SR; 7603 ConditionLoc = SL; 7604 CondDependOnLC = doesDependOnLoopCounter(UB, /*IsInitializer=*/false); 7605 return false; 7606 } 7607 7608 bool OpenMPIterationSpaceChecker::setStep(Expr *NewStep, bool Subtract) { 7609 // State consistency checking to ensure correct usage. 7610 assert(LCDecl != nullptr && LB != nullptr && Step == nullptr); 7611 if (!NewStep || NewStep->containsErrors()) 7612 return true; 7613 if (!NewStep->isValueDependent()) { 7614 // Check that the step is integer expression. 7615 SourceLocation StepLoc = NewStep->getBeginLoc(); 7616 ExprResult Val = SemaRef.PerformOpenMPImplicitIntegerConversion( 7617 StepLoc, getExprAsWritten(NewStep)); 7618 if (Val.isInvalid()) 7619 return true; 7620 NewStep = Val.get(); 7621 7622 // OpenMP [2.6, Canonical Loop Form, Restrictions] 7623 // If test-expr is of form var relational-op b and relational-op is < or 7624 // <= then incr-expr must cause var to increase on each iteration of the 7625 // loop. If test-expr is of form var relational-op b and relational-op is 7626 // > or >= then incr-expr must cause var to decrease on each iteration of 7627 // the loop. 7628 // If test-expr is of form b relational-op var and relational-op is < or 7629 // <= then incr-expr must cause var to decrease on each iteration of the 7630 // loop. If test-expr is of form b relational-op var and relational-op is 7631 // > or >= then incr-expr must cause var to increase on each iteration of 7632 // the loop. 7633 Optional<llvm::APSInt> Result = 7634 NewStep->getIntegerConstantExpr(SemaRef.Context); 7635 bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation(); 7636 bool IsConstNeg = 7637 Result && Result->isSigned() && (Subtract != Result->isNegative()); 7638 bool IsConstPos = 7639 Result && Result->isSigned() && (Subtract == Result->isNegative()); 7640 bool IsConstZero = Result && !Result->getBoolValue(); 7641 7642 // != with increment is treated as <; != with decrement is treated as > 7643 if (!TestIsLessOp.hasValue()) 7644 TestIsLessOp = IsConstPos || (IsUnsigned && !Subtract); 7645 if (UB && 7646 (IsConstZero || (TestIsLessOp.getValue() 7647 ? (IsConstNeg || (IsUnsigned && Subtract)) 7648 : (IsConstPos || (IsUnsigned && !Subtract))))) { 7649 SemaRef.Diag(NewStep->getExprLoc(), 7650 diag::err_omp_loop_incr_not_compatible) 7651 << LCDecl << TestIsLessOp.getValue() << NewStep->getSourceRange(); 7652 SemaRef.Diag(ConditionLoc, 7653 diag::note_omp_loop_cond_requres_compatible_incr) 7654 << TestIsLessOp.getValue() << ConditionSrcRange; 7655 return true; 7656 } 7657 if (TestIsLessOp.getValue() == Subtract) { 7658 NewStep = 7659 SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus, NewStep) 7660 .get(); 7661 Subtract = !Subtract; 7662 } 7663 } 7664 7665 Step = NewStep; 7666 SubtractStep = Subtract; 7667 return false; 7668 } 7669 7670 namespace { 7671 /// Checker for the non-rectangular loops. Checks if the initializer or 7672 /// condition expression references loop counter variable. 7673 class LoopCounterRefChecker final 7674 : public ConstStmtVisitor<LoopCounterRefChecker, bool> { 7675 Sema &SemaRef; 7676 DSAStackTy &Stack; 7677 const ValueDecl *CurLCDecl = nullptr; 7678 const ValueDecl *DepDecl = nullptr; 7679 const ValueDecl *PrevDepDecl = nullptr; 7680 bool IsInitializer = true; 7681 bool SupportsNonRectangular; 7682 unsigned BaseLoopId = 0; 7683 bool checkDecl(const Expr *E, const ValueDecl *VD) { 7684 if (getCanonicalDecl(VD) == getCanonicalDecl(CurLCDecl)) { 7685 SemaRef.Diag(E->getExprLoc(), diag::err_omp_stmt_depends_on_loop_counter) 7686 << (IsInitializer ? 0 : 1); 7687 return false; 7688 } 7689 const auto &&Data = Stack.isLoopControlVariable(VD); 7690 // OpenMP, 2.9.1 Canonical Loop Form, Restrictions. 7691 // The type of the loop iterator on which we depend may not have a random 7692 // access iterator type. 7693 if (Data.first && VD->getType()->isRecordType()) { 7694 SmallString<128> Name; 7695 llvm::raw_svector_ostream OS(Name); 7696 VD->getNameForDiagnostic(OS, SemaRef.getPrintingPolicy(), 7697 /*Qualified=*/true); 7698 SemaRef.Diag(E->getExprLoc(), 7699 diag::err_omp_wrong_dependency_iterator_type) 7700 << OS.str(); 7701 SemaRef.Diag(VD->getLocation(), diag::note_previous_decl) << VD; 7702 return false; 7703 } 7704 if (Data.first && !SupportsNonRectangular) { 7705 SemaRef.Diag(E->getExprLoc(), diag::err_omp_invariant_dependency); 7706 return false; 7707 } 7708 if (Data.first && 7709 (DepDecl || (PrevDepDecl && 7710 getCanonicalDecl(VD) != getCanonicalDecl(PrevDepDecl)))) { 7711 if (!DepDecl && PrevDepDecl) 7712 DepDecl = PrevDepDecl; 7713 SmallString<128> Name; 7714 llvm::raw_svector_ostream OS(Name); 7715 DepDecl->getNameForDiagnostic(OS, SemaRef.getPrintingPolicy(), 7716 /*Qualified=*/true); 7717 SemaRef.Diag(E->getExprLoc(), 7718 diag::err_omp_invariant_or_linear_dependency) 7719 << OS.str(); 7720 return false; 7721 } 7722 if (Data.first) { 7723 DepDecl = VD; 7724 BaseLoopId = Data.first; 7725 } 7726 return Data.first; 7727 } 7728 7729 public: 7730 bool VisitDeclRefExpr(const DeclRefExpr *E) { 7731 const ValueDecl *VD = E->getDecl(); 7732 if (isa<VarDecl>(VD)) 7733 return checkDecl(E, VD); 7734 return false; 7735 } 7736 bool VisitMemberExpr(const MemberExpr *E) { 7737 if (isa<CXXThisExpr>(E->getBase()->IgnoreParens())) { 7738 const ValueDecl *VD = E->getMemberDecl(); 7739 if (isa<VarDecl>(VD) || isa<FieldDecl>(VD)) 7740 return checkDecl(E, VD); 7741 } 7742 return false; 7743 } 7744 bool VisitStmt(const Stmt *S) { 7745 bool Res = false; 7746 for (const Stmt *Child : S->children()) 7747 Res = (Child && Visit(Child)) || Res; 7748 return Res; 7749 } 7750 explicit LoopCounterRefChecker(Sema &SemaRef, DSAStackTy &Stack, 7751 const ValueDecl *CurLCDecl, bool IsInitializer, 7752 const ValueDecl *PrevDepDecl = nullptr, 7753 bool SupportsNonRectangular = true) 7754 : SemaRef(SemaRef), Stack(Stack), CurLCDecl(CurLCDecl), 7755 PrevDepDecl(PrevDepDecl), IsInitializer(IsInitializer), 7756 SupportsNonRectangular(SupportsNonRectangular) {} 7757 unsigned getBaseLoopId() const { 7758 assert(CurLCDecl && "Expected loop dependency."); 7759 return BaseLoopId; 7760 } 7761 const ValueDecl *getDepDecl() const { 7762 assert(CurLCDecl && "Expected loop dependency."); 7763 return DepDecl; 7764 } 7765 }; 7766 } // namespace 7767 7768 Optional<unsigned> 7769 OpenMPIterationSpaceChecker::doesDependOnLoopCounter(const Stmt *S, 7770 bool IsInitializer) { 7771 // Check for the non-rectangular loops. 7772 LoopCounterRefChecker LoopStmtChecker(SemaRef, Stack, LCDecl, IsInitializer, 7773 DepDecl, SupportsNonRectangular); 7774 if (LoopStmtChecker.Visit(S)) { 7775 DepDecl = LoopStmtChecker.getDepDecl(); 7776 return LoopStmtChecker.getBaseLoopId(); 7777 } 7778 return llvm::None; 7779 } 7780 7781 bool OpenMPIterationSpaceChecker::checkAndSetInit(Stmt *S, bool EmitDiags) { 7782 // Check init-expr for canonical loop form and save loop counter 7783 // variable - #Var and its initialization value - #LB. 7784 // OpenMP [2.6] Canonical loop form. init-expr may be one of the following: 7785 // var = lb 7786 // integer-type var = lb 7787 // random-access-iterator-type var = lb 7788 // pointer-type var = lb 7789 // 7790 if (!S) { 7791 if (EmitDiags) { 7792 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init); 7793 } 7794 return true; 7795 } 7796 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S)) 7797 if (!ExprTemp->cleanupsHaveSideEffects()) 7798 S = ExprTemp->getSubExpr(); 7799 7800 InitSrcRange = S->getSourceRange(); 7801 if (Expr *E = dyn_cast<Expr>(S)) 7802 S = E->IgnoreParens(); 7803 if (auto *BO = dyn_cast<BinaryOperator>(S)) { 7804 if (BO->getOpcode() == BO_Assign) { 7805 Expr *LHS = BO->getLHS()->IgnoreParens(); 7806 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) { 7807 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl())) 7808 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit()))) 7809 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(), 7810 EmitDiags); 7811 return setLCDeclAndLB(DRE->getDecl(), DRE, BO->getRHS(), EmitDiags); 7812 } 7813 if (auto *ME = dyn_cast<MemberExpr>(LHS)) { 7814 if (ME->isArrow() && 7815 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts())) 7816 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(), 7817 EmitDiags); 7818 } 7819 } 7820 } else if (auto *DS = dyn_cast<DeclStmt>(S)) { 7821 if (DS->isSingleDecl()) { 7822 if (auto *Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) { 7823 if (Var->hasInit() && !Var->getType()->isReferenceType()) { 7824 // Accept non-canonical init form here but emit ext. warning. 7825 if (Var->getInitStyle() != VarDecl::CInit && EmitDiags) 7826 SemaRef.Diag(S->getBeginLoc(), 7827 diag::ext_omp_loop_not_canonical_init) 7828 << S->getSourceRange(); 7829 return setLCDeclAndLB( 7830 Var, 7831 buildDeclRefExpr(SemaRef, Var, 7832 Var->getType().getNonReferenceType(), 7833 DS->getBeginLoc()), 7834 Var->getInit(), EmitDiags); 7835 } 7836 } 7837 } 7838 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) { 7839 if (CE->getOperator() == OO_Equal) { 7840 Expr *LHS = CE->getArg(0); 7841 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) { 7842 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl())) 7843 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit()))) 7844 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(), 7845 EmitDiags); 7846 return setLCDeclAndLB(DRE->getDecl(), DRE, CE->getArg(1), EmitDiags); 7847 } 7848 if (auto *ME = dyn_cast<MemberExpr>(LHS)) { 7849 if (ME->isArrow() && 7850 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts())) 7851 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(), 7852 EmitDiags); 7853 } 7854 } 7855 } 7856 7857 if (dependent() || SemaRef.CurContext->isDependentContext()) 7858 return false; 7859 if (EmitDiags) { 7860 SemaRef.Diag(S->getBeginLoc(), diag::err_omp_loop_not_canonical_init) 7861 << S->getSourceRange(); 7862 } 7863 return true; 7864 } 7865 7866 /// Ignore parenthesizes, implicit casts, copy constructor and return the 7867 /// variable (which may be the loop variable) if possible. 7868 static const ValueDecl *getInitLCDecl(const Expr *E) { 7869 if (!E) 7870 return nullptr; 7871 E = getExprAsWritten(E); 7872 if (const auto *CE = dyn_cast_or_null<CXXConstructExpr>(E)) 7873 if (const CXXConstructorDecl *Ctor = CE->getConstructor()) 7874 if ((Ctor->isCopyOrMoveConstructor() || 7875 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) && 7876 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr) 7877 E = CE->getArg(0)->IgnoreParenImpCasts(); 7878 if (const auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) { 7879 if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) 7880 return getCanonicalDecl(VD); 7881 } 7882 if (const auto *ME = dyn_cast_or_null<MemberExpr>(E)) 7883 if (ME->isArrow() && isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts())) 7884 return getCanonicalDecl(ME->getMemberDecl()); 7885 return nullptr; 7886 } 7887 7888 bool OpenMPIterationSpaceChecker::checkAndSetCond(Expr *S) { 7889 // Check test-expr for canonical form, save upper-bound UB, flags for 7890 // less/greater and for strict/non-strict comparison. 7891 // OpenMP [2.9] Canonical loop form. Test-expr may be one of the following: 7892 // var relational-op b 7893 // b relational-op var 7894 // 7895 bool IneqCondIsCanonical = SemaRef.getLangOpts().OpenMP >= 50; 7896 if (!S) { 7897 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond) 7898 << (IneqCondIsCanonical ? 1 : 0) << LCDecl; 7899 return true; 7900 } 7901 Condition = S; 7902 S = getExprAsWritten(S); 7903 SourceLocation CondLoc = S->getBeginLoc(); 7904 auto &&CheckAndSetCond = [this, IneqCondIsCanonical]( 7905 BinaryOperatorKind Opcode, const Expr *LHS, 7906 const Expr *RHS, SourceRange SR, 7907 SourceLocation OpLoc) -> llvm::Optional<bool> { 7908 if (BinaryOperator::isRelationalOp(Opcode)) { 7909 if (getInitLCDecl(LHS) == LCDecl) 7910 return setUB(const_cast<Expr *>(RHS), 7911 (Opcode == BO_LT || Opcode == BO_LE), 7912 (Opcode == BO_LT || Opcode == BO_GT), SR, OpLoc); 7913 if (getInitLCDecl(RHS) == LCDecl) 7914 return setUB(const_cast<Expr *>(LHS), 7915 (Opcode == BO_GT || Opcode == BO_GE), 7916 (Opcode == BO_LT || Opcode == BO_GT), SR, OpLoc); 7917 } else if (IneqCondIsCanonical && Opcode == BO_NE) { 7918 return setUB(const_cast<Expr *>(getInitLCDecl(LHS) == LCDecl ? RHS : LHS), 7919 /*LessOp=*/llvm::None, 7920 /*StrictOp=*/true, SR, OpLoc); 7921 } 7922 return llvm::None; 7923 }; 7924 llvm::Optional<bool> Res; 7925 if (auto *RBO = dyn_cast<CXXRewrittenBinaryOperator>(S)) { 7926 CXXRewrittenBinaryOperator::DecomposedForm DF = RBO->getDecomposedForm(); 7927 Res = CheckAndSetCond(DF.Opcode, DF.LHS, DF.RHS, RBO->getSourceRange(), 7928 RBO->getOperatorLoc()); 7929 } else if (auto *BO = dyn_cast<BinaryOperator>(S)) { 7930 Res = CheckAndSetCond(BO->getOpcode(), BO->getLHS(), BO->getRHS(), 7931 BO->getSourceRange(), BO->getOperatorLoc()); 7932 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) { 7933 if (CE->getNumArgs() == 2) { 7934 Res = CheckAndSetCond( 7935 BinaryOperator::getOverloadedOpcode(CE->getOperator()), CE->getArg(0), 7936 CE->getArg(1), CE->getSourceRange(), CE->getOperatorLoc()); 7937 } 7938 } 7939 if (Res.hasValue()) 7940 return *Res; 7941 if (dependent() || SemaRef.CurContext->isDependentContext()) 7942 return false; 7943 SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond) 7944 << (IneqCondIsCanonical ? 1 : 0) << S->getSourceRange() << LCDecl; 7945 return true; 7946 } 7947 7948 bool OpenMPIterationSpaceChecker::checkAndSetIncRHS(Expr *RHS) { 7949 // RHS of canonical loop form increment can be: 7950 // var + incr 7951 // incr + var 7952 // var - incr 7953 // 7954 RHS = RHS->IgnoreParenImpCasts(); 7955 if (auto *BO = dyn_cast<BinaryOperator>(RHS)) { 7956 if (BO->isAdditiveOp()) { 7957 bool IsAdd = BO->getOpcode() == BO_Add; 7958 if (getInitLCDecl(BO->getLHS()) == LCDecl) 7959 return setStep(BO->getRHS(), !IsAdd); 7960 if (IsAdd && getInitLCDecl(BO->getRHS()) == LCDecl) 7961 return setStep(BO->getLHS(), /*Subtract=*/false); 7962 } 7963 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(RHS)) { 7964 bool IsAdd = CE->getOperator() == OO_Plus; 7965 if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) { 7966 if (getInitLCDecl(CE->getArg(0)) == LCDecl) 7967 return setStep(CE->getArg(1), !IsAdd); 7968 if (IsAdd && getInitLCDecl(CE->getArg(1)) == LCDecl) 7969 return setStep(CE->getArg(0), /*Subtract=*/false); 7970 } 7971 } 7972 if (dependent() || SemaRef.CurContext->isDependentContext()) 7973 return false; 7974 SemaRef.Diag(RHS->getBeginLoc(), diag::err_omp_loop_not_canonical_incr) 7975 << RHS->getSourceRange() << LCDecl; 7976 return true; 7977 } 7978 7979 bool OpenMPIterationSpaceChecker::checkAndSetInc(Expr *S) { 7980 // Check incr-expr for canonical loop form and return true if it 7981 // does not conform. 7982 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following: 7983 // ++var 7984 // var++ 7985 // --var 7986 // var-- 7987 // var += incr 7988 // var -= incr 7989 // var = var + incr 7990 // var = incr + var 7991 // var = var - incr 7992 // 7993 if (!S) { 7994 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << LCDecl; 7995 return true; 7996 } 7997 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S)) 7998 if (!ExprTemp->cleanupsHaveSideEffects()) 7999 S = ExprTemp->getSubExpr(); 8000 8001 IncrementSrcRange = S->getSourceRange(); 8002 S = S->IgnoreParens(); 8003 if (auto *UO = dyn_cast<UnaryOperator>(S)) { 8004 if (UO->isIncrementDecrementOp() && 8005 getInitLCDecl(UO->getSubExpr()) == LCDecl) 8006 return setStep(SemaRef 8007 .ActOnIntegerConstant(UO->getBeginLoc(), 8008 (UO->isDecrementOp() ? -1 : 1)) 8009 .get(), 8010 /*Subtract=*/false); 8011 } else if (auto *BO = dyn_cast<BinaryOperator>(S)) { 8012 switch (BO->getOpcode()) { 8013 case BO_AddAssign: 8014 case BO_SubAssign: 8015 if (getInitLCDecl(BO->getLHS()) == LCDecl) 8016 return setStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign); 8017 break; 8018 case BO_Assign: 8019 if (getInitLCDecl(BO->getLHS()) == LCDecl) 8020 return checkAndSetIncRHS(BO->getRHS()); 8021 break; 8022 default: 8023 break; 8024 } 8025 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) { 8026 switch (CE->getOperator()) { 8027 case OO_PlusPlus: 8028 case OO_MinusMinus: 8029 if (getInitLCDecl(CE->getArg(0)) == LCDecl) 8030 return setStep(SemaRef 8031 .ActOnIntegerConstant( 8032 CE->getBeginLoc(), 8033 ((CE->getOperator() == OO_MinusMinus) ? -1 : 1)) 8034 .get(), 8035 /*Subtract=*/false); 8036 break; 8037 case OO_PlusEqual: 8038 case OO_MinusEqual: 8039 if (getInitLCDecl(CE->getArg(0)) == LCDecl) 8040 return setStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual); 8041 break; 8042 case OO_Equal: 8043 if (getInitLCDecl(CE->getArg(0)) == LCDecl) 8044 return checkAndSetIncRHS(CE->getArg(1)); 8045 break; 8046 default: 8047 break; 8048 } 8049 } 8050 if (dependent() || SemaRef.CurContext->isDependentContext()) 8051 return false; 8052 SemaRef.Diag(S->getBeginLoc(), diag::err_omp_loop_not_canonical_incr) 8053 << S->getSourceRange() << LCDecl; 8054 return true; 8055 } 8056 8057 static ExprResult 8058 tryBuildCapture(Sema &SemaRef, Expr *Capture, 8059 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) { 8060 if (SemaRef.CurContext->isDependentContext() || Capture->containsErrors()) 8061 return Capture; 8062 if (Capture->isEvaluatable(SemaRef.Context, Expr::SE_AllowSideEffects)) 8063 return SemaRef.PerformImplicitConversion( 8064 Capture->IgnoreImpCasts(), Capture->getType(), Sema::AA_Converting, 8065 /*AllowExplicit=*/true); 8066 auto I = Captures.find(Capture); 8067 if (I != Captures.end()) 8068 return buildCapture(SemaRef, Capture, I->second); 8069 DeclRefExpr *Ref = nullptr; 8070 ExprResult Res = buildCapture(SemaRef, Capture, Ref); 8071 Captures[Capture] = Ref; 8072 return Res; 8073 } 8074 8075 /// Calculate number of iterations, transforming to unsigned, if number of 8076 /// iterations may be larger than the original type. 8077 static Expr * 8078 calculateNumIters(Sema &SemaRef, Scope *S, SourceLocation DefaultLoc, 8079 Expr *Lower, Expr *Upper, Expr *Step, QualType LCTy, 8080 bool TestIsStrictOp, bool RoundToStep, 8081 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) { 8082 ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures); 8083 if (!NewStep.isUsable()) 8084 return nullptr; 8085 llvm::APSInt LRes, SRes; 8086 bool IsLowerConst = false, IsStepConst = false; 8087 if (Optional<llvm::APSInt> Res = 8088 Lower->getIntegerConstantExpr(SemaRef.Context)) { 8089 LRes = *Res; 8090 IsLowerConst = true; 8091 } 8092 if (Optional<llvm::APSInt> Res = 8093 Step->getIntegerConstantExpr(SemaRef.Context)) { 8094 SRes = *Res; 8095 IsStepConst = true; 8096 } 8097 bool NoNeedToConvert = IsLowerConst && !RoundToStep && 8098 ((!TestIsStrictOp && LRes.isNonNegative()) || 8099 (TestIsStrictOp && LRes.isStrictlyPositive())); 8100 bool NeedToReorganize = false; 8101 // Check if any subexpressions in Lower -Step [+ 1] lead to overflow. 8102 if (!NoNeedToConvert && IsLowerConst && 8103 (TestIsStrictOp || (RoundToStep && IsStepConst))) { 8104 NoNeedToConvert = true; 8105 if (RoundToStep) { 8106 unsigned BW = LRes.getBitWidth() > SRes.getBitWidth() 8107 ? LRes.getBitWidth() 8108 : SRes.getBitWidth(); 8109 LRes = LRes.extend(BW + 1); 8110 LRes.setIsSigned(true); 8111 SRes = SRes.extend(BW + 1); 8112 SRes.setIsSigned(true); 8113 LRes -= SRes; 8114 NoNeedToConvert = LRes.trunc(BW).extend(BW + 1) == LRes; 8115 LRes = LRes.trunc(BW); 8116 } 8117 if (TestIsStrictOp) { 8118 unsigned BW = LRes.getBitWidth(); 8119 LRes = LRes.extend(BW + 1); 8120 LRes.setIsSigned(true); 8121 ++LRes; 8122 NoNeedToConvert = 8123 NoNeedToConvert && LRes.trunc(BW).extend(BW + 1) == LRes; 8124 // truncate to the original bitwidth. 8125 LRes = LRes.trunc(BW); 8126 } 8127 NeedToReorganize = NoNeedToConvert; 8128 } 8129 llvm::APSInt URes; 8130 bool IsUpperConst = false; 8131 if (Optional<llvm::APSInt> Res = 8132 Upper->getIntegerConstantExpr(SemaRef.Context)) { 8133 URes = *Res; 8134 IsUpperConst = true; 8135 } 8136 if (NoNeedToConvert && IsLowerConst && IsUpperConst && 8137 (!RoundToStep || IsStepConst)) { 8138 unsigned BW = LRes.getBitWidth() > URes.getBitWidth() ? LRes.getBitWidth() 8139 : URes.getBitWidth(); 8140 LRes = LRes.extend(BW + 1); 8141 LRes.setIsSigned(true); 8142 URes = URes.extend(BW + 1); 8143 URes.setIsSigned(true); 8144 URes -= LRes; 8145 NoNeedToConvert = URes.trunc(BW).extend(BW + 1) == URes; 8146 NeedToReorganize = NoNeedToConvert; 8147 } 8148 // If the boundaries are not constant or (Lower - Step [+ 1]) is not constant 8149 // or less than zero (Upper - (Lower - Step [+ 1]) may overflow) - promote to 8150 // unsigned. 8151 if ((!NoNeedToConvert || (LRes.isNegative() && !IsUpperConst)) && 8152 !LCTy->isDependentType() && LCTy->isIntegerType()) { 8153 QualType LowerTy = Lower->getType(); 8154 QualType UpperTy = Upper->getType(); 8155 uint64_t LowerSize = SemaRef.Context.getTypeSize(LowerTy); 8156 uint64_t UpperSize = SemaRef.Context.getTypeSize(UpperTy); 8157 if ((LowerSize <= UpperSize && UpperTy->hasSignedIntegerRepresentation()) || 8158 (LowerSize > UpperSize && LowerTy->hasSignedIntegerRepresentation())) { 8159 QualType CastType = SemaRef.Context.getIntTypeForBitwidth( 8160 LowerSize > UpperSize ? LowerSize : UpperSize, /*Signed=*/0); 8161 Upper = 8162 SemaRef 8163 .PerformImplicitConversion( 8164 SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Upper).get(), 8165 CastType, Sema::AA_Converting) 8166 .get(); 8167 Lower = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Lower).get(); 8168 NewStep = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, NewStep.get()); 8169 } 8170 } 8171 if (!Lower || !Upper || NewStep.isInvalid()) 8172 return nullptr; 8173 8174 ExprResult Diff; 8175 // If need to reorganize, then calculate the form as Upper - (Lower - Step [+ 8176 // 1]). 8177 if (NeedToReorganize) { 8178 Diff = Lower; 8179 8180 if (RoundToStep) { 8181 // Lower - Step 8182 Diff = 8183 SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Diff.get(), NewStep.get()); 8184 if (!Diff.isUsable()) 8185 return nullptr; 8186 } 8187 8188 // Lower - Step [+ 1] 8189 if (TestIsStrictOp) 8190 Diff = SemaRef.BuildBinOp( 8191 S, DefaultLoc, BO_Add, Diff.get(), 8192 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get()); 8193 if (!Diff.isUsable()) 8194 return nullptr; 8195 8196 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get()); 8197 if (!Diff.isUsable()) 8198 return nullptr; 8199 8200 // Upper - (Lower - Step [+ 1]). 8201 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Diff.get()); 8202 if (!Diff.isUsable()) 8203 return nullptr; 8204 } else { 8205 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower); 8206 8207 if (!Diff.isUsable() && LCTy->getAsCXXRecordDecl()) { 8208 // BuildBinOp already emitted error, this one is to point user to upper 8209 // and lower bound, and to tell what is passed to 'operator-'. 8210 SemaRef.Diag(Upper->getBeginLoc(), diag::err_omp_loop_diff_cxx) 8211 << Upper->getSourceRange() << Lower->getSourceRange(); 8212 return nullptr; 8213 } 8214 8215 if (!Diff.isUsable()) 8216 return nullptr; 8217 8218 // Upper - Lower [- 1] 8219 if (TestIsStrictOp) 8220 Diff = SemaRef.BuildBinOp( 8221 S, DefaultLoc, BO_Sub, Diff.get(), 8222 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get()); 8223 if (!Diff.isUsable()) 8224 return nullptr; 8225 8226 if (RoundToStep) { 8227 // Upper - Lower [- 1] + Step 8228 Diff = 8229 SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get()); 8230 if (!Diff.isUsable()) 8231 return nullptr; 8232 } 8233 } 8234 8235 // Parentheses (for dumping/debugging purposes only). 8236 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get()); 8237 if (!Diff.isUsable()) 8238 return nullptr; 8239 8240 // (Upper - Lower [- 1] + Step) / Step or (Upper - Lower) / Step 8241 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get()); 8242 if (!Diff.isUsable()) 8243 return nullptr; 8244 8245 return Diff.get(); 8246 } 8247 8248 /// Build the expression to calculate the number of iterations. 8249 Expr *OpenMPIterationSpaceChecker::buildNumIterations( 8250 Scope *S, ArrayRef<LoopIterationSpace> ResultIterSpaces, bool LimitedType, 8251 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const { 8252 QualType VarType = LCDecl->getType().getNonReferenceType(); 8253 if (!VarType->isIntegerType() && !VarType->isPointerType() && 8254 !SemaRef.getLangOpts().CPlusPlus) 8255 return nullptr; 8256 Expr *LBVal = LB; 8257 Expr *UBVal = UB; 8258 // LB = TestIsLessOp.getValue() ? min(LB(MinVal), LB(MaxVal)) : 8259 // max(LB(MinVal), LB(MaxVal)) 8260 if (InitDependOnLC) { 8261 const LoopIterationSpace &IS = ResultIterSpaces[*InitDependOnLC - 1]; 8262 if (!IS.MinValue || !IS.MaxValue) 8263 return nullptr; 8264 // OuterVar = Min 8265 ExprResult MinValue = 8266 SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MinValue); 8267 if (!MinValue.isUsable()) 8268 return nullptr; 8269 8270 ExprResult LBMinVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign, 8271 IS.CounterVar, MinValue.get()); 8272 if (!LBMinVal.isUsable()) 8273 return nullptr; 8274 // OuterVar = Min, LBVal 8275 LBMinVal = 8276 SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, LBMinVal.get(), LBVal); 8277 if (!LBMinVal.isUsable()) 8278 return nullptr; 8279 // (OuterVar = Min, LBVal) 8280 LBMinVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, LBMinVal.get()); 8281 if (!LBMinVal.isUsable()) 8282 return nullptr; 8283 8284 // OuterVar = Max 8285 ExprResult MaxValue = 8286 SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MaxValue); 8287 if (!MaxValue.isUsable()) 8288 return nullptr; 8289 8290 ExprResult LBMaxVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign, 8291 IS.CounterVar, MaxValue.get()); 8292 if (!LBMaxVal.isUsable()) 8293 return nullptr; 8294 // OuterVar = Max, LBVal 8295 LBMaxVal = 8296 SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, LBMaxVal.get(), LBVal); 8297 if (!LBMaxVal.isUsable()) 8298 return nullptr; 8299 // (OuterVar = Max, LBVal) 8300 LBMaxVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, LBMaxVal.get()); 8301 if (!LBMaxVal.isUsable()) 8302 return nullptr; 8303 8304 Expr *LBMin = tryBuildCapture(SemaRef, LBMinVal.get(), Captures).get(); 8305 Expr *LBMax = tryBuildCapture(SemaRef, LBMaxVal.get(), Captures).get(); 8306 if (!LBMin || !LBMax) 8307 return nullptr; 8308 // LB(MinVal) < LB(MaxVal) 8309 ExprResult MinLessMaxRes = 8310 SemaRef.BuildBinOp(S, DefaultLoc, BO_LT, LBMin, LBMax); 8311 if (!MinLessMaxRes.isUsable()) 8312 return nullptr; 8313 Expr *MinLessMax = 8314 tryBuildCapture(SemaRef, MinLessMaxRes.get(), Captures).get(); 8315 if (!MinLessMax) 8316 return nullptr; 8317 if (TestIsLessOp.getValue()) { 8318 // LB(MinVal) < LB(MaxVal) ? LB(MinVal) : LB(MaxVal) - min(LB(MinVal), 8319 // LB(MaxVal)) 8320 ExprResult MinLB = SemaRef.ActOnConditionalOp(DefaultLoc, DefaultLoc, 8321 MinLessMax, LBMin, LBMax); 8322 if (!MinLB.isUsable()) 8323 return nullptr; 8324 LBVal = MinLB.get(); 8325 } else { 8326 // LB(MinVal) < LB(MaxVal) ? LB(MaxVal) : LB(MinVal) - max(LB(MinVal), 8327 // LB(MaxVal)) 8328 ExprResult MaxLB = SemaRef.ActOnConditionalOp(DefaultLoc, DefaultLoc, 8329 MinLessMax, LBMax, LBMin); 8330 if (!MaxLB.isUsable()) 8331 return nullptr; 8332 LBVal = MaxLB.get(); 8333 } 8334 } 8335 // UB = TestIsLessOp.getValue() ? max(UB(MinVal), UB(MaxVal)) : 8336 // min(UB(MinVal), UB(MaxVal)) 8337 if (CondDependOnLC) { 8338 const LoopIterationSpace &IS = ResultIterSpaces[*CondDependOnLC - 1]; 8339 if (!IS.MinValue || !IS.MaxValue) 8340 return nullptr; 8341 // OuterVar = Min 8342 ExprResult MinValue = 8343 SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MinValue); 8344 if (!MinValue.isUsable()) 8345 return nullptr; 8346 8347 ExprResult UBMinVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign, 8348 IS.CounterVar, MinValue.get()); 8349 if (!UBMinVal.isUsable()) 8350 return nullptr; 8351 // OuterVar = Min, UBVal 8352 UBMinVal = 8353 SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, UBMinVal.get(), UBVal); 8354 if (!UBMinVal.isUsable()) 8355 return nullptr; 8356 // (OuterVar = Min, UBVal) 8357 UBMinVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, UBMinVal.get()); 8358 if (!UBMinVal.isUsable()) 8359 return nullptr; 8360 8361 // OuterVar = Max 8362 ExprResult MaxValue = 8363 SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MaxValue); 8364 if (!MaxValue.isUsable()) 8365 return nullptr; 8366 8367 ExprResult UBMaxVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign, 8368 IS.CounterVar, MaxValue.get()); 8369 if (!UBMaxVal.isUsable()) 8370 return nullptr; 8371 // OuterVar = Max, UBVal 8372 UBMaxVal = 8373 SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, UBMaxVal.get(), UBVal); 8374 if (!UBMaxVal.isUsable()) 8375 return nullptr; 8376 // (OuterVar = Max, UBVal) 8377 UBMaxVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, UBMaxVal.get()); 8378 if (!UBMaxVal.isUsable()) 8379 return nullptr; 8380 8381 Expr *UBMin = tryBuildCapture(SemaRef, UBMinVal.get(), Captures).get(); 8382 Expr *UBMax = tryBuildCapture(SemaRef, UBMaxVal.get(), Captures).get(); 8383 if (!UBMin || !UBMax) 8384 return nullptr; 8385 // UB(MinVal) > UB(MaxVal) 8386 ExprResult MinGreaterMaxRes = 8387 SemaRef.BuildBinOp(S, DefaultLoc, BO_GT, UBMin, UBMax); 8388 if (!MinGreaterMaxRes.isUsable()) 8389 return nullptr; 8390 Expr *MinGreaterMax = 8391 tryBuildCapture(SemaRef, MinGreaterMaxRes.get(), Captures).get(); 8392 if (!MinGreaterMax) 8393 return nullptr; 8394 if (TestIsLessOp.getValue()) { 8395 // UB(MinVal) > UB(MaxVal) ? UB(MinVal) : UB(MaxVal) - max(UB(MinVal), 8396 // UB(MaxVal)) 8397 ExprResult MaxUB = SemaRef.ActOnConditionalOp( 8398 DefaultLoc, DefaultLoc, MinGreaterMax, UBMin, UBMax); 8399 if (!MaxUB.isUsable()) 8400 return nullptr; 8401 UBVal = MaxUB.get(); 8402 } else { 8403 // UB(MinVal) > UB(MaxVal) ? UB(MaxVal) : UB(MinVal) - min(UB(MinVal), 8404 // UB(MaxVal)) 8405 ExprResult MinUB = SemaRef.ActOnConditionalOp( 8406 DefaultLoc, DefaultLoc, MinGreaterMax, UBMax, UBMin); 8407 if (!MinUB.isUsable()) 8408 return nullptr; 8409 UBVal = MinUB.get(); 8410 } 8411 } 8412 Expr *UBExpr = TestIsLessOp.getValue() ? UBVal : LBVal; 8413 Expr *LBExpr = TestIsLessOp.getValue() ? LBVal : UBVal; 8414 Expr *Upper = tryBuildCapture(SemaRef, UBExpr, Captures).get(); 8415 Expr *Lower = tryBuildCapture(SemaRef, LBExpr, Captures).get(); 8416 if (!Upper || !Lower) 8417 return nullptr; 8418 8419 ExprResult Diff = calculateNumIters(SemaRef, S, DefaultLoc, Lower, Upper, 8420 Step, VarType, TestIsStrictOp, 8421 /*RoundToStep=*/true, Captures); 8422 if (!Diff.isUsable()) 8423 return nullptr; 8424 8425 // OpenMP runtime requires 32-bit or 64-bit loop variables. 8426 QualType Type = Diff.get()->getType(); 8427 ASTContext &C = SemaRef.Context; 8428 bool UseVarType = VarType->hasIntegerRepresentation() && 8429 C.getTypeSize(Type) > C.getTypeSize(VarType); 8430 if (!Type->isIntegerType() || UseVarType) { 8431 unsigned NewSize = 8432 UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type); 8433 bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation() 8434 : Type->hasSignedIntegerRepresentation(); 8435 Type = C.getIntTypeForBitwidth(NewSize, IsSigned); 8436 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), Type)) { 8437 Diff = SemaRef.PerformImplicitConversion( 8438 Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true); 8439 if (!Diff.isUsable()) 8440 return nullptr; 8441 } 8442 } 8443 if (LimitedType) { 8444 unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32; 8445 if (NewSize != C.getTypeSize(Type)) { 8446 if (NewSize < C.getTypeSize(Type)) { 8447 assert(NewSize == 64 && "incorrect loop var size"); 8448 SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var) 8449 << InitSrcRange << ConditionSrcRange; 8450 } 8451 QualType NewType = C.getIntTypeForBitwidth( 8452 NewSize, Type->hasSignedIntegerRepresentation() || 8453 C.getTypeSize(Type) < NewSize); 8454 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), NewType)) { 8455 Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType, 8456 Sema::AA_Converting, true); 8457 if (!Diff.isUsable()) 8458 return nullptr; 8459 } 8460 } 8461 } 8462 8463 return Diff.get(); 8464 } 8465 8466 std::pair<Expr *, Expr *> OpenMPIterationSpaceChecker::buildMinMaxValues( 8467 Scope *S, llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const { 8468 // Do not build for iterators, they cannot be used in non-rectangular loop 8469 // nests. 8470 if (LCDecl->getType()->isRecordType()) 8471 return std::make_pair(nullptr, nullptr); 8472 // If we subtract, the min is in the condition, otherwise the min is in the 8473 // init value. 8474 Expr *MinExpr = nullptr; 8475 Expr *MaxExpr = nullptr; 8476 Expr *LBExpr = TestIsLessOp.getValue() ? LB : UB; 8477 Expr *UBExpr = TestIsLessOp.getValue() ? UB : LB; 8478 bool LBNonRect = TestIsLessOp.getValue() ? InitDependOnLC.hasValue() 8479 : CondDependOnLC.hasValue(); 8480 bool UBNonRect = TestIsLessOp.getValue() ? CondDependOnLC.hasValue() 8481 : InitDependOnLC.hasValue(); 8482 Expr *Lower = 8483 LBNonRect ? LBExpr : tryBuildCapture(SemaRef, LBExpr, Captures).get(); 8484 Expr *Upper = 8485 UBNonRect ? UBExpr : tryBuildCapture(SemaRef, UBExpr, Captures).get(); 8486 if (!Upper || !Lower) 8487 return std::make_pair(nullptr, nullptr); 8488 8489 if (TestIsLessOp.getValue()) 8490 MinExpr = Lower; 8491 else 8492 MaxExpr = Upper; 8493 8494 // Build minimum/maximum value based on number of iterations. 8495 QualType VarType = LCDecl->getType().getNonReferenceType(); 8496 8497 ExprResult Diff = calculateNumIters(SemaRef, S, DefaultLoc, Lower, Upper, 8498 Step, VarType, TestIsStrictOp, 8499 /*RoundToStep=*/false, Captures); 8500 if (!Diff.isUsable()) 8501 return std::make_pair(nullptr, nullptr); 8502 8503 // ((Upper - Lower [- 1]) / Step) * Step 8504 // Parentheses (for dumping/debugging purposes only). 8505 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get()); 8506 if (!Diff.isUsable()) 8507 return std::make_pair(nullptr, nullptr); 8508 8509 ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures); 8510 if (!NewStep.isUsable()) 8511 return std::make_pair(nullptr, nullptr); 8512 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Mul, Diff.get(), NewStep.get()); 8513 if (!Diff.isUsable()) 8514 return std::make_pair(nullptr, nullptr); 8515 8516 // Parentheses (for dumping/debugging purposes only). 8517 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get()); 8518 if (!Diff.isUsable()) 8519 return std::make_pair(nullptr, nullptr); 8520 8521 // Convert to the ptrdiff_t, if original type is pointer. 8522 if (VarType->isAnyPointerType() && 8523 !SemaRef.Context.hasSameType( 8524 Diff.get()->getType(), 8525 SemaRef.Context.getUnsignedPointerDiffType())) { 8526 Diff = SemaRef.PerformImplicitConversion( 8527 Diff.get(), SemaRef.Context.getUnsignedPointerDiffType(), 8528 Sema::AA_Converting, /*AllowExplicit=*/true); 8529 } 8530 if (!Diff.isUsable()) 8531 return std::make_pair(nullptr, nullptr); 8532 8533 if (TestIsLessOp.getValue()) { 8534 // MinExpr = Lower; 8535 // MaxExpr = Lower + (((Upper - Lower [- 1]) / Step) * Step) 8536 Diff = SemaRef.BuildBinOp( 8537 S, DefaultLoc, BO_Add, 8538 SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Lower).get(), 8539 Diff.get()); 8540 if (!Diff.isUsable()) 8541 return std::make_pair(nullptr, nullptr); 8542 } else { 8543 // MaxExpr = Upper; 8544 // MinExpr = Upper - (((Upper - Lower [- 1]) / Step) * Step) 8545 Diff = SemaRef.BuildBinOp( 8546 S, DefaultLoc, BO_Sub, 8547 SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Upper).get(), 8548 Diff.get()); 8549 if (!Diff.isUsable()) 8550 return std::make_pair(nullptr, nullptr); 8551 } 8552 8553 // Convert to the original type. 8554 if (SemaRef.Context.hasSameType(Diff.get()->getType(), VarType)) 8555 Diff = SemaRef.PerformImplicitConversion(Diff.get(), VarType, 8556 Sema::AA_Converting, 8557 /*AllowExplicit=*/true); 8558 if (!Diff.isUsable()) 8559 return std::make_pair(nullptr, nullptr); 8560 8561 Sema::TentativeAnalysisScope Trap(SemaRef); 8562 Diff = SemaRef.ActOnFinishFullExpr(Diff.get(), /*DiscardedValue=*/false); 8563 if (!Diff.isUsable()) 8564 return std::make_pair(nullptr, nullptr); 8565 8566 if (TestIsLessOp.getValue()) 8567 MaxExpr = Diff.get(); 8568 else 8569 MinExpr = Diff.get(); 8570 8571 return std::make_pair(MinExpr, MaxExpr); 8572 } 8573 8574 Expr *OpenMPIterationSpaceChecker::buildFinalCondition(Scope *S) const { 8575 if (InitDependOnLC || CondDependOnLC) 8576 return Condition; 8577 return nullptr; 8578 } 8579 8580 Expr *OpenMPIterationSpaceChecker::buildPreCond( 8581 Scope *S, Expr *Cond, 8582 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const { 8583 // Do not build a precondition when the condition/initialization is dependent 8584 // to prevent pessimistic early loop exit. 8585 // TODO: this can be improved by calculating min/max values but not sure that 8586 // it will be very effective. 8587 if (CondDependOnLC || InitDependOnLC) 8588 return SemaRef 8589 .PerformImplicitConversion( 8590 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get(), 8591 SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting, 8592 /*AllowExplicit=*/true) 8593 .get(); 8594 8595 // Try to build LB <op> UB, where <op> is <, >, <=, or >=. 8596 Sema::TentativeAnalysisScope Trap(SemaRef); 8597 8598 ExprResult NewLB = tryBuildCapture(SemaRef, LB, Captures); 8599 ExprResult NewUB = tryBuildCapture(SemaRef, UB, Captures); 8600 if (!NewLB.isUsable() || !NewUB.isUsable()) 8601 return nullptr; 8602 8603 ExprResult CondExpr = SemaRef.BuildBinOp( 8604 S, DefaultLoc, 8605 TestIsLessOp.getValue() ? (TestIsStrictOp ? BO_LT : BO_LE) 8606 : (TestIsStrictOp ? BO_GT : BO_GE), 8607 NewLB.get(), NewUB.get()); 8608 if (CondExpr.isUsable()) { 8609 if (!SemaRef.Context.hasSameUnqualifiedType(CondExpr.get()->getType(), 8610 SemaRef.Context.BoolTy)) 8611 CondExpr = SemaRef.PerformImplicitConversion( 8612 CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting, 8613 /*AllowExplicit=*/true); 8614 } 8615 8616 // Otherwise use original loop condition and evaluate it in runtime. 8617 return CondExpr.isUsable() ? CondExpr.get() : Cond; 8618 } 8619 8620 /// Build reference expression to the counter be used for codegen. 8621 DeclRefExpr *OpenMPIterationSpaceChecker::buildCounterVar( 8622 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures, 8623 DSAStackTy &DSA) const { 8624 auto *VD = dyn_cast<VarDecl>(LCDecl); 8625 if (!VD) { 8626 VD = SemaRef.isOpenMPCapturedDecl(LCDecl); 8627 DeclRefExpr *Ref = buildDeclRefExpr( 8628 SemaRef, VD, VD->getType().getNonReferenceType(), DefaultLoc); 8629 const DSAStackTy::DSAVarData Data = 8630 DSA.getTopDSA(LCDecl, /*FromParent=*/false); 8631 // If the loop control decl is explicitly marked as private, do not mark it 8632 // as captured again. 8633 if (!isOpenMPPrivate(Data.CKind) || !Data.RefExpr) 8634 Captures.insert(std::make_pair(LCRef, Ref)); 8635 return Ref; 8636 } 8637 return cast<DeclRefExpr>(LCRef); 8638 } 8639 8640 Expr *OpenMPIterationSpaceChecker::buildPrivateCounterVar() const { 8641 if (LCDecl && !LCDecl->isInvalidDecl()) { 8642 QualType Type = LCDecl->getType().getNonReferenceType(); 8643 VarDecl *PrivateVar = buildVarDecl( 8644 SemaRef, DefaultLoc, Type, LCDecl->getName(), 8645 LCDecl->hasAttrs() ? &LCDecl->getAttrs() : nullptr, 8646 isa<VarDecl>(LCDecl) 8647 ? buildDeclRefExpr(SemaRef, cast<VarDecl>(LCDecl), Type, DefaultLoc) 8648 : nullptr); 8649 if (PrivateVar->isInvalidDecl()) 8650 return nullptr; 8651 return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc); 8652 } 8653 return nullptr; 8654 } 8655 8656 /// Build initialization of the counter to be used for codegen. 8657 Expr *OpenMPIterationSpaceChecker::buildCounterInit() const { return LB; } 8658 8659 /// Build step of the counter be used for codegen. 8660 Expr *OpenMPIterationSpaceChecker::buildCounterStep() const { return Step; } 8661 8662 Expr *OpenMPIterationSpaceChecker::buildOrderedLoopData( 8663 Scope *S, Expr *Counter, 8664 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures, SourceLocation Loc, 8665 Expr *Inc, OverloadedOperatorKind OOK) { 8666 Expr *Cnt = SemaRef.DefaultLvalueConversion(Counter).get(); 8667 if (!Cnt) 8668 return nullptr; 8669 if (Inc) { 8670 assert((OOK == OO_Plus || OOK == OO_Minus) && 8671 "Expected only + or - operations for depend clauses."); 8672 BinaryOperatorKind BOK = (OOK == OO_Plus) ? BO_Add : BO_Sub; 8673 Cnt = SemaRef.BuildBinOp(S, Loc, BOK, Cnt, Inc).get(); 8674 if (!Cnt) 8675 return nullptr; 8676 } 8677 QualType VarType = LCDecl->getType().getNonReferenceType(); 8678 if (!VarType->isIntegerType() && !VarType->isPointerType() && 8679 !SemaRef.getLangOpts().CPlusPlus) 8680 return nullptr; 8681 // Upper - Lower 8682 Expr *Upper = TestIsLessOp.getValue() 8683 ? Cnt 8684 : tryBuildCapture(SemaRef, LB, Captures).get(); 8685 Expr *Lower = TestIsLessOp.getValue() 8686 ? tryBuildCapture(SemaRef, LB, Captures).get() 8687 : Cnt; 8688 if (!Upper || !Lower) 8689 return nullptr; 8690 8691 ExprResult Diff = calculateNumIters( 8692 SemaRef, S, DefaultLoc, Lower, Upper, Step, VarType, 8693 /*TestIsStrictOp=*/false, /*RoundToStep=*/false, Captures); 8694 if (!Diff.isUsable()) 8695 return nullptr; 8696 8697 return Diff.get(); 8698 } 8699 } // namespace 8700 8701 void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) { 8702 assert(getLangOpts().OpenMP && "OpenMP is not active."); 8703 assert(Init && "Expected loop in canonical form."); 8704 unsigned AssociatedLoops = DSAStack->getAssociatedLoops(); 8705 if (AssociatedLoops > 0 && 8706 isOpenMPLoopDirective(DSAStack->getCurrentDirective())) { 8707 DSAStack->loopStart(); 8708 OpenMPIterationSpaceChecker ISC(*this, /*SupportsNonRectangular=*/true, 8709 *DSAStack, ForLoc); 8710 if (!ISC.checkAndSetInit(Init, /*EmitDiags=*/false)) { 8711 if (ValueDecl *D = ISC.getLoopDecl()) { 8712 auto *VD = dyn_cast<VarDecl>(D); 8713 DeclRefExpr *PrivateRef = nullptr; 8714 if (!VD) { 8715 if (VarDecl *Private = isOpenMPCapturedDecl(D)) { 8716 VD = Private; 8717 } else { 8718 PrivateRef = buildCapture(*this, D, ISC.getLoopDeclRefExpr(), 8719 /*WithInit=*/false); 8720 VD = cast<VarDecl>(PrivateRef->getDecl()); 8721 } 8722 } 8723 DSAStack->addLoopControlVariable(D, VD); 8724 const Decl *LD = DSAStack->getPossiblyLoopCunter(); 8725 if (LD != D->getCanonicalDecl()) { 8726 DSAStack->resetPossibleLoopCounter(); 8727 if (auto *Var = dyn_cast_or_null<VarDecl>(LD)) 8728 MarkDeclarationsReferencedInExpr( 8729 buildDeclRefExpr(*this, const_cast<VarDecl *>(Var), 8730 Var->getType().getNonLValueExprType(Context), 8731 ForLoc, /*RefersToCapture=*/true)); 8732 } 8733 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective(); 8734 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables 8735 // Referenced in a Construct, C/C++]. The loop iteration variable in the 8736 // associated for-loop of a simd construct with just one associated 8737 // for-loop may be listed in a linear clause with a constant-linear-step 8738 // that is the increment of the associated for-loop. The loop iteration 8739 // variable(s) in the associated for-loop(s) of a for or parallel for 8740 // construct may be listed in a private or lastprivate clause. 8741 DSAStackTy::DSAVarData DVar = 8742 DSAStack->getTopDSA(D, /*FromParent=*/false); 8743 // If LoopVarRefExpr is nullptr it means the corresponding loop variable 8744 // is declared in the loop and it is predetermined as a private. 8745 Expr *LoopDeclRefExpr = ISC.getLoopDeclRefExpr(); 8746 OpenMPClauseKind PredeterminedCKind = 8747 isOpenMPSimdDirective(DKind) 8748 ? (DSAStack->hasMutipleLoops() ? OMPC_lastprivate : OMPC_linear) 8749 : OMPC_private; 8750 if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown && 8751 DVar.CKind != PredeterminedCKind && DVar.RefExpr && 8752 (LangOpts.OpenMP <= 45 || (DVar.CKind != OMPC_lastprivate && 8753 DVar.CKind != OMPC_private))) || 8754 ((isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop || 8755 DKind == OMPD_master_taskloop || 8756 DKind == OMPD_parallel_master_taskloop || 8757 isOpenMPDistributeDirective(DKind)) && 8758 !isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown && 8759 DVar.CKind != OMPC_private && DVar.CKind != OMPC_lastprivate)) && 8760 (DVar.CKind != OMPC_private || DVar.RefExpr)) { 8761 Diag(Init->getBeginLoc(), diag::err_omp_loop_var_dsa) 8762 << getOpenMPClauseName(DVar.CKind) 8763 << getOpenMPDirectiveName(DKind) 8764 << getOpenMPClauseName(PredeterminedCKind); 8765 if (DVar.RefExpr == nullptr) 8766 DVar.CKind = PredeterminedCKind; 8767 reportOriginalDsa(*this, DSAStack, D, DVar, 8768 /*IsLoopIterVar=*/true); 8769 } else if (LoopDeclRefExpr) { 8770 // Make the loop iteration variable private (for worksharing 8771 // constructs), linear (for simd directives with the only one 8772 // associated loop) or lastprivate (for simd directives with several 8773 // collapsed or ordered loops). 8774 if (DVar.CKind == OMPC_unknown) 8775 DSAStack->addDSA(D, LoopDeclRefExpr, PredeterminedCKind, 8776 PrivateRef); 8777 } 8778 } 8779 } 8780 DSAStack->setAssociatedLoops(AssociatedLoops - 1); 8781 } 8782 } 8783 8784 /// Called on a for stmt to check and extract its iteration space 8785 /// for further processing (such as collapsing). 8786 static bool checkOpenMPIterationSpace( 8787 OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA, 8788 unsigned CurrentNestedLoopCount, unsigned NestedLoopCount, 8789 unsigned TotalNestedLoopCount, Expr *CollapseLoopCountExpr, 8790 Expr *OrderedLoopCountExpr, 8791 Sema::VarsWithInheritedDSAType &VarsWithImplicitDSA, 8792 llvm::MutableArrayRef<LoopIterationSpace> ResultIterSpaces, 8793 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) { 8794 bool SupportsNonRectangular = !isOpenMPLoopTransformationDirective(DKind); 8795 // OpenMP [2.9.1, Canonical Loop Form] 8796 // for (init-expr; test-expr; incr-expr) structured-block 8797 // for (range-decl: range-expr) structured-block 8798 if (auto *CanonLoop = dyn_cast_or_null<OMPCanonicalLoop>(S)) 8799 S = CanonLoop->getLoopStmt(); 8800 auto *For = dyn_cast_or_null<ForStmt>(S); 8801 auto *CXXFor = dyn_cast_or_null<CXXForRangeStmt>(S); 8802 // Ranged for is supported only in OpenMP 5.0. 8803 if (!For && (SemaRef.LangOpts.OpenMP <= 45 || !CXXFor)) { 8804 SemaRef.Diag(S->getBeginLoc(), diag::err_omp_not_for) 8805 << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr) 8806 << getOpenMPDirectiveName(DKind) << TotalNestedLoopCount 8807 << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount; 8808 if (TotalNestedLoopCount > 1) { 8809 if (CollapseLoopCountExpr && OrderedLoopCountExpr) 8810 SemaRef.Diag(DSA.getConstructLoc(), 8811 diag::note_omp_collapse_ordered_expr) 8812 << 2 << CollapseLoopCountExpr->getSourceRange() 8813 << OrderedLoopCountExpr->getSourceRange(); 8814 else if (CollapseLoopCountExpr) 8815 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(), 8816 diag::note_omp_collapse_ordered_expr) 8817 << 0 << CollapseLoopCountExpr->getSourceRange(); 8818 else 8819 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(), 8820 diag::note_omp_collapse_ordered_expr) 8821 << 1 << OrderedLoopCountExpr->getSourceRange(); 8822 } 8823 return true; 8824 } 8825 assert(((For && For->getBody()) || (CXXFor && CXXFor->getBody())) && 8826 "No loop body."); 8827 // Postpone analysis in dependent contexts for ranged for loops. 8828 if (CXXFor && SemaRef.CurContext->isDependentContext()) 8829 return false; 8830 8831 OpenMPIterationSpaceChecker ISC(SemaRef, SupportsNonRectangular, DSA, 8832 For ? For->getForLoc() : CXXFor->getForLoc()); 8833 8834 // Check init. 8835 Stmt *Init = For ? For->getInit() : CXXFor->getBeginStmt(); 8836 if (ISC.checkAndSetInit(Init)) 8837 return true; 8838 8839 bool HasErrors = false; 8840 8841 // Check loop variable's type. 8842 if (ValueDecl *LCDecl = ISC.getLoopDecl()) { 8843 // OpenMP [2.6, Canonical Loop Form] 8844 // Var is one of the following: 8845 // A variable of signed or unsigned integer type. 8846 // For C++, a variable of a random access iterator type. 8847 // For C, a variable of a pointer type. 8848 QualType VarType = LCDecl->getType().getNonReferenceType(); 8849 if (!VarType->isDependentType() && !VarType->isIntegerType() && 8850 !VarType->isPointerType() && 8851 !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) { 8852 SemaRef.Diag(Init->getBeginLoc(), diag::err_omp_loop_variable_type) 8853 << SemaRef.getLangOpts().CPlusPlus; 8854 HasErrors = true; 8855 } 8856 8857 // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in 8858 // a Construct 8859 // The loop iteration variable(s) in the associated for-loop(s) of a for or 8860 // parallel for construct is (are) private. 8861 // The loop iteration variable in the associated for-loop of a simd 8862 // construct with just one associated for-loop is linear with a 8863 // constant-linear-step that is the increment of the associated for-loop. 8864 // Exclude loop var from the list of variables with implicitly defined data 8865 // sharing attributes. 8866 VarsWithImplicitDSA.erase(LCDecl); 8867 8868 assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars"); 8869 8870 // Check test-expr. 8871 HasErrors |= ISC.checkAndSetCond(For ? For->getCond() : CXXFor->getCond()); 8872 8873 // Check incr-expr. 8874 HasErrors |= ISC.checkAndSetInc(For ? For->getInc() : CXXFor->getInc()); 8875 } 8876 8877 if (ISC.dependent() || SemaRef.CurContext->isDependentContext() || HasErrors) 8878 return HasErrors; 8879 8880 // Build the loop's iteration space representation. 8881 ResultIterSpaces[CurrentNestedLoopCount].PreCond = ISC.buildPreCond( 8882 DSA.getCurScope(), For ? For->getCond() : CXXFor->getCond(), Captures); 8883 ResultIterSpaces[CurrentNestedLoopCount].NumIterations = 8884 ISC.buildNumIterations(DSA.getCurScope(), ResultIterSpaces, 8885 (isOpenMPWorksharingDirective(DKind) || 8886 isOpenMPGenericLoopDirective(DKind) || 8887 isOpenMPTaskLoopDirective(DKind) || 8888 isOpenMPDistributeDirective(DKind) || 8889 isOpenMPLoopTransformationDirective(DKind)), 8890 Captures); 8891 ResultIterSpaces[CurrentNestedLoopCount].CounterVar = 8892 ISC.buildCounterVar(Captures, DSA); 8893 ResultIterSpaces[CurrentNestedLoopCount].PrivateCounterVar = 8894 ISC.buildPrivateCounterVar(); 8895 ResultIterSpaces[CurrentNestedLoopCount].CounterInit = ISC.buildCounterInit(); 8896 ResultIterSpaces[CurrentNestedLoopCount].CounterStep = ISC.buildCounterStep(); 8897 ResultIterSpaces[CurrentNestedLoopCount].InitSrcRange = ISC.getInitSrcRange(); 8898 ResultIterSpaces[CurrentNestedLoopCount].CondSrcRange = 8899 ISC.getConditionSrcRange(); 8900 ResultIterSpaces[CurrentNestedLoopCount].IncSrcRange = 8901 ISC.getIncrementSrcRange(); 8902 ResultIterSpaces[CurrentNestedLoopCount].Subtract = ISC.shouldSubtractStep(); 8903 ResultIterSpaces[CurrentNestedLoopCount].IsStrictCompare = 8904 ISC.isStrictTestOp(); 8905 std::tie(ResultIterSpaces[CurrentNestedLoopCount].MinValue, 8906 ResultIterSpaces[CurrentNestedLoopCount].MaxValue) = 8907 ISC.buildMinMaxValues(DSA.getCurScope(), Captures); 8908 ResultIterSpaces[CurrentNestedLoopCount].FinalCondition = 8909 ISC.buildFinalCondition(DSA.getCurScope()); 8910 ResultIterSpaces[CurrentNestedLoopCount].IsNonRectangularLB = 8911 ISC.doesInitDependOnLC(); 8912 ResultIterSpaces[CurrentNestedLoopCount].IsNonRectangularUB = 8913 ISC.doesCondDependOnLC(); 8914 ResultIterSpaces[CurrentNestedLoopCount].LoopDependentIdx = 8915 ISC.getLoopDependentIdx(); 8916 8917 HasErrors |= 8918 (ResultIterSpaces[CurrentNestedLoopCount].PreCond == nullptr || 8919 ResultIterSpaces[CurrentNestedLoopCount].NumIterations == nullptr || 8920 ResultIterSpaces[CurrentNestedLoopCount].CounterVar == nullptr || 8921 ResultIterSpaces[CurrentNestedLoopCount].PrivateCounterVar == nullptr || 8922 ResultIterSpaces[CurrentNestedLoopCount].CounterInit == nullptr || 8923 ResultIterSpaces[CurrentNestedLoopCount].CounterStep == nullptr); 8924 if (!HasErrors && DSA.isOrderedRegion()) { 8925 if (DSA.getOrderedRegionParam().second->getNumForLoops()) { 8926 if (CurrentNestedLoopCount < 8927 DSA.getOrderedRegionParam().second->getLoopNumIterations().size()) { 8928 DSA.getOrderedRegionParam().second->setLoopNumIterations( 8929 CurrentNestedLoopCount, 8930 ResultIterSpaces[CurrentNestedLoopCount].NumIterations); 8931 DSA.getOrderedRegionParam().second->setLoopCounter( 8932 CurrentNestedLoopCount, 8933 ResultIterSpaces[CurrentNestedLoopCount].CounterVar); 8934 } 8935 } 8936 for (auto &Pair : DSA.getDoacrossDependClauses()) { 8937 if (CurrentNestedLoopCount >= Pair.first->getNumLoops()) { 8938 // Erroneous case - clause has some problems. 8939 continue; 8940 } 8941 if (Pair.first->getDependencyKind() == OMPC_DEPEND_sink && 8942 Pair.second.size() <= CurrentNestedLoopCount) { 8943 // Erroneous case - clause has some problems. 8944 Pair.first->setLoopData(CurrentNestedLoopCount, nullptr); 8945 continue; 8946 } 8947 Expr *CntValue; 8948 if (Pair.first->getDependencyKind() == OMPC_DEPEND_source) 8949 CntValue = ISC.buildOrderedLoopData( 8950 DSA.getCurScope(), 8951 ResultIterSpaces[CurrentNestedLoopCount].CounterVar, Captures, 8952 Pair.first->getDependencyLoc()); 8953 else 8954 CntValue = ISC.buildOrderedLoopData( 8955 DSA.getCurScope(), 8956 ResultIterSpaces[CurrentNestedLoopCount].CounterVar, Captures, 8957 Pair.first->getDependencyLoc(), 8958 Pair.second[CurrentNestedLoopCount].first, 8959 Pair.second[CurrentNestedLoopCount].second); 8960 Pair.first->setLoopData(CurrentNestedLoopCount, CntValue); 8961 } 8962 } 8963 8964 return HasErrors; 8965 } 8966 8967 /// Build 'VarRef = Start. 8968 static ExprResult 8969 buildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef, 8970 ExprResult Start, bool IsNonRectangularLB, 8971 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) { 8972 // Build 'VarRef = Start. 8973 ExprResult NewStart = IsNonRectangularLB 8974 ? Start.get() 8975 : tryBuildCapture(SemaRef, Start.get(), Captures); 8976 if (!NewStart.isUsable()) 8977 return ExprError(); 8978 if (!SemaRef.Context.hasSameType(NewStart.get()->getType(), 8979 VarRef.get()->getType())) { 8980 NewStart = SemaRef.PerformImplicitConversion( 8981 NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting, 8982 /*AllowExplicit=*/true); 8983 if (!NewStart.isUsable()) 8984 return ExprError(); 8985 } 8986 8987 ExprResult Init = 8988 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get()); 8989 return Init; 8990 } 8991 8992 /// Build 'VarRef = Start + Iter * Step'. 8993 static ExprResult buildCounterUpdate( 8994 Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef, 8995 ExprResult Start, ExprResult Iter, ExprResult Step, bool Subtract, 8996 bool IsNonRectangularLB, 8997 llvm::MapVector<const Expr *, DeclRefExpr *> *Captures = nullptr) { 8998 // Add parentheses (for debugging purposes only). 8999 Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get()); 9000 if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() || 9001 !Step.isUsable()) 9002 return ExprError(); 9003 9004 ExprResult NewStep = Step; 9005 if (Captures) 9006 NewStep = tryBuildCapture(SemaRef, Step.get(), *Captures); 9007 if (NewStep.isInvalid()) 9008 return ExprError(); 9009 ExprResult Update = 9010 SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get()); 9011 if (!Update.isUsable()) 9012 return ExprError(); 9013 9014 // Try to build 'VarRef = Start, VarRef (+|-)= Iter * Step' or 9015 // 'VarRef = Start (+|-) Iter * Step'. 9016 if (!Start.isUsable()) 9017 return ExprError(); 9018 ExprResult NewStart = SemaRef.ActOnParenExpr(Loc, Loc, Start.get()); 9019 if (!NewStart.isUsable()) 9020 return ExprError(); 9021 if (Captures && !IsNonRectangularLB) 9022 NewStart = tryBuildCapture(SemaRef, Start.get(), *Captures); 9023 if (NewStart.isInvalid()) 9024 return ExprError(); 9025 9026 // First attempt: try to build 'VarRef = Start, VarRef += Iter * Step'. 9027 ExprResult SavedUpdate = Update; 9028 ExprResult UpdateVal; 9029 if (VarRef.get()->getType()->isOverloadableType() || 9030 NewStart.get()->getType()->isOverloadableType() || 9031 Update.get()->getType()->isOverloadableType()) { 9032 Sema::TentativeAnalysisScope Trap(SemaRef); 9033 9034 Update = 9035 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get()); 9036 if (Update.isUsable()) { 9037 UpdateVal = 9038 SemaRef.BuildBinOp(S, Loc, Subtract ? BO_SubAssign : BO_AddAssign, 9039 VarRef.get(), SavedUpdate.get()); 9040 if (UpdateVal.isUsable()) { 9041 Update = SemaRef.CreateBuiltinBinOp(Loc, BO_Comma, Update.get(), 9042 UpdateVal.get()); 9043 } 9044 } 9045 } 9046 9047 // Second attempt: try to build 'VarRef = Start (+|-) Iter * Step'. 9048 if (!Update.isUsable() || !UpdateVal.isUsable()) { 9049 Update = SemaRef.BuildBinOp(S, Loc, Subtract ? BO_Sub : BO_Add, 9050 NewStart.get(), SavedUpdate.get()); 9051 if (!Update.isUsable()) 9052 return ExprError(); 9053 9054 if (!SemaRef.Context.hasSameType(Update.get()->getType(), 9055 VarRef.get()->getType())) { 9056 Update = SemaRef.PerformImplicitConversion( 9057 Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true); 9058 if (!Update.isUsable()) 9059 return ExprError(); 9060 } 9061 9062 Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get()); 9063 } 9064 return Update; 9065 } 9066 9067 /// Convert integer expression \a E to make it have at least \a Bits 9068 /// bits. 9069 static ExprResult widenIterationCount(unsigned Bits, Expr *E, Sema &SemaRef) { 9070 if (E == nullptr) 9071 return ExprError(); 9072 ASTContext &C = SemaRef.Context; 9073 QualType OldType = E->getType(); 9074 unsigned HasBits = C.getTypeSize(OldType); 9075 if (HasBits >= Bits) 9076 return ExprResult(E); 9077 // OK to convert to signed, because new type has more bits than old. 9078 QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true); 9079 return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting, 9080 true); 9081 } 9082 9083 /// Check if the given expression \a E is a constant integer that fits 9084 /// into \a Bits bits. 9085 static bool fitsInto(unsigned Bits, bool Signed, const Expr *E, Sema &SemaRef) { 9086 if (E == nullptr) 9087 return false; 9088 if (Optional<llvm::APSInt> Result = 9089 E->getIntegerConstantExpr(SemaRef.Context)) 9090 return Signed ? Result->isSignedIntN(Bits) : Result->isIntN(Bits); 9091 return false; 9092 } 9093 9094 /// Build preinits statement for the given declarations. 9095 static Stmt *buildPreInits(ASTContext &Context, 9096 MutableArrayRef<Decl *> PreInits) { 9097 if (!PreInits.empty()) { 9098 return new (Context) DeclStmt( 9099 DeclGroupRef::Create(Context, PreInits.begin(), PreInits.size()), 9100 SourceLocation(), SourceLocation()); 9101 } 9102 return nullptr; 9103 } 9104 9105 /// Build preinits statement for the given declarations. 9106 static Stmt * 9107 buildPreInits(ASTContext &Context, 9108 const llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) { 9109 if (!Captures.empty()) { 9110 SmallVector<Decl *, 16> PreInits; 9111 for (const auto &Pair : Captures) 9112 PreInits.push_back(Pair.second->getDecl()); 9113 return buildPreInits(Context, PreInits); 9114 } 9115 return nullptr; 9116 } 9117 9118 /// Build postupdate expression for the given list of postupdates expressions. 9119 static Expr *buildPostUpdate(Sema &S, ArrayRef<Expr *> PostUpdates) { 9120 Expr *PostUpdate = nullptr; 9121 if (!PostUpdates.empty()) { 9122 for (Expr *E : PostUpdates) { 9123 Expr *ConvE = S.BuildCStyleCastExpr( 9124 E->getExprLoc(), 9125 S.Context.getTrivialTypeSourceInfo(S.Context.VoidTy), 9126 E->getExprLoc(), E) 9127 .get(); 9128 PostUpdate = PostUpdate 9129 ? S.CreateBuiltinBinOp(ConvE->getExprLoc(), BO_Comma, 9130 PostUpdate, ConvE) 9131 .get() 9132 : ConvE; 9133 } 9134 } 9135 return PostUpdate; 9136 } 9137 9138 /// Called on a for stmt to check itself and nested loops (if any). 9139 /// \return Returns 0 if one of the collapsed stmts is not canonical for loop, 9140 /// number of collapsed loops otherwise. 9141 static unsigned 9142 checkOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr, 9143 Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef, 9144 DSAStackTy &DSA, 9145 Sema::VarsWithInheritedDSAType &VarsWithImplicitDSA, 9146 OMPLoopBasedDirective::HelperExprs &Built) { 9147 unsigned NestedLoopCount = 1; 9148 bool SupportsNonPerfectlyNested = (SemaRef.LangOpts.OpenMP >= 50) && 9149 !isOpenMPLoopTransformationDirective(DKind); 9150 9151 if (CollapseLoopCountExpr) { 9152 // Found 'collapse' clause - calculate collapse number. 9153 Expr::EvalResult Result; 9154 if (!CollapseLoopCountExpr->isValueDependent() && 9155 CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext())) { 9156 NestedLoopCount = Result.Val.getInt().getLimitedValue(); 9157 } else { 9158 Built.clear(/*Size=*/1); 9159 return 1; 9160 } 9161 } 9162 unsigned OrderedLoopCount = 1; 9163 if (OrderedLoopCountExpr) { 9164 // Found 'ordered' clause - calculate collapse number. 9165 Expr::EvalResult EVResult; 9166 if (!OrderedLoopCountExpr->isValueDependent() && 9167 OrderedLoopCountExpr->EvaluateAsInt(EVResult, 9168 SemaRef.getASTContext())) { 9169 llvm::APSInt Result = EVResult.Val.getInt(); 9170 if (Result.getLimitedValue() < NestedLoopCount) { 9171 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(), 9172 diag::err_omp_wrong_ordered_loop_count) 9173 << OrderedLoopCountExpr->getSourceRange(); 9174 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(), 9175 diag::note_collapse_loop_count) 9176 << CollapseLoopCountExpr->getSourceRange(); 9177 } 9178 OrderedLoopCount = Result.getLimitedValue(); 9179 } else { 9180 Built.clear(/*Size=*/1); 9181 return 1; 9182 } 9183 } 9184 // This is helper routine for loop directives (e.g., 'for', 'simd', 9185 // 'for simd', etc.). 9186 llvm::MapVector<const Expr *, DeclRefExpr *> Captures; 9187 unsigned NumLoops = std::max(OrderedLoopCount, NestedLoopCount); 9188 SmallVector<LoopIterationSpace, 4> IterSpaces(NumLoops); 9189 if (!OMPLoopBasedDirective::doForAllLoops( 9190 AStmt->IgnoreContainers(!isOpenMPLoopTransformationDirective(DKind)), 9191 SupportsNonPerfectlyNested, NumLoops, 9192 [DKind, &SemaRef, &DSA, NumLoops, NestedLoopCount, 9193 CollapseLoopCountExpr, OrderedLoopCountExpr, &VarsWithImplicitDSA, 9194 &IterSpaces, &Captures](unsigned Cnt, Stmt *CurStmt) { 9195 if (checkOpenMPIterationSpace( 9196 DKind, CurStmt, SemaRef, DSA, Cnt, NestedLoopCount, 9197 NumLoops, CollapseLoopCountExpr, OrderedLoopCountExpr, 9198 VarsWithImplicitDSA, IterSpaces, Captures)) 9199 return true; 9200 if (Cnt > 0 && Cnt >= NestedLoopCount && 9201 IterSpaces[Cnt].CounterVar) { 9202 // Handle initialization of captured loop iterator variables. 9203 auto *DRE = cast<DeclRefExpr>(IterSpaces[Cnt].CounterVar); 9204 if (isa<OMPCapturedExprDecl>(DRE->getDecl())) { 9205 Captures[DRE] = DRE; 9206 } 9207 } 9208 return false; 9209 }, 9210 [&SemaRef, &Captures](OMPLoopTransformationDirective *Transform) { 9211 Stmt *DependentPreInits = Transform->getPreInits(); 9212 if (!DependentPreInits) 9213 return; 9214 for (Decl *C : cast<DeclStmt>(DependentPreInits)->getDeclGroup()) { 9215 auto *D = cast<VarDecl>(C); 9216 DeclRefExpr *Ref = buildDeclRefExpr(SemaRef, D, D->getType(), 9217 Transform->getBeginLoc()); 9218 Captures[Ref] = Ref; 9219 } 9220 })) 9221 return 0; 9222 9223 Built.clear(/* size */ NestedLoopCount); 9224 9225 if (SemaRef.CurContext->isDependentContext()) 9226 return NestedLoopCount; 9227 9228 // An example of what is generated for the following code: 9229 // 9230 // #pragma omp simd collapse(2) ordered(2) 9231 // for (i = 0; i < NI; ++i) 9232 // for (k = 0; k < NK; ++k) 9233 // for (j = J0; j < NJ; j+=2) { 9234 // <loop body> 9235 // } 9236 // 9237 // We generate the code below. 9238 // Note: the loop body may be outlined in CodeGen. 9239 // Note: some counters may be C++ classes, operator- is used to find number of 9240 // iterations and operator+= to calculate counter value. 9241 // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32 9242 // or i64 is currently supported). 9243 // 9244 // #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2)) 9245 // for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) { 9246 // .local.i = IV / ((NJ - J0 - 1 + 2) / 2); 9247 // .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2; 9248 // // similar updates for vars in clauses (e.g. 'linear') 9249 // <loop body (using local i and j)> 9250 // } 9251 // i = NI; // assign final values of counters 9252 // j = NJ; 9253 // 9254 9255 // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are 9256 // the iteration counts of the collapsed for loops. 9257 // Precondition tests if there is at least one iteration (all conditions are 9258 // true). 9259 auto PreCond = ExprResult(IterSpaces[0].PreCond); 9260 Expr *N0 = IterSpaces[0].NumIterations; 9261 ExprResult LastIteration32 = 9262 widenIterationCount(/*Bits=*/32, 9263 SemaRef 9264 .PerformImplicitConversion( 9265 N0->IgnoreImpCasts(), N0->getType(), 9266 Sema::AA_Converting, /*AllowExplicit=*/true) 9267 .get(), 9268 SemaRef); 9269 ExprResult LastIteration64 = widenIterationCount( 9270 /*Bits=*/64, 9271 SemaRef 9272 .PerformImplicitConversion(N0->IgnoreImpCasts(), N0->getType(), 9273 Sema::AA_Converting, 9274 /*AllowExplicit=*/true) 9275 .get(), 9276 SemaRef); 9277 9278 if (!LastIteration32.isUsable() || !LastIteration64.isUsable()) 9279 return NestedLoopCount; 9280 9281 ASTContext &C = SemaRef.Context; 9282 bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32; 9283 9284 Scope *CurScope = DSA.getCurScope(); 9285 for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) { 9286 if (PreCond.isUsable()) { 9287 PreCond = 9288 SemaRef.BuildBinOp(CurScope, PreCond.get()->getExprLoc(), BO_LAnd, 9289 PreCond.get(), IterSpaces[Cnt].PreCond); 9290 } 9291 Expr *N = IterSpaces[Cnt].NumIterations; 9292 SourceLocation Loc = N->getExprLoc(); 9293 AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32; 9294 if (LastIteration32.isUsable()) 9295 LastIteration32 = SemaRef.BuildBinOp( 9296 CurScope, Loc, BO_Mul, LastIteration32.get(), 9297 SemaRef 9298 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(), 9299 Sema::AA_Converting, 9300 /*AllowExplicit=*/true) 9301 .get()); 9302 if (LastIteration64.isUsable()) 9303 LastIteration64 = SemaRef.BuildBinOp( 9304 CurScope, Loc, BO_Mul, LastIteration64.get(), 9305 SemaRef 9306 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(), 9307 Sema::AA_Converting, 9308 /*AllowExplicit=*/true) 9309 .get()); 9310 } 9311 9312 // Choose either the 32-bit or 64-bit version. 9313 ExprResult LastIteration = LastIteration64; 9314 if (SemaRef.getLangOpts().OpenMPOptimisticCollapse || 9315 (LastIteration32.isUsable() && 9316 C.getTypeSize(LastIteration32.get()->getType()) == 32 && 9317 (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 || 9318 fitsInto( 9319 /*Bits=*/32, 9320 LastIteration32.get()->getType()->hasSignedIntegerRepresentation(), 9321 LastIteration64.get(), SemaRef)))) 9322 LastIteration = LastIteration32; 9323 QualType VType = LastIteration.get()->getType(); 9324 QualType RealVType = VType; 9325 QualType StrideVType = VType; 9326 if (isOpenMPTaskLoopDirective(DKind)) { 9327 VType = 9328 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0); 9329 StrideVType = 9330 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1); 9331 } 9332 9333 if (!LastIteration.isUsable()) 9334 return 0; 9335 9336 // Save the number of iterations. 9337 ExprResult NumIterations = LastIteration; 9338 { 9339 LastIteration = SemaRef.BuildBinOp( 9340 CurScope, LastIteration.get()->getExprLoc(), BO_Sub, 9341 LastIteration.get(), 9342 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get()); 9343 if (!LastIteration.isUsable()) 9344 return 0; 9345 } 9346 9347 // Calculate the last iteration number beforehand instead of doing this on 9348 // each iteration. Do not do this if the number of iterations may be kfold-ed. 9349 bool IsConstant = LastIteration.get()->isIntegerConstantExpr(SemaRef.Context); 9350 ExprResult CalcLastIteration; 9351 if (!IsConstant) { 9352 ExprResult SaveRef = 9353 tryBuildCapture(SemaRef, LastIteration.get(), Captures); 9354 LastIteration = SaveRef; 9355 9356 // Prepare SaveRef + 1. 9357 NumIterations = SemaRef.BuildBinOp( 9358 CurScope, SaveRef.get()->getExprLoc(), BO_Add, SaveRef.get(), 9359 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get()); 9360 if (!NumIterations.isUsable()) 9361 return 0; 9362 } 9363 9364 SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin(); 9365 9366 // Build variables passed into runtime, necessary for worksharing directives. 9367 ExprResult LB, UB, IL, ST, EUB, CombLB, CombUB, PrevLB, PrevUB, CombEUB; 9368 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) || 9369 isOpenMPDistributeDirective(DKind) || 9370 isOpenMPGenericLoopDirective(DKind) || 9371 isOpenMPLoopTransformationDirective(DKind)) { 9372 // Lower bound variable, initialized with zero. 9373 VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb"); 9374 LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc); 9375 SemaRef.AddInitializerToDecl(LBDecl, 9376 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(), 9377 /*DirectInit*/ false); 9378 9379 // Upper bound variable, initialized with last iteration number. 9380 VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub"); 9381 UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc); 9382 SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(), 9383 /*DirectInit*/ false); 9384 9385 // A 32-bit variable-flag where runtime returns 1 for the last iteration. 9386 // This will be used to implement clause 'lastprivate'. 9387 QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true); 9388 VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last"); 9389 IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc); 9390 SemaRef.AddInitializerToDecl(ILDecl, 9391 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(), 9392 /*DirectInit*/ false); 9393 9394 // Stride variable returned by runtime (we initialize it to 1 by default). 9395 VarDecl *STDecl = 9396 buildVarDecl(SemaRef, InitLoc, StrideVType, ".omp.stride"); 9397 ST = buildDeclRefExpr(SemaRef, STDecl, StrideVType, InitLoc); 9398 SemaRef.AddInitializerToDecl(STDecl, 9399 SemaRef.ActOnIntegerConstant(InitLoc, 1).get(), 9400 /*DirectInit*/ false); 9401 9402 // Build expression: UB = min(UB, LastIteration) 9403 // It is necessary for CodeGen of directives with static scheduling. 9404 ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT, 9405 UB.get(), LastIteration.get()); 9406 ExprResult CondOp = SemaRef.ActOnConditionalOp( 9407 LastIteration.get()->getExprLoc(), InitLoc, IsUBGreater.get(), 9408 LastIteration.get(), UB.get()); 9409 EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(), 9410 CondOp.get()); 9411 EUB = SemaRef.ActOnFinishFullExpr(EUB.get(), /*DiscardedValue*/ false); 9412 9413 // If we have a combined directive that combines 'distribute', 'for' or 9414 // 'simd' we need to be able to access the bounds of the schedule of the 9415 // enclosing region. E.g. in 'distribute parallel for' the bounds obtained 9416 // by scheduling 'distribute' have to be passed to the schedule of 'for'. 9417 if (isOpenMPLoopBoundSharingDirective(DKind)) { 9418 // Lower bound variable, initialized with zero. 9419 VarDecl *CombLBDecl = 9420 buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.lb"); 9421 CombLB = buildDeclRefExpr(SemaRef, CombLBDecl, VType, InitLoc); 9422 SemaRef.AddInitializerToDecl( 9423 CombLBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(), 9424 /*DirectInit*/ false); 9425 9426 // Upper bound variable, initialized with last iteration number. 9427 VarDecl *CombUBDecl = 9428 buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.ub"); 9429 CombUB = buildDeclRefExpr(SemaRef, CombUBDecl, VType, InitLoc); 9430 SemaRef.AddInitializerToDecl(CombUBDecl, LastIteration.get(), 9431 /*DirectInit*/ false); 9432 9433 ExprResult CombIsUBGreater = SemaRef.BuildBinOp( 9434 CurScope, InitLoc, BO_GT, CombUB.get(), LastIteration.get()); 9435 ExprResult CombCondOp = 9436 SemaRef.ActOnConditionalOp(InitLoc, InitLoc, CombIsUBGreater.get(), 9437 LastIteration.get(), CombUB.get()); 9438 CombEUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, CombUB.get(), 9439 CombCondOp.get()); 9440 CombEUB = 9441 SemaRef.ActOnFinishFullExpr(CombEUB.get(), /*DiscardedValue*/ false); 9442 9443 const CapturedDecl *CD = cast<CapturedStmt>(AStmt)->getCapturedDecl(); 9444 // We expect to have at least 2 more parameters than the 'parallel' 9445 // directive does - the lower and upper bounds of the previous schedule. 9446 assert(CD->getNumParams() >= 4 && 9447 "Unexpected number of parameters in loop combined directive"); 9448 9449 // Set the proper type for the bounds given what we learned from the 9450 // enclosed loops. 9451 ImplicitParamDecl *PrevLBDecl = CD->getParam(/*PrevLB=*/2); 9452 ImplicitParamDecl *PrevUBDecl = CD->getParam(/*PrevUB=*/3); 9453 9454 // Previous lower and upper bounds are obtained from the region 9455 // parameters. 9456 PrevLB = 9457 buildDeclRefExpr(SemaRef, PrevLBDecl, PrevLBDecl->getType(), InitLoc); 9458 PrevUB = 9459 buildDeclRefExpr(SemaRef, PrevUBDecl, PrevUBDecl->getType(), InitLoc); 9460 } 9461 } 9462 9463 // Build the iteration variable and its initialization before loop. 9464 ExprResult IV; 9465 ExprResult Init, CombInit; 9466 { 9467 VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, RealVType, ".omp.iv"); 9468 IV = buildDeclRefExpr(SemaRef, IVDecl, RealVType, InitLoc); 9469 Expr *RHS = (isOpenMPWorksharingDirective(DKind) || 9470 isOpenMPGenericLoopDirective(DKind) || 9471 isOpenMPTaskLoopDirective(DKind) || 9472 isOpenMPDistributeDirective(DKind) || 9473 isOpenMPLoopTransformationDirective(DKind)) 9474 ? LB.get() 9475 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get(); 9476 Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS); 9477 Init = SemaRef.ActOnFinishFullExpr(Init.get(), /*DiscardedValue*/ false); 9478 9479 if (isOpenMPLoopBoundSharingDirective(DKind)) { 9480 Expr *CombRHS = 9481 (isOpenMPWorksharingDirective(DKind) || 9482 isOpenMPGenericLoopDirective(DKind) || 9483 isOpenMPTaskLoopDirective(DKind) || 9484 isOpenMPDistributeDirective(DKind)) 9485 ? CombLB.get() 9486 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get(); 9487 CombInit = 9488 SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), CombRHS); 9489 CombInit = 9490 SemaRef.ActOnFinishFullExpr(CombInit.get(), /*DiscardedValue*/ false); 9491 } 9492 } 9493 9494 bool UseStrictCompare = 9495 RealVType->hasUnsignedIntegerRepresentation() && 9496 llvm::all_of(IterSpaces, [](const LoopIterationSpace &LIS) { 9497 return LIS.IsStrictCompare; 9498 }); 9499 // Loop condition (IV < NumIterations) or (IV <= UB or IV < UB + 1 (for 9500 // unsigned IV)) for worksharing loops. 9501 SourceLocation CondLoc = AStmt->getBeginLoc(); 9502 Expr *BoundUB = UB.get(); 9503 if (UseStrictCompare) { 9504 BoundUB = 9505 SemaRef 9506 .BuildBinOp(CurScope, CondLoc, BO_Add, BoundUB, 9507 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get()) 9508 .get(); 9509 BoundUB = 9510 SemaRef.ActOnFinishFullExpr(BoundUB, /*DiscardedValue*/ false).get(); 9511 } 9512 ExprResult Cond = 9513 (isOpenMPWorksharingDirective(DKind) || 9514 isOpenMPGenericLoopDirective(DKind) || 9515 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind) || 9516 isOpenMPLoopTransformationDirective(DKind)) 9517 ? SemaRef.BuildBinOp(CurScope, CondLoc, 9518 UseStrictCompare ? BO_LT : BO_LE, IV.get(), 9519 BoundUB) 9520 : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(), 9521 NumIterations.get()); 9522 ExprResult CombDistCond; 9523 if (isOpenMPLoopBoundSharingDirective(DKind)) { 9524 CombDistCond = SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(), 9525 NumIterations.get()); 9526 } 9527 9528 ExprResult CombCond; 9529 if (isOpenMPLoopBoundSharingDirective(DKind)) { 9530 Expr *BoundCombUB = CombUB.get(); 9531 if (UseStrictCompare) { 9532 BoundCombUB = 9533 SemaRef 9534 .BuildBinOp( 9535 CurScope, CondLoc, BO_Add, BoundCombUB, 9536 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get()) 9537 .get(); 9538 BoundCombUB = 9539 SemaRef.ActOnFinishFullExpr(BoundCombUB, /*DiscardedValue*/ false) 9540 .get(); 9541 } 9542 CombCond = 9543 SemaRef.BuildBinOp(CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE, 9544 IV.get(), BoundCombUB); 9545 } 9546 // Loop increment (IV = IV + 1) 9547 SourceLocation IncLoc = AStmt->getBeginLoc(); 9548 ExprResult Inc = 9549 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(), 9550 SemaRef.ActOnIntegerConstant(IncLoc, 1).get()); 9551 if (!Inc.isUsable()) 9552 return 0; 9553 Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get()); 9554 Inc = SemaRef.ActOnFinishFullExpr(Inc.get(), /*DiscardedValue*/ false); 9555 if (!Inc.isUsable()) 9556 return 0; 9557 9558 // Increments for worksharing loops (LB = LB + ST; UB = UB + ST). 9559 // Used for directives with static scheduling. 9560 // In combined construct, add combined version that use CombLB and CombUB 9561 // base variables for the update 9562 ExprResult NextLB, NextUB, CombNextLB, CombNextUB; 9563 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) || 9564 isOpenMPGenericLoopDirective(DKind) || 9565 isOpenMPDistributeDirective(DKind) || 9566 isOpenMPLoopTransformationDirective(DKind)) { 9567 // LB + ST 9568 NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get()); 9569 if (!NextLB.isUsable()) 9570 return 0; 9571 // LB = LB + ST 9572 NextLB = 9573 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get()); 9574 NextLB = 9575 SemaRef.ActOnFinishFullExpr(NextLB.get(), /*DiscardedValue*/ false); 9576 if (!NextLB.isUsable()) 9577 return 0; 9578 // UB + ST 9579 NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get()); 9580 if (!NextUB.isUsable()) 9581 return 0; 9582 // UB = UB + ST 9583 NextUB = 9584 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get()); 9585 NextUB = 9586 SemaRef.ActOnFinishFullExpr(NextUB.get(), /*DiscardedValue*/ false); 9587 if (!NextUB.isUsable()) 9588 return 0; 9589 if (isOpenMPLoopBoundSharingDirective(DKind)) { 9590 CombNextLB = 9591 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombLB.get(), ST.get()); 9592 if (!NextLB.isUsable()) 9593 return 0; 9594 // LB = LB + ST 9595 CombNextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombLB.get(), 9596 CombNextLB.get()); 9597 CombNextLB = SemaRef.ActOnFinishFullExpr(CombNextLB.get(), 9598 /*DiscardedValue*/ false); 9599 if (!CombNextLB.isUsable()) 9600 return 0; 9601 // UB + ST 9602 CombNextUB = 9603 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombUB.get(), ST.get()); 9604 if (!CombNextUB.isUsable()) 9605 return 0; 9606 // UB = UB + ST 9607 CombNextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombUB.get(), 9608 CombNextUB.get()); 9609 CombNextUB = SemaRef.ActOnFinishFullExpr(CombNextUB.get(), 9610 /*DiscardedValue*/ false); 9611 if (!CombNextUB.isUsable()) 9612 return 0; 9613 } 9614 } 9615 9616 // Create increment expression for distribute loop when combined in a same 9617 // directive with for as IV = IV + ST; ensure upper bound expression based 9618 // on PrevUB instead of NumIterations - used to implement 'for' when found 9619 // in combination with 'distribute', like in 'distribute parallel for' 9620 SourceLocation DistIncLoc = AStmt->getBeginLoc(); 9621 ExprResult DistCond, DistInc, PrevEUB, ParForInDistCond; 9622 if (isOpenMPLoopBoundSharingDirective(DKind)) { 9623 DistCond = SemaRef.BuildBinOp( 9624 CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE, IV.get(), BoundUB); 9625 assert(DistCond.isUsable() && "distribute cond expr was not built"); 9626 9627 DistInc = 9628 SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Add, IV.get(), ST.get()); 9629 assert(DistInc.isUsable() && "distribute inc expr was not built"); 9630 DistInc = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, IV.get(), 9631 DistInc.get()); 9632 DistInc = 9633 SemaRef.ActOnFinishFullExpr(DistInc.get(), /*DiscardedValue*/ false); 9634 assert(DistInc.isUsable() && "distribute inc expr was not built"); 9635 9636 // Build expression: UB = min(UB, prevUB) for #for in composite or combined 9637 // construct 9638 ExprResult NewPrevUB = PrevUB; 9639 SourceLocation DistEUBLoc = AStmt->getBeginLoc(); 9640 if (!SemaRef.Context.hasSameType(UB.get()->getType(), 9641 PrevUB.get()->getType())) { 9642 NewPrevUB = SemaRef.BuildCStyleCastExpr( 9643 DistEUBLoc, 9644 SemaRef.Context.getTrivialTypeSourceInfo(UB.get()->getType()), 9645 DistEUBLoc, NewPrevUB.get()); 9646 if (!NewPrevUB.isUsable()) 9647 return 0; 9648 } 9649 ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, DistEUBLoc, BO_GT, 9650 UB.get(), NewPrevUB.get()); 9651 ExprResult CondOp = SemaRef.ActOnConditionalOp( 9652 DistEUBLoc, DistEUBLoc, IsUBGreater.get(), NewPrevUB.get(), UB.get()); 9653 PrevEUB = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, UB.get(), 9654 CondOp.get()); 9655 PrevEUB = 9656 SemaRef.ActOnFinishFullExpr(PrevEUB.get(), /*DiscardedValue*/ false); 9657 9658 // Build IV <= PrevUB or IV < PrevUB + 1 for unsigned IV to be used in 9659 // parallel for is in combination with a distribute directive with 9660 // schedule(static, 1) 9661 Expr *BoundPrevUB = PrevUB.get(); 9662 if (UseStrictCompare) { 9663 BoundPrevUB = 9664 SemaRef 9665 .BuildBinOp( 9666 CurScope, CondLoc, BO_Add, BoundPrevUB, 9667 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get()) 9668 .get(); 9669 BoundPrevUB = 9670 SemaRef.ActOnFinishFullExpr(BoundPrevUB, /*DiscardedValue*/ false) 9671 .get(); 9672 } 9673 ParForInDistCond = 9674 SemaRef.BuildBinOp(CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE, 9675 IV.get(), BoundPrevUB); 9676 } 9677 9678 // Build updates and final values of the loop counters. 9679 bool HasErrors = false; 9680 Built.Counters.resize(NestedLoopCount); 9681 Built.Inits.resize(NestedLoopCount); 9682 Built.Updates.resize(NestedLoopCount); 9683 Built.Finals.resize(NestedLoopCount); 9684 Built.DependentCounters.resize(NestedLoopCount); 9685 Built.DependentInits.resize(NestedLoopCount); 9686 Built.FinalsConditions.resize(NestedLoopCount); 9687 { 9688 // We implement the following algorithm for obtaining the 9689 // original loop iteration variable values based on the 9690 // value of the collapsed loop iteration variable IV. 9691 // 9692 // Let n+1 be the number of collapsed loops in the nest. 9693 // Iteration variables (I0, I1, .... In) 9694 // Iteration counts (N0, N1, ... Nn) 9695 // 9696 // Acc = IV; 9697 // 9698 // To compute Ik for loop k, 0 <= k <= n, generate: 9699 // Prod = N(k+1) * N(k+2) * ... * Nn; 9700 // Ik = Acc / Prod; 9701 // Acc -= Ik * Prod; 9702 // 9703 ExprResult Acc = IV; 9704 for (unsigned int Cnt = 0; Cnt < NestedLoopCount; ++Cnt) { 9705 LoopIterationSpace &IS = IterSpaces[Cnt]; 9706 SourceLocation UpdLoc = IS.IncSrcRange.getBegin(); 9707 ExprResult Iter; 9708 9709 // Compute prod 9710 ExprResult Prod = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get(); 9711 for (unsigned int K = Cnt + 1; K < NestedLoopCount; ++K) 9712 Prod = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Prod.get(), 9713 IterSpaces[K].NumIterations); 9714 9715 // Iter = Acc / Prod 9716 // If there is at least one more inner loop to avoid 9717 // multiplication by 1. 9718 if (Cnt + 1 < NestedLoopCount) 9719 Iter = 9720 SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div, Acc.get(), Prod.get()); 9721 else 9722 Iter = Acc; 9723 if (!Iter.isUsable()) { 9724 HasErrors = true; 9725 break; 9726 } 9727 9728 // Update Acc: 9729 // Acc -= Iter * Prod 9730 // Check if there is at least one more inner loop to avoid 9731 // multiplication by 1. 9732 if (Cnt + 1 < NestedLoopCount) 9733 Prod = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Iter.get(), 9734 Prod.get()); 9735 else 9736 Prod = Iter; 9737 Acc = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Sub, Acc.get(), Prod.get()); 9738 9739 // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step 9740 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl()); 9741 DeclRefExpr *CounterVar = buildDeclRefExpr( 9742 SemaRef, VD, IS.CounterVar->getType(), IS.CounterVar->getExprLoc(), 9743 /*RefersToCapture=*/true); 9744 ExprResult Init = 9745 buildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar, 9746 IS.CounterInit, IS.IsNonRectangularLB, Captures); 9747 if (!Init.isUsable()) { 9748 HasErrors = true; 9749 break; 9750 } 9751 ExprResult Update = buildCounterUpdate( 9752 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, Iter, 9753 IS.CounterStep, IS.Subtract, IS.IsNonRectangularLB, &Captures); 9754 if (!Update.isUsable()) { 9755 HasErrors = true; 9756 break; 9757 } 9758 9759 // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step 9760 ExprResult Final = 9761 buildCounterUpdate(SemaRef, CurScope, UpdLoc, CounterVar, 9762 IS.CounterInit, IS.NumIterations, IS.CounterStep, 9763 IS.Subtract, IS.IsNonRectangularLB, &Captures); 9764 if (!Final.isUsable()) { 9765 HasErrors = true; 9766 break; 9767 } 9768 9769 if (!Update.isUsable() || !Final.isUsable()) { 9770 HasErrors = true; 9771 break; 9772 } 9773 // Save results 9774 Built.Counters[Cnt] = IS.CounterVar; 9775 Built.PrivateCounters[Cnt] = IS.PrivateCounterVar; 9776 Built.Inits[Cnt] = Init.get(); 9777 Built.Updates[Cnt] = Update.get(); 9778 Built.Finals[Cnt] = Final.get(); 9779 Built.DependentCounters[Cnt] = nullptr; 9780 Built.DependentInits[Cnt] = nullptr; 9781 Built.FinalsConditions[Cnt] = nullptr; 9782 if (IS.IsNonRectangularLB || IS.IsNonRectangularUB) { 9783 Built.DependentCounters[Cnt] = 9784 Built.Counters[NestedLoopCount - 1 - IS.LoopDependentIdx]; 9785 Built.DependentInits[Cnt] = 9786 Built.Inits[NestedLoopCount - 1 - IS.LoopDependentIdx]; 9787 Built.FinalsConditions[Cnt] = IS.FinalCondition; 9788 } 9789 } 9790 } 9791 9792 if (HasErrors) 9793 return 0; 9794 9795 // Save results 9796 Built.IterationVarRef = IV.get(); 9797 Built.LastIteration = LastIteration.get(); 9798 Built.NumIterations = NumIterations.get(); 9799 Built.CalcLastIteration = SemaRef 9800 .ActOnFinishFullExpr(CalcLastIteration.get(), 9801 /*DiscardedValue=*/false) 9802 .get(); 9803 Built.PreCond = PreCond.get(); 9804 Built.PreInits = buildPreInits(C, Captures); 9805 Built.Cond = Cond.get(); 9806 Built.Init = Init.get(); 9807 Built.Inc = Inc.get(); 9808 Built.LB = LB.get(); 9809 Built.UB = UB.get(); 9810 Built.IL = IL.get(); 9811 Built.ST = ST.get(); 9812 Built.EUB = EUB.get(); 9813 Built.NLB = NextLB.get(); 9814 Built.NUB = NextUB.get(); 9815 Built.PrevLB = PrevLB.get(); 9816 Built.PrevUB = PrevUB.get(); 9817 Built.DistInc = DistInc.get(); 9818 Built.PrevEUB = PrevEUB.get(); 9819 Built.DistCombinedFields.LB = CombLB.get(); 9820 Built.DistCombinedFields.UB = CombUB.get(); 9821 Built.DistCombinedFields.EUB = CombEUB.get(); 9822 Built.DistCombinedFields.Init = CombInit.get(); 9823 Built.DistCombinedFields.Cond = CombCond.get(); 9824 Built.DistCombinedFields.NLB = CombNextLB.get(); 9825 Built.DistCombinedFields.NUB = CombNextUB.get(); 9826 Built.DistCombinedFields.DistCond = CombDistCond.get(); 9827 Built.DistCombinedFields.ParForInDistCond = ParForInDistCond.get(); 9828 9829 return NestedLoopCount; 9830 } 9831 9832 static Expr *getCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) { 9833 auto CollapseClauses = 9834 OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses); 9835 if (CollapseClauses.begin() != CollapseClauses.end()) 9836 return (*CollapseClauses.begin())->getNumForLoops(); 9837 return nullptr; 9838 } 9839 9840 static Expr *getOrderedNumberExpr(ArrayRef<OMPClause *> Clauses) { 9841 auto OrderedClauses = 9842 OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses); 9843 if (OrderedClauses.begin() != OrderedClauses.end()) 9844 return (*OrderedClauses.begin())->getNumForLoops(); 9845 return nullptr; 9846 } 9847 9848 static bool checkSimdlenSafelenSpecified(Sema &S, 9849 const ArrayRef<OMPClause *> Clauses) { 9850 const OMPSafelenClause *Safelen = nullptr; 9851 const OMPSimdlenClause *Simdlen = nullptr; 9852 9853 for (const OMPClause *Clause : Clauses) { 9854 if (Clause->getClauseKind() == OMPC_safelen) 9855 Safelen = cast<OMPSafelenClause>(Clause); 9856 else if (Clause->getClauseKind() == OMPC_simdlen) 9857 Simdlen = cast<OMPSimdlenClause>(Clause); 9858 if (Safelen && Simdlen) 9859 break; 9860 } 9861 9862 if (Simdlen && Safelen) { 9863 const Expr *SimdlenLength = Simdlen->getSimdlen(); 9864 const Expr *SafelenLength = Safelen->getSafelen(); 9865 if (SimdlenLength->isValueDependent() || SimdlenLength->isTypeDependent() || 9866 SimdlenLength->isInstantiationDependent() || 9867 SimdlenLength->containsUnexpandedParameterPack()) 9868 return false; 9869 if (SafelenLength->isValueDependent() || SafelenLength->isTypeDependent() || 9870 SafelenLength->isInstantiationDependent() || 9871 SafelenLength->containsUnexpandedParameterPack()) 9872 return false; 9873 Expr::EvalResult SimdlenResult, SafelenResult; 9874 SimdlenLength->EvaluateAsInt(SimdlenResult, S.Context); 9875 SafelenLength->EvaluateAsInt(SafelenResult, S.Context); 9876 llvm::APSInt SimdlenRes = SimdlenResult.Val.getInt(); 9877 llvm::APSInt SafelenRes = SafelenResult.Val.getInt(); 9878 // OpenMP 4.5 [2.8.1, simd Construct, Restrictions] 9879 // If both simdlen and safelen clauses are specified, the value of the 9880 // simdlen parameter must be less than or equal to the value of the safelen 9881 // parameter. 9882 if (SimdlenRes > SafelenRes) { 9883 S.Diag(SimdlenLength->getExprLoc(), 9884 diag::err_omp_wrong_simdlen_safelen_values) 9885 << SimdlenLength->getSourceRange() << SafelenLength->getSourceRange(); 9886 return true; 9887 } 9888 } 9889 return false; 9890 } 9891 9892 StmtResult 9893 Sema::ActOnOpenMPSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, 9894 SourceLocation StartLoc, SourceLocation EndLoc, 9895 VarsWithInheritedDSAType &VarsWithImplicitDSA) { 9896 if (!AStmt) 9897 return StmtError(); 9898 9899 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 9900 OMPLoopBasedDirective::HelperExprs B; 9901 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 9902 // define the nested loops number. 9903 unsigned NestedLoopCount = checkOpenMPLoop( 9904 OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses), 9905 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B); 9906 if (NestedLoopCount == 0) 9907 return StmtError(); 9908 9909 assert((CurContext->isDependentContext() || B.builtAll()) && 9910 "omp simd loop exprs were not built"); 9911 9912 if (!CurContext->isDependentContext()) { 9913 // Finalize the clauses that need pre-built expressions for CodeGen. 9914 for (OMPClause *C : Clauses) { 9915 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 9916 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 9917 B.NumIterations, *this, CurScope, 9918 DSAStack)) 9919 return StmtError(); 9920 } 9921 } 9922 9923 if (checkSimdlenSafelenSpecified(*this, Clauses)) 9924 return StmtError(); 9925 9926 setFunctionHasBranchProtectedScope(); 9927 return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount, 9928 Clauses, AStmt, B); 9929 } 9930 9931 StmtResult 9932 Sema::ActOnOpenMPForDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, 9933 SourceLocation StartLoc, SourceLocation EndLoc, 9934 VarsWithInheritedDSAType &VarsWithImplicitDSA) { 9935 if (!AStmt) 9936 return StmtError(); 9937 9938 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 9939 OMPLoopBasedDirective::HelperExprs B; 9940 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 9941 // define the nested loops number. 9942 unsigned NestedLoopCount = checkOpenMPLoop( 9943 OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses), 9944 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B); 9945 if (NestedLoopCount == 0) 9946 return StmtError(); 9947 9948 assert((CurContext->isDependentContext() || B.builtAll()) && 9949 "omp for loop exprs were not built"); 9950 9951 if (!CurContext->isDependentContext()) { 9952 // Finalize the clauses that need pre-built expressions for CodeGen. 9953 for (OMPClause *C : Clauses) { 9954 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 9955 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 9956 B.NumIterations, *this, CurScope, 9957 DSAStack)) 9958 return StmtError(); 9959 } 9960 } 9961 9962 setFunctionHasBranchProtectedScope(); 9963 return OMPForDirective::Create( 9964 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B, 9965 DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion()); 9966 } 9967 9968 StmtResult Sema::ActOnOpenMPForSimdDirective( 9969 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 9970 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 9971 if (!AStmt) 9972 return StmtError(); 9973 9974 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 9975 OMPLoopBasedDirective::HelperExprs B; 9976 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 9977 // define the nested loops number. 9978 unsigned NestedLoopCount = 9979 checkOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses), 9980 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack, 9981 VarsWithImplicitDSA, B); 9982 if (NestedLoopCount == 0) 9983 return StmtError(); 9984 9985 assert((CurContext->isDependentContext() || B.builtAll()) && 9986 "omp for simd loop exprs were not built"); 9987 9988 if (!CurContext->isDependentContext()) { 9989 // Finalize the clauses that need pre-built expressions for CodeGen. 9990 for (OMPClause *C : Clauses) { 9991 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 9992 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 9993 B.NumIterations, *this, CurScope, 9994 DSAStack)) 9995 return StmtError(); 9996 } 9997 } 9998 9999 if (checkSimdlenSafelenSpecified(*this, Clauses)) 10000 return StmtError(); 10001 10002 setFunctionHasBranchProtectedScope(); 10003 return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount, 10004 Clauses, AStmt, B); 10005 } 10006 10007 StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses, 10008 Stmt *AStmt, 10009 SourceLocation StartLoc, 10010 SourceLocation EndLoc) { 10011 if (!AStmt) 10012 return StmtError(); 10013 10014 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 10015 auto BaseStmt = AStmt; 10016 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt)) 10017 BaseStmt = CS->getCapturedStmt(); 10018 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) { 10019 auto S = C->children(); 10020 if (S.begin() == S.end()) 10021 return StmtError(); 10022 // All associated statements must be '#pragma omp section' except for 10023 // the first one. 10024 for (Stmt *SectionStmt : llvm::drop_begin(S)) { 10025 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) { 10026 if (SectionStmt) 10027 Diag(SectionStmt->getBeginLoc(), 10028 diag::err_omp_sections_substmt_not_section); 10029 return StmtError(); 10030 } 10031 cast<OMPSectionDirective>(SectionStmt) 10032 ->setHasCancel(DSAStack->isCancelRegion()); 10033 } 10034 } else { 10035 Diag(AStmt->getBeginLoc(), diag::err_omp_sections_not_compound_stmt); 10036 return StmtError(); 10037 } 10038 10039 setFunctionHasBranchProtectedScope(); 10040 10041 return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt, 10042 DSAStack->getTaskgroupReductionRef(), 10043 DSAStack->isCancelRegion()); 10044 } 10045 10046 StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt, 10047 SourceLocation StartLoc, 10048 SourceLocation EndLoc) { 10049 if (!AStmt) 10050 return StmtError(); 10051 10052 setFunctionHasBranchProtectedScope(); 10053 DSAStack->setParentCancelRegion(DSAStack->isCancelRegion()); 10054 10055 return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt, 10056 DSAStack->isCancelRegion()); 10057 } 10058 10059 static Expr *getDirectCallExpr(Expr *E) { 10060 E = E->IgnoreParenCasts()->IgnoreImplicit(); 10061 if (auto *CE = dyn_cast<CallExpr>(E)) 10062 if (CE->getDirectCallee()) 10063 return E; 10064 return nullptr; 10065 } 10066 10067 StmtResult Sema::ActOnOpenMPDispatchDirective(ArrayRef<OMPClause *> Clauses, 10068 Stmt *AStmt, 10069 SourceLocation StartLoc, 10070 SourceLocation EndLoc) { 10071 if (!AStmt) 10072 return StmtError(); 10073 10074 Stmt *S = cast<CapturedStmt>(AStmt)->getCapturedStmt(); 10075 10076 // 5.1 OpenMP 10077 // expression-stmt : an expression statement with one of the following forms: 10078 // expression = target-call ( [expression-list] ); 10079 // target-call ( [expression-list] ); 10080 10081 SourceLocation TargetCallLoc; 10082 10083 if (!CurContext->isDependentContext()) { 10084 Expr *TargetCall = nullptr; 10085 10086 auto *E = dyn_cast<Expr>(S); 10087 if (!E) { 10088 Diag(S->getBeginLoc(), diag::err_omp_dispatch_statement_call); 10089 return StmtError(); 10090 } 10091 10092 E = E->IgnoreParenCasts()->IgnoreImplicit(); 10093 10094 if (auto *BO = dyn_cast<BinaryOperator>(E)) { 10095 if (BO->getOpcode() == BO_Assign) 10096 TargetCall = getDirectCallExpr(BO->getRHS()); 10097 } else { 10098 if (auto *COCE = dyn_cast<CXXOperatorCallExpr>(E)) 10099 if (COCE->getOperator() == OO_Equal) 10100 TargetCall = getDirectCallExpr(COCE->getArg(1)); 10101 if (!TargetCall) 10102 TargetCall = getDirectCallExpr(E); 10103 } 10104 if (!TargetCall) { 10105 Diag(E->getBeginLoc(), diag::err_omp_dispatch_statement_call); 10106 return StmtError(); 10107 } 10108 TargetCallLoc = TargetCall->getExprLoc(); 10109 } 10110 10111 setFunctionHasBranchProtectedScope(); 10112 10113 return OMPDispatchDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt, 10114 TargetCallLoc); 10115 } 10116 10117 StmtResult Sema::ActOnOpenMPGenericLoopDirective( 10118 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 10119 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 10120 if (!AStmt) 10121 return StmtError(); 10122 10123 // OpenMP 5.1 [2.11.7, loop construct] 10124 // A list item may not appear in a lastprivate clause unless it is the 10125 // loop iteration variable of a loop that is associated with the construct. 10126 for (OMPClause *C : Clauses) { 10127 if (auto *LPC = dyn_cast<OMPLastprivateClause>(C)) { 10128 for (Expr *RefExpr : LPC->varlists()) { 10129 SourceLocation ELoc; 10130 SourceRange ERange; 10131 Expr *SimpleRefExpr = RefExpr; 10132 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 10133 if (ValueDecl *D = Res.first) { 10134 auto &&Info = DSAStack->isLoopControlVariable(D); 10135 if (!Info.first) { 10136 Diag(ELoc, diag::err_omp_lastprivate_loop_var_non_loop_iteration); 10137 return StmtError(); 10138 } 10139 } 10140 } 10141 } 10142 } 10143 10144 auto *CS = cast<CapturedStmt>(AStmt); 10145 // 1.2.2 OpenMP Language Terminology 10146 // Structured block - An executable statement with a single entry at the 10147 // top and a single exit at the bottom. 10148 // The point of exit cannot be a branch out of the structured block. 10149 // longjmp() and throw() must not violate the entry/exit criteria. 10150 CS->getCapturedDecl()->setNothrow(); 10151 10152 OMPLoopDirective::HelperExprs B; 10153 // In presence of clause 'collapse', it will define the nested loops number. 10154 unsigned NestedLoopCount = checkOpenMPLoop( 10155 OMPD_loop, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses), 10156 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B); 10157 if (NestedLoopCount == 0) 10158 return StmtError(); 10159 10160 assert((CurContext->isDependentContext() || B.builtAll()) && 10161 "omp loop exprs were not built"); 10162 10163 setFunctionHasBranchProtectedScope(); 10164 return OMPGenericLoopDirective::Create(Context, StartLoc, EndLoc, 10165 NestedLoopCount, Clauses, AStmt, B); 10166 } 10167 10168 StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses, 10169 Stmt *AStmt, 10170 SourceLocation StartLoc, 10171 SourceLocation EndLoc) { 10172 if (!AStmt) 10173 return StmtError(); 10174 10175 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 10176 10177 setFunctionHasBranchProtectedScope(); 10178 10179 // OpenMP [2.7.3, single Construct, Restrictions] 10180 // The copyprivate clause must not be used with the nowait clause. 10181 const OMPClause *Nowait = nullptr; 10182 const OMPClause *Copyprivate = nullptr; 10183 for (const OMPClause *Clause : Clauses) { 10184 if (Clause->getClauseKind() == OMPC_nowait) 10185 Nowait = Clause; 10186 else if (Clause->getClauseKind() == OMPC_copyprivate) 10187 Copyprivate = Clause; 10188 if (Copyprivate && Nowait) { 10189 Diag(Copyprivate->getBeginLoc(), 10190 diag::err_omp_single_copyprivate_with_nowait); 10191 Diag(Nowait->getBeginLoc(), diag::note_omp_nowait_clause_here); 10192 return StmtError(); 10193 } 10194 } 10195 10196 return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt); 10197 } 10198 10199 StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt, 10200 SourceLocation StartLoc, 10201 SourceLocation EndLoc) { 10202 if (!AStmt) 10203 return StmtError(); 10204 10205 setFunctionHasBranchProtectedScope(); 10206 10207 return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt); 10208 } 10209 10210 StmtResult Sema::ActOnOpenMPMaskedDirective(ArrayRef<OMPClause *> Clauses, 10211 Stmt *AStmt, 10212 SourceLocation StartLoc, 10213 SourceLocation EndLoc) { 10214 if (!AStmt) 10215 return StmtError(); 10216 10217 setFunctionHasBranchProtectedScope(); 10218 10219 return OMPMaskedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt); 10220 } 10221 10222 StmtResult Sema::ActOnOpenMPCriticalDirective( 10223 const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses, 10224 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) { 10225 if (!AStmt) 10226 return StmtError(); 10227 10228 bool ErrorFound = false; 10229 llvm::APSInt Hint; 10230 SourceLocation HintLoc; 10231 bool DependentHint = false; 10232 for (const OMPClause *C : Clauses) { 10233 if (C->getClauseKind() == OMPC_hint) { 10234 if (!DirName.getName()) { 10235 Diag(C->getBeginLoc(), diag::err_omp_hint_clause_no_name); 10236 ErrorFound = true; 10237 } 10238 Expr *E = cast<OMPHintClause>(C)->getHint(); 10239 if (E->isTypeDependent() || E->isValueDependent() || 10240 E->isInstantiationDependent()) { 10241 DependentHint = true; 10242 } else { 10243 Hint = E->EvaluateKnownConstInt(Context); 10244 HintLoc = C->getBeginLoc(); 10245 } 10246 } 10247 } 10248 if (ErrorFound) 10249 return StmtError(); 10250 const auto Pair = DSAStack->getCriticalWithHint(DirName); 10251 if (Pair.first && DirName.getName() && !DependentHint) { 10252 if (llvm::APSInt::compareValues(Hint, Pair.second) != 0) { 10253 Diag(StartLoc, diag::err_omp_critical_with_hint); 10254 if (HintLoc.isValid()) 10255 Diag(HintLoc, diag::note_omp_critical_hint_here) 10256 << 0 << toString(Hint, /*Radix=*/10, /*Signed=*/false); 10257 else 10258 Diag(StartLoc, diag::note_omp_critical_no_hint) << 0; 10259 if (const auto *C = Pair.first->getSingleClause<OMPHintClause>()) { 10260 Diag(C->getBeginLoc(), diag::note_omp_critical_hint_here) 10261 << 1 10262 << toString(C->getHint()->EvaluateKnownConstInt(Context), 10263 /*Radix=*/10, /*Signed=*/false); 10264 } else { 10265 Diag(Pair.first->getBeginLoc(), diag::note_omp_critical_no_hint) << 1; 10266 } 10267 } 10268 } 10269 10270 setFunctionHasBranchProtectedScope(); 10271 10272 auto *Dir = OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc, 10273 Clauses, AStmt); 10274 if (!Pair.first && DirName.getName() && !DependentHint) 10275 DSAStack->addCriticalWithHint(Dir, Hint); 10276 return Dir; 10277 } 10278 10279 StmtResult Sema::ActOnOpenMPParallelForDirective( 10280 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 10281 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 10282 if (!AStmt) 10283 return StmtError(); 10284 10285 auto *CS = cast<CapturedStmt>(AStmt); 10286 // 1.2.2 OpenMP Language Terminology 10287 // Structured block - An executable statement with a single entry at the 10288 // top and a single exit at the bottom. 10289 // The point of exit cannot be a branch out of the structured block. 10290 // longjmp() and throw() must not violate the entry/exit criteria. 10291 CS->getCapturedDecl()->setNothrow(); 10292 10293 OMPLoopBasedDirective::HelperExprs B; 10294 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 10295 // define the nested loops number. 10296 unsigned NestedLoopCount = 10297 checkOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses), 10298 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack, 10299 VarsWithImplicitDSA, B); 10300 if (NestedLoopCount == 0) 10301 return StmtError(); 10302 10303 assert((CurContext->isDependentContext() || B.builtAll()) && 10304 "omp parallel for loop exprs were not built"); 10305 10306 if (!CurContext->isDependentContext()) { 10307 // Finalize the clauses that need pre-built expressions for CodeGen. 10308 for (OMPClause *C : Clauses) { 10309 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 10310 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 10311 B.NumIterations, *this, CurScope, 10312 DSAStack)) 10313 return StmtError(); 10314 } 10315 } 10316 10317 setFunctionHasBranchProtectedScope(); 10318 return OMPParallelForDirective::Create( 10319 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B, 10320 DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion()); 10321 } 10322 10323 StmtResult Sema::ActOnOpenMPParallelForSimdDirective( 10324 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 10325 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 10326 if (!AStmt) 10327 return StmtError(); 10328 10329 auto *CS = cast<CapturedStmt>(AStmt); 10330 // 1.2.2 OpenMP Language Terminology 10331 // Structured block - An executable statement with a single entry at the 10332 // top and a single exit at the bottom. 10333 // The point of exit cannot be a branch out of the structured block. 10334 // longjmp() and throw() must not violate the entry/exit criteria. 10335 CS->getCapturedDecl()->setNothrow(); 10336 10337 OMPLoopBasedDirective::HelperExprs B; 10338 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 10339 // define the nested loops number. 10340 unsigned NestedLoopCount = 10341 checkOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses), 10342 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack, 10343 VarsWithImplicitDSA, B); 10344 if (NestedLoopCount == 0) 10345 return StmtError(); 10346 10347 if (!CurContext->isDependentContext()) { 10348 // Finalize the clauses that need pre-built expressions for CodeGen. 10349 for (OMPClause *C : Clauses) { 10350 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 10351 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 10352 B.NumIterations, *this, CurScope, 10353 DSAStack)) 10354 return StmtError(); 10355 } 10356 } 10357 10358 if (checkSimdlenSafelenSpecified(*this, Clauses)) 10359 return StmtError(); 10360 10361 setFunctionHasBranchProtectedScope(); 10362 return OMPParallelForSimdDirective::Create( 10363 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 10364 } 10365 10366 StmtResult 10367 Sema::ActOnOpenMPParallelMasterDirective(ArrayRef<OMPClause *> Clauses, 10368 Stmt *AStmt, SourceLocation StartLoc, 10369 SourceLocation EndLoc) { 10370 if (!AStmt) 10371 return StmtError(); 10372 10373 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 10374 auto *CS = cast<CapturedStmt>(AStmt); 10375 // 1.2.2 OpenMP Language Terminology 10376 // Structured block - An executable statement with a single entry at the 10377 // top and a single exit at the bottom. 10378 // The point of exit cannot be a branch out of the structured block. 10379 // longjmp() and throw() must not violate the entry/exit criteria. 10380 CS->getCapturedDecl()->setNothrow(); 10381 10382 setFunctionHasBranchProtectedScope(); 10383 10384 return OMPParallelMasterDirective::Create( 10385 Context, StartLoc, EndLoc, Clauses, AStmt, 10386 DSAStack->getTaskgroupReductionRef()); 10387 } 10388 10389 StmtResult 10390 Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses, 10391 Stmt *AStmt, SourceLocation StartLoc, 10392 SourceLocation EndLoc) { 10393 if (!AStmt) 10394 return StmtError(); 10395 10396 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 10397 auto BaseStmt = AStmt; 10398 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt)) 10399 BaseStmt = CS->getCapturedStmt(); 10400 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) { 10401 auto S = C->children(); 10402 if (S.begin() == S.end()) 10403 return StmtError(); 10404 // All associated statements must be '#pragma omp section' except for 10405 // the first one. 10406 for (Stmt *SectionStmt : llvm::drop_begin(S)) { 10407 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) { 10408 if (SectionStmt) 10409 Diag(SectionStmt->getBeginLoc(), 10410 diag::err_omp_parallel_sections_substmt_not_section); 10411 return StmtError(); 10412 } 10413 cast<OMPSectionDirective>(SectionStmt) 10414 ->setHasCancel(DSAStack->isCancelRegion()); 10415 } 10416 } else { 10417 Diag(AStmt->getBeginLoc(), 10418 diag::err_omp_parallel_sections_not_compound_stmt); 10419 return StmtError(); 10420 } 10421 10422 setFunctionHasBranchProtectedScope(); 10423 10424 return OMPParallelSectionsDirective::Create( 10425 Context, StartLoc, EndLoc, Clauses, AStmt, 10426 DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion()); 10427 } 10428 10429 /// Find and diagnose mutually exclusive clause kinds. 10430 static bool checkMutuallyExclusiveClauses( 10431 Sema &S, ArrayRef<OMPClause *> Clauses, 10432 ArrayRef<OpenMPClauseKind> MutuallyExclusiveClauses) { 10433 const OMPClause *PrevClause = nullptr; 10434 bool ErrorFound = false; 10435 for (const OMPClause *C : Clauses) { 10436 if (llvm::is_contained(MutuallyExclusiveClauses, C->getClauseKind())) { 10437 if (!PrevClause) { 10438 PrevClause = C; 10439 } else if (PrevClause->getClauseKind() != C->getClauseKind()) { 10440 S.Diag(C->getBeginLoc(), diag::err_omp_clauses_mutually_exclusive) 10441 << getOpenMPClauseName(C->getClauseKind()) 10442 << getOpenMPClauseName(PrevClause->getClauseKind()); 10443 S.Diag(PrevClause->getBeginLoc(), diag::note_omp_previous_clause) 10444 << getOpenMPClauseName(PrevClause->getClauseKind()); 10445 ErrorFound = true; 10446 } 10447 } 10448 } 10449 return ErrorFound; 10450 } 10451 10452 StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses, 10453 Stmt *AStmt, SourceLocation StartLoc, 10454 SourceLocation EndLoc) { 10455 if (!AStmt) 10456 return StmtError(); 10457 10458 // OpenMP 5.0, 2.10.1 task Construct 10459 // If a detach clause appears on the directive, then a mergeable clause cannot 10460 // appear on the same directive. 10461 if (checkMutuallyExclusiveClauses(*this, Clauses, 10462 {OMPC_detach, OMPC_mergeable})) 10463 return StmtError(); 10464 10465 auto *CS = cast<CapturedStmt>(AStmt); 10466 // 1.2.2 OpenMP Language Terminology 10467 // Structured block - An executable statement with a single entry at the 10468 // top and a single exit at the bottom. 10469 // The point of exit cannot be a branch out of the structured block. 10470 // longjmp() and throw() must not violate the entry/exit criteria. 10471 CS->getCapturedDecl()->setNothrow(); 10472 10473 setFunctionHasBranchProtectedScope(); 10474 10475 return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt, 10476 DSAStack->isCancelRegion()); 10477 } 10478 10479 StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc, 10480 SourceLocation EndLoc) { 10481 return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc); 10482 } 10483 10484 StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc, 10485 SourceLocation EndLoc) { 10486 return OMPBarrierDirective::Create(Context, StartLoc, EndLoc); 10487 } 10488 10489 StmtResult Sema::ActOnOpenMPTaskwaitDirective(ArrayRef<OMPClause *> Clauses, 10490 SourceLocation StartLoc, 10491 SourceLocation EndLoc) { 10492 return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc, Clauses); 10493 } 10494 10495 StmtResult Sema::ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses, 10496 Stmt *AStmt, 10497 SourceLocation StartLoc, 10498 SourceLocation EndLoc) { 10499 if (!AStmt) 10500 return StmtError(); 10501 10502 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 10503 10504 setFunctionHasBranchProtectedScope(); 10505 10506 return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, Clauses, 10507 AStmt, 10508 DSAStack->getTaskgroupReductionRef()); 10509 } 10510 10511 StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses, 10512 SourceLocation StartLoc, 10513 SourceLocation EndLoc) { 10514 OMPFlushClause *FC = nullptr; 10515 OMPClause *OrderClause = nullptr; 10516 for (OMPClause *C : Clauses) { 10517 if (C->getClauseKind() == OMPC_flush) 10518 FC = cast<OMPFlushClause>(C); 10519 else 10520 OrderClause = C; 10521 } 10522 OpenMPClauseKind MemOrderKind = OMPC_unknown; 10523 SourceLocation MemOrderLoc; 10524 for (const OMPClause *C : Clauses) { 10525 if (C->getClauseKind() == OMPC_acq_rel || 10526 C->getClauseKind() == OMPC_acquire || 10527 C->getClauseKind() == OMPC_release) { 10528 if (MemOrderKind != OMPC_unknown) { 10529 Diag(C->getBeginLoc(), diag::err_omp_several_mem_order_clauses) 10530 << getOpenMPDirectiveName(OMPD_flush) << 1 10531 << SourceRange(C->getBeginLoc(), C->getEndLoc()); 10532 Diag(MemOrderLoc, diag::note_omp_previous_mem_order_clause) 10533 << getOpenMPClauseName(MemOrderKind); 10534 } else { 10535 MemOrderKind = C->getClauseKind(); 10536 MemOrderLoc = C->getBeginLoc(); 10537 } 10538 } 10539 } 10540 if (FC && OrderClause) { 10541 Diag(FC->getLParenLoc(), diag::err_omp_flush_order_clause_and_list) 10542 << getOpenMPClauseName(OrderClause->getClauseKind()); 10543 Diag(OrderClause->getBeginLoc(), diag::note_omp_flush_order_clause_here) 10544 << getOpenMPClauseName(OrderClause->getClauseKind()); 10545 return StmtError(); 10546 } 10547 return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses); 10548 } 10549 10550 StmtResult Sema::ActOnOpenMPDepobjDirective(ArrayRef<OMPClause *> Clauses, 10551 SourceLocation StartLoc, 10552 SourceLocation EndLoc) { 10553 if (Clauses.empty()) { 10554 Diag(StartLoc, diag::err_omp_depobj_expected); 10555 return StmtError(); 10556 } else if (Clauses[0]->getClauseKind() != OMPC_depobj) { 10557 Diag(Clauses[0]->getBeginLoc(), diag::err_omp_depobj_expected); 10558 return StmtError(); 10559 } 10560 // Only depobj expression and another single clause is allowed. 10561 if (Clauses.size() > 2) { 10562 Diag(Clauses[2]->getBeginLoc(), 10563 diag::err_omp_depobj_single_clause_expected); 10564 return StmtError(); 10565 } else if (Clauses.size() < 1) { 10566 Diag(Clauses[0]->getEndLoc(), diag::err_omp_depobj_single_clause_expected); 10567 return StmtError(); 10568 } 10569 return OMPDepobjDirective::Create(Context, StartLoc, EndLoc, Clauses); 10570 } 10571 10572 StmtResult Sema::ActOnOpenMPScanDirective(ArrayRef<OMPClause *> Clauses, 10573 SourceLocation StartLoc, 10574 SourceLocation EndLoc) { 10575 // Check that exactly one clause is specified. 10576 if (Clauses.size() != 1) { 10577 Diag(Clauses.empty() ? EndLoc : Clauses[1]->getBeginLoc(), 10578 diag::err_omp_scan_single_clause_expected); 10579 return StmtError(); 10580 } 10581 // Check that scan directive is used in the scopeof the OpenMP loop body. 10582 if (Scope *S = DSAStack->getCurScope()) { 10583 Scope *ParentS = S->getParent(); 10584 if (!ParentS || ParentS->getParent() != ParentS->getBreakParent() || 10585 !ParentS->getBreakParent()->isOpenMPLoopScope()) 10586 return StmtError(Diag(StartLoc, diag::err_omp_orphaned_device_directive) 10587 << getOpenMPDirectiveName(OMPD_scan) << 5); 10588 } 10589 // Check that only one instance of scan directives is used in the same outer 10590 // region. 10591 if (DSAStack->doesParentHasScanDirective()) { 10592 Diag(StartLoc, diag::err_omp_several_directives_in_region) << "scan"; 10593 Diag(DSAStack->getParentScanDirectiveLoc(), 10594 diag::note_omp_previous_directive) 10595 << "scan"; 10596 return StmtError(); 10597 } 10598 DSAStack->setParentHasScanDirective(StartLoc); 10599 return OMPScanDirective::Create(Context, StartLoc, EndLoc, Clauses); 10600 } 10601 10602 StmtResult Sema::ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses, 10603 Stmt *AStmt, 10604 SourceLocation StartLoc, 10605 SourceLocation EndLoc) { 10606 const OMPClause *DependFound = nullptr; 10607 const OMPClause *DependSourceClause = nullptr; 10608 const OMPClause *DependSinkClause = nullptr; 10609 bool ErrorFound = false; 10610 const OMPThreadsClause *TC = nullptr; 10611 const OMPSIMDClause *SC = nullptr; 10612 for (const OMPClause *C : Clauses) { 10613 if (auto *DC = dyn_cast<OMPDependClause>(C)) { 10614 DependFound = C; 10615 if (DC->getDependencyKind() == OMPC_DEPEND_source) { 10616 if (DependSourceClause) { 10617 Diag(C->getBeginLoc(), diag::err_omp_more_one_clause) 10618 << getOpenMPDirectiveName(OMPD_ordered) 10619 << getOpenMPClauseName(OMPC_depend) << 2; 10620 ErrorFound = true; 10621 } else { 10622 DependSourceClause = C; 10623 } 10624 if (DependSinkClause) { 10625 Diag(C->getBeginLoc(), diag::err_omp_depend_sink_source_not_allowed) 10626 << 0; 10627 ErrorFound = true; 10628 } 10629 } else if (DC->getDependencyKind() == OMPC_DEPEND_sink) { 10630 if (DependSourceClause) { 10631 Diag(C->getBeginLoc(), diag::err_omp_depend_sink_source_not_allowed) 10632 << 1; 10633 ErrorFound = true; 10634 } 10635 DependSinkClause = C; 10636 } 10637 } else if (C->getClauseKind() == OMPC_threads) { 10638 TC = cast<OMPThreadsClause>(C); 10639 } else if (C->getClauseKind() == OMPC_simd) { 10640 SC = cast<OMPSIMDClause>(C); 10641 } 10642 } 10643 if (!ErrorFound && !SC && 10644 isOpenMPSimdDirective(DSAStack->getParentDirective())) { 10645 // OpenMP [2.8.1,simd Construct, Restrictions] 10646 // An ordered construct with the simd clause is the only OpenMP construct 10647 // that can appear in the simd region. 10648 Diag(StartLoc, diag::err_omp_prohibited_region_simd) 10649 << (LangOpts.OpenMP >= 50 ? 1 : 0); 10650 ErrorFound = true; 10651 } else if (DependFound && (TC || SC)) { 10652 Diag(DependFound->getBeginLoc(), diag::err_omp_depend_clause_thread_simd) 10653 << getOpenMPClauseName(TC ? TC->getClauseKind() : SC->getClauseKind()); 10654 ErrorFound = true; 10655 } else if (DependFound && !DSAStack->getParentOrderedRegionParam().first) { 10656 Diag(DependFound->getBeginLoc(), 10657 diag::err_omp_ordered_directive_without_param); 10658 ErrorFound = true; 10659 } else if (TC || Clauses.empty()) { 10660 if (const Expr *Param = DSAStack->getParentOrderedRegionParam().first) { 10661 SourceLocation ErrLoc = TC ? TC->getBeginLoc() : StartLoc; 10662 Diag(ErrLoc, diag::err_omp_ordered_directive_with_param) 10663 << (TC != nullptr); 10664 Diag(Param->getBeginLoc(), diag::note_omp_ordered_param) << 1; 10665 ErrorFound = true; 10666 } 10667 } 10668 if ((!AStmt && !DependFound) || ErrorFound) 10669 return StmtError(); 10670 10671 // OpenMP 5.0, 2.17.9, ordered Construct, Restrictions. 10672 // During execution of an iteration of a worksharing-loop or a loop nest 10673 // within a worksharing-loop, simd, or worksharing-loop SIMD region, a thread 10674 // must not execute more than one ordered region corresponding to an ordered 10675 // construct without a depend clause. 10676 if (!DependFound) { 10677 if (DSAStack->doesParentHasOrderedDirective()) { 10678 Diag(StartLoc, diag::err_omp_several_directives_in_region) << "ordered"; 10679 Diag(DSAStack->getParentOrderedDirectiveLoc(), 10680 diag::note_omp_previous_directive) 10681 << "ordered"; 10682 return StmtError(); 10683 } 10684 DSAStack->setParentHasOrderedDirective(StartLoc); 10685 } 10686 10687 if (AStmt) { 10688 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 10689 10690 setFunctionHasBranchProtectedScope(); 10691 } 10692 10693 return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt); 10694 } 10695 10696 namespace { 10697 /// Helper class for checking expression in 'omp atomic [update]' 10698 /// construct. 10699 class OpenMPAtomicUpdateChecker { 10700 /// Error results for atomic update expressions. 10701 enum ExprAnalysisErrorCode { 10702 /// A statement is not an expression statement. 10703 NotAnExpression, 10704 /// Expression is not builtin binary or unary operation. 10705 NotABinaryOrUnaryExpression, 10706 /// Unary operation is not post-/pre- increment/decrement operation. 10707 NotAnUnaryIncDecExpression, 10708 /// An expression is not of scalar type. 10709 NotAScalarType, 10710 /// A binary operation is not an assignment operation. 10711 NotAnAssignmentOp, 10712 /// RHS part of the binary operation is not a binary expression. 10713 NotABinaryExpression, 10714 /// RHS part is not additive/multiplicative/shift/biwise binary 10715 /// expression. 10716 NotABinaryOperator, 10717 /// RHS binary operation does not have reference to the updated LHS 10718 /// part. 10719 NotAnUpdateExpression, 10720 /// No errors is found. 10721 NoError 10722 }; 10723 /// Reference to Sema. 10724 Sema &SemaRef; 10725 /// A location for note diagnostics (when error is found). 10726 SourceLocation NoteLoc; 10727 /// 'x' lvalue part of the source atomic expression. 10728 Expr *X; 10729 /// 'expr' rvalue part of the source atomic expression. 10730 Expr *E; 10731 /// Helper expression of the form 10732 /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or 10733 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'. 10734 Expr *UpdateExpr; 10735 /// Is 'x' a LHS in a RHS part of full update expression. It is 10736 /// important for non-associative operations. 10737 bool IsXLHSInRHSPart; 10738 BinaryOperatorKind Op; 10739 SourceLocation OpLoc; 10740 /// true if the source expression is a postfix unary operation, false 10741 /// if it is a prefix unary operation. 10742 bool IsPostfixUpdate; 10743 10744 public: 10745 OpenMPAtomicUpdateChecker(Sema &SemaRef) 10746 : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr), 10747 IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {} 10748 /// Check specified statement that it is suitable for 'atomic update' 10749 /// constructs and extract 'x', 'expr' and Operation from the original 10750 /// expression. If DiagId and NoteId == 0, then only check is performed 10751 /// without error notification. 10752 /// \param DiagId Diagnostic which should be emitted if error is found. 10753 /// \param NoteId Diagnostic note for the main error message. 10754 /// \return true if statement is not an update expression, false otherwise. 10755 bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0); 10756 /// Return the 'x' lvalue part of the source atomic expression. 10757 Expr *getX() const { return X; } 10758 /// Return the 'expr' rvalue part of the source atomic expression. 10759 Expr *getExpr() const { return E; } 10760 /// Return the update expression used in calculation of the updated 10761 /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or 10762 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'. 10763 Expr *getUpdateExpr() const { return UpdateExpr; } 10764 /// Return true if 'x' is LHS in RHS part of full update expression, 10765 /// false otherwise. 10766 bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; } 10767 10768 /// true if the source expression is a postfix unary operation, false 10769 /// if it is a prefix unary operation. 10770 bool isPostfixUpdate() const { return IsPostfixUpdate; } 10771 10772 private: 10773 bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0, 10774 unsigned NoteId = 0); 10775 }; 10776 10777 bool OpenMPAtomicUpdateChecker::checkBinaryOperation( 10778 BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) { 10779 ExprAnalysisErrorCode ErrorFound = NoError; 10780 SourceLocation ErrorLoc, NoteLoc; 10781 SourceRange ErrorRange, NoteRange; 10782 // Allowed constructs are: 10783 // x = x binop expr; 10784 // x = expr binop x; 10785 if (AtomicBinOp->getOpcode() == BO_Assign) { 10786 X = AtomicBinOp->getLHS(); 10787 if (const auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>( 10788 AtomicBinOp->getRHS()->IgnoreParenImpCasts())) { 10789 if (AtomicInnerBinOp->isMultiplicativeOp() || 10790 AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() || 10791 AtomicInnerBinOp->isBitwiseOp()) { 10792 Op = AtomicInnerBinOp->getOpcode(); 10793 OpLoc = AtomicInnerBinOp->getOperatorLoc(); 10794 Expr *LHS = AtomicInnerBinOp->getLHS(); 10795 Expr *RHS = AtomicInnerBinOp->getRHS(); 10796 llvm::FoldingSetNodeID XId, LHSId, RHSId; 10797 X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(), 10798 /*Canonical=*/true); 10799 LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(), 10800 /*Canonical=*/true); 10801 RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(), 10802 /*Canonical=*/true); 10803 if (XId == LHSId) { 10804 E = RHS; 10805 IsXLHSInRHSPart = true; 10806 } else if (XId == RHSId) { 10807 E = LHS; 10808 IsXLHSInRHSPart = false; 10809 } else { 10810 ErrorLoc = AtomicInnerBinOp->getExprLoc(); 10811 ErrorRange = AtomicInnerBinOp->getSourceRange(); 10812 NoteLoc = X->getExprLoc(); 10813 NoteRange = X->getSourceRange(); 10814 ErrorFound = NotAnUpdateExpression; 10815 } 10816 } else { 10817 ErrorLoc = AtomicInnerBinOp->getExprLoc(); 10818 ErrorRange = AtomicInnerBinOp->getSourceRange(); 10819 NoteLoc = AtomicInnerBinOp->getOperatorLoc(); 10820 NoteRange = SourceRange(NoteLoc, NoteLoc); 10821 ErrorFound = NotABinaryOperator; 10822 } 10823 } else { 10824 NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc(); 10825 NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange(); 10826 ErrorFound = NotABinaryExpression; 10827 } 10828 } else { 10829 ErrorLoc = AtomicBinOp->getExprLoc(); 10830 ErrorRange = AtomicBinOp->getSourceRange(); 10831 NoteLoc = AtomicBinOp->getOperatorLoc(); 10832 NoteRange = SourceRange(NoteLoc, NoteLoc); 10833 ErrorFound = NotAnAssignmentOp; 10834 } 10835 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) { 10836 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange; 10837 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange; 10838 return true; 10839 } 10840 if (SemaRef.CurContext->isDependentContext()) 10841 E = X = UpdateExpr = nullptr; 10842 return ErrorFound != NoError; 10843 } 10844 10845 bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId, 10846 unsigned NoteId) { 10847 ExprAnalysisErrorCode ErrorFound = NoError; 10848 SourceLocation ErrorLoc, NoteLoc; 10849 SourceRange ErrorRange, NoteRange; 10850 // Allowed constructs are: 10851 // x++; 10852 // x--; 10853 // ++x; 10854 // --x; 10855 // x binop= expr; 10856 // x = x binop expr; 10857 // x = expr binop x; 10858 if (auto *AtomicBody = dyn_cast<Expr>(S)) { 10859 AtomicBody = AtomicBody->IgnoreParenImpCasts(); 10860 if (AtomicBody->getType()->isScalarType() || 10861 AtomicBody->isInstantiationDependent()) { 10862 if (const auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>( 10863 AtomicBody->IgnoreParenImpCasts())) { 10864 // Check for Compound Assignment Operation 10865 Op = BinaryOperator::getOpForCompoundAssignment( 10866 AtomicCompAssignOp->getOpcode()); 10867 OpLoc = AtomicCompAssignOp->getOperatorLoc(); 10868 E = AtomicCompAssignOp->getRHS(); 10869 X = AtomicCompAssignOp->getLHS()->IgnoreParens(); 10870 IsXLHSInRHSPart = true; 10871 } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>( 10872 AtomicBody->IgnoreParenImpCasts())) { 10873 // Check for Binary Operation 10874 if (checkBinaryOperation(AtomicBinOp, DiagId, NoteId)) 10875 return true; 10876 } else if (const auto *AtomicUnaryOp = dyn_cast<UnaryOperator>( 10877 AtomicBody->IgnoreParenImpCasts())) { 10878 // Check for Unary Operation 10879 if (AtomicUnaryOp->isIncrementDecrementOp()) { 10880 IsPostfixUpdate = AtomicUnaryOp->isPostfix(); 10881 Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub; 10882 OpLoc = AtomicUnaryOp->getOperatorLoc(); 10883 X = AtomicUnaryOp->getSubExpr()->IgnoreParens(); 10884 E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get(); 10885 IsXLHSInRHSPart = true; 10886 } else { 10887 ErrorFound = NotAnUnaryIncDecExpression; 10888 ErrorLoc = AtomicUnaryOp->getExprLoc(); 10889 ErrorRange = AtomicUnaryOp->getSourceRange(); 10890 NoteLoc = AtomicUnaryOp->getOperatorLoc(); 10891 NoteRange = SourceRange(NoteLoc, NoteLoc); 10892 } 10893 } else if (!AtomicBody->isInstantiationDependent()) { 10894 ErrorFound = NotABinaryOrUnaryExpression; 10895 NoteLoc = ErrorLoc = AtomicBody->getExprLoc(); 10896 NoteRange = ErrorRange = AtomicBody->getSourceRange(); 10897 } 10898 } else { 10899 ErrorFound = NotAScalarType; 10900 NoteLoc = ErrorLoc = AtomicBody->getBeginLoc(); 10901 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc); 10902 } 10903 } else { 10904 ErrorFound = NotAnExpression; 10905 NoteLoc = ErrorLoc = S->getBeginLoc(); 10906 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc); 10907 } 10908 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) { 10909 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange; 10910 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange; 10911 return true; 10912 } 10913 if (SemaRef.CurContext->isDependentContext()) 10914 E = X = UpdateExpr = nullptr; 10915 if (ErrorFound == NoError && E && X) { 10916 // Build an update expression of form 'OpaqueValueExpr(x) binop 10917 // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop 10918 // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression. 10919 auto *OVEX = new (SemaRef.getASTContext()) 10920 OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_PRValue); 10921 auto *OVEExpr = new (SemaRef.getASTContext()) 10922 OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_PRValue); 10923 ExprResult Update = 10924 SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr, 10925 IsXLHSInRHSPart ? OVEExpr : OVEX); 10926 if (Update.isInvalid()) 10927 return true; 10928 Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(), 10929 Sema::AA_Casting); 10930 if (Update.isInvalid()) 10931 return true; 10932 UpdateExpr = Update.get(); 10933 } 10934 return ErrorFound != NoError; 10935 } 10936 10937 /// Get the node id of the fixed point of an expression \a S. 10938 llvm::FoldingSetNodeID getNodeId(ASTContext &Context, const Expr *S) { 10939 llvm::FoldingSetNodeID Id; 10940 S->IgnoreParenImpCasts()->Profile(Id, Context, true); 10941 return Id; 10942 } 10943 10944 /// Check if two expressions are same. 10945 bool checkIfTwoExprsAreSame(ASTContext &Context, const Expr *LHS, 10946 const Expr *RHS) { 10947 return getNodeId(Context, LHS) == getNodeId(Context, RHS); 10948 } 10949 10950 class OpenMPAtomicCompareChecker { 10951 public: 10952 /// All kinds of errors that can occur in `atomic compare` 10953 enum ErrorTy { 10954 /// Empty compound statement. 10955 NoStmt = 0, 10956 /// More than one statement in a compound statement. 10957 MoreThanOneStmt, 10958 /// Not an assignment binary operator. 10959 NotAnAssignment, 10960 /// Not a conditional operator. 10961 NotCondOp, 10962 /// Wrong false expr. According to the spec, 'x' should be at the false 10963 /// expression of a conditional expression. 10964 WrongFalseExpr, 10965 /// The condition of a conditional expression is not a binary operator. 10966 NotABinaryOp, 10967 /// Invalid binary operator (not <, >, or ==). 10968 InvalidBinaryOp, 10969 /// Invalid comparison (not x == e, e == x, x ordop expr, or expr ordop x). 10970 InvalidComparison, 10971 /// X is not a lvalue. 10972 XNotLValue, 10973 /// Not a scalar. 10974 NotScalar, 10975 /// Not an integer. 10976 NotInteger, 10977 /// No error. 10978 NoError, 10979 }; 10980 10981 struct ErrorInfoTy { 10982 ErrorTy Error; 10983 SourceLocation ErrorLoc; 10984 SourceRange ErrorRange; 10985 SourceLocation NoteLoc; 10986 SourceRange NoteRange; 10987 }; 10988 10989 OpenMPAtomicCompareChecker(Sema &S) : ContextRef(S.getASTContext()) {} 10990 10991 /// Check if statement \a S is valid for <tt>atomic compare</tt>. 10992 bool checkStmt(Stmt *S, ErrorInfoTy &ErrorInfo); 10993 10994 Expr *getX() const { return X; } 10995 Expr *getE() const { return E; } 10996 Expr *getD() const { return D; } 10997 Expr *getCond() const { return C; } 10998 bool isXBinopExpr() const { return IsXBinopExpr; } 10999 11000 private: 11001 /// Reference to ASTContext 11002 ASTContext &ContextRef; 11003 /// 'x' lvalue part of the source atomic expression. 11004 Expr *X = nullptr; 11005 /// 'expr' or 'e' rvalue part of the source atomic expression. 11006 Expr *E = nullptr; 11007 /// 'd' rvalue part of the source atomic expression. 11008 Expr *D = nullptr; 11009 /// 'cond' part of the source atomic expression. It is in one of the following 11010 /// forms: 11011 /// expr ordop x 11012 /// x ordop expr 11013 /// x == e 11014 /// e == x 11015 Expr *C = nullptr; 11016 /// True if the cond expr is in the form of 'x ordop expr'. 11017 bool IsXBinopExpr = true; 11018 /// The atomic compare operator. 11019 OMPAtomicCompareOp Op; 11020 11021 /// Check if it is a valid conditional update statement (cond-update-stmt). 11022 bool checkCondUpdateStmt(IfStmt *S, ErrorInfoTy &ErrorInfo); 11023 11024 /// Check if it is a valid conditional expression statement (cond-expr-stmt). 11025 bool checkCondExprStmt(Stmt *S, ErrorInfoTy &ErrorInfo); 11026 11027 /// Check if all captured values have right type. 11028 bool checkType(ErrorInfoTy &ErrorInfo) const; 11029 }; 11030 11031 bool OpenMPAtomicCompareChecker::checkCondUpdateStmt(IfStmt *S, 11032 ErrorInfoTy &ErrorInfo) { 11033 auto *Then = S->getThen(); 11034 if (auto *CS = dyn_cast<CompoundStmt>(Then)) { 11035 if (CS->body_empty()) { 11036 ErrorInfo.Error = ErrorTy::NoStmt; 11037 ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = CS->getBeginLoc(); 11038 ErrorInfo.ErrorRange = ErrorInfo.NoteRange = CS->getSourceRange(); 11039 return false; 11040 } 11041 if (CS->size() > 1) { 11042 ErrorInfo.Error = ErrorTy::MoreThanOneStmt; 11043 ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = CS->getBeginLoc(); 11044 ErrorInfo.ErrorRange = ErrorInfo.NoteRange = S->getSourceRange(); 11045 return false; 11046 } 11047 Then = CS->body_front(); 11048 } 11049 11050 auto *BO = dyn_cast<BinaryOperator>(Then); 11051 if (!BO) { 11052 ErrorInfo.Error = ErrorTy::NotAnAssignment; 11053 ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = Then->getBeginLoc(); 11054 ErrorInfo.ErrorRange = ErrorInfo.NoteRange = Then->getSourceRange(); 11055 return false; 11056 } 11057 if (BO->getOpcode() != BO_Assign) { 11058 ErrorInfo.Error = ErrorTy::NotAnAssignment; 11059 ErrorInfo.ErrorLoc = BO->getExprLoc(); 11060 ErrorInfo.NoteLoc = BO->getOperatorLoc(); 11061 ErrorInfo.ErrorRange = ErrorInfo.NoteRange = BO->getSourceRange(); 11062 return false; 11063 } 11064 11065 X = BO->getLHS(); 11066 11067 auto *Cond = dyn_cast<BinaryOperator>(S->getCond()); 11068 if (!Cond) { 11069 ErrorInfo.Error = ErrorTy::NotABinaryOp; 11070 ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = S->getCond()->getExprLoc(); 11071 ErrorInfo.ErrorRange = ErrorInfo.NoteRange = S->getCond()->getSourceRange(); 11072 return false; 11073 } 11074 11075 switch (Cond->getOpcode()) { 11076 case BO_EQ: 11077 Op = OMPAtomicCompareOp::EQ; 11078 break; 11079 case BO_LT: 11080 Op = OMPAtomicCompareOp::MIN; 11081 break; 11082 case BO_GT: 11083 Op = OMPAtomicCompareOp::MAX; 11084 break; 11085 default: 11086 ErrorInfo.Error = ErrorTy::InvalidBinaryOp; 11087 ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = Cond->getExprLoc(); 11088 ErrorInfo.ErrorRange = ErrorInfo.NoteRange = Cond->getSourceRange(); 11089 return false; 11090 } 11091 11092 if (Cond->getOpcode() == BO_EQ) { 11093 C = Cond; 11094 D = BO->getRHS(); 11095 if (checkIfTwoExprsAreSame(ContextRef, X, Cond->getLHS())) { 11096 E = Cond->getRHS(); 11097 } else if (checkIfTwoExprsAreSame(ContextRef, X, Cond->getRHS())) { 11098 E = Cond->getLHS(); 11099 } else { 11100 ErrorInfo.Error = ErrorTy::InvalidComparison; 11101 ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = Cond->getExprLoc(); 11102 ErrorInfo.ErrorRange = ErrorInfo.NoteRange = Cond->getSourceRange(); 11103 return false; 11104 } 11105 } else { 11106 E = BO->getRHS(); 11107 if (checkIfTwoExprsAreSame(ContextRef, X, Cond->getLHS()) && 11108 checkIfTwoExprsAreSame(ContextRef, E, Cond->getRHS())) { 11109 C = Cond; 11110 } else if (checkIfTwoExprsAreSame(ContextRef, E, Cond->getLHS()) && 11111 checkIfTwoExprsAreSame(ContextRef, X, Cond->getRHS())) { 11112 C = Cond; 11113 IsXBinopExpr = false; 11114 } else { 11115 ErrorInfo.Error = ErrorTy::InvalidComparison; 11116 ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = Cond->getExprLoc(); 11117 ErrorInfo.ErrorRange = ErrorInfo.NoteRange = Cond->getSourceRange(); 11118 return false; 11119 } 11120 } 11121 11122 return true; 11123 } 11124 11125 bool OpenMPAtomicCompareChecker::checkCondExprStmt(Stmt *S, 11126 ErrorInfoTy &ErrorInfo) { 11127 auto *BO = dyn_cast<BinaryOperator>(S); 11128 if (!BO) { 11129 ErrorInfo.Error = ErrorTy::NotAnAssignment; 11130 ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = S->getBeginLoc(); 11131 ErrorInfo.ErrorRange = ErrorInfo.NoteRange = S->getSourceRange(); 11132 return false; 11133 } 11134 if (BO->getOpcode() != BO_Assign) { 11135 ErrorInfo.Error = ErrorTy::NotAnAssignment; 11136 ErrorInfo.ErrorLoc = BO->getExprLoc(); 11137 ErrorInfo.NoteLoc = BO->getOperatorLoc(); 11138 ErrorInfo.ErrorRange = ErrorInfo.NoteRange = BO->getSourceRange(); 11139 return false; 11140 } 11141 11142 X = BO->getLHS(); 11143 11144 auto *CO = dyn_cast<ConditionalOperator>(BO->getRHS()->IgnoreParenImpCasts()); 11145 if (!CO) { 11146 ErrorInfo.Error = ErrorTy::NotCondOp; 11147 ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = BO->getRHS()->getExprLoc(); 11148 ErrorInfo.ErrorRange = ErrorInfo.NoteRange = BO->getRHS()->getSourceRange(); 11149 return false; 11150 } 11151 11152 if (!checkIfTwoExprsAreSame(ContextRef, X, CO->getFalseExpr())) { 11153 ErrorInfo.Error = ErrorTy::WrongFalseExpr; 11154 ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = CO->getFalseExpr()->getExprLoc(); 11155 ErrorInfo.ErrorRange = ErrorInfo.NoteRange = 11156 CO->getFalseExpr()->getSourceRange(); 11157 return false; 11158 } 11159 11160 auto *Cond = dyn_cast<BinaryOperator>(CO->getCond()); 11161 if (!Cond) { 11162 ErrorInfo.Error = ErrorTy::NotABinaryOp; 11163 ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = CO->getCond()->getExprLoc(); 11164 ErrorInfo.ErrorRange = ErrorInfo.NoteRange = 11165 CO->getCond()->getSourceRange(); 11166 return false; 11167 } 11168 11169 switch (Cond->getOpcode()) { 11170 case BO_EQ: 11171 Op = OMPAtomicCompareOp::EQ; 11172 break; 11173 case BO_LT: 11174 Op = OMPAtomicCompareOp::MIN; 11175 break; 11176 case BO_GT: 11177 Op = OMPAtomicCompareOp::MAX; 11178 break; 11179 default: 11180 ErrorInfo.Error = ErrorTy::InvalidBinaryOp; 11181 ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = Cond->getExprLoc(); 11182 ErrorInfo.ErrorRange = ErrorInfo.NoteRange = Cond->getSourceRange(); 11183 return false; 11184 } 11185 11186 if (Cond->getOpcode() == BO_EQ) { 11187 C = Cond; 11188 D = CO->getTrueExpr(); 11189 if (checkIfTwoExprsAreSame(ContextRef, X, Cond->getLHS())) { 11190 E = Cond->getRHS(); 11191 } else if (checkIfTwoExprsAreSame(ContextRef, X, Cond->getRHS())) { 11192 E = Cond->getLHS(); 11193 } else { 11194 ErrorInfo.Error = ErrorTy::InvalidComparison; 11195 ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = Cond->getExprLoc(); 11196 ErrorInfo.ErrorRange = ErrorInfo.NoteRange = Cond->getSourceRange(); 11197 return false; 11198 } 11199 } else { 11200 E = CO->getTrueExpr(); 11201 if (checkIfTwoExprsAreSame(ContextRef, X, Cond->getLHS()) && 11202 checkIfTwoExprsAreSame(ContextRef, E, Cond->getRHS())) { 11203 C = Cond; 11204 } else if (checkIfTwoExprsAreSame(ContextRef, E, Cond->getLHS()) && 11205 checkIfTwoExprsAreSame(ContextRef, X, Cond->getRHS())) { 11206 C = Cond; 11207 IsXBinopExpr = false; 11208 } else { 11209 ErrorInfo.Error = ErrorTy::InvalidComparison; 11210 ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = Cond->getExprLoc(); 11211 ErrorInfo.ErrorRange = ErrorInfo.NoteRange = Cond->getSourceRange(); 11212 return false; 11213 } 11214 } 11215 11216 return true; 11217 } 11218 11219 bool OpenMPAtomicCompareChecker::checkType(ErrorInfoTy &ErrorInfo) const { 11220 // 'x' and 'e' cannot be nullptr 11221 assert(X && E && "X and E cannot be nullptr"); 11222 11223 auto CheckValue = [&ErrorInfo](const Expr *E, OMPAtomicCompareOp Op, 11224 bool ShouldBeLValue) { 11225 if (ShouldBeLValue && !E->isLValue()) { 11226 ErrorInfo.Error = ErrorTy::XNotLValue; 11227 ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = E->getExprLoc(); 11228 ErrorInfo.ErrorRange = ErrorInfo.NoteRange = E->getSourceRange(); 11229 return false; 11230 } 11231 11232 if (!E->isInstantiationDependent()) { 11233 QualType QTy = E->getType(); 11234 if (!QTy->isScalarType()) { 11235 ErrorInfo.Error = ErrorTy::NotScalar; 11236 ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = E->getExprLoc(); 11237 ErrorInfo.ErrorRange = ErrorInfo.NoteRange = E->getSourceRange(); 11238 return false; 11239 } 11240 11241 if (Op != OMPAtomicCompareOp::EQ && !QTy->isIntegerType()) { 11242 ErrorInfo.Error = ErrorTy::NotInteger; 11243 ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = E->getExprLoc(); 11244 ErrorInfo.ErrorRange = ErrorInfo.NoteRange = E->getSourceRange(); 11245 return false; 11246 } 11247 } 11248 11249 return true; 11250 }; 11251 11252 if (!CheckValue(X, Op, true)) 11253 return false; 11254 11255 if (!CheckValue(E, Op, false)) 11256 return false; 11257 11258 if (D && !CheckValue(D, Op, false)) 11259 return false; 11260 11261 return true; 11262 } 11263 11264 bool OpenMPAtomicCompareChecker::checkStmt( 11265 Stmt *S, OpenMPAtomicCompareChecker::ErrorInfoTy &ErrorInfo) { 11266 auto *CS = dyn_cast<CompoundStmt>(S); 11267 if (CS) { 11268 if (CS->body_empty()) { 11269 ErrorInfo.Error = ErrorTy::NoStmt; 11270 ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = CS->getBeginLoc(); 11271 ErrorInfo.ErrorRange = ErrorInfo.NoteRange = CS->getSourceRange(); 11272 return false; 11273 } 11274 11275 if (CS->size() != 1) { 11276 ErrorInfo.Error = ErrorTy::MoreThanOneStmt; 11277 ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = CS->getBeginLoc(); 11278 ErrorInfo.ErrorRange = ErrorInfo.NoteRange = CS->getSourceRange(); 11279 return false; 11280 } 11281 S = CS->body_front(); 11282 } 11283 11284 auto Res = false; 11285 11286 if (auto *IS = dyn_cast<IfStmt>(S)) { 11287 // Check if the statement is in one of the following forms 11288 // (cond-update-stmt): 11289 // if (expr ordop x) { x = expr; } 11290 // if (x ordop expr) { x = expr; } 11291 // if (x == e) { x = d; } 11292 Res = checkCondUpdateStmt(IS, ErrorInfo); 11293 } else { 11294 // Check if the statement is in one of the following forms (cond-expr-stmt): 11295 // x = expr ordop x ? expr : x; 11296 // x = x ordop expr ? expr : x; 11297 // x = x == e ? d : x; 11298 Res = checkCondExprStmt(S, ErrorInfo); 11299 } 11300 11301 if (!Res) 11302 return false; 11303 11304 return checkType(ErrorInfo); 11305 } 11306 } // namespace 11307 11308 StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses, 11309 Stmt *AStmt, 11310 SourceLocation StartLoc, 11311 SourceLocation EndLoc) { 11312 // Register location of the first atomic directive. 11313 DSAStack->addAtomicDirectiveLoc(StartLoc); 11314 if (!AStmt) 11315 return StmtError(); 11316 11317 // 1.2.2 OpenMP Language Terminology 11318 // Structured block - An executable statement with a single entry at the 11319 // top and a single exit at the bottom. 11320 // The point of exit cannot be a branch out of the structured block. 11321 // longjmp() and throw() must not violate the entry/exit criteria. 11322 OpenMPClauseKind AtomicKind = OMPC_unknown; 11323 SourceLocation AtomicKindLoc; 11324 OpenMPClauseKind MemOrderKind = OMPC_unknown; 11325 SourceLocation MemOrderLoc; 11326 bool MutexClauseEncountered = false; 11327 llvm::SmallSet<OpenMPClauseKind, 2> EncounteredAtomicKinds; 11328 for (const OMPClause *C : Clauses) { 11329 switch (C->getClauseKind()) { 11330 case OMPC_read: 11331 case OMPC_write: 11332 case OMPC_update: 11333 MutexClauseEncountered = true; 11334 LLVM_FALLTHROUGH; 11335 case OMPC_capture: 11336 case OMPC_compare: { 11337 if (AtomicKind != OMPC_unknown && MutexClauseEncountered) { 11338 Diag(C->getBeginLoc(), diag::err_omp_atomic_several_clauses) 11339 << SourceRange(C->getBeginLoc(), C->getEndLoc()); 11340 Diag(AtomicKindLoc, diag::note_omp_previous_mem_order_clause) 11341 << getOpenMPClauseName(AtomicKind); 11342 } else { 11343 AtomicKind = C->getClauseKind(); 11344 AtomicKindLoc = C->getBeginLoc(); 11345 if (!EncounteredAtomicKinds.insert(C->getClauseKind()).second) { 11346 Diag(C->getBeginLoc(), diag::err_omp_atomic_several_clauses) 11347 << SourceRange(C->getBeginLoc(), C->getEndLoc()); 11348 Diag(AtomicKindLoc, diag::note_omp_previous_mem_order_clause) 11349 << getOpenMPClauseName(AtomicKind); 11350 } 11351 } 11352 break; 11353 } 11354 case OMPC_seq_cst: 11355 case OMPC_acq_rel: 11356 case OMPC_acquire: 11357 case OMPC_release: 11358 case OMPC_relaxed: { 11359 if (MemOrderKind != OMPC_unknown) { 11360 Diag(C->getBeginLoc(), diag::err_omp_several_mem_order_clauses) 11361 << getOpenMPDirectiveName(OMPD_atomic) << 0 11362 << SourceRange(C->getBeginLoc(), C->getEndLoc()); 11363 Diag(MemOrderLoc, diag::note_omp_previous_mem_order_clause) 11364 << getOpenMPClauseName(MemOrderKind); 11365 } else { 11366 MemOrderKind = C->getClauseKind(); 11367 MemOrderLoc = C->getBeginLoc(); 11368 } 11369 break; 11370 } 11371 // The following clauses are allowed, but we don't need to do anything here. 11372 case OMPC_hint: 11373 break; 11374 default: 11375 llvm_unreachable("unknown clause is encountered"); 11376 } 11377 } 11378 bool IsCompareCapture = false; 11379 if (EncounteredAtomicKinds.contains(OMPC_compare) && 11380 EncounteredAtomicKinds.contains(OMPC_capture)) { 11381 IsCompareCapture = true; 11382 AtomicKind = OMPC_compare; 11383 } 11384 // OpenMP 5.0, 2.17.7 atomic Construct, Restrictions 11385 // If atomic-clause is read then memory-order-clause must not be acq_rel or 11386 // release. 11387 // If atomic-clause is write then memory-order-clause must not be acq_rel or 11388 // acquire. 11389 // If atomic-clause is update or not present then memory-order-clause must not 11390 // be acq_rel or acquire. 11391 if ((AtomicKind == OMPC_read && 11392 (MemOrderKind == OMPC_acq_rel || MemOrderKind == OMPC_release)) || 11393 ((AtomicKind == OMPC_write || AtomicKind == OMPC_update || 11394 AtomicKind == OMPC_unknown) && 11395 (MemOrderKind == OMPC_acq_rel || MemOrderKind == OMPC_acquire))) { 11396 SourceLocation Loc = AtomicKindLoc; 11397 if (AtomicKind == OMPC_unknown) 11398 Loc = StartLoc; 11399 Diag(Loc, diag::err_omp_atomic_incompatible_mem_order_clause) 11400 << getOpenMPClauseName(AtomicKind) 11401 << (AtomicKind == OMPC_unknown ? 1 : 0) 11402 << getOpenMPClauseName(MemOrderKind); 11403 Diag(MemOrderLoc, diag::note_omp_previous_mem_order_clause) 11404 << getOpenMPClauseName(MemOrderKind); 11405 } 11406 11407 Stmt *Body = AStmt; 11408 if (auto *EWC = dyn_cast<ExprWithCleanups>(Body)) 11409 Body = EWC->getSubExpr(); 11410 11411 Expr *X = nullptr; 11412 Expr *V = nullptr; 11413 Expr *E = nullptr; 11414 Expr *UE = nullptr; 11415 bool IsXLHSInRHSPart = false; 11416 bool IsPostfixUpdate = false; 11417 // OpenMP [2.12.6, atomic Construct] 11418 // In the next expressions: 11419 // * x and v (as applicable) are both l-value expressions with scalar type. 11420 // * During the execution of an atomic region, multiple syntactic 11421 // occurrences of x must designate the same storage location. 11422 // * Neither of v and expr (as applicable) may access the storage location 11423 // designated by x. 11424 // * Neither of x and expr (as applicable) may access the storage location 11425 // designated by v. 11426 // * expr is an expression with scalar type. 11427 // * binop is one of +, *, -, /, &, ^, |, <<, or >>. 11428 // * binop, binop=, ++, and -- are not overloaded operators. 11429 // * The expression x binop expr must be numerically equivalent to x binop 11430 // (expr). This requirement is satisfied if the operators in expr have 11431 // precedence greater than binop, or by using parentheses around expr or 11432 // subexpressions of expr. 11433 // * The expression expr binop x must be numerically equivalent to (expr) 11434 // binop x. This requirement is satisfied if the operators in expr have 11435 // precedence equal to or greater than binop, or by using parentheses around 11436 // expr or subexpressions of expr. 11437 // * For forms that allow multiple occurrences of x, the number of times 11438 // that x is evaluated is unspecified. 11439 if (AtomicKind == OMPC_read) { 11440 enum { 11441 NotAnExpression, 11442 NotAnAssignmentOp, 11443 NotAScalarType, 11444 NotAnLValue, 11445 NoError 11446 } ErrorFound = NoError; 11447 SourceLocation ErrorLoc, NoteLoc; 11448 SourceRange ErrorRange, NoteRange; 11449 // If clause is read: 11450 // v = x; 11451 if (const auto *AtomicBody = dyn_cast<Expr>(Body)) { 11452 const auto *AtomicBinOp = 11453 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts()); 11454 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) { 11455 X = AtomicBinOp->getRHS()->IgnoreParenImpCasts(); 11456 V = AtomicBinOp->getLHS()->IgnoreParenImpCasts(); 11457 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) && 11458 (V->isInstantiationDependent() || V->getType()->isScalarType())) { 11459 if (!X->isLValue() || !V->isLValue()) { 11460 const Expr *NotLValueExpr = X->isLValue() ? V : X; 11461 ErrorFound = NotAnLValue; 11462 ErrorLoc = AtomicBinOp->getExprLoc(); 11463 ErrorRange = AtomicBinOp->getSourceRange(); 11464 NoteLoc = NotLValueExpr->getExprLoc(); 11465 NoteRange = NotLValueExpr->getSourceRange(); 11466 } 11467 } else if (!X->isInstantiationDependent() || 11468 !V->isInstantiationDependent()) { 11469 const Expr *NotScalarExpr = 11470 (X->isInstantiationDependent() || X->getType()->isScalarType()) 11471 ? V 11472 : X; 11473 ErrorFound = NotAScalarType; 11474 ErrorLoc = AtomicBinOp->getExprLoc(); 11475 ErrorRange = AtomicBinOp->getSourceRange(); 11476 NoteLoc = NotScalarExpr->getExprLoc(); 11477 NoteRange = NotScalarExpr->getSourceRange(); 11478 } 11479 } else if (!AtomicBody->isInstantiationDependent()) { 11480 ErrorFound = NotAnAssignmentOp; 11481 ErrorLoc = AtomicBody->getExprLoc(); 11482 ErrorRange = AtomicBody->getSourceRange(); 11483 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc() 11484 : AtomicBody->getExprLoc(); 11485 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange() 11486 : AtomicBody->getSourceRange(); 11487 } 11488 } else { 11489 ErrorFound = NotAnExpression; 11490 NoteLoc = ErrorLoc = Body->getBeginLoc(); 11491 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc); 11492 } 11493 if (ErrorFound != NoError) { 11494 Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement) 11495 << ErrorRange; 11496 Diag(NoteLoc, diag::note_omp_atomic_read_write) 11497 << ErrorFound << NoteRange; 11498 return StmtError(); 11499 } 11500 if (CurContext->isDependentContext()) 11501 V = X = nullptr; 11502 } else if (AtomicKind == OMPC_write) { 11503 enum { 11504 NotAnExpression, 11505 NotAnAssignmentOp, 11506 NotAScalarType, 11507 NotAnLValue, 11508 NoError 11509 } ErrorFound = NoError; 11510 SourceLocation ErrorLoc, NoteLoc; 11511 SourceRange ErrorRange, NoteRange; 11512 // If clause is write: 11513 // x = expr; 11514 if (const auto *AtomicBody = dyn_cast<Expr>(Body)) { 11515 const auto *AtomicBinOp = 11516 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts()); 11517 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) { 11518 X = AtomicBinOp->getLHS(); 11519 E = AtomicBinOp->getRHS(); 11520 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) && 11521 (E->isInstantiationDependent() || E->getType()->isScalarType())) { 11522 if (!X->isLValue()) { 11523 ErrorFound = NotAnLValue; 11524 ErrorLoc = AtomicBinOp->getExprLoc(); 11525 ErrorRange = AtomicBinOp->getSourceRange(); 11526 NoteLoc = X->getExprLoc(); 11527 NoteRange = X->getSourceRange(); 11528 } 11529 } else if (!X->isInstantiationDependent() || 11530 !E->isInstantiationDependent()) { 11531 const Expr *NotScalarExpr = 11532 (X->isInstantiationDependent() || X->getType()->isScalarType()) 11533 ? E 11534 : X; 11535 ErrorFound = NotAScalarType; 11536 ErrorLoc = AtomicBinOp->getExprLoc(); 11537 ErrorRange = AtomicBinOp->getSourceRange(); 11538 NoteLoc = NotScalarExpr->getExprLoc(); 11539 NoteRange = NotScalarExpr->getSourceRange(); 11540 } 11541 } else if (!AtomicBody->isInstantiationDependent()) { 11542 ErrorFound = NotAnAssignmentOp; 11543 ErrorLoc = AtomicBody->getExprLoc(); 11544 ErrorRange = AtomicBody->getSourceRange(); 11545 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc() 11546 : AtomicBody->getExprLoc(); 11547 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange() 11548 : AtomicBody->getSourceRange(); 11549 } 11550 } else { 11551 ErrorFound = NotAnExpression; 11552 NoteLoc = ErrorLoc = Body->getBeginLoc(); 11553 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc); 11554 } 11555 if (ErrorFound != NoError) { 11556 Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement) 11557 << ErrorRange; 11558 Diag(NoteLoc, diag::note_omp_atomic_read_write) 11559 << ErrorFound << NoteRange; 11560 return StmtError(); 11561 } 11562 if (CurContext->isDependentContext()) 11563 E = X = nullptr; 11564 } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) { 11565 // If clause is update: 11566 // x++; 11567 // x--; 11568 // ++x; 11569 // --x; 11570 // x binop= expr; 11571 // x = x binop expr; 11572 // x = expr binop x; 11573 OpenMPAtomicUpdateChecker Checker(*this); 11574 if (Checker.checkStatement( 11575 Body, 11576 (AtomicKind == OMPC_update) 11577 ? diag::err_omp_atomic_update_not_expression_statement 11578 : diag::err_omp_atomic_not_expression_statement, 11579 diag::note_omp_atomic_update)) 11580 return StmtError(); 11581 if (!CurContext->isDependentContext()) { 11582 E = Checker.getExpr(); 11583 X = Checker.getX(); 11584 UE = Checker.getUpdateExpr(); 11585 IsXLHSInRHSPart = Checker.isXLHSInRHSPart(); 11586 } 11587 } else if (AtomicKind == OMPC_capture) { 11588 enum { 11589 NotAnAssignmentOp, 11590 NotACompoundStatement, 11591 NotTwoSubstatements, 11592 NotASpecificExpression, 11593 NoError 11594 } ErrorFound = NoError; 11595 SourceLocation ErrorLoc, NoteLoc; 11596 SourceRange ErrorRange, NoteRange; 11597 if (const auto *AtomicBody = dyn_cast<Expr>(Body)) { 11598 // If clause is a capture: 11599 // v = x++; 11600 // v = x--; 11601 // v = ++x; 11602 // v = --x; 11603 // v = x binop= expr; 11604 // v = x = x binop expr; 11605 // v = x = expr binop x; 11606 const auto *AtomicBinOp = 11607 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts()); 11608 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) { 11609 V = AtomicBinOp->getLHS(); 11610 Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts(); 11611 OpenMPAtomicUpdateChecker Checker(*this); 11612 if (Checker.checkStatement( 11613 Body, diag::err_omp_atomic_capture_not_expression_statement, 11614 diag::note_omp_atomic_update)) 11615 return StmtError(); 11616 E = Checker.getExpr(); 11617 X = Checker.getX(); 11618 UE = Checker.getUpdateExpr(); 11619 IsXLHSInRHSPart = Checker.isXLHSInRHSPart(); 11620 IsPostfixUpdate = Checker.isPostfixUpdate(); 11621 } else if (!AtomicBody->isInstantiationDependent()) { 11622 ErrorLoc = AtomicBody->getExprLoc(); 11623 ErrorRange = AtomicBody->getSourceRange(); 11624 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc() 11625 : AtomicBody->getExprLoc(); 11626 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange() 11627 : AtomicBody->getSourceRange(); 11628 ErrorFound = NotAnAssignmentOp; 11629 } 11630 if (ErrorFound != NoError) { 11631 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement) 11632 << ErrorRange; 11633 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange; 11634 return StmtError(); 11635 } 11636 if (CurContext->isDependentContext()) 11637 UE = V = E = X = nullptr; 11638 } else { 11639 // If clause is a capture: 11640 // { v = x; x = expr; } 11641 // { v = x; x++; } 11642 // { v = x; x--; } 11643 // { v = x; ++x; } 11644 // { v = x; --x; } 11645 // { v = x; x binop= expr; } 11646 // { v = x; x = x binop expr; } 11647 // { v = x; x = expr binop x; } 11648 // { x++; v = x; } 11649 // { x--; v = x; } 11650 // { ++x; v = x; } 11651 // { --x; v = x; } 11652 // { x binop= expr; v = x; } 11653 // { x = x binop expr; v = x; } 11654 // { x = expr binop x; v = x; } 11655 if (auto *CS = dyn_cast<CompoundStmt>(Body)) { 11656 // Check that this is { expr1; expr2; } 11657 if (CS->size() == 2) { 11658 Stmt *First = CS->body_front(); 11659 Stmt *Second = CS->body_back(); 11660 if (auto *EWC = dyn_cast<ExprWithCleanups>(First)) 11661 First = EWC->getSubExpr()->IgnoreParenImpCasts(); 11662 if (auto *EWC = dyn_cast<ExprWithCleanups>(Second)) 11663 Second = EWC->getSubExpr()->IgnoreParenImpCasts(); 11664 // Need to find what subexpression is 'v' and what is 'x'. 11665 OpenMPAtomicUpdateChecker Checker(*this); 11666 bool IsUpdateExprFound = !Checker.checkStatement(Second); 11667 BinaryOperator *BinOp = nullptr; 11668 if (IsUpdateExprFound) { 11669 BinOp = dyn_cast<BinaryOperator>(First); 11670 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign; 11671 } 11672 if (IsUpdateExprFound && !CurContext->isDependentContext()) { 11673 // { v = x; x++; } 11674 // { v = x; x--; } 11675 // { v = x; ++x; } 11676 // { v = x; --x; } 11677 // { v = x; x binop= expr; } 11678 // { v = x; x = x binop expr; } 11679 // { v = x; x = expr binop x; } 11680 // Check that the first expression has form v = x. 11681 Expr *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts(); 11682 llvm::FoldingSetNodeID XId, PossibleXId; 11683 Checker.getX()->Profile(XId, Context, /*Canonical=*/true); 11684 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true); 11685 IsUpdateExprFound = XId == PossibleXId; 11686 if (IsUpdateExprFound) { 11687 V = BinOp->getLHS(); 11688 X = Checker.getX(); 11689 E = Checker.getExpr(); 11690 UE = Checker.getUpdateExpr(); 11691 IsXLHSInRHSPart = Checker.isXLHSInRHSPart(); 11692 IsPostfixUpdate = true; 11693 } 11694 } 11695 if (!IsUpdateExprFound) { 11696 IsUpdateExprFound = !Checker.checkStatement(First); 11697 BinOp = nullptr; 11698 if (IsUpdateExprFound) { 11699 BinOp = dyn_cast<BinaryOperator>(Second); 11700 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign; 11701 } 11702 if (IsUpdateExprFound && !CurContext->isDependentContext()) { 11703 // { x++; v = x; } 11704 // { x--; v = x; } 11705 // { ++x; v = x; } 11706 // { --x; v = x; } 11707 // { x binop= expr; v = x; } 11708 // { x = x binop expr; v = x; } 11709 // { x = expr binop x; v = x; } 11710 // Check that the second expression has form v = x. 11711 Expr *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts(); 11712 llvm::FoldingSetNodeID XId, PossibleXId; 11713 Checker.getX()->Profile(XId, Context, /*Canonical=*/true); 11714 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true); 11715 IsUpdateExprFound = XId == PossibleXId; 11716 if (IsUpdateExprFound) { 11717 V = BinOp->getLHS(); 11718 X = Checker.getX(); 11719 E = Checker.getExpr(); 11720 UE = Checker.getUpdateExpr(); 11721 IsXLHSInRHSPart = Checker.isXLHSInRHSPart(); 11722 IsPostfixUpdate = false; 11723 } 11724 } 11725 } 11726 if (!IsUpdateExprFound) { 11727 // { v = x; x = expr; } 11728 auto *FirstExpr = dyn_cast<Expr>(First); 11729 auto *SecondExpr = dyn_cast<Expr>(Second); 11730 if (!FirstExpr || !SecondExpr || 11731 !(FirstExpr->isInstantiationDependent() || 11732 SecondExpr->isInstantiationDependent())) { 11733 auto *FirstBinOp = dyn_cast<BinaryOperator>(First); 11734 if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) { 11735 ErrorFound = NotAnAssignmentOp; 11736 NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc() 11737 : First->getBeginLoc(); 11738 NoteRange = ErrorRange = FirstBinOp 11739 ? FirstBinOp->getSourceRange() 11740 : SourceRange(ErrorLoc, ErrorLoc); 11741 } else { 11742 auto *SecondBinOp = dyn_cast<BinaryOperator>(Second); 11743 if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) { 11744 ErrorFound = NotAnAssignmentOp; 11745 NoteLoc = ErrorLoc = SecondBinOp 11746 ? SecondBinOp->getOperatorLoc() 11747 : Second->getBeginLoc(); 11748 NoteRange = ErrorRange = 11749 SecondBinOp ? SecondBinOp->getSourceRange() 11750 : SourceRange(ErrorLoc, ErrorLoc); 11751 } else { 11752 Expr *PossibleXRHSInFirst = 11753 FirstBinOp->getRHS()->IgnoreParenImpCasts(); 11754 Expr *PossibleXLHSInSecond = 11755 SecondBinOp->getLHS()->IgnoreParenImpCasts(); 11756 llvm::FoldingSetNodeID X1Id, X2Id; 11757 PossibleXRHSInFirst->Profile(X1Id, Context, 11758 /*Canonical=*/true); 11759 PossibleXLHSInSecond->Profile(X2Id, Context, 11760 /*Canonical=*/true); 11761 IsUpdateExprFound = X1Id == X2Id; 11762 if (IsUpdateExprFound) { 11763 V = FirstBinOp->getLHS(); 11764 X = SecondBinOp->getLHS(); 11765 E = SecondBinOp->getRHS(); 11766 UE = nullptr; 11767 IsXLHSInRHSPart = false; 11768 IsPostfixUpdate = true; 11769 } else { 11770 ErrorFound = NotASpecificExpression; 11771 ErrorLoc = FirstBinOp->getExprLoc(); 11772 ErrorRange = FirstBinOp->getSourceRange(); 11773 NoteLoc = SecondBinOp->getLHS()->getExprLoc(); 11774 NoteRange = SecondBinOp->getRHS()->getSourceRange(); 11775 } 11776 } 11777 } 11778 } 11779 } 11780 } else { 11781 NoteLoc = ErrorLoc = Body->getBeginLoc(); 11782 NoteRange = ErrorRange = 11783 SourceRange(Body->getBeginLoc(), Body->getBeginLoc()); 11784 ErrorFound = NotTwoSubstatements; 11785 } 11786 } else { 11787 NoteLoc = ErrorLoc = Body->getBeginLoc(); 11788 NoteRange = ErrorRange = 11789 SourceRange(Body->getBeginLoc(), Body->getBeginLoc()); 11790 ErrorFound = NotACompoundStatement; 11791 } 11792 } 11793 if (ErrorFound != NoError) { 11794 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement) 11795 << ErrorRange; 11796 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange; 11797 return StmtError(); 11798 } 11799 if (CurContext->isDependentContext()) 11800 UE = V = E = X = nullptr; 11801 } else if (AtomicKind == OMPC_compare) { 11802 if (IsCompareCapture) { 11803 // TODO: We don't set X, D, E, etc. here because in code gen we will emit 11804 // error directly. 11805 } else { 11806 OpenMPAtomicCompareChecker::ErrorInfoTy ErrorInfo; 11807 OpenMPAtomicCompareChecker Checker(*this); 11808 if (!Checker.checkStmt(Body, ErrorInfo)) { 11809 Diag(ErrorInfo.ErrorLoc, diag::err_omp_atomic_compare) 11810 << ErrorInfo.ErrorRange; 11811 Diag(ErrorInfo.NoteLoc, diag::note_omp_atomic_compare) 11812 << ErrorInfo.Error << ErrorInfo.NoteRange; 11813 return StmtError(); 11814 } 11815 // TODO: We don't set X, D, E, etc. here because in code gen we will emit 11816 // error directly. 11817 } 11818 } 11819 11820 setFunctionHasBranchProtectedScope(); 11821 11822 return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt, 11823 X, V, E, UE, IsXLHSInRHSPart, 11824 IsPostfixUpdate); 11825 } 11826 11827 StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses, 11828 Stmt *AStmt, 11829 SourceLocation StartLoc, 11830 SourceLocation EndLoc) { 11831 if (!AStmt) 11832 return StmtError(); 11833 11834 auto *CS = cast<CapturedStmt>(AStmt); 11835 // 1.2.2 OpenMP Language Terminology 11836 // Structured block - An executable statement with a single entry at the 11837 // top and a single exit at the bottom. 11838 // The point of exit cannot be a branch out of the structured block. 11839 // longjmp() and throw() must not violate the entry/exit criteria. 11840 CS->getCapturedDecl()->setNothrow(); 11841 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target); 11842 ThisCaptureLevel > 1; --ThisCaptureLevel) { 11843 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 11844 // 1.2.2 OpenMP Language Terminology 11845 // Structured block - An executable statement with a single entry at the 11846 // top and a single exit at the bottom. 11847 // The point of exit cannot be a branch out of the structured block. 11848 // longjmp() and throw() must not violate the entry/exit criteria. 11849 CS->getCapturedDecl()->setNothrow(); 11850 } 11851 11852 // OpenMP [2.16, Nesting of Regions] 11853 // If specified, a teams construct must be contained within a target 11854 // construct. That target construct must contain no statements or directives 11855 // outside of the teams construct. 11856 if (DSAStack->hasInnerTeamsRegion()) { 11857 const Stmt *S = CS->IgnoreContainers(/*IgnoreCaptured=*/true); 11858 bool OMPTeamsFound = true; 11859 if (const auto *CS = dyn_cast<CompoundStmt>(S)) { 11860 auto I = CS->body_begin(); 11861 while (I != CS->body_end()) { 11862 const auto *OED = dyn_cast<OMPExecutableDirective>(*I); 11863 if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind()) || 11864 OMPTeamsFound) { 11865 11866 OMPTeamsFound = false; 11867 break; 11868 } 11869 ++I; 11870 } 11871 assert(I != CS->body_end() && "Not found statement"); 11872 S = *I; 11873 } else { 11874 const auto *OED = dyn_cast<OMPExecutableDirective>(S); 11875 OMPTeamsFound = OED && isOpenMPTeamsDirective(OED->getDirectiveKind()); 11876 } 11877 if (!OMPTeamsFound) { 11878 Diag(StartLoc, diag::err_omp_target_contains_not_only_teams); 11879 Diag(DSAStack->getInnerTeamsRegionLoc(), 11880 diag::note_omp_nested_teams_construct_here); 11881 Diag(S->getBeginLoc(), diag::note_omp_nested_statement_here) 11882 << isa<OMPExecutableDirective>(S); 11883 return StmtError(); 11884 } 11885 } 11886 11887 setFunctionHasBranchProtectedScope(); 11888 11889 return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt); 11890 } 11891 11892 StmtResult 11893 Sema::ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses, 11894 Stmt *AStmt, SourceLocation StartLoc, 11895 SourceLocation EndLoc) { 11896 if (!AStmt) 11897 return StmtError(); 11898 11899 auto *CS = cast<CapturedStmt>(AStmt); 11900 // 1.2.2 OpenMP Language Terminology 11901 // Structured block - An executable statement with a single entry at the 11902 // top and a single exit at the bottom. 11903 // The point of exit cannot be a branch out of the structured block. 11904 // longjmp() and throw() must not violate the entry/exit criteria. 11905 CS->getCapturedDecl()->setNothrow(); 11906 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel); 11907 ThisCaptureLevel > 1; --ThisCaptureLevel) { 11908 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 11909 // 1.2.2 OpenMP Language Terminology 11910 // Structured block - An executable statement with a single entry at the 11911 // top and a single exit at the bottom. 11912 // The point of exit cannot be a branch out of the structured block. 11913 // longjmp() and throw() must not violate the entry/exit criteria. 11914 CS->getCapturedDecl()->setNothrow(); 11915 } 11916 11917 setFunctionHasBranchProtectedScope(); 11918 11919 return OMPTargetParallelDirective::Create( 11920 Context, StartLoc, EndLoc, Clauses, AStmt, 11921 DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion()); 11922 } 11923 11924 StmtResult Sema::ActOnOpenMPTargetParallelForDirective( 11925 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 11926 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 11927 if (!AStmt) 11928 return StmtError(); 11929 11930 auto *CS = cast<CapturedStmt>(AStmt); 11931 // 1.2.2 OpenMP Language Terminology 11932 // Structured block - An executable statement with a single entry at the 11933 // top and a single exit at the bottom. 11934 // The point of exit cannot be a branch out of the structured block. 11935 // longjmp() and throw() must not violate the entry/exit criteria. 11936 CS->getCapturedDecl()->setNothrow(); 11937 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for); 11938 ThisCaptureLevel > 1; --ThisCaptureLevel) { 11939 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 11940 // 1.2.2 OpenMP Language Terminology 11941 // Structured block - An executable statement with a single entry at the 11942 // top and a single exit at the bottom. 11943 // The point of exit cannot be a branch out of the structured block. 11944 // longjmp() and throw() must not violate the entry/exit criteria. 11945 CS->getCapturedDecl()->setNothrow(); 11946 } 11947 11948 OMPLoopBasedDirective::HelperExprs B; 11949 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 11950 // define the nested loops number. 11951 unsigned NestedLoopCount = 11952 checkOpenMPLoop(OMPD_target_parallel_for, getCollapseNumberExpr(Clauses), 11953 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack, 11954 VarsWithImplicitDSA, B); 11955 if (NestedLoopCount == 0) 11956 return StmtError(); 11957 11958 assert((CurContext->isDependentContext() || B.builtAll()) && 11959 "omp target parallel for loop exprs were not built"); 11960 11961 if (!CurContext->isDependentContext()) { 11962 // Finalize the clauses that need pre-built expressions for CodeGen. 11963 for (OMPClause *C : Clauses) { 11964 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 11965 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 11966 B.NumIterations, *this, CurScope, 11967 DSAStack)) 11968 return StmtError(); 11969 } 11970 } 11971 11972 setFunctionHasBranchProtectedScope(); 11973 return OMPTargetParallelForDirective::Create( 11974 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B, 11975 DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion()); 11976 } 11977 11978 /// Check for existence of a map clause in the list of clauses. 11979 static bool hasClauses(ArrayRef<OMPClause *> Clauses, 11980 const OpenMPClauseKind K) { 11981 return llvm::any_of( 11982 Clauses, [K](const OMPClause *C) { return C->getClauseKind() == K; }); 11983 } 11984 11985 template <typename... Params> 11986 static bool hasClauses(ArrayRef<OMPClause *> Clauses, const OpenMPClauseKind K, 11987 const Params... ClauseTypes) { 11988 return hasClauses(Clauses, K) || hasClauses(Clauses, ClauseTypes...); 11989 } 11990 11991 StmtResult Sema::ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses, 11992 Stmt *AStmt, 11993 SourceLocation StartLoc, 11994 SourceLocation EndLoc) { 11995 if (!AStmt) 11996 return StmtError(); 11997 11998 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 11999 12000 // OpenMP [2.12.2, target data Construct, Restrictions] 12001 // At least one map, use_device_addr or use_device_ptr clause must appear on 12002 // the directive. 12003 if (!hasClauses(Clauses, OMPC_map, OMPC_use_device_ptr) && 12004 (LangOpts.OpenMP < 50 || !hasClauses(Clauses, OMPC_use_device_addr))) { 12005 StringRef Expected; 12006 if (LangOpts.OpenMP < 50) 12007 Expected = "'map' or 'use_device_ptr'"; 12008 else 12009 Expected = "'map', 'use_device_ptr', or 'use_device_addr'"; 12010 Diag(StartLoc, diag::err_omp_no_clause_for_directive) 12011 << Expected << getOpenMPDirectiveName(OMPD_target_data); 12012 return StmtError(); 12013 } 12014 12015 setFunctionHasBranchProtectedScope(); 12016 12017 return OMPTargetDataDirective::Create(Context, StartLoc, EndLoc, Clauses, 12018 AStmt); 12019 } 12020 12021 StmtResult 12022 Sema::ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses, 12023 SourceLocation StartLoc, 12024 SourceLocation EndLoc, Stmt *AStmt) { 12025 if (!AStmt) 12026 return StmtError(); 12027 12028 auto *CS = cast<CapturedStmt>(AStmt); 12029 // 1.2.2 OpenMP Language Terminology 12030 // Structured block - An executable statement with a single entry at the 12031 // top and a single exit at the bottom. 12032 // The point of exit cannot be a branch out of the structured block. 12033 // longjmp() and throw() must not violate the entry/exit criteria. 12034 CS->getCapturedDecl()->setNothrow(); 12035 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_enter_data); 12036 ThisCaptureLevel > 1; --ThisCaptureLevel) { 12037 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 12038 // 1.2.2 OpenMP Language Terminology 12039 // Structured block - An executable statement with a single entry at the 12040 // top and a single exit at the bottom. 12041 // The point of exit cannot be a branch out of the structured block. 12042 // longjmp() and throw() must not violate the entry/exit criteria. 12043 CS->getCapturedDecl()->setNothrow(); 12044 } 12045 12046 // OpenMP [2.10.2, Restrictions, p. 99] 12047 // At least one map clause must appear on the directive. 12048 if (!hasClauses(Clauses, OMPC_map)) { 12049 Diag(StartLoc, diag::err_omp_no_clause_for_directive) 12050 << "'map'" << getOpenMPDirectiveName(OMPD_target_enter_data); 12051 return StmtError(); 12052 } 12053 12054 return OMPTargetEnterDataDirective::Create(Context, StartLoc, EndLoc, Clauses, 12055 AStmt); 12056 } 12057 12058 StmtResult 12059 Sema::ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses, 12060 SourceLocation StartLoc, 12061 SourceLocation EndLoc, Stmt *AStmt) { 12062 if (!AStmt) 12063 return StmtError(); 12064 12065 auto *CS = cast<CapturedStmt>(AStmt); 12066 // 1.2.2 OpenMP Language Terminology 12067 // Structured block - An executable statement with a single entry at the 12068 // top and a single exit at the bottom. 12069 // The point of exit cannot be a branch out of the structured block. 12070 // longjmp() and throw() must not violate the entry/exit criteria. 12071 CS->getCapturedDecl()->setNothrow(); 12072 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_exit_data); 12073 ThisCaptureLevel > 1; --ThisCaptureLevel) { 12074 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 12075 // 1.2.2 OpenMP Language Terminology 12076 // Structured block - An executable statement with a single entry at the 12077 // top and a single exit at the bottom. 12078 // The point of exit cannot be a branch out of the structured block. 12079 // longjmp() and throw() must not violate the entry/exit criteria. 12080 CS->getCapturedDecl()->setNothrow(); 12081 } 12082 12083 // OpenMP [2.10.3, Restrictions, p. 102] 12084 // At least one map clause must appear on the directive. 12085 if (!hasClauses(Clauses, OMPC_map)) { 12086 Diag(StartLoc, diag::err_omp_no_clause_for_directive) 12087 << "'map'" << getOpenMPDirectiveName(OMPD_target_exit_data); 12088 return StmtError(); 12089 } 12090 12091 return OMPTargetExitDataDirective::Create(Context, StartLoc, EndLoc, Clauses, 12092 AStmt); 12093 } 12094 12095 StmtResult Sema::ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses, 12096 SourceLocation StartLoc, 12097 SourceLocation EndLoc, 12098 Stmt *AStmt) { 12099 if (!AStmt) 12100 return StmtError(); 12101 12102 auto *CS = cast<CapturedStmt>(AStmt); 12103 // 1.2.2 OpenMP Language Terminology 12104 // Structured block - An executable statement with a single entry at the 12105 // top and a single exit at the bottom. 12106 // The point of exit cannot be a branch out of the structured block. 12107 // longjmp() and throw() must not violate the entry/exit criteria. 12108 CS->getCapturedDecl()->setNothrow(); 12109 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_update); 12110 ThisCaptureLevel > 1; --ThisCaptureLevel) { 12111 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 12112 // 1.2.2 OpenMP Language Terminology 12113 // Structured block - An executable statement with a single entry at the 12114 // top and a single exit at the bottom. 12115 // The point of exit cannot be a branch out of the structured block. 12116 // longjmp() and throw() must not violate the entry/exit criteria. 12117 CS->getCapturedDecl()->setNothrow(); 12118 } 12119 12120 if (!hasClauses(Clauses, OMPC_to, OMPC_from)) { 12121 Diag(StartLoc, diag::err_omp_at_least_one_motion_clause_required); 12122 return StmtError(); 12123 } 12124 return OMPTargetUpdateDirective::Create(Context, StartLoc, EndLoc, Clauses, 12125 AStmt); 12126 } 12127 12128 StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses, 12129 Stmt *AStmt, SourceLocation StartLoc, 12130 SourceLocation EndLoc) { 12131 if (!AStmt) 12132 return StmtError(); 12133 12134 auto *CS = cast<CapturedStmt>(AStmt); 12135 // 1.2.2 OpenMP Language Terminology 12136 // Structured block - An executable statement with a single entry at the 12137 // top and a single exit at the bottom. 12138 // The point of exit cannot be a branch out of the structured block. 12139 // longjmp() and throw() must not violate the entry/exit criteria. 12140 CS->getCapturedDecl()->setNothrow(); 12141 12142 setFunctionHasBranchProtectedScope(); 12143 12144 DSAStack->setParentTeamsRegionLoc(StartLoc); 12145 12146 return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt); 12147 } 12148 12149 StmtResult 12150 Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc, 12151 SourceLocation EndLoc, 12152 OpenMPDirectiveKind CancelRegion) { 12153 if (DSAStack->isParentNowaitRegion()) { 12154 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0; 12155 return StmtError(); 12156 } 12157 if (DSAStack->isParentOrderedRegion()) { 12158 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0; 12159 return StmtError(); 12160 } 12161 return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc, 12162 CancelRegion); 12163 } 12164 12165 StmtResult Sema::ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses, 12166 SourceLocation StartLoc, 12167 SourceLocation EndLoc, 12168 OpenMPDirectiveKind CancelRegion) { 12169 if (DSAStack->isParentNowaitRegion()) { 12170 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1; 12171 return StmtError(); 12172 } 12173 if (DSAStack->isParentOrderedRegion()) { 12174 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1; 12175 return StmtError(); 12176 } 12177 DSAStack->setParentCancelRegion(/*Cancel=*/true); 12178 return OMPCancelDirective::Create(Context, StartLoc, EndLoc, Clauses, 12179 CancelRegion); 12180 } 12181 12182 static bool checkReductionClauseWithNogroup(Sema &S, 12183 ArrayRef<OMPClause *> Clauses) { 12184 const OMPClause *ReductionClause = nullptr; 12185 const OMPClause *NogroupClause = nullptr; 12186 for (const OMPClause *C : Clauses) { 12187 if (C->getClauseKind() == OMPC_reduction) { 12188 ReductionClause = C; 12189 if (NogroupClause) 12190 break; 12191 continue; 12192 } 12193 if (C->getClauseKind() == OMPC_nogroup) { 12194 NogroupClause = C; 12195 if (ReductionClause) 12196 break; 12197 continue; 12198 } 12199 } 12200 if (ReductionClause && NogroupClause) { 12201 S.Diag(ReductionClause->getBeginLoc(), diag::err_omp_reduction_with_nogroup) 12202 << SourceRange(NogroupClause->getBeginLoc(), 12203 NogroupClause->getEndLoc()); 12204 return true; 12205 } 12206 return false; 12207 } 12208 12209 StmtResult Sema::ActOnOpenMPTaskLoopDirective( 12210 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 12211 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 12212 if (!AStmt) 12213 return StmtError(); 12214 12215 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 12216 OMPLoopBasedDirective::HelperExprs B; 12217 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 12218 // define the nested loops number. 12219 unsigned NestedLoopCount = 12220 checkOpenMPLoop(OMPD_taskloop, getCollapseNumberExpr(Clauses), 12221 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack, 12222 VarsWithImplicitDSA, B); 12223 if (NestedLoopCount == 0) 12224 return StmtError(); 12225 12226 assert((CurContext->isDependentContext() || B.builtAll()) && 12227 "omp for loop exprs were not built"); 12228 12229 // OpenMP, [2.9.2 taskloop Construct, Restrictions] 12230 // The grainsize clause and num_tasks clause are mutually exclusive and may 12231 // not appear on the same taskloop directive. 12232 if (checkMutuallyExclusiveClauses(*this, Clauses, 12233 {OMPC_grainsize, OMPC_num_tasks})) 12234 return StmtError(); 12235 // OpenMP, [2.9.2 taskloop Construct, Restrictions] 12236 // If a reduction clause is present on the taskloop directive, the nogroup 12237 // clause must not be specified. 12238 if (checkReductionClauseWithNogroup(*this, Clauses)) 12239 return StmtError(); 12240 12241 setFunctionHasBranchProtectedScope(); 12242 return OMPTaskLoopDirective::Create(Context, StartLoc, EndLoc, 12243 NestedLoopCount, Clauses, AStmt, B, 12244 DSAStack->isCancelRegion()); 12245 } 12246 12247 StmtResult Sema::ActOnOpenMPTaskLoopSimdDirective( 12248 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 12249 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 12250 if (!AStmt) 12251 return StmtError(); 12252 12253 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 12254 OMPLoopBasedDirective::HelperExprs B; 12255 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 12256 // define the nested loops number. 12257 unsigned NestedLoopCount = 12258 checkOpenMPLoop(OMPD_taskloop_simd, getCollapseNumberExpr(Clauses), 12259 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack, 12260 VarsWithImplicitDSA, B); 12261 if (NestedLoopCount == 0) 12262 return StmtError(); 12263 12264 assert((CurContext->isDependentContext() || B.builtAll()) && 12265 "omp for loop exprs were not built"); 12266 12267 if (!CurContext->isDependentContext()) { 12268 // Finalize the clauses that need pre-built expressions for CodeGen. 12269 for (OMPClause *C : Clauses) { 12270 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 12271 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 12272 B.NumIterations, *this, CurScope, 12273 DSAStack)) 12274 return StmtError(); 12275 } 12276 } 12277 12278 // OpenMP, [2.9.2 taskloop Construct, Restrictions] 12279 // The grainsize clause and num_tasks clause are mutually exclusive and may 12280 // not appear on the same taskloop directive. 12281 if (checkMutuallyExclusiveClauses(*this, Clauses, 12282 {OMPC_grainsize, OMPC_num_tasks})) 12283 return StmtError(); 12284 // OpenMP, [2.9.2 taskloop Construct, Restrictions] 12285 // If a reduction clause is present on the taskloop directive, the nogroup 12286 // clause must not be specified. 12287 if (checkReductionClauseWithNogroup(*this, Clauses)) 12288 return StmtError(); 12289 if (checkSimdlenSafelenSpecified(*this, Clauses)) 12290 return StmtError(); 12291 12292 setFunctionHasBranchProtectedScope(); 12293 return OMPTaskLoopSimdDirective::Create(Context, StartLoc, EndLoc, 12294 NestedLoopCount, Clauses, AStmt, B); 12295 } 12296 12297 StmtResult Sema::ActOnOpenMPMasterTaskLoopDirective( 12298 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 12299 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 12300 if (!AStmt) 12301 return StmtError(); 12302 12303 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 12304 OMPLoopBasedDirective::HelperExprs B; 12305 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 12306 // define the nested loops number. 12307 unsigned NestedLoopCount = 12308 checkOpenMPLoop(OMPD_master_taskloop, getCollapseNumberExpr(Clauses), 12309 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack, 12310 VarsWithImplicitDSA, B); 12311 if (NestedLoopCount == 0) 12312 return StmtError(); 12313 12314 assert((CurContext->isDependentContext() || B.builtAll()) && 12315 "omp for loop exprs were not built"); 12316 12317 // OpenMP, [2.9.2 taskloop Construct, Restrictions] 12318 // The grainsize clause and num_tasks clause are mutually exclusive and may 12319 // not appear on the same taskloop directive. 12320 if (checkMutuallyExclusiveClauses(*this, Clauses, 12321 {OMPC_grainsize, OMPC_num_tasks})) 12322 return StmtError(); 12323 // OpenMP, [2.9.2 taskloop Construct, Restrictions] 12324 // If a reduction clause is present on the taskloop directive, the nogroup 12325 // clause must not be specified. 12326 if (checkReductionClauseWithNogroup(*this, Clauses)) 12327 return StmtError(); 12328 12329 setFunctionHasBranchProtectedScope(); 12330 return OMPMasterTaskLoopDirective::Create(Context, StartLoc, EndLoc, 12331 NestedLoopCount, Clauses, AStmt, B, 12332 DSAStack->isCancelRegion()); 12333 } 12334 12335 StmtResult Sema::ActOnOpenMPMasterTaskLoopSimdDirective( 12336 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 12337 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 12338 if (!AStmt) 12339 return StmtError(); 12340 12341 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 12342 OMPLoopBasedDirective::HelperExprs B; 12343 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 12344 // define the nested loops number. 12345 unsigned NestedLoopCount = 12346 checkOpenMPLoop(OMPD_master_taskloop_simd, getCollapseNumberExpr(Clauses), 12347 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack, 12348 VarsWithImplicitDSA, B); 12349 if (NestedLoopCount == 0) 12350 return StmtError(); 12351 12352 assert((CurContext->isDependentContext() || B.builtAll()) && 12353 "omp for loop exprs were not built"); 12354 12355 if (!CurContext->isDependentContext()) { 12356 // Finalize the clauses that need pre-built expressions for CodeGen. 12357 for (OMPClause *C : Clauses) { 12358 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 12359 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 12360 B.NumIterations, *this, CurScope, 12361 DSAStack)) 12362 return StmtError(); 12363 } 12364 } 12365 12366 // OpenMP, [2.9.2 taskloop Construct, Restrictions] 12367 // The grainsize clause and num_tasks clause are mutually exclusive and may 12368 // not appear on the same taskloop directive. 12369 if (checkMutuallyExclusiveClauses(*this, Clauses, 12370 {OMPC_grainsize, OMPC_num_tasks})) 12371 return StmtError(); 12372 // OpenMP, [2.9.2 taskloop Construct, Restrictions] 12373 // If a reduction clause is present on the taskloop directive, the nogroup 12374 // clause must not be specified. 12375 if (checkReductionClauseWithNogroup(*this, Clauses)) 12376 return StmtError(); 12377 if (checkSimdlenSafelenSpecified(*this, Clauses)) 12378 return StmtError(); 12379 12380 setFunctionHasBranchProtectedScope(); 12381 return OMPMasterTaskLoopSimdDirective::Create( 12382 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 12383 } 12384 12385 StmtResult Sema::ActOnOpenMPParallelMasterTaskLoopDirective( 12386 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 12387 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 12388 if (!AStmt) 12389 return StmtError(); 12390 12391 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 12392 auto *CS = cast<CapturedStmt>(AStmt); 12393 // 1.2.2 OpenMP Language Terminology 12394 // Structured block - An executable statement with a single entry at the 12395 // top and a single exit at the bottom. 12396 // The point of exit cannot be a branch out of the structured block. 12397 // longjmp() and throw() must not violate the entry/exit criteria. 12398 CS->getCapturedDecl()->setNothrow(); 12399 for (int ThisCaptureLevel = 12400 getOpenMPCaptureLevels(OMPD_parallel_master_taskloop); 12401 ThisCaptureLevel > 1; --ThisCaptureLevel) { 12402 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 12403 // 1.2.2 OpenMP Language Terminology 12404 // Structured block - An executable statement with a single entry at the 12405 // top and a single exit at the bottom. 12406 // The point of exit cannot be a branch out of the structured block. 12407 // longjmp() and throw() must not violate the entry/exit criteria. 12408 CS->getCapturedDecl()->setNothrow(); 12409 } 12410 12411 OMPLoopBasedDirective::HelperExprs B; 12412 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 12413 // define the nested loops number. 12414 unsigned NestedLoopCount = checkOpenMPLoop( 12415 OMPD_parallel_master_taskloop, getCollapseNumberExpr(Clauses), 12416 /*OrderedLoopCountExpr=*/nullptr, CS, *this, *DSAStack, 12417 VarsWithImplicitDSA, B); 12418 if (NestedLoopCount == 0) 12419 return StmtError(); 12420 12421 assert((CurContext->isDependentContext() || B.builtAll()) && 12422 "omp for loop exprs were not built"); 12423 12424 // OpenMP, [2.9.2 taskloop Construct, Restrictions] 12425 // The grainsize clause and num_tasks clause are mutually exclusive and may 12426 // not appear on the same taskloop directive. 12427 if (checkMutuallyExclusiveClauses(*this, Clauses, 12428 {OMPC_grainsize, OMPC_num_tasks})) 12429 return StmtError(); 12430 // OpenMP, [2.9.2 taskloop Construct, Restrictions] 12431 // If a reduction clause is present on the taskloop directive, the nogroup 12432 // clause must not be specified. 12433 if (checkReductionClauseWithNogroup(*this, Clauses)) 12434 return StmtError(); 12435 12436 setFunctionHasBranchProtectedScope(); 12437 return OMPParallelMasterTaskLoopDirective::Create( 12438 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B, 12439 DSAStack->isCancelRegion()); 12440 } 12441 12442 StmtResult Sema::ActOnOpenMPParallelMasterTaskLoopSimdDirective( 12443 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 12444 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 12445 if (!AStmt) 12446 return StmtError(); 12447 12448 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 12449 auto *CS = cast<CapturedStmt>(AStmt); 12450 // 1.2.2 OpenMP Language Terminology 12451 // Structured block - An executable statement with a single entry at the 12452 // top and a single exit at the bottom. 12453 // The point of exit cannot be a branch out of the structured block. 12454 // longjmp() and throw() must not violate the entry/exit criteria. 12455 CS->getCapturedDecl()->setNothrow(); 12456 for (int ThisCaptureLevel = 12457 getOpenMPCaptureLevels(OMPD_parallel_master_taskloop_simd); 12458 ThisCaptureLevel > 1; --ThisCaptureLevel) { 12459 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 12460 // 1.2.2 OpenMP Language Terminology 12461 // Structured block - An executable statement with a single entry at the 12462 // top and a single exit at the bottom. 12463 // The point of exit cannot be a branch out of the structured block. 12464 // longjmp() and throw() must not violate the entry/exit criteria. 12465 CS->getCapturedDecl()->setNothrow(); 12466 } 12467 12468 OMPLoopBasedDirective::HelperExprs B; 12469 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 12470 // define the nested loops number. 12471 unsigned NestedLoopCount = checkOpenMPLoop( 12472 OMPD_parallel_master_taskloop_simd, getCollapseNumberExpr(Clauses), 12473 /*OrderedLoopCountExpr=*/nullptr, CS, *this, *DSAStack, 12474 VarsWithImplicitDSA, B); 12475 if (NestedLoopCount == 0) 12476 return StmtError(); 12477 12478 assert((CurContext->isDependentContext() || B.builtAll()) && 12479 "omp for loop exprs were not built"); 12480 12481 if (!CurContext->isDependentContext()) { 12482 // Finalize the clauses that need pre-built expressions for CodeGen. 12483 for (OMPClause *C : Clauses) { 12484 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 12485 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 12486 B.NumIterations, *this, CurScope, 12487 DSAStack)) 12488 return StmtError(); 12489 } 12490 } 12491 12492 // OpenMP, [2.9.2 taskloop Construct, Restrictions] 12493 // The grainsize clause and num_tasks clause are mutually exclusive and may 12494 // not appear on the same taskloop directive. 12495 if (checkMutuallyExclusiveClauses(*this, Clauses, 12496 {OMPC_grainsize, OMPC_num_tasks})) 12497 return StmtError(); 12498 // OpenMP, [2.9.2 taskloop Construct, Restrictions] 12499 // If a reduction clause is present on the taskloop directive, the nogroup 12500 // clause must not be specified. 12501 if (checkReductionClauseWithNogroup(*this, Clauses)) 12502 return StmtError(); 12503 if (checkSimdlenSafelenSpecified(*this, Clauses)) 12504 return StmtError(); 12505 12506 setFunctionHasBranchProtectedScope(); 12507 return OMPParallelMasterTaskLoopSimdDirective::Create( 12508 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 12509 } 12510 12511 StmtResult Sema::ActOnOpenMPDistributeDirective( 12512 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 12513 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 12514 if (!AStmt) 12515 return StmtError(); 12516 12517 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 12518 OMPLoopBasedDirective::HelperExprs B; 12519 // In presence of clause 'collapse' with number of loops, it will 12520 // define the nested loops number. 12521 unsigned NestedLoopCount = 12522 checkOpenMPLoop(OMPD_distribute, getCollapseNumberExpr(Clauses), 12523 nullptr /*ordered not a clause on distribute*/, AStmt, 12524 *this, *DSAStack, VarsWithImplicitDSA, B); 12525 if (NestedLoopCount == 0) 12526 return StmtError(); 12527 12528 assert((CurContext->isDependentContext() || B.builtAll()) && 12529 "omp for loop exprs were not built"); 12530 12531 setFunctionHasBranchProtectedScope(); 12532 return OMPDistributeDirective::Create(Context, StartLoc, EndLoc, 12533 NestedLoopCount, Clauses, AStmt, B); 12534 } 12535 12536 StmtResult Sema::ActOnOpenMPDistributeParallelForDirective( 12537 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 12538 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 12539 if (!AStmt) 12540 return StmtError(); 12541 12542 auto *CS = cast<CapturedStmt>(AStmt); 12543 // 1.2.2 OpenMP Language Terminology 12544 // Structured block - An executable statement with a single entry at the 12545 // top and a single exit at the bottom. 12546 // The point of exit cannot be a branch out of the structured block. 12547 // longjmp() and throw() must not violate the entry/exit criteria. 12548 CS->getCapturedDecl()->setNothrow(); 12549 for (int ThisCaptureLevel = 12550 getOpenMPCaptureLevels(OMPD_distribute_parallel_for); 12551 ThisCaptureLevel > 1; --ThisCaptureLevel) { 12552 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 12553 // 1.2.2 OpenMP Language Terminology 12554 // Structured block - An executable statement with a single entry at the 12555 // top and a single exit at the bottom. 12556 // The point of exit cannot be a branch out of the structured block. 12557 // longjmp() and throw() must not violate the entry/exit criteria. 12558 CS->getCapturedDecl()->setNothrow(); 12559 } 12560 12561 OMPLoopBasedDirective::HelperExprs B; 12562 // In presence of clause 'collapse' with number of loops, it will 12563 // define the nested loops number. 12564 unsigned NestedLoopCount = checkOpenMPLoop( 12565 OMPD_distribute_parallel_for, getCollapseNumberExpr(Clauses), 12566 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack, 12567 VarsWithImplicitDSA, B); 12568 if (NestedLoopCount == 0) 12569 return StmtError(); 12570 12571 assert((CurContext->isDependentContext() || B.builtAll()) && 12572 "omp for loop exprs were not built"); 12573 12574 setFunctionHasBranchProtectedScope(); 12575 return OMPDistributeParallelForDirective::Create( 12576 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B, 12577 DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion()); 12578 } 12579 12580 StmtResult Sema::ActOnOpenMPDistributeParallelForSimdDirective( 12581 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 12582 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 12583 if (!AStmt) 12584 return StmtError(); 12585 12586 auto *CS = cast<CapturedStmt>(AStmt); 12587 // 1.2.2 OpenMP Language Terminology 12588 // Structured block - An executable statement with a single entry at the 12589 // top and a single exit at the bottom. 12590 // The point of exit cannot be a branch out of the structured block. 12591 // longjmp() and throw() must not violate the entry/exit criteria. 12592 CS->getCapturedDecl()->setNothrow(); 12593 for (int ThisCaptureLevel = 12594 getOpenMPCaptureLevels(OMPD_distribute_parallel_for_simd); 12595 ThisCaptureLevel > 1; --ThisCaptureLevel) { 12596 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 12597 // 1.2.2 OpenMP Language Terminology 12598 // Structured block - An executable statement with a single entry at the 12599 // top and a single exit at the bottom. 12600 // The point of exit cannot be a branch out of the structured block. 12601 // longjmp() and throw() must not violate the entry/exit criteria. 12602 CS->getCapturedDecl()->setNothrow(); 12603 } 12604 12605 OMPLoopBasedDirective::HelperExprs B; 12606 // In presence of clause 'collapse' with number of loops, it will 12607 // define the nested loops number. 12608 unsigned NestedLoopCount = checkOpenMPLoop( 12609 OMPD_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses), 12610 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack, 12611 VarsWithImplicitDSA, B); 12612 if (NestedLoopCount == 0) 12613 return StmtError(); 12614 12615 assert((CurContext->isDependentContext() || B.builtAll()) && 12616 "omp for loop exprs were not built"); 12617 12618 if (!CurContext->isDependentContext()) { 12619 // Finalize the clauses that need pre-built expressions for CodeGen. 12620 for (OMPClause *C : Clauses) { 12621 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 12622 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 12623 B.NumIterations, *this, CurScope, 12624 DSAStack)) 12625 return StmtError(); 12626 } 12627 } 12628 12629 if (checkSimdlenSafelenSpecified(*this, Clauses)) 12630 return StmtError(); 12631 12632 setFunctionHasBranchProtectedScope(); 12633 return OMPDistributeParallelForSimdDirective::Create( 12634 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 12635 } 12636 12637 StmtResult Sema::ActOnOpenMPDistributeSimdDirective( 12638 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 12639 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 12640 if (!AStmt) 12641 return StmtError(); 12642 12643 auto *CS = cast<CapturedStmt>(AStmt); 12644 // 1.2.2 OpenMP Language Terminology 12645 // Structured block - An executable statement with a single entry at the 12646 // top and a single exit at the bottom. 12647 // The point of exit cannot be a branch out of the structured block. 12648 // longjmp() and throw() must not violate the entry/exit criteria. 12649 CS->getCapturedDecl()->setNothrow(); 12650 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_distribute_simd); 12651 ThisCaptureLevel > 1; --ThisCaptureLevel) { 12652 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 12653 // 1.2.2 OpenMP Language Terminology 12654 // Structured block - An executable statement with a single entry at the 12655 // top and a single exit at the bottom. 12656 // The point of exit cannot be a branch out of the structured block. 12657 // longjmp() and throw() must not violate the entry/exit criteria. 12658 CS->getCapturedDecl()->setNothrow(); 12659 } 12660 12661 OMPLoopBasedDirective::HelperExprs B; 12662 // In presence of clause 'collapse' with number of loops, it will 12663 // define the nested loops number. 12664 unsigned NestedLoopCount = 12665 checkOpenMPLoop(OMPD_distribute_simd, getCollapseNumberExpr(Clauses), 12666 nullptr /*ordered not a clause on distribute*/, CS, *this, 12667 *DSAStack, VarsWithImplicitDSA, B); 12668 if (NestedLoopCount == 0) 12669 return StmtError(); 12670 12671 assert((CurContext->isDependentContext() || B.builtAll()) && 12672 "omp for loop exprs were not built"); 12673 12674 if (!CurContext->isDependentContext()) { 12675 // Finalize the clauses that need pre-built expressions for CodeGen. 12676 for (OMPClause *C : Clauses) { 12677 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 12678 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 12679 B.NumIterations, *this, CurScope, 12680 DSAStack)) 12681 return StmtError(); 12682 } 12683 } 12684 12685 if (checkSimdlenSafelenSpecified(*this, Clauses)) 12686 return StmtError(); 12687 12688 setFunctionHasBranchProtectedScope(); 12689 return OMPDistributeSimdDirective::Create(Context, StartLoc, EndLoc, 12690 NestedLoopCount, Clauses, AStmt, B); 12691 } 12692 12693 StmtResult Sema::ActOnOpenMPTargetParallelForSimdDirective( 12694 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 12695 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 12696 if (!AStmt) 12697 return StmtError(); 12698 12699 auto *CS = cast<CapturedStmt>(AStmt); 12700 // 1.2.2 OpenMP Language Terminology 12701 // Structured block - An executable statement with a single entry at the 12702 // top and a single exit at the bottom. 12703 // The point of exit cannot be a branch out of the structured block. 12704 // longjmp() and throw() must not violate the entry/exit criteria. 12705 CS->getCapturedDecl()->setNothrow(); 12706 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for); 12707 ThisCaptureLevel > 1; --ThisCaptureLevel) { 12708 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 12709 // 1.2.2 OpenMP Language Terminology 12710 // Structured block - An executable statement with a single entry at the 12711 // top and a single exit at the bottom. 12712 // The point of exit cannot be a branch out of the structured block. 12713 // longjmp() and throw() must not violate the entry/exit criteria. 12714 CS->getCapturedDecl()->setNothrow(); 12715 } 12716 12717 OMPLoopBasedDirective::HelperExprs B; 12718 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 12719 // define the nested loops number. 12720 unsigned NestedLoopCount = checkOpenMPLoop( 12721 OMPD_target_parallel_for_simd, getCollapseNumberExpr(Clauses), 12722 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack, VarsWithImplicitDSA, 12723 B); 12724 if (NestedLoopCount == 0) 12725 return StmtError(); 12726 12727 assert((CurContext->isDependentContext() || B.builtAll()) && 12728 "omp target parallel for simd loop exprs were not built"); 12729 12730 if (!CurContext->isDependentContext()) { 12731 // Finalize the clauses that need pre-built expressions for CodeGen. 12732 for (OMPClause *C : Clauses) { 12733 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 12734 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 12735 B.NumIterations, *this, CurScope, 12736 DSAStack)) 12737 return StmtError(); 12738 } 12739 } 12740 if (checkSimdlenSafelenSpecified(*this, Clauses)) 12741 return StmtError(); 12742 12743 setFunctionHasBranchProtectedScope(); 12744 return OMPTargetParallelForSimdDirective::Create( 12745 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 12746 } 12747 12748 StmtResult Sema::ActOnOpenMPTargetSimdDirective( 12749 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 12750 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 12751 if (!AStmt) 12752 return StmtError(); 12753 12754 auto *CS = cast<CapturedStmt>(AStmt); 12755 // 1.2.2 OpenMP Language Terminology 12756 // Structured block - An executable statement with a single entry at the 12757 // top and a single exit at the bottom. 12758 // The point of exit cannot be a branch out of the structured block. 12759 // longjmp() and throw() must not violate the entry/exit criteria. 12760 CS->getCapturedDecl()->setNothrow(); 12761 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_simd); 12762 ThisCaptureLevel > 1; --ThisCaptureLevel) { 12763 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 12764 // 1.2.2 OpenMP Language Terminology 12765 // Structured block - An executable statement with a single entry at the 12766 // top and a single exit at the bottom. 12767 // The point of exit cannot be a branch out of the structured block. 12768 // longjmp() and throw() must not violate the entry/exit criteria. 12769 CS->getCapturedDecl()->setNothrow(); 12770 } 12771 12772 OMPLoopBasedDirective::HelperExprs B; 12773 // In presence of clause 'collapse' with number of loops, it will define the 12774 // nested loops number. 12775 unsigned NestedLoopCount = 12776 checkOpenMPLoop(OMPD_target_simd, getCollapseNumberExpr(Clauses), 12777 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack, 12778 VarsWithImplicitDSA, B); 12779 if (NestedLoopCount == 0) 12780 return StmtError(); 12781 12782 assert((CurContext->isDependentContext() || B.builtAll()) && 12783 "omp target simd loop exprs were not built"); 12784 12785 if (!CurContext->isDependentContext()) { 12786 // Finalize the clauses that need pre-built expressions for CodeGen. 12787 for (OMPClause *C : Clauses) { 12788 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 12789 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 12790 B.NumIterations, *this, CurScope, 12791 DSAStack)) 12792 return StmtError(); 12793 } 12794 } 12795 12796 if (checkSimdlenSafelenSpecified(*this, Clauses)) 12797 return StmtError(); 12798 12799 setFunctionHasBranchProtectedScope(); 12800 return OMPTargetSimdDirective::Create(Context, StartLoc, EndLoc, 12801 NestedLoopCount, Clauses, AStmt, B); 12802 } 12803 12804 StmtResult Sema::ActOnOpenMPTeamsDistributeDirective( 12805 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 12806 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 12807 if (!AStmt) 12808 return StmtError(); 12809 12810 auto *CS = cast<CapturedStmt>(AStmt); 12811 // 1.2.2 OpenMP Language Terminology 12812 // Structured block - An executable statement with a single entry at the 12813 // top and a single exit at the bottom. 12814 // The point of exit cannot be a branch out of the structured block. 12815 // longjmp() and throw() must not violate the entry/exit criteria. 12816 CS->getCapturedDecl()->setNothrow(); 12817 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_teams_distribute); 12818 ThisCaptureLevel > 1; --ThisCaptureLevel) { 12819 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 12820 // 1.2.2 OpenMP Language Terminology 12821 // Structured block - An executable statement with a single entry at the 12822 // top and a single exit at the bottom. 12823 // The point of exit cannot be a branch out of the structured block. 12824 // longjmp() and throw() must not violate the entry/exit criteria. 12825 CS->getCapturedDecl()->setNothrow(); 12826 } 12827 12828 OMPLoopBasedDirective::HelperExprs B; 12829 // In presence of clause 'collapse' with number of loops, it will 12830 // define the nested loops number. 12831 unsigned NestedLoopCount = 12832 checkOpenMPLoop(OMPD_teams_distribute, getCollapseNumberExpr(Clauses), 12833 nullptr /*ordered not a clause on distribute*/, CS, *this, 12834 *DSAStack, VarsWithImplicitDSA, B); 12835 if (NestedLoopCount == 0) 12836 return StmtError(); 12837 12838 assert((CurContext->isDependentContext() || B.builtAll()) && 12839 "omp teams distribute loop exprs were not built"); 12840 12841 setFunctionHasBranchProtectedScope(); 12842 12843 DSAStack->setParentTeamsRegionLoc(StartLoc); 12844 12845 return OMPTeamsDistributeDirective::Create( 12846 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 12847 } 12848 12849 StmtResult Sema::ActOnOpenMPTeamsDistributeSimdDirective( 12850 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 12851 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 12852 if (!AStmt) 12853 return StmtError(); 12854 12855 auto *CS = cast<CapturedStmt>(AStmt); 12856 // 1.2.2 OpenMP Language Terminology 12857 // Structured block - An executable statement with a single entry at the 12858 // top and a single exit at the bottom. 12859 // The point of exit cannot be a branch out of the structured block. 12860 // longjmp() and throw() must not violate the entry/exit criteria. 12861 CS->getCapturedDecl()->setNothrow(); 12862 for (int ThisCaptureLevel = 12863 getOpenMPCaptureLevels(OMPD_teams_distribute_simd); 12864 ThisCaptureLevel > 1; --ThisCaptureLevel) { 12865 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 12866 // 1.2.2 OpenMP Language Terminology 12867 // Structured block - An executable statement with a single entry at the 12868 // top and a single exit at the bottom. 12869 // The point of exit cannot be a branch out of the structured block. 12870 // longjmp() and throw() must not violate the entry/exit criteria. 12871 CS->getCapturedDecl()->setNothrow(); 12872 } 12873 12874 OMPLoopBasedDirective::HelperExprs B; 12875 // In presence of clause 'collapse' with number of loops, it will 12876 // define the nested loops number. 12877 unsigned NestedLoopCount = checkOpenMPLoop( 12878 OMPD_teams_distribute_simd, getCollapseNumberExpr(Clauses), 12879 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack, 12880 VarsWithImplicitDSA, B); 12881 12882 if (NestedLoopCount == 0) 12883 return StmtError(); 12884 12885 assert((CurContext->isDependentContext() || B.builtAll()) && 12886 "omp teams distribute simd loop exprs were not built"); 12887 12888 if (!CurContext->isDependentContext()) { 12889 // Finalize the clauses that need pre-built expressions for CodeGen. 12890 for (OMPClause *C : Clauses) { 12891 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 12892 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 12893 B.NumIterations, *this, CurScope, 12894 DSAStack)) 12895 return StmtError(); 12896 } 12897 } 12898 12899 if (checkSimdlenSafelenSpecified(*this, Clauses)) 12900 return StmtError(); 12901 12902 setFunctionHasBranchProtectedScope(); 12903 12904 DSAStack->setParentTeamsRegionLoc(StartLoc); 12905 12906 return OMPTeamsDistributeSimdDirective::Create( 12907 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 12908 } 12909 12910 StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForSimdDirective( 12911 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 12912 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 12913 if (!AStmt) 12914 return StmtError(); 12915 12916 auto *CS = cast<CapturedStmt>(AStmt); 12917 // 1.2.2 OpenMP Language Terminology 12918 // Structured block - An executable statement with a single entry at the 12919 // top and a single exit at the bottom. 12920 // The point of exit cannot be a branch out of the structured block. 12921 // longjmp() and throw() must not violate the entry/exit criteria. 12922 CS->getCapturedDecl()->setNothrow(); 12923 12924 for (int ThisCaptureLevel = 12925 getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for_simd); 12926 ThisCaptureLevel > 1; --ThisCaptureLevel) { 12927 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 12928 // 1.2.2 OpenMP Language Terminology 12929 // Structured block - An executable statement with a single entry at the 12930 // top and a single exit at the bottom. 12931 // The point of exit cannot be a branch out of the structured block. 12932 // longjmp() and throw() must not violate the entry/exit criteria. 12933 CS->getCapturedDecl()->setNothrow(); 12934 } 12935 12936 OMPLoopBasedDirective::HelperExprs B; 12937 // In presence of clause 'collapse' with number of loops, it will 12938 // define the nested loops number. 12939 unsigned NestedLoopCount = checkOpenMPLoop( 12940 OMPD_teams_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses), 12941 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack, 12942 VarsWithImplicitDSA, B); 12943 12944 if (NestedLoopCount == 0) 12945 return StmtError(); 12946 12947 assert((CurContext->isDependentContext() || B.builtAll()) && 12948 "omp for loop exprs were not built"); 12949 12950 if (!CurContext->isDependentContext()) { 12951 // Finalize the clauses that need pre-built expressions for CodeGen. 12952 for (OMPClause *C : Clauses) { 12953 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 12954 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 12955 B.NumIterations, *this, CurScope, 12956 DSAStack)) 12957 return StmtError(); 12958 } 12959 } 12960 12961 if (checkSimdlenSafelenSpecified(*this, Clauses)) 12962 return StmtError(); 12963 12964 setFunctionHasBranchProtectedScope(); 12965 12966 DSAStack->setParentTeamsRegionLoc(StartLoc); 12967 12968 return OMPTeamsDistributeParallelForSimdDirective::Create( 12969 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 12970 } 12971 12972 StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForDirective( 12973 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 12974 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 12975 if (!AStmt) 12976 return StmtError(); 12977 12978 auto *CS = cast<CapturedStmt>(AStmt); 12979 // 1.2.2 OpenMP Language Terminology 12980 // Structured block - An executable statement with a single entry at the 12981 // top and a single exit at the bottom. 12982 // The point of exit cannot be a branch out of the structured block. 12983 // longjmp() and throw() must not violate the entry/exit criteria. 12984 CS->getCapturedDecl()->setNothrow(); 12985 12986 for (int ThisCaptureLevel = 12987 getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for); 12988 ThisCaptureLevel > 1; --ThisCaptureLevel) { 12989 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 12990 // 1.2.2 OpenMP Language Terminology 12991 // Structured block - An executable statement with a single entry at the 12992 // top and a single exit at the bottom. 12993 // The point of exit cannot be a branch out of the structured block. 12994 // longjmp() and throw() must not violate the entry/exit criteria. 12995 CS->getCapturedDecl()->setNothrow(); 12996 } 12997 12998 OMPLoopBasedDirective::HelperExprs B; 12999 // In presence of clause 'collapse' with number of loops, it will 13000 // define the nested loops number. 13001 unsigned NestedLoopCount = checkOpenMPLoop( 13002 OMPD_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses), 13003 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack, 13004 VarsWithImplicitDSA, B); 13005 13006 if (NestedLoopCount == 0) 13007 return StmtError(); 13008 13009 assert((CurContext->isDependentContext() || B.builtAll()) && 13010 "omp for loop exprs were not built"); 13011 13012 setFunctionHasBranchProtectedScope(); 13013 13014 DSAStack->setParentTeamsRegionLoc(StartLoc); 13015 13016 return OMPTeamsDistributeParallelForDirective::Create( 13017 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B, 13018 DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion()); 13019 } 13020 13021 StmtResult Sema::ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses, 13022 Stmt *AStmt, 13023 SourceLocation StartLoc, 13024 SourceLocation EndLoc) { 13025 if (!AStmt) 13026 return StmtError(); 13027 13028 auto *CS = cast<CapturedStmt>(AStmt); 13029 // 1.2.2 OpenMP Language Terminology 13030 // Structured block - An executable statement with a single entry at the 13031 // top and a single exit at the bottom. 13032 // The point of exit cannot be a branch out of the structured block. 13033 // longjmp() and throw() must not violate the entry/exit criteria. 13034 CS->getCapturedDecl()->setNothrow(); 13035 13036 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_teams); 13037 ThisCaptureLevel > 1; --ThisCaptureLevel) { 13038 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 13039 // 1.2.2 OpenMP Language Terminology 13040 // Structured block - An executable statement with a single entry at the 13041 // top and a single exit at the bottom. 13042 // The point of exit cannot be a branch out of the structured block. 13043 // longjmp() and throw() must not violate the entry/exit criteria. 13044 CS->getCapturedDecl()->setNothrow(); 13045 } 13046 setFunctionHasBranchProtectedScope(); 13047 13048 return OMPTargetTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, 13049 AStmt); 13050 } 13051 13052 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeDirective( 13053 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 13054 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 13055 if (!AStmt) 13056 return StmtError(); 13057 13058 auto *CS = cast<CapturedStmt>(AStmt); 13059 // 1.2.2 OpenMP Language Terminology 13060 // Structured block - An executable statement with a single entry at the 13061 // top and a single exit at the bottom. 13062 // The point of exit cannot be a branch out of the structured block. 13063 // longjmp() and throw() must not violate the entry/exit criteria. 13064 CS->getCapturedDecl()->setNothrow(); 13065 for (int ThisCaptureLevel = 13066 getOpenMPCaptureLevels(OMPD_target_teams_distribute); 13067 ThisCaptureLevel > 1; --ThisCaptureLevel) { 13068 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 13069 // 1.2.2 OpenMP Language Terminology 13070 // Structured block - An executable statement with a single entry at the 13071 // top and a single exit at the bottom. 13072 // The point of exit cannot be a branch out of the structured block. 13073 // longjmp() and throw() must not violate the entry/exit criteria. 13074 CS->getCapturedDecl()->setNothrow(); 13075 } 13076 13077 OMPLoopBasedDirective::HelperExprs B; 13078 // In presence of clause 'collapse' with number of loops, it will 13079 // define the nested loops number. 13080 unsigned NestedLoopCount = checkOpenMPLoop( 13081 OMPD_target_teams_distribute, getCollapseNumberExpr(Clauses), 13082 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack, 13083 VarsWithImplicitDSA, B); 13084 if (NestedLoopCount == 0) 13085 return StmtError(); 13086 13087 assert((CurContext->isDependentContext() || B.builtAll()) && 13088 "omp target teams distribute loop exprs were not built"); 13089 13090 setFunctionHasBranchProtectedScope(); 13091 return OMPTargetTeamsDistributeDirective::Create( 13092 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 13093 } 13094 13095 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForDirective( 13096 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 13097 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 13098 if (!AStmt) 13099 return StmtError(); 13100 13101 auto *CS = cast<CapturedStmt>(AStmt); 13102 // 1.2.2 OpenMP Language Terminology 13103 // Structured block - An executable statement with a single entry at the 13104 // top and a single exit at the bottom. 13105 // The point of exit cannot be a branch out of the structured block. 13106 // longjmp() and throw() must not violate the entry/exit criteria. 13107 CS->getCapturedDecl()->setNothrow(); 13108 for (int ThisCaptureLevel = 13109 getOpenMPCaptureLevels(OMPD_target_teams_distribute_parallel_for); 13110 ThisCaptureLevel > 1; --ThisCaptureLevel) { 13111 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 13112 // 1.2.2 OpenMP Language Terminology 13113 // Structured block - An executable statement with a single entry at the 13114 // top and a single exit at the bottom. 13115 // The point of exit cannot be a branch out of the structured block. 13116 // longjmp() and throw() must not violate the entry/exit criteria. 13117 CS->getCapturedDecl()->setNothrow(); 13118 } 13119 13120 OMPLoopBasedDirective::HelperExprs B; 13121 // In presence of clause 'collapse' with number of loops, it will 13122 // define the nested loops number. 13123 unsigned NestedLoopCount = checkOpenMPLoop( 13124 OMPD_target_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses), 13125 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack, 13126 VarsWithImplicitDSA, B); 13127 if (NestedLoopCount == 0) 13128 return StmtError(); 13129 13130 assert((CurContext->isDependentContext() || B.builtAll()) && 13131 "omp target teams distribute parallel for loop exprs were not built"); 13132 13133 if (!CurContext->isDependentContext()) { 13134 // Finalize the clauses that need pre-built expressions for CodeGen. 13135 for (OMPClause *C : Clauses) { 13136 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 13137 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 13138 B.NumIterations, *this, CurScope, 13139 DSAStack)) 13140 return StmtError(); 13141 } 13142 } 13143 13144 setFunctionHasBranchProtectedScope(); 13145 return OMPTargetTeamsDistributeParallelForDirective::Create( 13146 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B, 13147 DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion()); 13148 } 13149 13150 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective( 13151 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 13152 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 13153 if (!AStmt) 13154 return StmtError(); 13155 13156 auto *CS = cast<CapturedStmt>(AStmt); 13157 // 1.2.2 OpenMP Language Terminology 13158 // Structured block - An executable statement with a single entry at the 13159 // top and a single exit at the bottom. 13160 // The point of exit cannot be a branch out of the structured block. 13161 // longjmp() and throw() must not violate the entry/exit criteria. 13162 CS->getCapturedDecl()->setNothrow(); 13163 for (int ThisCaptureLevel = getOpenMPCaptureLevels( 13164 OMPD_target_teams_distribute_parallel_for_simd); 13165 ThisCaptureLevel > 1; --ThisCaptureLevel) { 13166 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 13167 // 1.2.2 OpenMP Language Terminology 13168 // Structured block - An executable statement with a single entry at the 13169 // top and a single exit at the bottom. 13170 // The point of exit cannot be a branch out of the structured block. 13171 // longjmp() and throw() must not violate the entry/exit criteria. 13172 CS->getCapturedDecl()->setNothrow(); 13173 } 13174 13175 OMPLoopBasedDirective::HelperExprs B; 13176 // In presence of clause 'collapse' with number of loops, it will 13177 // define the nested loops number. 13178 unsigned NestedLoopCount = 13179 checkOpenMPLoop(OMPD_target_teams_distribute_parallel_for_simd, 13180 getCollapseNumberExpr(Clauses), 13181 nullptr /*ordered not a clause on distribute*/, CS, *this, 13182 *DSAStack, VarsWithImplicitDSA, B); 13183 if (NestedLoopCount == 0) 13184 return StmtError(); 13185 13186 assert((CurContext->isDependentContext() || B.builtAll()) && 13187 "omp target teams distribute parallel for simd loop exprs were not " 13188 "built"); 13189 13190 if (!CurContext->isDependentContext()) { 13191 // Finalize the clauses that need pre-built expressions for CodeGen. 13192 for (OMPClause *C : Clauses) { 13193 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 13194 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 13195 B.NumIterations, *this, CurScope, 13196 DSAStack)) 13197 return StmtError(); 13198 } 13199 } 13200 13201 if (checkSimdlenSafelenSpecified(*this, Clauses)) 13202 return StmtError(); 13203 13204 setFunctionHasBranchProtectedScope(); 13205 return OMPTargetTeamsDistributeParallelForSimdDirective::Create( 13206 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 13207 } 13208 13209 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeSimdDirective( 13210 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 13211 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 13212 if (!AStmt) 13213 return StmtError(); 13214 13215 auto *CS = cast<CapturedStmt>(AStmt); 13216 // 1.2.2 OpenMP Language Terminology 13217 // Structured block - An executable statement with a single entry at the 13218 // top and a single exit at the bottom. 13219 // The point of exit cannot be a branch out of the structured block. 13220 // longjmp() and throw() must not violate the entry/exit criteria. 13221 CS->getCapturedDecl()->setNothrow(); 13222 for (int ThisCaptureLevel = 13223 getOpenMPCaptureLevels(OMPD_target_teams_distribute_simd); 13224 ThisCaptureLevel > 1; --ThisCaptureLevel) { 13225 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 13226 // 1.2.2 OpenMP Language Terminology 13227 // Structured block - An executable statement with a single entry at the 13228 // top and a single exit at the bottom. 13229 // The point of exit cannot be a branch out of the structured block. 13230 // longjmp() and throw() must not violate the entry/exit criteria. 13231 CS->getCapturedDecl()->setNothrow(); 13232 } 13233 13234 OMPLoopBasedDirective::HelperExprs B; 13235 // In presence of clause 'collapse' with number of loops, it will 13236 // define the nested loops number. 13237 unsigned NestedLoopCount = checkOpenMPLoop( 13238 OMPD_target_teams_distribute_simd, getCollapseNumberExpr(Clauses), 13239 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack, 13240 VarsWithImplicitDSA, B); 13241 if (NestedLoopCount == 0) 13242 return StmtError(); 13243 13244 assert((CurContext->isDependentContext() || B.builtAll()) && 13245 "omp target teams distribute simd loop exprs were not built"); 13246 13247 if (!CurContext->isDependentContext()) { 13248 // Finalize the clauses that need pre-built expressions for CodeGen. 13249 for (OMPClause *C : Clauses) { 13250 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 13251 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 13252 B.NumIterations, *this, CurScope, 13253 DSAStack)) 13254 return StmtError(); 13255 } 13256 } 13257 13258 if (checkSimdlenSafelenSpecified(*this, Clauses)) 13259 return StmtError(); 13260 13261 setFunctionHasBranchProtectedScope(); 13262 return OMPTargetTeamsDistributeSimdDirective::Create( 13263 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 13264 } 13265 13266 bool Sema::checkTransformableLoopNest( 13267 OpenMPDirectiveKind Kind, Stmt *AStmt, int NumLoops, 13268 SmallVectorImpl<OMPLoopBasedDirective::HelperExprs> &LoopHelpers, 13269 Stmt *&Body, 13270 SmallVectorImpl<SmallVector<llvm::PointerUnion<Stmt *, Decl *>, 0>> 13271 &OriginalInits) { 13272 OriginalInits.emplace_back(); 13273 bool Result = OMPLoopBasedDirective::doForAllLoops( 13274 AStmt->IgnoreContainers(), /*TryImperfectlyNestedLoops=*/false, NumLoops, 13275 [this, &LoopHelpers, &Body, &OriginalInits, Kind](unsigned Cnt, 13276 Stmt *CurStmt) { 13277 VarsWithInheritedDSAType TmpDSA; 13278 unsigned SingleNumLoops = 13279 checkOpenMPLoop(Kind, nullptr, nullptr, CurStmt, *this, *DSAStack, 13280 TmpDSA, LoopHelpers[Cnt]); 13281 if (SingleNumLoops == 0) 13282 return true; 13283 assert(SingleNumLoops == 1 && "Expect single loop iteration space"); 13284 if (auto *For = dyn_cast<ForStmt>(CurStmt)) { 13285 OriginalInits.back().push_back(For->getInit()); 13286 Body = For->getBody(); 13287 } else { 13288 assert(isa<CXXForRangeStmt>(CurStmt) && 13289 "Expected canonical for or range-based for loops."); 13290 auto *CXXFor = cast<CXXForRangeStmt>(CurStmt); 13291 OriginalInits.back().push_back(CXXFor->getBeginStmt()); 13292 Body = CXXFor->getBody(); 13293 } 13294 OriginalInits.emplace_back(); 13295 return false; 13296 }, 13297 [&OriginalInits](OMPLoopBasedDirective *Transform) { 13298 Stmt *DependentPreInits; 13299 if (auto *Dir = dyn_cast<OMPTileDirective>(Transform)) 13300 DependentPreInits = Dir->getPreInits(); 13301 else if (auto *Dir = dyn_cast<OMPUnrollDirective>(Transform)) 13302 DependentPreInits = Dir->getPreInits(); 13303 else 13304 llvm_unreachable("Unhandled loop transformation"); 13305 if (!DependentPreInits) 13306 return; 13307 for (Decl *C : cast<DeclStmt>(DependentPreInits)->getDeclGroup()) 13308 OriginalInits.back().push_back(C); 13309 }); 13310 assert(OriginalInits.back().empty() && "No preinit after innermost loop"); 13311 OriginalInits.pop_back(); 13312 return Result; 13313 } 13314 13315 StmtResult Sema::ActOnOpenMPTileDirective(ArrayRef<OMPClause *> Clauses, 13316 Stmt *AStmt, SourceLocation StartLoc, 13317 SourceLocation EndLoc) { 13318 auto SizesClauses = 13319 OMPExecutableDirective::getClausesOfKind<OMPSizesClause>(Clauses); 13320 if (SizesClauses.empty()) { 13321 // A missing 'sizes' clause is already reported by the parser. 13322 return StmtError(); 13323 } 13324 const OMPSizesClause *SizesClause = *SizesClauses.begin(); 13325 unsigned NumLoops = SizesClause->getNumSizes(); 13326 13327 // Empty statement should only be possible if there already was an error. 13328 if (!AStmt) 13329 return StmtError(); 13330 13331 // Verify and diagnose loop nest. 13332 SmallVector<OMPLoopBasedDirective::HelperExprs, 4> LoopHelpers(NumLoops); 13333 Stmt *Body = nullptr; 13334 SmallVector<SmallVector<llvm::PointerUnion<Stmt *, Decl *>, 0>, 4> 13335 OriginalInits; 13336 if (!checkTransformableLoopNest(OMPD_tile, AStmt, NumLoops, LoopHelpers, Body, 13337 OriginalInits)) 13338 return StmtError(); 13339 13340 // Delay tiling to when template is completely instantiated. 13341 if (CurContext->isDependentContext()) 13342 return OMPTileDirective::Create(Context, StartLoc, EndLoc, Clauses, 13343 NumLoops, AStmt, nullptr, nullptr); 13344 13345 SmallVector<Decl *, 4> PreInits; 13346 13347 // Create iteration variables for the generated loops. 13348 SmallVector<VarDecl *, 4> FloorIndVars; 13349 SmallVector<VarDecl *, 4> TileIndVars; 13350 FloorIndVars.resize(NumLoops); 13351 TileIndVars.resize(NumLoops); 13352 for (unsigned I = 0; I < NumLoops; ++I) { 13353 OMPLoopBasedDirective::HelperExprs &LoopHelper = LoopHelpers[I]; 13354 13355 assert(LoopHelper.Counters.size() == 1 && 13356 "Expect single-dimensional loop iteration space"); 13357 auto *OrigCntVar = cast<DeclRefExpr>(LoopHelper.Counters.front()); 13358 std::string OrigVarName = OrigCntVar->getNameInfo().getAsString(); 13359 DeclRefExpr *IterVarRef = cast<DeclRefExpr>(LoopHelper.IterationVarRef); 13360 QualType CntTy = IterVarRef->getType(); 13361 13362 // Iteration variable for the floor (i.e. outer) loop. 13363 { 13364 std::string FloorCntName = 13365 (Twine(".floor_") + llvm::utostr(I) + ".iv." + OrigVarName).str(); 13366 VarDecl *FloorCntDecl = 13367 buildVarDecl(*this, {}, CntTy, FloorCntName, nullptr, OrigCntVar); 13368 FloorIndVars[I] = FloorCntDecl; 13369 } 13370 13371 // Iteration variable for the tile (i.e. inner) loop. 13372 { 13373 std::string TileCntName = 13374 (Twine(".tile_") + llvm::utostr(I) + ".iv." + OrigVarName).str(); 13375 13376 // Reuse the iteration variable created by checkOpenMPLoop. It is also 13377 // used by the expressions to derive the original iteration variable's 13378 // value from the logical iteration number. 13379 auto *TileCntDecl = cast<VarDecl>(IterVarRef->getDecl()); 13380 TileCntDecl->setDeclName(&PP.getIdentifierTable().get(TileCntName)); 13381 TileIndVars[I] = TileCntDecl; 13382 } 13383 for (auto &P : OriginalInits[I]) { 13384 if (auto *D = P.dyn_cast<Decl *>()) 13385 PreInits.push_back(D); 13386 else if (auto *PI = dyn_cast_or_null<DeclStmt>(P.dyn_cast<Stmt *>())) 13387 PreInits.append(PI->decl_begin(), PI->decl_end()); 13388 } 13389 if (auto *PI = cast_or_null<DeclStmt>(LoopHelper.PreInits)) 13390 PreInits.append(PI->decl_begin(), PI->decl_end()); 13391 // Gather declarations for the data members used as counters. 13392 for (Expr *CounterRef : LoopHelper.Counters) { 13393 auto *CounterDecl = cast<DeclRefExpr>(CounterRef)->getDecl(); 13394 if (isa<OMPCapturedExprDecl>(CounterDecl)) 13395 PreInits.push_back(CounterDecl); 13396 } 13397 } 13398 13399 // Once the original iteration values are set, append the innermost body. 13400 Stmt *Inner = Body; 13401 13402 // Create tile loops from the inside to the outside. 13403 for (int I = NumLoops - 1; I >= 0; --I) { 13404 OMPLoopBasedDirective::HelperExprs &LoopHelper = LoopHelpers[I]; 13405 Expr *NumIterations = LoopHelper.NumIterations; 13406 auto *OrigCntVar = cast<DeclRefExpr>(LoopHelper.Counters[0]); 13407 QualType CntTy = OrigCntVar->getType(); 13408 Expr *DimTileSize = SizesClause->getSizesRefs()[I]; 13409 Scope *CurScope = getCurScope(); 13410 13411 // Commonly used variables. 13412 DeclRefExpr *TileIV = buildDeclRefExpr(*this, TileIndVars[I], CntTy, 13413 OrigCntVar->getExprLoc()); 13414 DeclRefExpr *FloorIV = buildDeclRefExpr(*this, FloorIndVars[I], CntTy, 13415 OrigCntVar->getExprLoc()); 13416 13417 // For init-statement: auto .tile.iv = .floor.iv 13418 AddInitializerToDecl(TileIndVars[I], DefaultLvalueConversion(FloorIV).get(), 13419 /*DirectInit=*/false); 13420 Decl *CounterDecl = TileIndVars[I]; 13421 StmtResult InitStmt = new (Context) 13422 DeclStmt(DeclGroupRef::Create(Context, &CounterDecl, 1), 13423 OrigCntVar->getBeginLoc(), OrigCntVar->getEndLoc()); 13424 if (!InitStmt.isUsable()) 13425 return StmtError(); 13426 13427 // For cond-expression: .tile.iv < min(.floor.iv + DimTileSize, 13428 // NumIterations) 13429 ExprResult EndOfTile = BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(), 13430 BO_Add, FloorIV, DimTileSize); 13431 if (!EndOfTile.isUsable()) 13432 return StmtError(); 13433 ExprResult IsPartialTile = 13434 BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(), BO_LT, 13435 NumIterations, EndOfTile.get()); 13436 if (!IsPartialTile.isUsable()) 13437 return StmtError(); 13438 ExprResult MinTileAndIterSpace = ActOnConditionalOp( 13439 LoopHelper.Cond->getBeginLoc(), LoopHelper.Cond->getEndLoc(), 13440 IsPartialTile.get(), NumIterations, EndOfTile.get()); 13441 if (!MinTileAndIterSpace.isUsable()) 13442 return StmtError(); 13443 ExprResult CondExpr = BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(), 13444 BO_LT, TileIV, MinTileAndIterSpace.get()); 13445 if (!CondExpr.isUsable()) 13446 return StmtError(); 13447 13448 // For incr-statement: ++.tile.iv 13449 ExprResult IncrStmt = 13450 BuildUnaryOp(CurScope, LoopHelper.Inc->getExprLoc(), UO_PreInc, TileIV); 13451 if (!IncrStmt.isUsable()) 13452 return StmtError(); 13453 13454 // Statements to set the original iteration variable's value from the 13455 // logical iteration number. 13456 // Generated for loop is: 13457 // Original_for_init; 13458 // for (auto .tile.iv = .floor.iv; .tile.iv < min(.floor.iv + DimTileSize, 13459 // NumIterations); ++.tile.iv) { 13460 // Original_Body; 13461 // Original_counter_update; 13462 // } 13463 // FIXME: If the innermost body is an loop itself, inserting these 13464 // statements stops it being recognized as a perfectly nested loop (e.g. 13465 // for applying tiling again). If this is the case, sink the expressions 13466 // further into the inner loop. 13467 SmallVector<Stmt *, 4> BodyParts; 13468 BodyParts.append(LoopHelper.Updates.begin(), LoopHelper.Updates.end()); 13469 BodyParts.push_back(Inner); 13470 Inner = CompoundStmt::Create(Context, BodyParts, Inner->getBeginLoc(), 13471 Inner->getEndLoc()); 13472 Inner = new (Context) 13473 ForStmt(Context, InitStmt.get(), CondExpr.get(), nullptr, 13474 IncrStmt.get(), Inner, LoopHelper.Init->getBeginLoc(), 13475 LoopHelper.Init->getBeginLoc(), LoopHelper.Inc->getEndLoc()); 13476 } 13477 13478 // Create floor loops from the inside to the outside. 13479 for (int I = NumLoops - 1; I >= 0; --I) { 13480 auto &LoopHelper = LoopHelpers[I]; 13481 Expr *NumIterations = LoopHelper.NumIterations; 13482 DeclRefExpr *OrigCntVar = cast<DeclRefExpr>(LoopHelper.Counters[0]); 13483 QualType CntTy = OrigCntVar->getType(); 13484 Expr *DimTileSize = SizesClause->getSizesRefs()[I]; 13485 Scope *CurScope = getCurScope(); 13486 13487 // Commonly used variables. 13488 DeclRefExpr *FloorIV = buildDeclRefExpr(*this, FloorIndVars[I], CntTy, 13489 OrigCntVar->getExprLoc()); 13490 13491 // For init-statement: auto .floor.iv = 0 13492 AddInitializerToDecl( 13493 FloorIndVars[I], 13494 ActOnIntegerConstant(LoopHelper.Init->getExprLoc(), 0).get(), 13495 /*DirectInit=*/false); 13496 Decl *CounterDecl = FloorIndVars[I]; 13497 StmtResult InitStmt = new (Context) 13498 DeclStmt(DeclGroupRef::Create(Context, &CounterDecl, 1), 13499 OrigCntVar->getBeginLoc(), OrigCntVar->getEndLoc()); 13500 if (!InitStmt.isUsable()) 13501 return StmtError(); 13502 13503 // For cond-expression: .floor.iv < NumIterations 13504 ExprResult CondExpr = BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(), 13505 BO_LT, FloorIV, NumIterations); 13506 if (!CondExpr.isUsable()) 13507 return StmtError(); 13508 13509 // For incr-statement: .floor.iv += DimTileSize 13510 ExprResult IncrStmt = BuildBinOp(CurScope, LoopHelper.Inc->getExprLoc(), 13511 BO_AddAssign, FloorIV, DimTileSize); 13512 if (!IncrStmt.isUsable()) 13513 return StmtError(); 13514 13515 Inner = new (Context) 13516 ForStmt(Context, InitStmt.get(), CondExpr.get(), nullptr, 13517 IncrStmt.get(), Inner, LoopHelper.Init->getBeginLoc(), 13518 LoopHelper.Init->getBeginLoc(), LoopHelper.Inc->getEndLoc()); 13519 } 13520 13521 return OMPTileDirective::Create(Context, StartLoc, EndLoc, Clauses, NumLoops, 13522 AStmt, Inner, 13523 buildPreInits(Context, PreInits)); 13524 } 13525 13526 StmtResult Sema::ActOnOpenMPUnrollDirective(ArrayRef<OMPClause *> Clauses, 13527 Stmt *AStmt, 13528 SourceLocation StartLoc, 13529 SourceLocation EndLoc) { 13530 // Empty statement should only be possible if there already was an error. 13531 if (!AStmt) 13532 return StmtError(); 13533 13534 if (checkMutuallyExclusiveClauses(*this, Clauses, {OMPC_partial, OMPC_full})) 13535 return StmtError(); 13536 13537 const OMPFullClause *FullClause = 13538 OMPExecutableDirective::getSingleClause<OMPFullClause>(Clauses); 13539 const OMPPartialClause *PartialClause = 13540 OMPExecutableDirective::getSingleClause<OMPPartialClause>(Clauses); 13541 assert(!(FullClause && PartialClause) && 13542 "mutual exclusivity must have been checked before"); 13543 13544 constexpr unsigned NumLoops = 1; 13545 Stmt *Body = nullptr; 13546 SmallVector<OMPLoopBasedDirective::HelperExprs, NumLoops> LoopHelpers( 13547 NumLoops); 13548 SmallVector<SmallVector<llvm::PointerUnion<Stmt *, Decl *>, 0>, NumLoops + 1> 13549 OriginalInits; 13550 if (!checkTransformableLoopNest(OMPD_unroll, AStmt, NumLoops, LoopHelpers, 13551 Body, OriginalInits)) 13552 return StmtError(); 13553 13554 unsigned NumGeneratedLoops = PartialClause ? 1 : 0; 13555 13556 // Delay unrolling to when template is completely instantiated. 13557 if (CurContext->isDependentContext()) 13558 return OMPUnrollDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt, 13559 NumGeneratedLoops, nullptr, nullptr); 13560 13561 OMPLoopBasedDirective::HelperExprs &LoopHelper = LoopHelpers.front(); 13562 13563 if (FullClause) { 13564 if (!VerifyPositiveIntegerConstantInClause( 13565 LoopHelper.NumIterations, OMPC_full, /*StrictlyPositive=*/false, 13566 /*SuppressExprDiags=*/true) 13567 .isUsable()) { 13568 Diag(AStmt->getBeginLoc(), diag::err_omp_unroll_full_variable_trip_count); 13569 Diag(FullClause->getBeginLoc(), diag::note_omp_directive_here) 13570 << "#pragma omp unroll full"; 13571 return StmtError(); 13572 } 13573 } 13574 13575 // The generated loop may only be passed to other loop-associated directive 13576 // when a partial clause is specified. Without the requirement it is 13577 // sufficient to generate loop unroll metadata at code-generation. 13578 if (NumGeneratedLoops == 0) 13579 return OMPUnrollDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt, 13580 NumGeneratedLoops, nullptr, nullptr); 13581 13582 // Otherwise, we need to provide a de-sugared/transformed AST that can be 13583 // associated with another loop directive. 13584 // 13585 // The canonical loop analysis return by checkTransformableLoopNest assumes 13586 // the following structure to be the same loop without transformations or 13587 // directives applied: \code OriginalInits; LoopHelper.PreInits; 13588 // LoopHelper.Counters; 13589 // for (; IV < LoopHelper.NumIterations; ++IV) { 13590 // LoopHelper.Updates; 13591 // Body; 13592 // } 13593 // \endcode 13594 // where IV is a variable declared and initialized to 0 in LoopHelper.PreInits 13595 // and referenced by LoopHelper.IterationVarRef. 13596 // 13597 // The unrolling directive transforms this into the following loop: 13598 // \code 13599 // OriginalInits; \ 13600 // LoopHelper.PreInits; > NewPreInits 13601 // LoopHelper.Counters; / 13602 // for (auto UIV = 0; UIV < LoopHelper.NumIterations; UIV+=Factor) { 13603 // #pragma clang loop unroll_count(Factor) 13604 // for (IV = UIV; IV < UIV + Factor && UIV < LoopHelper.NumIterations; ++IV) 13605 // { 13606 // LoopHelper.Updates; 13607 // Body; 13608 // } 13609 // } 13610 // \endcode 13611 // where UIV is a new logical iteration counter. IV must be the same VarDecl 13612 // as the original LoopHelper.IterationVarRef because LoopHelper.Updates 13613 // references it. If the partially unrolled loop is associated with another 13614 // loop directive (like an OMPForDirective), it will use checkOpenMPLoop to 13615 // analyze this loop, i.e. the outer loop must fulfill the constraints of an 13616 // OpenMP canonical loop. The inner loop is not an associable canonical loop 13617 // and only exists to defer its unrolling to LLVM's LoopUnroll instead of 13618 // doing it in the frontend (by adding loop metadata). NewPreInits becomes a 13619 // property of the OMPLoopBasedDirective instead of statements in 13620 // CompoundStatement. This is to allow the loop to become a non-outermost loop 13621 // of a canonical loop nest where these PreInits are emitted before the 13622 // outermost directive. 13623 13624 // Determine the PreInit declarations. 13625 SmallVector<Decl *, 4> PreInits; 13626 assert(OriginalInits.size() == 1 && 13627 "Expecting a single-dimensional loop iteration space"); 13628 for (auto &P : OriginalInits[0]) { 13629 if (auto *D = P.dyn_cast<Decl *>()) 13630 PreInits.push_back(D); 13631 else if (auto *PI = dyn_cast_or_null<DeclStmt>(P.dyn_cast<Stmt *>())) 13632 PreInits.append(PI->decl_begin(), PI->decl_end()); 13633 } 13634 if (auto *PI = cast_or_null<DeclStmt>(LoopHelper.PreInits)) 13635 PreInits.append(PI->decl_begin(), PI->decl_end()); 13636 // Gather declarations for the data members used as counters. 13637 for (Expr *CounterRef : LoopHelper.Counters) { 13638 auto *CounterDecl = cast<DeclRefExpr>(CounterRef)->getDecl(); 13639 if (isa<OMPCapturedExprDecl>(CounterDecl)) 13640 PreInits.push_back(CounterDecl); 13641 } 13642 13643 auto *IterationVarRef = cast<DeclRefExpr>(LoopHelper.IterationVarRef); 13644 QualType IVTy = IterationVarRef->getType(); 13645 assert(LoopHelper.Counters.size() == 1 && 13646 "Expecting a single-dimensional loop iteration space"); 13647 auto *OrigVar = cast<DeclRefExpr>(LoopHelper.Counters.front()); 13648 13649 // Determine the unroll factor. 13650 uint64_t Factor; 13651 SourceLocation FactorLoc; 13652 if (Expr *FactorVal = PartialClause->getFactor()) { 13653 Factor = 13654 FactorVal->getIntegerConstantExpr(Context).getValue().getZExtValue(); 13655 FactorLoc = FactorVal->getExprLoc(); 13656 } else { 13657 // TODO: Use a better profitability model. 13658 Factor = 2; 13659 } 13660 assert(Factor > 0 && "Expected positive unroll factor"); 13661 auto MakeFactorExpr = [this, Factor, IVTy, FactorLoc]() { 13662 return IntegerLiteral::Create( 13663 Context, llvm::APInt(Context.getIntWidth(IVTy), Factor), IVTy, 13664 FactorLoc); 13665 }; 13666 13667 // Iteration variable SourceLocations. 13668 SourceLocation OrigVarLoc = OrigVar->getExprLoc(); 13669 SourceLocation OrigVarLocBegin = OrigVar->getBeginLoc(); 13670 SourceLocation OrigVarLocEnd = OrigVar->getEndLoc(); 13671 13672 // Internal variable names. 13673 std::string OrigVarName = OrigVar->getNameInfo().getAsString(); 13674 std::string OuterIVName = (Twine(".unrolled.iv.") + OrigVarName).str(); 13675 std::string InnerIVName = (Twine(".unroll_inner.iv.") + OrigVarName).str(); 13676 std::string InnerTripCountName = 13677 (Twine(".unroll_inner.tripcount.") + OrigVarName).str(); 13678 13679 // Create the iteration variable for the unrolled loop. 13680 VarDecl *OuterIVDecl = 13681 buildVarDecl(*this, {}, IVTy, OuterIVName, nullptr, OrigVar); 13682 auto MakeOuterRef = [this, OuterIVDecl, IVTy, OrigVarLoc]() { 13683 return buildDeclRefExpr(*this, OuterIVDecl, IVTy, OrigVarLoc); 13684 }; 13685 13686 // Iteration variable for the inner loop: Reuse the iteration variable created 13687 // by checkOpenMPLoop. 13688 auto *InnerIVDecl = cast<VarDecl>(IterationVarRef->getDecl()); 13689 InnerIVDecl->setDeclName(&PP.getIdentifierTable().get(InnerIVName)); 13690 auto MakeInnerRef = [this, InnerIVDecl, IVTy, OrigVarLoc]() { 13691 return buildDeclRefExpr(*this, InnerIVDecl, IVTy, OrigVarLoc); 13692 }; 13693 13694 // Make a copy of the NumIterations expression for each use: By the AST 13695 // constraints, every expression object in a DeclContext must be unique. 13696 CaptureVars CopyTransformer(*this); 13697 auto MakeNumIterations = [&CopyTransformer, &LoopHelper]() -> Expr * { 13698 return AssertSuccess( 13699 CopyTransformer.TransformExpr(LoopHelper.NumIterations)); 13700 }; 13701 13702 // Inner For init-statement: auto .unroll_inner.iv = .unrolled.iv 13703 ExprResult LValueConv = DefaultLvalueConversion(MakeOuterRef()); 13704 AddInitializerToDecl(InnerIVDecl, LValueConv.get(), /*DirectInit=*/false); 13705 StmtResult InnerInit = new (Context) 13706 DeclStmt(DeclGroupRef(InnerIVDecl), OrigVarLocBegin, OrigVarLocEnd); 13707 if (!InnerInit.isUsable()) 13708 return StmtError(); 13709 13710 // Inner For cond-expression: 13711 // \code 13712 // .unroll_inner.iv < .unrolled.iv + Factor && 13713 // .unroll_inner.iv < NumIterations 13714 // \endcode 13715 // This conjunction of two conditions allows ScalarEvolution to derive the 13716 // maximum trip count of the inner loop. 13717 ExprResult EndOfTile = BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(), 13718 BO_Add, MakeOuterRef(), MakeFactorExpr()); 13719 if (!EndOfTile.isUsable()) 13720 return StmtError(); 13721 ExprResult InnerCond1 = BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(), 13722 BO_LE, MakeInnerRef(), EndOfTile.get()); 13723 if (!InnerCond1.isUsable()) 13724 return StmtError(); 13725 ExprResult InnerCond2 = 13726 BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(), BO_LE, MakeInnerRef(), 13727 MakeNumIterations()); 13728 if (!InnerCond2.isUsable()) 13729 return StmtError(); 13730 ExprResult InnerCond = 13731 BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(), BO_LAnd, 13732 InnerCond1.get(), InnerCond2.get()); 13733 if (!InnerCond.isUsable()) 13734 return StmtError(); 13735 13736 // Inner For incr-statement: ++.unroll_inner.iv 13737 ExprResult InnerIncr = BuildUnaryOp(CurScope, LoopHelper.Inc->getExprLoc(), 13738 UO_PreInc, MakeInnerRef()); 13739 if (!InnerIncr.isUsable()) 13740 return StmtError(); 13741 13742 // Inner For statement. 13743 SmallVector<Stmt *> InnerBodyStmts; 13744 InnerBodyStmts.append(LoopHelper.Updates.begin(), LoopHelper.Updates.end()); 13745 InnerBodyStmts.push_back(Body); 13746 CompoundStmt *InnerBody = CompoundStmt::Create( 13747 Context, InnerBodyStmts, Body->getBeginLoc(), Body->getEndLoc()); 13748 ForStmt *InnerFor = new (Context) 13749 ForStmt(Context, InnerInit.get(), InnerCond.get(), nullptr, 13750 InnerIncr.get(), InnerBody, LoopHelper.Init->getBeginLoc(), 13751 LoopHelper.Init->getBeginLoc(), LoopHelper.Inc->getEndLoc()); 13752 13753 // Unroll metadata for the inner loop. 13754 // This needs to take into account the remainder portion of the unrolled loop, 13755 // hence `unroll(full)` does not apply here, even though the LoopUnroll pass 13756 // supports multiple loop exits. Instead, unroll using a factor equivalent to 13757 // the maximum trip count, which will also generate a remainder loop. Just 13758 // `unroll(enable)` (which could have been useful if the user has not 13759 // specified a concrete factor; even though the outer loop cannot be 13760 // influenced anymore, would avoid more code bloat than necessary) will refuse 13761 // the loop because "Won't unroll; remainder loop could not be generated when 13762 // assuming runtime trip count". Even if it did work, it must not choose a 13763 // larger unroll factor than the maximum loop length, or it would always just 13764 // execute the remainder loop. 13765 LoopHintAttr *UnrollHintAttr = 13766 LoopHintAttr::CreateImplicit(Context, LoopHintAttr::UnrollCount, 13767 LoopHintAttr::Numeric, MakeFactorExpr()); 13768 AttributedStmt *InnerUnrolled = 13769 AttributedStmt::Create(Context, StartLoc, {UnrollHintAttr}, InnerFor); 13770 13771 // Outer For init-statement: auto .unrolled.iv = 0 13772 AddInitializerToDecl( 13773 OuterIVDecl, ActOnIntegerConstant(LoopHelper.Init->getExprLoc(), 0).get(), 13774 /*DirectInit=*/false); 13775 StmtResult OuterInit = new (Context) 13776 DeclStmt(DeclGroupRef(OuterIVDecl), OrigVarLocBegin, OrigVarLocEnd); 13777 if (!OuterInit.isUsable()) 13778 return StmtError(); 13779 13780 // Outer For cond-expression: .unrolled.iv < NumIterations 13781 ExprResult OuterConde = 13782 BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(), BO_LT, MakeOuterRef(), 13783 MakeNumIterations()); 13784 if (!OuterConde.isUsable()) 13785 return StmtError(); 13786 13787 // Outer For incr-statement: .unrolled.iv += Factor 13788 ExprResult OuterIncr = 13789 BuildBinOp(CurScope, LoopHelper.Inc->getExprLoc(), BO_AddAssign, 13790 MakeOuterRef(), MakeFactorExpr()); 13791 if (!OuterIncr.isUsable()) 13792 return StmtError(); 13793 13794 // Outer For statement. 13795 ForStmt *OuterFor = new (Context) 13796 ForStmt(Context, OuterInit.get(), OuterConde.get(), nullptr, 13797 OuterIncr.get(), InnerUnrolled, LoopHelper.Init->getBeginLoc(), 13798 LoopHelper.Init->getBeginLoc(), LoopHelper.Inc->getEndLoc()); 13799 13800 return OMPUnrollDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt, 13801 NumGeneratedLoops, OuterFor, 13802 buildPreInits(Context, PreInits)); 13803 } 13804 13805 OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr, 13806 SourceLocation StartLoc, 13807 SourceLocation LParenLoc, 13808 SourceLocation EndLoc) { 13809 OMPClause *Res = nullptr; 13810 switch (Kind) { 13811 case OMPC_final: 13812 Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc); 13813 break; 13814 case OMPC_num_threads: 13815 Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc); 13816 break; 13817 case OMPC_safelen: 13818 Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc); 13819 break; 13820 case OMPC_simdlen: 13821 Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc); 13822 break; 13823 case OMPC_allocator: 13824 Res = ActOnOpenMPAllocatorClause(Expr, StartLoc, LParenLoc, EndLoc); 13825 break; 13826 case OMPC_collapse: 13827 Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc); 13828 break; 13829 case OMPC_ordered: 13830 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr); 13831 break; 13832 case OMPC_num_teams: 13833 Res = ActOnOpenMPNumTeamsClause(Expr, StartLoc, LParenLoc, EndLoc); 13834 break; 13835 case OMPC_thread_limit: 13836 Res = ActOnOpenMPThreadLimitClause(Expr, StartLoc, LParenLoc, EndLoc); 13837 break; 13838 case OMPC_priority: 13839 Res = ActOnOpenMPPriorityClause(Expr, StartLoc, LParenLoc, EndLoc); 13840 break; 13841 case OMPC_grainsize: 13842 Res = ActOnOpenMPGrainsizeClause(Expr, StartLoc, LParenLoc, EndLoc); 13843 break; 13844 case OMPC_num_tasks: 13845 Res = ActOnOpenMPNumTasksClause(Expr, StartLoc, LParenLoc, EndLoc); 13846 break; 13847 case OMPC_hint: 13848 Res = ActOnOpenMPHintClause(Expr, StartLoc, LParenLoc, EndLoc); 13849 break; 13850 case OMPC_depobj: 13851 Res = ActOnOpenMPDepobjClause(Expr, StartLoc, LParenLoc, EndLoc); 13852 break; 13853 case OMPC_detach: 13854 Res = ActOnOpenMPDetachClause(Expr, StartLoc, LParenLoc, EndLoc); 13855 break; 13856 case OMPC_novariants: 13857 Res = ActOnOpenMPNovariantsClause(Expr, StartLoc, LParenLoc, EndLoc); 13858 break; 13859 case OMPC_nocontext: 13860 Res = ActOnOpenMPNocontextClause(Expr, StartLoc, LParenLoc, EndLoc); 13861 break; 13862 case OMPC_filter: 13863 Res = ActOnOpenMPFilterClause(Expr, StartLoc, LParenLoc, EndLoc); 13864 break; 13865 case OMPC_partial: 13866 Res = ActOnOpenMPPartialClause(Expr, StartLoc, LParenLoc, EndLoc); 13867 break; 13868 case OMPC_align: 13869 Res = ActOnOpenMPAlignClause(Expr, StartLoc, LParenLoc, EndLoc); 13870 break; 13871 case OMPC_device: 13872 case OMPC_if: 13873 case OMPC_default: 13874 case OMPC_proc_bind: 13875 case OMPC_schedule: 13876 case OMPC_private: 13877 case OMPC_firstprivate: 13878 case OMPC_lastprivate: 13879 case OMPC_shared: 13880 case OMPC_reduction: 13881 case OMPC_task_reduction: 13882 case OMPC_in_reduction: 13883 case OMPC_linear: 13884 case OMPC_aligned: 13885 case OMPC_copyin: 13886 case OMPC_copyprivate: 13887 case OMPC_nowait: 13888 case OMPC_untied: 13889 case OMPC_mergeable: 13890 case OMPC_threadprivate: 13891 case OMPC_sizes: 13892 case OMPC_allocate: 13893 case OMPC_flush: 13894 case OMPC_read: 13895 case OMPC_write: 13896 case OMPC_update: 13897 case OMPC_capture: 13898 case OMPC_compare: 13899 case OMPC_seq_cst: 13900 case OMPC_acq_rel: 13901 case OMPC_acquire: 13902 case OMPC_release: 13903 case OMPC_relaxed: 13904 case OMPC_depend: 13905 case OMPC_threads: 13906 case OMPC_simd: 13907 case OMPC_map: 13908 case OMPC_nogroup: 13909 case OMPC_dist_schedule: 13910 case OMPC_defaultmap: 13911 case OMPC_unknown: 13912 case OMPC_uniform: 13913 case OMPC_to: 13914 case OMPC_from: 13915 case OMPC_use_device_ptr: 13916 case OMPC_use_device_addr: 13917 case OMPC_is_device_ptr: 13918 case OMPC_unified_address: 13919 case OMPC_unified_shared_memory: 13920 case OMPC_reverse_offload: 13921 case OMPC_dynamic_allocators: 13922 case OMPC_atomic_default_mem_order: 13923 case OMPC_device_type: 13924 case OMPC_match: 13925 case OMPC_nontemporal: 13926 case OMPC_order: 13927 case OMPC_destroy: 13928 case OMPC_inclusive: 13929 case OMPC_exclusive: 13930 case OMPC_uses_allocators: 13931 case OMPC_affinity: 13932 case OMPC_when: 13933 case OMPC_bind: 13934 default: 13935 llvm_unreachable("Clause is not allowed."); 13936 } 13937 return Res; 13938 } 13939 13940 // An OpenMP directive such as 'target parallel' has two captured regions: 13941 // for the 'target' and 'parallel' respectively. This function returns 13942 // the region in which to capture expressions associated with a clause. 13943 // A return value of OMPD_unknown signifies that the expression should not 13944 // be captured. 13945 static OpenMPDirectiveKind getOpenMPCaptureRegionForClause( 13946 OpenMPDirectiveKind DKind, OpenMPClauseKind CKind, unsigned OpenMPVersion, 13947 OpenMPDirectiveKind NameModifier = OMPD_unknown) { 13948 OpenMPDirectiveKind CaptureRegion = OMPD_unknown; 13949 switch (CKind) { 13950 case OMPC_if: 13951 switch (DKind) { 13952 case OMPD_target_parallel_for_simd: 13953 if (OpenMPVersion >= 50 && 13954 (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)) { 13955 CaptureRegion = OMPD_parallel; 13956 break; 13957 } 13958 LLVM_FALLTHROUGH; 13959 case OMPD_target_parallel: 13960 case OMPD_target_parallel_for: 13961 // If this clause applies to the nested 'parallel' region, capture within 13962 // the 'target' region, otherwise do not capture. 13963 if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel) 13964 CaptureRegion = OMPD_target; 13965 break; 13966 case OMPD_target_teams_distribute_parallel_for_simd: 13967 if (OpenMPVersion >= 50 && 13968 (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)) { 13969 CaptureRegion = OMPD_parallel; 13970 break; 13971 } 13972 LLVM_FALLTHROUGH; 13973 case OMPD_target_teams_distribute_parallel_for: 13974 // If this clause applies to the nested 'parallel' region, capture within 13975 // the 'teams' region, otherwise do not capture. 13976 if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel) 13977 CaptureRegion = OMPD_teams; 13978 break; 13979 case OMPD_teams_distribute_parallel_for_simd: 13980 if (OpenMPVersion >= 50 && 13981 (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)) { 13982 CaptureRegion = OMPD_parallel; 13983 break; 13984 } 13985 LLVM_FALLTHROUGH; 13986 case OMPD_teams_distribute_parallel_for: 13987 CaptureRegion = OMPD_teams; 13988 break; 13989 case OMPD_target_update: 13990 case OMPD_target_enter_data: 13991 case OMPD_target_exit_data: 13992 CaptureRegion = OMPD_task; 13993 break; 13994 case OMPD_parallel_master_taskloop: 13995 if (NameModifier == OMPD_unknown || NameModifier == OMPD_taskloop) 13996 CaptureRegion = OMPD_parallel; 13997 break; 13998 case OMPD_parallel_master_taskloop_simd: 13999 if ((OpenMPVersion <= 45 && NameModifier == OMPD_unknown) || 14000 NameModifier == OMPD_taskloop) { 14001 CaptureRegion = OMPD_parallel; 14002 break; 14003 } 14004 if (OpenMPVersion <= 45) 14005 break; 14006 if (NameModifier == OMPD_unknown || NameModifier == OMPD_simd) 14007 CaptureRegion = OMPD_taskloop; 14008 break; 14009 case OMPD_parallel_for_simd: 14010 if (OpenMPVersion <= 45) 14011 break; 14012 if (NameModifier == OMPD_unknown || NameModifier == OMPD_simd) 14013 CaptureRegion = OMPD_parallel; 14014 break; 14015 case OMPD_taskloop_simd: 14016 case OMPD_master_taskloop_simd: 14017 if (OpenMPVersion <= 45) 14018 break; 14019 if (NameModifier == OMPD_unknown || NameModifier == OMPD_simd) 14020 CaptureRegion = OMPD_taskloop; 14021 break; 14022 case OMPD_distribute_parallel_for_simd: 14023 if (OpenMPVersion <= 45) 14024 break; 14025 if (NameModifier == OMPD_unknown || NameModifier == OMPD_simd) 14026 CaptureRegion = OMPD_parallel; 14027 break; 14028 case OMPD_target_simd: 14029 if (OpenMPVersion >= 50 && 14030 (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)) 14031 CaptureRegion = OMPD_target; 14032 break; 14033 case OMPD_teams_distribute_simd: 14034 case OMPD_target_teams_distribute_simd: 14035 if (OpenMPVersion >= 50 && 14036 (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)) 14037 CaptureRegion = OMPD_teams; 14038 break; 14039 case OMPD_cancel: 14040 case OMPD_parallel: 14041 case OMPD_parallel_master: 14042 case OMPD_parallel_sections: 14043 case OMPD_parallel_for: 14044 case OMPD_target: 14045 case OMPD_target_teams: 14046 case OMPD_target_teams_distribute: 14047 case OMPD_distribute_parallel_for: 14048 case OMPD_task: 14049 case OMPD_taskloop: 14050 case OMPD_master_taskloop: 14051 case OMPD_target_data: 14052 case OMPD_simd: 14053 case OMPD_for_simd: 14054 case OMPD_distribute_simd: 14055 // Do not capture if-clause expressions. 14056 break; 14057 case OMPD_threadprivate: 14058 case OMPD_allocate: 14059 case OMPD_taskyield: 14060 case OMPD_barrier: 14061 case OMPD_taskwait: 14062 case OMPD_cancellation_point: 14063 case OMPD_flush: 14064 case OMPD_depobj: 14065 case OMPD_scan: 14066 case OMPD_declare_reduction: 14067 case OMPD_declare_mapper: 14068 case OMPD_declare_simd: 14069 case OMPD_declare_variant: 14070 case OMPD_begin_declare_variant: 14071 case OMPD_end_declare_variant: 14072 case OMPD_declare_target: 14073 case OMPD_end_declare_target: 14074 case OMPD_loop: 14075 case OMPD_teams: 14076 case OMPD_tile: 14077 case OMPD_unroll: 14078 case OMPD_for: 14079 case OMPD_sections: 14080 case OMPD_section: 14081 case OMPD_single: 14082 case OMPD_master: 14083 case OMPD_masked: 14084 case OMPD_critical: 14085 case OMPD_taskgroup: 14086 case OMPD_distribute: 14087 case OMPD_ordered: 14088 case OMPD_atomic: 14089 case OMPD_teams_distribute: 14090 case OMPD_requires: 14091 case OMPD_metadirective: 14092 llvm_unreachable("Unexpected OpenMP directive with if-clause"); 14093 case OMPD_unknown: 14094 default: 14095 llvm_unreachable("Unknown OpenMP directive"); 14096 } 14097 break; 14098 case OMPC_num_threads: 14099 switch (DKind) { 14100 case OMPD_target_parallel: 14101 case OMPD_target_parallel_for: 14102 case OMPD_target_parallel_for_simd: 14103 CaptureRegion = OMPD_target; 14104 break; 14105 case OMPD_teams_distribute_parallel_for: 14106 case OMPD_teams_distribute_parallel_for_simd: 14107 case OMPD_target_teams_distribute_parallel_for: 14108 case OMPD_target_teams_distribute_parallel_for_simd: 14109 CaptureRegion = OMPD_teams; 14110 break; 14111 case OMPD_parallel: 14112 case OMPD_parallel_master: 14113 case OMPD_parallel_sections: 14114 case OMPD_parallel_for: 14115 case OMPD_parallel_for_simd: 14116 case OMPD_distribute_parallel_for: 14117 case OMPD_distribute_parallel_for_simd: 14118 case OMPD_parallel_master_taskloop: 14119 case OMPD_parallel_master_taskloop_simd: 14120 // Do not capture num_threads-clause expressions. 14121 break; 14122 case OMPD_target_data: 14123 case OMPD_target_enter_data: 14124 case OMPD_target_exit_data: 14125 case OMPD_target_update: 14126 case OMPD_target: 14127 case OMPD_target_simd: 14128 case OMPD_target_teams: 14129 case OMPD_target_teams_distribute: 14130 case OMPD_target_teams_distribute_simd: 14131 case OMPD_cancel: 14132 case OMPD_task: 14133 case OMPD_taskloop: 14134 case OMPD_taskloop_simd: 14135 case OMPD_master_taskloop: 14136 case OMPD_master_taskloop_simd: 14137 case OMPD_threadprivate: 14138 case OMPD_allocate: 14139 case OMPD_taskyield: 14140 case OMPD_barrier: 14141 case OMPD_taskwait: 14142 case OMPD_cancellation_point: 14143 case OMPD_flush: 14144 case OMPD_depobj: 14145 case OMPD_scan: 14146 case OMPD_declare_reduction: 14147 case OMPD_declare_mapper: 14148 case OMPD_declare_simd: 14149 case OMPD_declare_variant: 14150 case OMPD_begin_declare_variant: 14151 case OMPD_end_declare_variant: 14152 case OMPD_declare_target: 14153 case OMPD_end_declare_target: 14154 case OMPD_loop: 14155 case OMPD_teams: 14156 case OMPD_simd: 14157 case OMPD_tile: 14158 case OMPD_unroll: 14159 case OMPD_for: 14160 case OMPD_for_simd: 14161 case OMPD_sections: 14162 case OMPD_section: 14163 case OMPD_single: 14164 case OMPD_master: 14165 case OMPD_masked: 14166 case OMPD_critical: 14167 case OMPD_taskgroup: 14168 case OMPD_distribute: 14169 case OMPD_ordered: 14170 case OMPD_atomic: 14171 case OMPD_distribute_simd: 14172 case OMPD_teams_distribute: 14173 case OMPD_teams_distribute_simd: 14174 case OMPD_requires: 14175 case OMPD_metadirective: 14176 llvm_unreachable("Unexpected OpenMP directive with num_threads-clause"); 14177 case OMPD_unknown: 14178 default: 14179 llvm_unreachable("Unknown OpenMP directive"); 14180 } 14181 break; 14182 case OMPC_num_teams: 14183 switch (DKind) { 14184 case OMPD_target_teams: 14185 case OMPD_target_teams_distribute: 14186 case OMPD_target_teams_distribute_simd: 14187 case OMPD_target_teams_distribute_parallel_for: 14188 case OMPD_target_teams_distribute_parallel_for_simd: 14189 CaptureRegion = OMPD_target; 14190 break; 14191 case OMPD_teams_distribute_parallel_for: 14192 case OMPD_teams_distribute_parallel_for_simd: 14193 case OMPD_teams: 14194 case OMPD_teams_distribute: 14195 case OMPD_teams_distribute_simd: 14196 // Do not capture num_teams-clause expressions. 14197 break; 14198 case OMPD_distribute_parallel_for: 14199 case OMPD_distribute_parallel_for_simd: 14200 case OMPD_task: 14201 case OMPD_taskloop: 14202 case OMPD_taskloop_simd: 14203 case OMPD_master_taskloop: 14204 case OMPD_master_taskloop_simd: 14205 case OMPD_parallel_master_taskloop: 14206 case OMPD_parallel_master_taskloop_simd: 14207 case OMPD_target_data: 14208 case OMPD_target_enter_data: 14209 case OMPD_target_exit_data: 14210 case OMPD_target_update: 14211 case OMPD_cancel: 14212 case OMPD_parallel: 14213 case OMPD_parallel_master: 14214 case OMPD_parallel_sections: 14215 case OMPD_parallel_for: 14216 case OMPD_parallel_for_simd: 14217 case OMPD_target: 14218 case OMPD_target_simd: 14219 case OMPD_target_parallel: 14220 case OMPD_target_parallel_for: 14221 case OMPD_target_parallel_for_simd: 14222 case OMPD_threadprivate: 14223 case OMPD_allocate: 14224 case OMPD_taskyield: 14225 case OMPD_barrier: 14226 case OMPD_taskwait: 14227 case OMPD_cancellation_point: 14228 case OMPD_flush: 14229 case OMPD_depobj: 14230 case OMPD_scan: 14231 case OMPD_declare_reduction: 14232 case OMPD_declare_mapper: 14233 case OMPD_declare_simd: 14234 case OMPD_declare_variant: 14235 case OMPD_begin_declare_variant: 14236 case OMPD_end_declare_variant: 14237 case OMPD_declare_target: 14238 case OMPD_end_declare_target: 14239 case OMPD_loop: 14240 case OMPD_simd: 14241 case OMPD_tile: 14242 case OMPD_unroll: 14243 case OMPD_for: 14244 case OMPD_for_simd: 14245 case OMPD_sections: 14246 case OMPD_section: 14247 case OMPD_single: 14248 case OMPD_master: 14249 case OMPD_masked: 14250 case OMPD_critical: 14251 case OMPD_taskgroup: 14252 case OMPD_distribute: 14253 case OMPD_ordered: 14254 case OMPD_atomic: 14255 case OMPD_distribute_simd: 14256 case OMPD_requires: 14257 case OMPD_metadirective: 14258 llvm_unreachable("Unexpected OpenMP directive with num_teams-clause"); 14259 case OMPD_unknown: 14260 default: 14261 llvm_unreachable("Unknown OpenMP directive"); 14262 } 14263 break; 14264 case OMPC_thread_limit: 14265 switch (DKind) { 14266 case OMPD_target_teams: 14267 case OMPD_target_teams_distribute: 14268 case OMPD_target_teams_distribute_simd: 14269 case OMPD_target_teams_distribute_parallel_for: 14270 case OMPD_target_teams_distribute_parallel_for_simd: 14271 CaptureRegion = OMPD_target; 14272 break; 14273 case OMPD_teams_distribute_parallel_for: 14274 case OMPD_teams_distribute_parallel_for_simd: 14275 case OMPD_teams: 14276 case OMPD_teams_distribute: 14277 case OMPD_teams_distribute_simd: 14278 // Do not capture thread_limit-clause expressions. 14279 break; 14280 case OMPD_distribute_parallel_for: 14281 case OMPD_distribute_parallel_for_simd: 14282 case OMPD_task: 14283 case OMPD_taskloop: 14284 case OMPD_taskloop_simd: 14285 case OMPD_master_taskloop: 14286 case OMPD_master_taskloop_simd: 14287 case OMPD_parallel_master_taskloop: 14288 case OMPD_parallel_master_taskloop_simd: 14289 case OMPD_target_data: 14290 case OMPD_target_enter_data: 14291 case OMPD_target_exit_data: 14292 case OMPD_target_update: 14293 case OMPD_cancel: 14294 case OMPD_parallel: 14295 case OMPD_parallel_master: 14296 case OMPD_parallel_sections: 14297 case OMPD_parallel_for: 14298 case OMPD_parallel_for_simd: 14299 case OMPD_target: 14300 case OMPD_target_simd: 14301 case OMPD_target_parallel: 14302 case OMPD_target_parallel_for: 14303 case OMPD_target_parallel_for_simd: 14304 case OMPD_threadprivate: 14305 case OMPD_allocate: 14306 case OMPD_taskyield: 14307 case OMPD_barrier: 14308 case OMPD_taskwait: 14309 case OMPD_cancellation_point: 14310 case OMPD_flush: 14311 case OMPD_depobj: 14312 case OMPD_scan: 14313 case OMPD_declare_reduction: 14314 case OMPD_declare_mapper: 14315 case OMPD_declare_simd: 14316 case OMPD_declare_variant: 14317 case OMPD_begin_declare_variant: 14318 case OMPD_end_declare_variant: 14319 case OMPD_declare_target: 14320 case OMPD_end_declare_target: 14321 case OMPD_loop: 14322 case OMPD_simd: 14323 case OMPD_tile: 14324 case OMPD_unroll: 14325 case OMPD_for: 14326 case OMPD_for_simd: 14327 case OMPD_sections: 14328 case OMPD_section: 14329 case OMPD_single: 14330 case OMPD_master: 14331 case OMPD_masked: 14332 case OMPD_critical: 14333 case OMPD_taskgroup: 14334 case OMPD_distribute: 14335 case OMPD_ordered: 14336 case OMPD_atomic: 14337 case OMPD_distribute_simd: 14338 case OMPD_requires: 14339 case OMPD_metadirective: 14340 llvm_unreachable("Unexpected OpenMP directive with thread_limit-clause"); 14341 case OMPD_unknown: 14342 default: 14343 llvm_unreachable("Unknown OpenMP directive"); 14344 } 14345 break; 14346 case OMPC_schedule: 14347 switch (DKind) { 14348 case OMPD_parallel_for: 14349 case OMPD_parallel_for_simd: 14350 case OMPD_distribute_parallel_for: 14351 case OMPD_distribute_parallel_for_simd: 14352 case OMPD_teams_distribute_parallel_for: 14353 case OMPD_teams_distribute_parallel_for_simd: 14354 case OMPD_target_parallel_for: 14355 case OMPD_target_parallel_for_simd: 14356 case OMPD_target_teams_distribute_parallel_for: 14357 case OMPD_target_teams_distribute_parallel_for_simd: 14358 CaptureRegion = OMPD_parallel; 14359 break; 14360 case OMPD_for: 14361 case OMPD_for_simd: 14362 // Do not capture schedule-clause expressions. 14363 break; 14364 case OMPD_task: 14365 case OMPD_taskloop: 14366 case OMPD_taskloop_simd: 14367 case OMPD_master_taskloop: 14368 case OMPD_master_taskloop_simd: 14369 case OMPD_parallel_master_taskloop: 14370 case OMPD_parallel_master_taskloop_simd: 14371 case OMPD_target_data: 14372 case OMPD_target_enter_data: 14373 case OMPD_target_exit_data: 14374 case OMPD_target_update: 14375 case OMPD_teams: 14376 case OMPD_teams_distribute: 14377 case OMPD_teams_distribute_simd: 14378 case OMPD_target_teams_distribute: 14379 case OMPD_target_teams_distribute_simd: 14380 case OMPD_target: 14381 case OMPD_target_simd: 14382 case OMPD_target_parallel: 14383 case OMPD_cancel: 14384 case OMPD_parallel: 14385 case OMPD_parallel_master: 14386 case OMPD_parallel_sections: 14387 case OMPD_threadprivate: 14388 case OMPD_allocate: 14389 case OMPD_taskyield: 14390 case OMPD_barrier: 14391 case OMPD_taskwait: 14392 case OMPD_cancellation_point: 14393 case OMPD_flush: 14394 case OMPD_depobj: 14395 case OMPD_scan: 14396 case OMPD_declare_reduction: 14397 case OMPD_declare_mapper: 14398 case OMPD_declare_simd: 14399 case OMPD_declare_variant: 14400 case OMPD_begin_declare_variant: 14401 case OMPD_end_declare_variant: 14402 case OMPD_declare_target: 14403 case OMPD_end_declare_target: 14404 case OMPD_loop: 14405 case OMPD_simd: 14406 case OMPD_tile: 14407 case OMPD_unroll: 14408 case OMPD_sections: 14409 case OMPD_section: 14410 case OMPD_single: 14411 case OMPD_master: 14412 case OMPD_masked: 14413 case OMPD_critical: 14414 case OMPD_taskgroup: 14415 case OMPD_distribute: 14416 case OMPD_ordered: 14417 case OMPD_atomic: 14418 case OMPD_distribute_simd: 14419 case OMPD_target_teams: 14420 case OMPD_requires: 14421 case OMPD_metadirective: 14422 llvm_unreachable("Unexpected OpenMP directive with schedule clause"); 14423 case OMPD_unknown: 14424 default: 14425 llvm_unreachable("Unknown OpenMP directive"); 14426 } 14427 break; 14428 case OMPC_dist_schedule: 14429 switch (DKind) { 14430 case OMPD_teams_distribute_parallel_for: 14431 case OMPD_teams_distribute_parallel_for_simd: 14432 case OMPD_teams_distribute: 14433 case OMPD_teams_distribute_simd: 14434 case OMPD_target_teams_distribute_parallel_for: 14435 case OMPD_target_teams_distribute_parallel_for_simd: 14436 case OMPD_target_teams_distribute: 14437 case OMPD_target_teams_distribute_simd: 14438 CaptureRegion = OMPD_teams; 14439 break; 14440 case OMPD_distribute_parallel_for: 14441 case OMPD_distribute_parallel_for_simd: 14442 case OMPD_distribute: 14443 case OMPD_distribute_simd: 14444 // Do not capture dist_schedule-clause expressions. 14445 break; 14446 case OMPD_parallel_for: 14447 case OMPD_parallel_for_simd: 14448 case OMPD_target_parallel_for_simd: 14449 case OMPD_target_parallel_for: 14450 case OMPD_task: 14451 case OMPD_taskloop: 14452 case OMPD_taskloop_simd: 14453 case OMPD_master_taskloop: 14454 case OMPD_master_taskloop_simd: 14455 case OMPD_parallel_master_taskloop: 14456 case OMPD_parallel_master_taskloop_simd: 14457 case OMPD_target_data: 14458 case OMPD_target_enter_data: 14459 case OMPD_target_exit_data: 14460 case OMPD_target_update: 14461 case OMPD_teams: 14462 case OMPD_target: 14463 case OMPD_target_simd: 14464 case OMPD_target_parallel: 14465 case OMPD_cancel: 14466 case OMPD_parallel: 14467 case OMPD_parallel_master: 14468 case OMPD_parallel_sections: 14469 case OMPD_threadprivate: 14470 case OMPD_allocate: 14471 case OMPD_taskyield: 14472 case OMPD_barrier: 14473 case OMPD_taskwait: 14474 case OMPD_cancellation_point: 14475 case OMPD_flush: 14476 case OMPD_depobj: 14477 case OMPD_scan: 14478 case OMPD_declare_reduction: 14479 case OMPD_declare_mapper: 14480 case OMPD_declare_simd: 14481 case OMPD_declare_variant: 14482 case OMPD_begin_declare_variant: 14483 case OMPD_end_declare_variant: 14484 case OMPD_declare_target: 14485 case OMPD_end_declare_target: 14486 case OMPD_loop: 14487 case OMPD_simd: 14488 case OMPD_tile: 14489 case OMPD_unroll: 14490 case OMPD_for: 14491 case OMPD_for_simd: 14492 case OMPD_sections: 14493 case OMPD_section: 14494 case OMPD_single: 14495 case OMPD_master: 14496 case OMPD_masked: 14497 case OMPD_critical: 14498 case OMPD_taskgroup: 14499 case OMPD_ordered: 14500 case OMPD_atomic: 14501 case OMPD_target_teams: 14502 case OMPD_requires: 14503 case OMPD_metadirective: 14504 llvm_unreachable("Unexpected OpenMP directive with dist_schedule clause"); 14505 case OMPD_unknown: 14506 default: 14507 llvm_unreachable("Unknown OpenMP directive"); 14508 } 14509 break; 14510 case OMPC_device: 14511 switch (DKind) { 14512 case OMPD_target_update: 14513 case OMPD_target_enter_data: 14514 case OMPD_target_exit_data: 14515 case OMPD_target: 14516 case OMPD_target_simd: 14517 case OMPD_target_teams: 14518 case OMPD_target_parallel: 14519 case OMPD_target_teams_distribute: 14520 case OMPD_target_teams_distribute_simd: 14521 case OMPD_target_parallel_for: 14522 case OMPD_target_parallel_for_simd: 14523 case OMPD_target_teams_distribute_parallel_for: 14524 case OMPD_target_teams_distribute_parallel_for_simd: 14525 case OMPD_dispatch: 14526 CaptureRegion = OMPD_task; 14527 break; 14528 case OMPD_target_data: 14529 case OMPD_interop: 14530 // Do not capture device-clause expressions. 14531 break; 14532 case OMPD_teams_distribute_parallel_for: 14533 case OMPD_teams_distribute_parallel_for_simd: 14534 case OMPD_teams: 14535 case OMPD_teams_distribute: 14536 case OMPD_teams_distribute_simd: 14537 case OMPD_distribute_parallel_for: 14538 case OMPD_distribute_parallel_for_simd: 14539 case OMPD_task: 14540 case OMPD_taskloop: 14541 case OMPD_taskloop_simd: 14542 case OMPD_master_taskloop: 14543 case OMPD_master_taskloop_simd: 14544 case OMPD_parallel_master_taskloop: 14545 case OMPD_parallel_master_taskloop_simd: 14546 case OMPD_cancel: 14547 case OMPD_parallel: 14548 case OMPD_parallel_master: 14549 case OMPD_parallel_sections: 14550 case OMPD_parallel_for: 14551 case OMPD_parallel_for_simd: 14552 case OMPD_threadprivate: 14553 case OMPD_allocate: 14554 case OMPD_taskyield: 14555 case OMPD_barrier: 14556 case OMPD_taskwait: 14557 case OMPD_cancellation_point: 14558 case OMPD_flush: 14559 case OMPD_depobj: 14560 case OMPD_scan: 14561 case OMPD_declare_reduction: 14562 case OMPD_declare_mapper: 14563 case OMPD_declare_simd: 14564 case OMPD_declare_variant: 14565 case OMPD_begin_declare_variant: 14566 case OMPD_end_declare_variant: 14567 case OMPD_declare_target: 14568 case OMPD_end_declare_target: 14569 case OMPD_loop: 14570 case OMPD_simd: 14571 case OMPD_tile: 14572 case OMPD_unroll: 14573 case OMPD_for: 14574 case OMPD_for_simd: 14575 case OMPD_sections: 14576 case OMPD_section: 14577 case OMPD_single: 14578 case OMPD_master: 14579 case OMPD_masked: 14580 case OMPD_critical: 14581 case OMPD_taskgroup: 14582 case OMPD_distribute: 14583 case OMPD_ordered: 14584 case OMPD_atomic: 14585 case OMPD_distribute_simd: 14586 case OMPD_requires: 14587 case OMPD_metadirective: 14588 llvm_unreachable("Unexpected OpenMP directive with device-clause"); 14589 case OMPD_unknown: 14590 default: 14591 llvm_unreachable("Unknown OpenMP directive"); 14592 } 14593 break; 14594 case OMPC_grainsize: 14595 case OMPC_num_tasks: 14596 case OMPC_final: 14597 case OMPC_priority: 14598 switch (DKind) { 14599 case OMPD_task: 14600 case OMPD_taskloop: 14601 case OMPD_taskloop_simd: 14602 case OMPD_master_taskloop: 14603 case OMPD_master_taskloop_simd: 14604 break; 14605 case OMPD_parallel_master_taskloop: 14606 case OMPD_parallel_master_taskloop_simd: 14607 CaptureRegion = OMPD_parallel; 14608 break; 14609 case OMPD_target_update: 14610 case OMPD_target_enter_data: 14611 case OMPD_target_exit_data: 14612 case OMPD_target: 14613 case OMPD_target_simd: 14614 case OMPD_target_teams: 14615 case OMPD_target_parallel: 14616 case OMPD_target_teams_distribute: 14617 case OMPD_target_teams_distribute_simd: 14618 case OMPD_target_parallel_for: 14619 case OMPD_target_parallel_for_simd: 14620 case OMPD_target_teams_distribute_parallel_for: 14621 case OMPD_target_teams_distribute_parallel_for_simd: 14622 case OMPD_target_data: 14623 case OMPD_teams_distribute_parallel_for: 14624 case OMPD_teams_distribute_parallel_for_simd: 14625 case OMPD_teams: 14626 case OMPD_teams_distribute: 14627 case OMPD_teams_distribute_simd: 14628 case OMPD_distribute_parallel_for: 14629 case OMPD_distribute_parallel_for_simd: 14630 case OMPD_cancel: 14631 case OMPD_parallel: 14632 case OMPD_parallel_master: 14633 case OMPD_parallel_sections: 14634 case OMPD_parallel_for: 14635 case OMPD_parallel_for_simd: 14636 case OMPD_threadprivate: 14637 case OMPD_allocate: 14638 case OMPD_taskyield: 14639 case OMPD_barrier: 14640 case OMPD_taskwait: 14641 case OMPD_cancellation_point: 14642 case OMPD_flush: 14643 case OMPD_depobj: 14644 case OMPD_scan: 14645 case OMPD_declare_reduction: 14646 case OMPD_declare_mapper: 14647 case OMPD_declare_simd: 14648 case OMPD_declare_variant: 14649 case OMPD_begin_declare_variant: 14650 case OMPD_end_declare_variant: 14651 case OMPD_declare_target: 14652 case OMPD_end_declare_target: 14653 case OMPD_loop: 14654 case OMPD_simd: 14655 case OMPD_tile: 14656 case OMPD_unroll: 14657 case OMPD_for: 14658 case OMPD_for_simd: 14659 case OMPD_sections: 14660 case OMPD_section: 14661 case OMPD_single: 14662 case OMPD_master: 14663 case OMPD_masked: 14664 case OMPD_critical: 14665 case OMPD_taskgroup: 14666 case OMPD_distribute: 14667 case OMPD_ordered: 14668 case OMPD_atomic: 14669 case OMPD_distribute_simd: 14670 case OMPD_requires: 14671 case OMPD_metadirective: 14672 llvm_unreachable("Unexpected OpenMP directive with grainsize-clause"); 14673 case OMPD_unknown: 14674 default: 14675 llvm_unreachable("Unknown OpenMP directive"); 14676 } 14677 break; 14678 case OMPC_novariants: 14679 case OMPC_nocontext: 14680 switch (DKind) { 14681 case OMPD_dispatch: 14682 CaptureRegion = OMPD_task; 14683 break; 14684 default: 14685 llvm_unreachable("Unexpected OpenMP directive"); 14686 } 14687 break; 14688 case OMPC_filter: 14689 // Do not capture filter-clause expressions. 14690 break; 14691 case OMPC_when: 14692 if (DKind == OMPD_metadirective) { 14693 CaptureRegion = OMPD_metadirective; 14694 } else if (DKind == OMPD_unknown) { 14695 llvm_unreachable("Unknown OpenMP directive"); 14696 } else { 14697 llvm_unreachable("Unexpected OpenMP directive with when clause"); 14698 } 14699 break; 14700 case OMPC_firstprivate: 14701 case OMPC_lastprivate: 14702 case OMPC_reduction: 14703 case OMPC_task_reduction: 14704 case OMPC_in_reduction: 14705 case OMPC_linear: 14706 case OMPC_default: 14707 case OMPC_proc_bind: 14708 case OMPC_safelen: 14709 case OMPC_simdlen: 14710 case OMPC_sizes: 14711 case OMPC_allocator: 14712 case OMPC_collapse: 14713 case OMPC_private: 14714 case OMPC_shared: 14715 case OMPC_aligned: 14716 case OMPC_copyin: 14717 case OMPC_copyprivate: 14718 case OMPC_ordered: 14719 case OMPC_nowait: 14720 case OMPC_untied: 14721 case OMPC_mergeable: 14722 case OMPC_threadprivate: 14723 case OMPC_allocate: 14724 case OMPC_flush: 14725 case OMPC_depobj: 14726 case OMPC_read: 14727 case OMPC_write: 14728 case OMPC_update: 14729 case OMPC_capture: 14730 case OMPC_compare: 14731 case OMPC_seq_cst: 14732 case OMPC_acq_rel: 14733 case OMPC_acquire: 14734 case OMPC_release: 14735 case OMPC_relaxed: 14736 case OMPC_depend: 14737 case OMPC_threads: 14738 case OMPC_simd: 14739 case OMPC_map: 14740 case OMPC_nogroup: 14741 case OMPC_hint: 14742 case OMPC_defaultmap: 14743 case OMPC_unknown: 14744 case OMPC_uniform: 14745 case OMPC_to: 14746 case OMPC_from: 14747 case OMPC_use_device_ptr: 14748 case OMPC_use_device_addr: 14749 case OMPC_is_device_ptr: 14750 case OMPC_unified_address: 14751 case OMPC_unified_shared_memory: 14752 case OMPC_reverse_offload: 14753 case OMPC_dynamic_allocators: 14754 case OMPC_atomic_default_mem_order: 14755 case OMPC_device_type: 14756 case OMPC_match: 14757 case OMPC_nontemporal: 14758 case OMPC_order: 14759 case OMPC_destroy: 14760 case OMPC_detach: 14761 case OMPC_inclusive: 14762 case OMPC_exclusive: 14763 case OMPC_uses_allocators: 14764 case OMPC_affinity: 14765 case OMPC_bind: 14766 default: 14767 llvm_unreachable("Unexpected OpenMP clause."); 14768 } 14769 return CaptureRegion; 14770 } 14771 14772 OMPClause *Sema::ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier, 14773 Expr *Condition, SourceLocation StartLoc, 14774 SourceLocation LParenLoc, 14775 SourceLocation NameModifierLoc, 14776 SourceLocation ColonLoc, 14777 SourceLocation EndLoc) { 14778 Expr *ValExpr = Condition; 14779 Stmt *HelperValStmt = nullptr; 14780 OpenMPDirectiveKind CaptureRegion = OMPD_unknown; 14781 if (!Condition->isValueDependent() && !Condition->isTypeDependent() && 14782 !Condition->isInstantiationDependent() && 14783 !Condition->containsUnexpandedParameterPack()) { 14784 ExprResult Val = CheckBooleanCondition(StartLoc, Condition); 14785 if (Val.isInvalid()) 14786 return nullptr; 14787 14788 ValExpr = Val.get(); 14789 14790 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective(); 14791 CaptureRegion = getOpenMPCaptureRegionForClause( 14792 DKind, OMPC_if, LangOpts.OpenMP, NameModifier); 14793 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) { 14794 ValExpr = MakeFullExpr(ValExpr).get(); 14795 llvm::MapVector<const Expr *, DeclRefExpr *> Captures; 14796 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 14797 HelperValStmt = buildPreInits(Context, Captures); 14798 } 14799 } 14800 14801 return new (Context) 14802 OMPIfClause(NameModifier, ValExpr, HelperValStmt, CaptureRegion, StartLoc, 14803 LParenLoc, NameModifierLoc, ColonLoc, EndLoc); 14804 } 14805 14806 OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition, 14807 SourceLocation StartLoc, 14808 SourceLocation LParenLoc, 14809 SourceLocation EndLoc) { 14810 Expr *ValExpr = Condition; 14811 Stmt *HelperValStmt = nullptr; 14812 OpenMPDirectiveKind CaptureRegion = OMPD_unknown; 14813 if (!Condition->isValueDependent() && !Condition->isTypeDependent() && 14814 !Condition->isInstantiationDependent() && 14815 !Condition->containsUnexpandedParameterPack()) { 14816 ExprResult Val = CheckBooleanCondition(StartLoc, Condition); 14817 if (Val.isInvalid()) 14818 return nullptr; 14819 14820 ValExpr = MakeFullExpr(Val.get()).get(); 14821 14822 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective(); 14823 CaptureRegion = 14824 getOpenMPCaptureRegionForClause(DKind, OMPC_final, LangOpts.OpenMP); 14825 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) { 14826 ValExpr = MakeFullExpr(ValExpr).get(); 14827 llvm::MapVector<const Expr *, DeclRefExpr *> Captures; 14828 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 14829 HelperValStmt = buildPreInits(Context, Captures); 14830 } 14831 } 14832 14833 return new (Context) OMPFinalClause(ValExpr, HelperValStmt, CaptureRegion, 14834 StartLoc, LParenLoc, EndLoc); 14835 } 14836 14837 ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc, 14838 Expr *Op) { 14839 if (!Op) 14840 return ExprError(); 14841 14842 class IntConvertDiagnoser : public ICEConvertDiagnoser { 14843 public: 14844 IntConvertDiagnoser() 14845 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {} 14846 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 14847 QualType T) override { 14848 return S.Diag(Loc, diag::err_omp_not_integral) << T; 14849 } 14850 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc, 14851 QualType T) override { 14852 return S.Diag(Loc, diag::err_omp_incomplete_type) << T; 14853 } 14854 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc, 14855 QualType T, 14856 QualType ConvTy) override { 14857 return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy; 14858 } 14859 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv, 14860 QualType ConvTy) override { 14861 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here) 14862 << ConvTy->isEnumeralType() << ConvTy; 14863 } 14864 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc, 14865 QualType T) override { 14866 return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T; 14867 } 14868 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv, 14869 QualType ConvTy) override { 14870 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here) 14871 << ConvTy->isEnumeralType() << ConvTy; 14872 } 14873 SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType, 14874 QualType) override { 14875 llvm_unreachable("conversion functions are permitted"); 14876 } 14877 } ConvertDiagnoser; 14878 return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser); 14879 } 14880 14881 static bool 14882 isNonNegativeIntegerValue(Expr *&ValExpr, Sema &SemaRef, OpenMPClauseKind CKind, 14883 bool StrictlyPositive, bool BuildCapture = false, 14884 OpenMPDirectiveKind DKind = OMPD_unknown, 14885 OpenMPDirectiveKind *CaptureRegion = nullptr, 14886 Stmt **HelperValStmt = nullptr) { 14887 if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() && 14888 !ValExpr->isInstantiationDependent()) { 14889 SourceLocation Loc = ValExpr->getExprLoc(); 14890 ExprResult Value = 14891 SemaRef.PerformOpenMPImplicitIntegerConversion(Loc, ValExpr); 14892 if (Value.isInvalid()) 14893 return false; 14894 14895 ValExpr = Value.get(); 14896 // The expression must evaluate to a non-negative integer value. 14897 if (Optional<llvm::APSInt> Result = 14898 ValExpr->getIntegerConstantExpr(SemaRef.Context)) { 14899 if (Result->isSigned() && 14900 !((!StrictlyPositive && Result->isNonNegative()) || 14901 (StrictlyPositive && Result->isStrictlyPositive()))) { 14902 SemaRef.Diag(Loc, diag::err_omp_negative_expression_in_clause) 14903 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0) 14904 << ValExpr->getSourceRange(); 14905 return false; 14906 } 14907 } 14908 if (!BuildCapture) 14909 return true; 14910 *CaptureRegion = 14911 getOpenMPCaptureRegionForClause(DKind, CKind, SemaRef.LangOpts.OpenMP); 14912 if (*CaptureRegion != OMPD_unknown && 14913 !SemaRef.CurContext->isDependentContext()) { 14914 ValExpr = SemaRef.MakeFullExpr(ValExpr).get(); 14915 llvm::MapVector<const Expr *, DeclRefExpr *> Captures; 14916 ValExpr = tryBuildCapture(SemaRef, ValExpr, Captures).get(); 14917 *HelperValStmt = buildPreInits(SemaRef.Context, Captures); 14918 } 14919 } 14920 return true; 14921 } 14922 14923 OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads, 14924 SourceLocation StartLoc, 14925 SourceLocation LParenLoc, 14926 SourceLocation EndLoc) { 14927 Expr *ValExpr = NumThreads; 14928 Stmt *HelperValStmt = nullptr; 14929 14930 // OpenMP [2.5, Restrictions] 14931 // The num_threads expression must evaluate to a positive integer value. 14932 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_threads, 14933 /*StrictlyPositive=*/true)) 14934 return nullptr; 14935 14936 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective(); 14937 OpenMPDirectiveKind CaptureRegion = 14938 getOpenMPCaptureRegionForClause(DKind, OMPC_num_threads, LangOpts.OpenMP); 14939 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) { 14940 ValExpr = MakeFullExpr(ValExpr).get(); 14941 llvm::MapVector<const Expr *, DeclRefExpr *> Captures; 14942 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 14943 HelperValStmt = buildPreInits(Context, Captures); 14944 } 14945 14946 return new (Context) OMPNumThreadsClause( 14947 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc); 14948 } 14949 14950 ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E, 14951 OpenMPClauseKind CKind, 14952 bool StrictlyPositive, 14953 bool SuppressExprDiags) { 14954 if (!E) 14955 return ExprError(); 14956 if (E->isValueDependent() || E->isTypeDependent() || 14957 E->isInstantiationDependent() || E->containsUnexpandedParameterPack()) 14958 return E; 14959 14960 llvm::APSInt Result; 14961 ExprResult ICE; 14962 if (SuppressExprDiags) { 14963 // Use a custom diagnoser that suppresses 'note' diagnostics about the 14964 // expression. 14965 struct SuppressedDiagnoser : public Sema::VerifyICEDiagnoser { 14966 SuppressedDiagnoser() : VerifyICEDiagnoser(/*Suppress=*/true) {} 14967 Sema::SemaDiagnosticBuilder diagnoseNotICE(Sema &S, 14968 SourceLocation Loc) override { 14969 llvm_unreachable("Diagnostic suppressed"); 14970 } 14971 } Diagnoser; 14972 ICE = VerifyIntegerConstantExpression(E, &Result, Diagnoser, AllowFold); 14973 } else { 14974 ICE = VerifyIntegerConstantExpression(E, &Result, /*FIXME*/ AllowFold); 14975 } 14976 if (ICE.isInvalid()) 14977 return ExprError(); 14978 14979 if ((StrictlyPositive && !Result.isStrictlyPositive()) || 14980 (!StrictlyPositive && !Result.isNonNegative())) { 14981 Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause) 14982 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0) 14983 << E->getSourceRange(); 14984 return ExprError(); 14985 } 14986 if ((CKind == OMPC_aligned || CKind == OMPC_align) && !Result.isPowerOf2()) { 14987 Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two) 14988 << E->getSourceRange(); 14989 return ExprError(); 14990 } 14991 if (CKind == OMPC_collapse && DSAStack->getAssociatedLoops() == 1) 14992 DSAStack->setAssociatedLoops(Result.getExtValue()); 14993 else if (CKind == OMPC_ordered) 14994 DSAStack->setAssociatedLoops(Result.getExtValue()); 14995 return ICE; 14996 } 14997 14998 OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc, 14999 SourceLocation LParenLoc, 15000 SourceLocation EndLoc) { 15001 // OpenMP [2.8.1, simd construct, Description] 15002 // The parameter of the safelen clause must be a constant 15003 // positive integer expression. 15004 ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen); 15005 if (Safelen.isInvalid()) 15006 return nullptr; 15007 return new (Context) 15008 OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc); 15009 } 15010 15011 OMPClause *Sema::ActOnOpenMPSimdlenClause(Expr *Len, SourceLocation StartLoc, 15012 SourceLocation LParenLoc, 15013 SourceLocation EndLoc) { 15014 // OpenMP [2.8.1, simd construct, Description] 15015 // The parameter of the simdlen clause must be a constant 15016 // positive integer expression. 15017 ExprResult Simdlen = VerifyPositiveIntegerConstantInClause(Len, OMPC_simdlen); 15018 if (Simdlen.isInvalid()) 15019 return nullptr; 15020 return new (Context) 15021 OMPSimdlenClause(Simdlen.get(), StartLoc, LParenLoc, EndLoc); 15022 } 15023 15024 /// Tries to find omp_allocator_handle_t type. 15025 static bool findOMPAllocatorHandleT(Sema &S, SourceLocation Loc, 15026 DSAStackTy *Stack) { 15027 QualType OMPAllocatorHandleT = Stack->getOMPAllocatorHandleT(); 15028 if (!OMPAllocatorHandleT.isNull()) 15029 return true; 15030 // Build the predefined allocator expressions. 15031 bool ErrorFound = false; 15032 for (int I = 0; I < OMPAllocateDeclAttr::OMPUserDefinedMemAlloc; ++I) { 15033 auto AllocatorKind = static_cast<OMPAllocateDeclAttr::AllocatorTypeTy>(I); 15034 StringRef Allocator = 15035 OMPAllocateDeclAttr::ConvertAllocatorTypeTyToStr(AllocatorKind); 15036 DeclarationName AllocatorName = &S.getASTContext().Idents.get(Allocator); 15037 auto *VD = dyn_cast_or_null<ValueDecl>( 15038 S.LookupSingleName(S.TUScope, AllocatorName, Loc, Sema::LookupAnyName)); 15039 if (!VD) { 15040 ErrorFound = true; 15041 break; 15042 } 15043 QualType AllocatorType = 15044 VD->getType().getNonLValueExprType(S.getASTContext()); 15045 ExprResult Res = S.BuildDeclRefExpr(VD, AllocatorType, VK_LValue, Loc); 15046 if (!Res.isUsable()) { 15047 ErrorFound = true; 15048 break; 15049 } 15050 if (OMPAllocatorHandleT.isNull()) 15051 OMPAllocatorHandleT = AllocatorType; 15052 if (!S.getASTContext().hasSameType(OMPAllocatorHandleT, AllocatorType)) { 15053 ErrorFound = true; 15054 break; 15055 } 15056 Stack->setAllocator(AllocatorKind, Res.get()); 15057 } 15058 if (ErrorFound) { 15059 S.Diag(Loc, diag::err_omp_implied_type_not_found) 15060 << "omp_allocator_handle_t"; 15061 return false; 15062 } 15063 OMPAllocatorHandleT.addConst(); 15064 Stack->setOMPAllocatorHandleT(OMPAllocatorHandleT); 15065 return true; 15066 } 15067 15068 OMPClause *Sema::ActOnOpenMPAllocatorClause(Expr *A, SourceLocation StartLoc, 15069 SourceLocation LParenLoc, 15070 SourceLocation EndLoc) { 15071 // OpenMP [2.11.3, allocate Directive, Description] 15072 // allocator is an expression of omp_allocator_handle_t type. 15073 if (!findOMPAllocatorHandleT(*this, A->getExprLoc(), DSAStack)) 15074 return nullptr; 15075 15076 ExprResult Allocator = DefaultLvalueConversion(A); 15077 if (Allocator.isInvalid()) 15078 return nullptr; 15079 Allocator = PerformImplicitConversion(Allocator.get(), 15080 DSAStack->getOMPAllocatorHandleT(), 15081 Sema::AA_Initializing, 15082 /*AllowExplicit=*/true); 15083 if (Allocator.isInvalid()) 15084 return nullptr; 15085 return new (Context) 15086 OMPAllocatorClause(Allocator.get(), StartLoc, LParenLoc, EndLoc); 15087 } 15088 15089 OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops, 15090 SourceLocation StartLoc, 15091 SourceLocation LParenLoc, 15092 SourceLocation EndLoc) { 15093 // OpenMP [2.7.1, loop construct, Description] 15094 // OpenMP [2.8.1, simd construct, Description] 15095 // OpenMP [2.9.6, distribute construct, Description] 15096 // The parameter of the collapse clause must be a constant 15097 // positive integer expression. 15098 ExprResult NumForLoopsResult = 15099 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse); 15100 if (NumForLoopsResult.isInvalid()) 15101 return nullptr; 15102 return new (Context) 15103 OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc); 15104 } 15105 15106 OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc, 15107 SourceLocation EndLoc, 15108 SourceLocation LParenLoc, 15109 Expr *NumForLoops) { 15110 // OpenMP [2.7.1, loop construct, Description] 15111 // OpenMP [2.8.1, simd construct, Description] 15112 // OpenMP [2.9.6, distribute construct, Description] 15113 // The parameter of the ordered clause must be a constant 15114 // positive integer expression if any. 15115 if (NumForLoops && LParenLoc.isValid()) { 15116 ExprResult NumForLoopsResult = 15117 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_ordered); 15118 if (NumForLoopsResult.isInvalid()) 15119 return nullptr; 15120 NumForLoops = NumForLoopsResult.get(); 15121 } else { 15122 NumForLoops = nullptr; 15123 } 15124 auto *Clause = OMPOrderedClause::Create( 15125 Context, NumForLoops, NumForLoops ? DSAStack->getAssociatedLoops() : 0, 15126 StartLoc, LParenLoc, EndLoc); 15127 DSAStack->setOrderedRegion(/*IsOrdered=*/true, NumForLoops, Clause); 15128 return Clause; 15129 } 15130 15131 OMPClause *Sema::ActOnOpenMPSimpleClause( 15132 OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc, 15133 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) { 15134 OMPClause *Res = nullptr; 15135 switch (Kind) { 15136 case OMPC_default: 15137 Res = ActOnOpenMPDefaultClause(static_cast<DefaultKind>(Argument), 15138 ArgumentLoc, StartLoc, LParenLoc, EndLoc); 15139 break; 15140 case OMPC_proc_bind: 15141 Res = ActOnOpenMPProcBindClause(static_cast<ProcBindKind>(Argument), 15142 ArgumentLoc, StartLoc, LParenLoc, EndLoc); 15143 break; 15144 case OMPC_atomic_default_mem_order: 15145 Res = ActOnOpenMPAtomicDefaultMemOrderClause( 15146 static_cast<OpenMPAtomicDefaultMemOrderClauseKind>(Argument), 15147 ArgumentLoc, StartLoc, LParenLoc, EndLoc); 15148 break; 15149 case OMPC_order: 15150 Res = ActOnOpenMPOrderClause(static_cast<OpenMPOrderClauseKind>(Argument), 15151 ArgumentLoc, StartLoc, LParenLoc, EndLoc); 15152 break; 15153 case OMPC_update: 15154 Res = ActOnOpenMPUpdateClause(static_cast<OpenMPDependClauseKind>(Argument), 15155 ArgumentLoc, StartLoc, LParenLoc, EndLoc); 15156 break; 15157 case OMPC_bind: 15158 Res = ActOnOpenMPBindClause(static_cast<OpenMPBindClauseKind>(Argument), 15159 ArgumentLoc, StartLoc, LParenLoc, EndLoc); 15160 break; 15161 case OMPC_if: 15162 case OMPC_final: 15163 case OMPC_num_threads: 15164 case OMPC_safelen: 15165 case OMPC_simdlen: 15166 case OMPC_sizes: 15167 case OMPC_allocator: 15168 case OMPC_collapse: 15169 case OMPC_schedule: 15170 case OMPC_private: 15171 case OMPC_firstprivate: 15172 case OMPC_lastprivate: 15173 case OMPC_shared: 15174 case OMPC_reduction: 15175 case OMPC_task_reduction: 15176 case OMPC_in_reduction: 15177 case OMPC_linear: 15178 case OMPC_aligned: 15179 case OMPC_copyin: 15180 case OMPC_copyprivate: 15181 case OMPC_ordered: 15182 case OMPC_nowait: 15183 case OMPC_untied: 15184 case OMPC_mergeable: 15185 case OMPC_threadprivate: 15186 case OMPC_allocate: 15187 case OMPC_flush: 15188 case OMPC_depobj: 15189 case OMPC_read: 15190 case OMPC_write: 15191 case OMPC_capture: 15192 case OMPC_compare: 15193 case OMPC_seq_cst: 15194 case OMPC_acq_rel: 15195 case OMPC_acquire: 15196 case OMPC_release: 15197 case OMPC_relaxed: 15198 case OMPC_depend: 15199 case OMPC_device: 15200 case OMPC_threads: 15201 case OMPC_simd: 15202 case OMPC_map: 15203 case OMPC_num_teams: 15204 case OMPC_thread_limit: 15205 case OMPC_priority: 15206 case OMPC_grainsize: 15207 case OMPC_nogroup: 15208 case OMPC_num_tasks: 15209 case OMPC_hint: 15210 case OMPC_dist_schedule: 15211 case OMPC_defaultmap: 15212 case OMPC_unknown: 15213 case OMPC_uniform: 15214 case OMPC_to: 15215 case OMPC_from: 15216 case OMPC_use_device_ptr: 15217 case OMPC_use_device_addr: 15218 case OMPC_is_device_ptr: 15219 case OMPC_unified_address: 15220 case OMPC_unified_shared_memory: 15221 case OMPC_reverse_offload: 15222 case OMPC_dynamic_allocators: 15223 case OMPC_device_type: 15224 case OMPC_match: 15225 case OMPC_nontemporal: 15226 case OMPC_destroy: 15227 case OMPC_novariants: 15228 case OMPC_nocontext: 15229 case OMPC_detach: 15230 case OMPC_inclusive: 15231 case OMPC_exclusive: 15232 case OMPC_uses_allocators: 15233 case OMPC_affinity: 15234 case OMPC_when: 15235 default: 15236 llvm_unreachable("Clause is not allowed."); 15237 } 15238 return Res; 15239 } 15240 15241 static std::string 15242 getListOfPossibleValues(OpenMPClauseKind K, unsigned First, unsigned Last, 15243 ArrayRef<unsigned> Exclude = llvm::None) { 15244 SmallString<256> Buffer; 15245 llvm::raw_svector_ostream Out(Buffer); 15246 unsigned Skipped = Exclude.size(); 15247 auto S = Exclude.begin(), E = Exclude.end(); 15248 for (unsigned I = First; I < Last; ++I) { 15249 if (std::find(S, E, I) != E) { 15250 --Skipped; 15251 continue; 15252 } 15253 Out << "'" << getOpenMPSimpleClauseTypeName(K, I) << "'"; 15254 if (I + Skipped + 2 == Last) 15255 Out << " or "; 15256 else if (I + Skipped + 1 != Last) 15257 Out << ", "; 15258 } 15259 return std::string(Out.str()); 15260 } 15261 15262 OMPClause *Sema::ActOnOpenMPDefaultClause(DefaultKind Kind, 15263 SourceLocation KindKwLoc, 15264 SourceLocation StartLoc, 15265 SourceLocation LParenLoc, 15266 SourceLocation EndLoc) { 15267 if (Kind == OMP_DEFAULT_unknown) { 15268 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value) 15269 << getListOfPossibleValues(OMPC_default, /*First=*/0, 15270 /*Last=*/unsigned(OMP_DEFAULT_unknown)) 15271 << getOpenMPClauseName(OMPC_default); 15272 return nullptr; 15273 } 15274 15275 switch (Kind) { 15276 case OMP_DEFAULT_none: 15277 DSAStack->setDefaultDSANone(KindKwLoc); 15278 break; 15279 case OMP_DEFAULT_shared: 15280 DSAStack->setDefaultDSAShared(KindKwLoc); 15281 break; 15282 case OMP_DEFAULT_firstprivate: 15283 DSAStack->setDefaultDSAFirstPrivate(KindKwLoc); 15284 break; 15285 default: 15286 llvm_unreachable("DSA unexpected in OpenMP default clause"); 15287 } 15288 15289 return new (Context) 15290 OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc); 15291 } 15292 15293 OMPClause *Sema::ActOnOpenMPProcBindClause(ProcBindKind Kind, 15294 SourceLocation KindKwLoc, 15295 SourceLocation StartLoc, 15296 SourceLocation LParenLoc, 15297 SourceLocation EndLoc) { 15298 if (Kind == OMP_PROC_BIND_unknown) { 15299 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value) 15300 << getListOfPossibleValues(OMPC_proc_bind, 15301 /*First=*/unsigned(OMP_PROC_BIND_master), 15302 /*Last=*/ 15303 unsigned(LangOpts.OpenMP > 50 15304 ? OMP_PROC_BIND_primary 15305 : OMP_PROC_BIND_spread) + 15306 1) 15307 << getOpenMPClauseName(OMPC_proc_bind); 15308 return nullptr; 15309 } 15310 if (Kind == OMP_PROC_BIND_primary && LangOpts.OpenMP < 51) 15311 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value) 15312 << getListOfPossibleValues(OMPC_proc_bind, 15313 /*First=*/unsigned(OMP_PROC_BIND_master), 15314 /*Last=*/ 15315 unsigned(OMP_PROC_BIND_spread) + 1) 15316 << getOpenMPClauseName(OMPC_proc_bind); 15317 return new (Context) 15318 OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc); 15319 } 15320 15321 OMPClause *Sema::ActOnOpenMPAtomicDefaultMemOrderClause( 15322 OpenMPAtomicDefaultMemOrderClauseKind Kind, SourceLocation KindKwLoc, 15323 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) { 15324 if (Kind == OMPC_ATOMIC_DEFAULT_MEM_ORDER_unknown) { 15325 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value) 15326 << getListOfPossibleValues( 15327 OMPC_atomic_default_mem_order, /*First=*/0, 15328 /*Last=*/OMPC_ATOMIC_DEFAULT_MEM_ORDER_unknown) 15329 << getOpenMPClauseName(OMPC_atomic_default_mem_order); 15330 return nullptr; 15331 } 15332 return new (Context) OMPAtomicDefaultMemOrderClause(Kind, KindKwLoc, StartLoc, 15333 LParenLoc, EndLoc); 15334 } 15335 15336 OMPClause *Sema::ActOnOpenMPOrderClause(OpenMPOrderClauseKind Kind, 15337 SourceLocation KindKwLoc, 15338 SourceLocation StartLoc, 15339 SourceLocation LParenLoc, 15340 SourceLocation EndLoc) { 15341 if (Kind == OMPC_ORDER_unknown) { 15342 static_assert(OMPC_ORDER_unknown > 0, 15343 "OMPC_ORDER_unknown not greater than 0"); 15344 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value) 15345 << getListOfPossibleValues(OMPC_order, /*First=*/0, 15346 /*Last=*/OMPC_ORDER_unknown) 15347 << getOpenMPClauseName(OMPC_order); 15348 return nullptr; 15349 } 15350 return new (Context) 15351 OMPOrderClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc); 15352 } 15353 15354 OMPClause *Sema::ActOnOpenMPUpdateClause(OpenMPDependClauseKind Kind, 15355 SourceLocation KindKwLoc, 15356 SourceLocation StartLoc, 15357 SourceLocation LParenLoc, 15358 SourceLocation EndLoc) { 15359 if (Kind == OMPC_DEPEND_unknown || Kind == OMPC_DEPEND_source || 15360 Kind == OMPC_DEPEND_sink || Kind == OMPC_DEPEND_depobj) { 15361 SmallVector<unsigned> Except = {OMPC_DEPEND_source, OMPC_DEPEND_sink, 15362 OMPC_DEPEND_depobj}; 15363 if (LangOpts.OpenMP < 51) 15364 Except.push_back(OMPC_DEPEND_inoutset); 15365 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value) 15366 << getListOfPossibleValues(OMPC_depend, /*First=*/0, 15367 /*Last=*/OMPC_DEPEND_unknown, Except) 15368 << getOpenMPClauseName(OMPC_update); 15369 return nullptr; 15370 } 15371 return OMPUpdateClause::Create(Context, StartLoc, LParenLoc, KindKwLoc, Kind, 15372 EndLoc); 15373 } 15374 15375 OMPClause *Sema::ActOnOpenMPSizesClause(ArrayRef<Expr *> SizeExprs, 15376 SourceLocation StartLoc, 15377 SourceLocation LParenLoc, 15378 SourceLocation EndLoc) { 15379 for (Expr *SizeExpr : SizeExprs) { 15380 ExprResult NumForLoopsResult = VerifyPositiveIntegerConstantInClause( 15381 SizeExpr, OMPC_sizes, /*StrictlyPositive=*/true); 15382 if (!NumForLoopsResult.isUsable()) 15383 return nullptr; 15384 } 15385 15386 DSAStack->setAssociatedLoops(SizeExprs.size()); 15387 return OMPSizesClause::Create(Context, StartLoc, LParenLoc, EndLoc, 15388 SizeExprs); 15389 } 15390 15391 OMPClause *Sema::ActOnOpenMPFullClause(SourceLocation StartLoc, 15392 SourceLocation EndLoc) { 15393 return OMPFullClause::Create(Context, StartLoc, EndLoc); 15394 } 15395 15396 OMPClause *Sema::ActOnOpenMPPartialClause(Expr *FactorExpr, 15397 SourceLocation StartLoc, 15398 SourceLocation LParenLoc, 15399 SourceLocation EndLoc) { 15400 if (FactorExpr) { 15401 // If an argument is specified, it must be a constant (or an unevaluated 15402 // template expression). 15403 ExprResult FactorResult = VerifyPositiveIntegerConstantInClause( 15404 FactorExpr, OMPC_partial, /*StrictlyPositive=*/true); 15405 if (FactorResult.isInvalid()) 15406 return nullptr; 15407 FactorExpr = FactorResult.get(); 15408 } 15409 15410 return OMPPartialClause::Create(Context, StartLoc, LParenLoc, EndLoc, 15411 FactorExpr); 15412 } 15413 15414 OMPClause *Sema::ActOnOpenMPAlignClause(Expr *A, SourceLocation StartLoc, 15415 SourceLocation LParenLoc, 15416 SourceLocation EndLoc) { 15417 ExprResult AlignVal; 15418 AlignVal = VerifyPositiveIntegerConstantInClause(A, OMPC_align); 15419 if (AlignVal.isInvalid()) 15420 return nullptr; 15421 return OMPAlignClause::Create(Context, AlignVal.get(), StartLoc, LParenLoc, 15422 EndLoc); 15423 } 15424 15425 OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause( 15426 OpenMPClauseKind Kind, ArrayRef<unsigned> Argument, Expr *Expr, 15427 SourceLocation StartLoc, SourceLocation LParenLoc, 15428 ArrayRef<SourceLocation> ArgumentLoc, SourceLocation DelimLoc, 15429 SourceLocation EndLoc) { 15430 OMPClause *Res = nullptr; 15431 switch (Kind) { 15432 case OMPC_schedule: 15433 enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements }; 15434 assert(Argument.size() == NumberOfElements && 15435 ArgumentLoc.size() == NumberOfElements); 15436 Res = ActOnOpenMPScheduleClause( 15437 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier1]), 15438 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier2]), 15439 static_cast<OpenMPScheduleClauseKind>(Argument[ScheduleKind]), Expr, 15440 StartLoc, LParenLoc, ArgumentLoc[Modifier1], ArgumentLoc[Modifier2], 15441 ArgumentLoc[ScheduleKind], DelimLoc, EndLoc); 15442 break; 15443 case OMPC_if: 15444 assert(Argument.size() == 1 && ArgumentLoc.size() == 1); 15445 Res = ActOnOpenMPIfClause(static_cast<OpenMPDirectiveKind>(Argument.back()), 15446 Expr, StartLoc, LParenLoc, ArgumentLoc.back(), 15447 DelimLoc, EndLoc); 15448 break; 15449 case OMPC_dist_schedule: 15450 Res = ActOnOpenMPDistScheduleClause( 15451 static_cast<OpenMPDistScheduleClauseKind>(Argument.back()), Expr, 15452 StartLoc, LParenLoc, ArgumentLoc.back(), DelimLoc, EndLoc); 15453 break; 15454 case OMPC_defaultmap: 15455 enum { Modifier, DefaultmapKind }; 15456 Res = ActOnOpenMPDefaultmapClause( 15457 static_cast<OpenMPDefaultmapClauseModifier>(Argument[Modifier]), 15458 static_cast<OpenMPDefaultmapClauseKind>(Argument[DefaultmapKind]), 15459 StartLoc, LParenLoc, ArgumentLoc[Modifier], ArgumentLoc[DefaultmapKind], 15460 EndLoc); 15461 break; 15462 case OMPC_device: 15463 assert(Argument.size() == 1 && ArgumentLoc.size() == 1); 15464 Res = ActOnOpenMPDeviceClause( 15465 static_cast<OpenMPDeviceClauseModifier>(Argument.back()), Expr, 15466 StartLoc, LParenLoc, ArgumentLoc.back(), EndLoc); 15467 break; 15468 case OMPC_final: 15469 case OMPC_num_threads: 15470 case OMPC_safelen: 15471 case OMPC_simdlen: 15472 case OMPC_sizes: 15473 case OMPC_allocator: 15474 case OMPC_collapse: 15475 case OMPC_default: 15476 case OMPC_proc_bind: 15477 case OMPC_private: 15478 case OMPC_firstprivate: 15479 case OMPC_lastprivate: 15480 case OMPC_shared: 15481 case OMPC_reduction: 15482 case OMPC_task_reduction: 15483 case OMPC_in_reduction: 15484 case OMPC_linear: 15485 case OMPC_aligned: 15486 case OMPC_copyin: 15487 case OMPC_copyprivate: 15488 case OMPC_ordered: 15489 case OMPC_nowait: 15490 case OMPC_untied: 15491 case OMPC_mergeable: 15492 case OMPC_threadprivate: 15493 case OMPC_allocate: 15494 case OMPC_flush: 15495 case OMPC_depobj: 15496 case OMPC_read: 15497 case OMPC_write: 15498 case OMPC_update: 15499 case OMPC_capture: 15500 case OMPC_compare: 15501 case OMPC_seq_cst: 15502 case OMPC_acq_rel: 15503 case OMPC_acquire: 15504 case OMPC_release: 15505 case OMPC_relaxed: 15506 case OMPC_depend: 15507 case OMPC_threads: 15508 case OMPC_simd: 15509 case OMPC_map: 15510 case OMPC_num_teams: 15511 case OMPC_thread_limit: 15512 case OMPC_priority: 15513 case OMPC_grainsize: 15514 case OMPC_nogroup: 15515 case OMPC_num_tasks: 15516 case OMPC_hint: 15517 case OMPC_unknown: 15518 case OMPC_uniform: 15519 case OMPC_to: 15520 case OMPC_from: 15521 case OMPC_use_device_ptr: 15522 case OMPC_use_device_addr: 15523 case OMPC_is_device_ptr: 15524 case OMPC_unified_address: 15525 case OMPC_unified_shared_memory: 15526 case OMPC_reverse_offload: 15527 case OMPC_dynamic_allocators: 15528 case OMPC_atomic_default_mem_order: 15529 case OMPC_device_type: 15530 case OMPC_match: 15531 case OMPC_nontemporal: 15532 case OMPC_order: 15533 case OMPC_destroy: 15534 case OMPC_novariants: 15535 case OMPC_nocontext: 15536 case OMPC_detach: 15537 case OMPC_inclusive: 15538 case OMPC_exclusive: 15539 case OMPC_uses_allocators: 15540 case OMPC_affinity: 15541 case OMPC_when: 15542 case OMPC_bind: 15543 default: 15544 llvm_unreachable("Clause is not allowed."); 15545 } 15546 return Res; 15547 } 15548 15549 static bool checkScheduleModifiers(Sema &S, OpenMPScheduleClauseModifier M1, 15550 OpenMPScheduleClauseModifier M2, 15551 SourceLocation M1Loc, SourceLocation M2Loc) { 15552 if (M1 == OMPC_SCHEDULE_MODIFIER_unknown && M1Loc.isValid()) { 15553 SmallVector<unsigned, 2> Excluded; 15554 if (M2 != OMPC_SCHEDULE_MODIFIER_unknown) 15555 Excluded.push_back(M2); 15556 if (M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) 15557 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_monotonic); 15558 if (M2 == OMPC_SCHEDULE_MODIFIER_monotonic) 15559 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_nonmonotonic); 15560 S.Diag(M1Loc, diag::err_omp_unexpected_clause_value) 15561 << getListOfPossibleValues(OMPC_schedule, 15562 /*First=*/OMPC_SCHEDULE_MODIFIER_unknown + 1, 15563 /*Last=*/OMPC_SCHEDULE_MODIFIER_last, 15564 Excluded) 15565 << getOpenMPClauseName(OMPC_schedule); 15566 return true; 15567 } 15568 return false; 15569 } 15570 15571 OMPClause *Sema::ActOnOpenMPScheduleClause( 15572 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2, 15573 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc, 15574 SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc, 15575 SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) { 15576 if (checkScheduleModifiers(*this, M1, M2, M1Loc, M2Loc) || 15577 checkScheduleModifiers(*this, M2, M1, M2Loc, M1Loc)) 15578 return nullptr; 15579 // OpenMP, 2.7.1, Loop Construct, Restrictions 15580 // Either the monotonic modifier or the nonmonotonic modifier can be specified 15581 // but not both. 15582 if ((M1 == M2 && M1 != OMPC_SCHEDULE_MODIFIER_unknown) || 15583 (M1 == OMPC_SCHEDULE_MODIFIER_monotonic && 15584 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) || 15585 (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic && 15586 M2 == OMPC_SCHEDULE_MODIFIER_monotonic)) { 15587 Diag(M2Loc, diag::err_omp_unexpected_schedule_modifier) 15588 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M2) 15589 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M1); 15590 return nullptr; 15591 } 15592 if (Kind == OMPC_SCHEDULE_unknown) { 15593 std::string Values; 15594 if (M1Loc.isInvalid() && M2Loc.isInvalid()) { 15595 unsigned Exclude[] = {OMPC_SCHEDULE_unknown}; 15596 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0, 15597 /*Last=*/OMPC_SCHEDULE_MODIFIER_last, 15598 Exclude); 15599 } else { 15600 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0, 15601 /*Last=*/OMPC_SCHEDULE_unknown); 15602 } 15603 Diag(KindLoc, diag::err_omp_unexpected_clause_value) 15604 << Values << getOpenMPClauseName(OMPC_schedule); 15605 return nullptr; 15606 } 15607 // OpenMP, 2.7.1, Loop Construct, Restrictions 15608 // The nonmonotonic modifier can only be specified with schedule(dynamic) or 15609 // schedule(guided). 15610 // OpenMP 5.0 does not have this restriction. 15611 if (LangOpts.OpenMP < 50 && 15612 (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic || 15613 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) && 15614 Kind != OMPC_SCHEDULE_dynamic && Kind != OMPC_SCHEDULE_guided) { 15615 Diag(M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ? M1Loc : M2Loc, 15616 diag::err_omp_schedule_nonmonotonic_static); 15617 return nullptr; 15618 } 15619 Expr *ValExpr = ChunkSize; 15620 Stmt *HelperValStmt = nullptr; 15621 if (ChunkSize) { 15622 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() && 15623 !ChunkSize->isInstantiationDependent() && 15624 !ChunkSize->containsUnexpandedParameterPack()) { 15625 SourceLocation ChunkSizeLoc = ChunkSize->getBeginLoc(); 15626 ExprResult Val = 15627 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize); 15628 if (Val.isInvalid()) 15629 return nullptr; 15630 15631 ValExpr = Val.get(); 15632 15633 // OpenMP [2.7.1, Restrictions] 15634 // chunk_size must be a loop invariant integer expression with a positive 15635 // value. 15636 if (Optional<llvm::APSInt> Result = 15637 ValExpr->getIntegerConstantExpr(Context)) { 15638 if (Result->isSigned() && !Result->isStrictlyPositive()) { 15639 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause) 15640 << "schedule" << 1 << ChunkSize->getSourceRange(); 15641 return nullptr; 15642 } 15643 } else if (getOpenMPCaptureRegionForClause( 15644 DSAStack->getCurrentDirective(), OMPC_schedule, 15645 LangOpts.OpenMP) != OMPD_unknown && 15646 !CurContext->isDependentContext()) { 15647 ValExpr = MakeFullExpr(ValExpr).get(); 15648 llvm::MapVector<const Expr *, DeclRefExpr *> Captures; 15649 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 15650 HelperValStmt = buildPreInits(Context, Captures); 15651 } 15652 } 15653 } 15654 15655 return new (Context) 15656 OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, Kind, 15657 ValExpr, HelperValStmt, M1, M1Loc, M2, M2Loc); 15658 } 15659 15660 OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind, 15661 SourceLocation StartLoc, 15662 SourceLocation EndLoc) { 15663 OMPClause *Res = nullptr; 15664 switch (Kind) { 15665 case OMPC_ordered: 15666 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc); 15667 break; 15668 case OMPC_nowait: 15669 Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc); 15670 break; 15671 case OMPC_untied: 15672 Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc); 15673 break; 15674 case OMPC_mergeable: 15675 Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc); 15676 break; 15677 case OMPC_read: 15678 Res = ActOnOpenMPReadClause(StartLoc, EndLoc); 15679 break; 15680 case OMPC_write: 15681 Res = ActOnOpenMPWriteClause(StartLoc, EndLoc); 15682 break; 15683 case OMPC_update: 15684 Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc); 15685 break; 15686 case OMPC_capture: 15687 Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc); 15688 break; 15689 case OMPC_compare: 15690 Res = ActOnOpenMPCompareClause(StartLoc, EndLoc); 15691 break; 15692 case OMPC_seq_cst: 15693 Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc); 15694 break; 15695 case OMPC_acq_rel: 15696 Res = ActOnOpenMPAcqRelClause(StartLoc, EndLoc); 15697 break; 15698 case OMPC_acquire: 15699 Res = ActOnOpenMPAcquireClause(StartLoc, EndLoc); 15700 break; 15701 case OMPC_release: 15702 Res = ActOnOpenMPReleaseClause(StartLoc, EndLoc); 15703 break; 15704 case OMPC_relaxed: 15705 Res = ActOnOpenMPRelaxedClause(StartLoc, EndLoc); 15706 break; 15707 case OMPC_threads: 15708 Res = ActOnOpenMPThreadsClause(StartLoc, EndLoc); 15709 break; 15710 case OMPC_simd: 15711 Res = ActOnOpenMPSIMDClause(StartLoc, EndLoc); 15712 break; 15713 case OMPC_nogroup: 15714 Res = ActOnOpenMPNogroupClause(StartLoc, EndLoc); 15715 break; 15716 case OMPC_unified_address: 15717 Res = ActOnOpenMPUnifiedAddressClause(StartLoc, EndLoc); 15718 break; 15719 case OMPC_unified_shared_memory: 15720 Res = ActOnOpenMPUnifiedSharedMemoryClause(StartLoc, EndLoc); 15721 break; 15722 case OMPC_reverse_offload: 15723 Res = ActOnOpenMPReverseOffloadClause(StartLoc, EndLoc); 15724 break; 15725 case OMPC_dynamic_allocators: 15726 Res = ActOnOpenMPDynamicAllocatorsClause(StartLoc, EndLoc); 15727 break; 15728 case OMPC_destroy: 15729 Res = ActOnOpenMPDestroyClause(/*InteropVar=*/nullptr, StartLoc, 15730 /*LParenLoc=*/SourceLocation(), 15731 /*VarLoc=*/SourceLocation(), EndLoc); 15732 break; 15733 case OMPC_full: 15734 Res = ActOnOpenMPFullClause(StartLoc, EndLoc); 15735 break; 15736 case OMPC_partial: 15737 Res = ActOnOpenMPPartialClause(nullptr, StartLoc, /*LParenLoc=*/{}, EndLoc); 15738 break; 15739 case OMPC_if: 15740 case OMPC_final: 15741 case OMPC_num_threads: 15742 case OMPC_safelen: 15743 case OMPC_simdlen: 15744 case OMPC_sizes: 15745 case OMPC_allocator: 15746 case OMPC_collapse: 15747 case OMPC_schedule: 15748 case OMPC_private: 15749 case OMPC_firstprivate: 15750 case OMPC_lastprivate: 15751 case OMPC_shared: 15752 case OMPC_reduction: 15753 case OMPC_task_reduction: 15754 case OMPC_in_reduction: 15755 case OMPC_linear: 15756 case OMPC_aligned: 15757 case OMPC_copyin: 15758 case OMPC_copyprivate: 15759 case OMPC_default: 15760 case OMPC_proc_bind: 15761 case OMPC_threadprivate: 15762 case OMPC_allocate: 15763 case OMPC_flush: 15764 case OMPC_depobj: 15765 case OMPC_depend: 15766 case OMPC_device: 15767 case OMPC_map: 15768 case OMPC_num_teams: 15769 case OMPC_thread_limit: 15770 case OMPC_priority: 15771 case OMPC_grainsize: 15772 case OMPC_num_tasks: 15773 case OMPC_hint: 15774 case OMPC_dist_schedule: 15775 case OMPC_defaultmap: 15776 case OMPC_unknown: 15777 case OMPC_uniform: 15778 case OMPC_to: 15779 case OMPC_from: 15780 case OMPC_use_device_ptr: 15781 case OMPC_use_device_addr: 15782 case OMPC_is_device_ptr: 15783 case OMPC_atomic_default_mem_order: 15784 case OMPC_device_type: 15785 case OMPC_match: 15786 case OMPC_nontemporal: 15787 case OMPC_order: 15788 case OMPC_novariants: 15789 case OMPC_nocontext: 15790 case OMPC_detach: 15791 case OMPC_inclusive: 15792 case OMPC_exclusive: 15793 case OMPC_uses_allocators: 15794 case OMPC_affinity: 15795 case OMPC_when: 15796 default: 15797 llvm_unreachable("Clause is not allowed."); 15798 } 15799 return Res; 15800 } 15801 15802 OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc, 15803 SourceLocation EndLoc) { 15804 DSAStack->setNowaitRegion(); 15805 return new (Context) OMPNowaitClause(StartLoc, EndLoc); 15806 } 15807 15808 OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc, 15809 SourceLocation EndLoc) { 15810 return new (Context) OMPUntiedClause(StartLoc, EndLoc); 15811 } 15812 15813 OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc, 15814 SourceLocation EndLoc) { 15815 return new (Context) OMPMergeableClause(StartLoc, EndLoc); 15816 } 15817 15818 OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc, 15819 SourceLocation EndLoc) { 15820 return new (Context) OMPReadClause(StartLoc, EndLoc); 15821 } 15822 15823 OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc, 15824 SourceLocation EndLoc) { 15825 return new (Context) OMPWriteClause(StartLoc, EndLoc); 15826 } 15827 15828 OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc, 15829 SourceLocation EndLoc) { 15830 return OMPUpdateClause::Create(Context, StartLoc, EndLoc); 15831 } 15832 15833 OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc, 15834 SourceLocation EndLoc) { 15835 return new (Context) OMPCaptureClause(StartLoc, EndLoc); 15836 } 15837 15838 OMPClause *Sema::ActOnOpenMPCompareClause(SourceLocation StartLoc, 15839 SourceLocation EndLoc) { 15840 return new (Context) OMPCompareClause(StartLoc, EndLoc); 15841 } 15842 15843 OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc, 15844 SourceLocation EndLoc) { 15845 return new (Context) OMPSeqCstClause(StartLoc, EndLoc); 15846 } 15847 15848 OMPClause *Sema::ActOnOpenMPAcqRelClause(SourceLocation StartLoc, 15849 SourceLocation EndLoc) { 15850 return new (Context) OMPAcqRelClause(StartLoc, EndLoc); 15851 } 15852 15853 OMPClause *Sema::ActOnOpenMPAcquireClause(SourceLocation StartLoc, 15854 SourceLocation EndLoc) { 15855 return new (Context) OMPAcquireClause(StartLoc, EndLoc); 15856 } 15857 15858 OMPClause *Sema::ActOnOpenMPReleaseClause(SourceLocation StartLoc, 15859 SourceLocation EndLoc) { 15860 return new (Context) OMPReleaseClause(StartLoc, EndLoc); 15861 } 15862 15863 OMPClause *Sema::ActOnOpenMPRelaxedClause(SourceLocation StartLoc, 15864 SourceLocation EndLoc) { 15865 return new (Context) OMPRelaxedClause(StartLoc, EndLoc); 15866 } 15867 15868 OMPClause *Sema::ActOnOpenMPThreadsClause(SourceLocation StartLoc, 15869 SourceLocation EndLoc) { 15870 return new (Context) OMPThreadsClause(StartLoc, EndLoc); 15871 } 15872 15873 OMPClause *Sema::ActOnOpenMPSIMDClause(SourceLocation StartLoc, 15874 SourceLocation EndLoc) { 15875 return new (Context) OMPSIMDClause(StartLoc, EndLoc); 15876 } 15877 15878 OMPClause *Sema::ActOnOpenMPNogroupClause(SourceLocation StartLoc, 15879 SourceLocation EndLoc) { 15880 return new (Context) OMPNogroupClause(StartLoc, EndLoc); 15881 } 15882 15883 OMPClause *Sema::ActOnOpenMPUnifiedAddressClause(SourceLocation StartLoc, 15884 SourceLocation EndLoc) { 15885 return new (Context) OMPUnifiedAddressClause(StartLoc, EndLoc); 15886 } 15887 15888 OMPClause *Sema::ActOnOpenMPUnifiedSharedMemoryClause(SourceLocation StartLoc, 15889 SourceLocation EndLoc) { 15890 return new (Context) OMPUnifiedSharedMemoryClause(StartLoc, EndLoc); 15891 } 15892 15893 OMPClause *Sema::ActOnOpenMPReverseOffloadClause(SourceLocation StartLoc, 15894 SourceLocation EndLoc) { 15895 return new (Context) OMPReverseOffloadClause(StartLoc, EndLoc); 15896 } 15897 15898 OMPClause *Sema::ActOnOpenMPDynamicAllocatorsClause(SourceLocation StartLoc, 15899 SourceLocation EndLoc) { 15900 return new (Context) OMPDynamicAllocatorsClause(StartLoc, EndLoc); 15901 } 15902 15903 StmtResult Sema::ActOnOpenMPInteropDirective(ArrayRef<OMPClause *> Clauses, 15904 SourceLocation StartLoc, 15905 SourceLocation EndLoc) { 15906 15907 // OpenMP 5.1 [2.15.1, interop Construct, Restrictions] 15908 // At least one action-clause must appear on a directive. 15909 if (!hasClauses(Clauses, OMPC_init, OMPC_use, OMPC_destroy, OMPC_nowait)) { 15910 StringRef Expected = "'init', 'use', 'destroy', or 'nowait'"; 15911 Diag(StartLoc, diag::err_omp_no_clause_for_directive) 15912 << Expected << getOpenMPDirectiveName(OMPD_interop); 15913 return StmtError(); 15914 } 15915 15916 // OpenMP 5.1 [2.15.1, interop Construct, Restrictions] 15917 // A depend clause can only appear on the directive if a targetsync 15918 // interop-type is present or the interop-var was initialized with 15919 // the targetsync interop-type. 15920 15921 // If there is any 'init' clause diagnose if there is no 'init' clause with 15922 // interop-type of 'targetsync'. Cases involving other directives cannot be 15923 // diagnosed. 15924 const OMPDependClause *DependClause = nullptr; 15925 bool HasInitClause = false; 15926 bool IsTargetSync = false; 15927 for (const OMPClause *C : Clauses) { 15928 if (IsTargetSync) 15929 break; 15930 if (const auto *InitClause = dyn_cast<OMPInitClause>(C)) { 15931 HasInitClause = true; 15932 if (InitClause->getIsTargetSync()) 15933 IsTargetSync = true; 15934 } else if (const auto *DC = dyn_cast<OMPDependClause>(C)) { 15935 DependClause = DC; 15936 } 15937 } 15938 if (DependClause && HasInitClause && !IsTargetSync) { 15939 Diag(DependClause->getBeginLoc(), diag::err_omp_interop_bad_depend_clause); 15940 return StmtError(); 15941 } 15942 15943 // OpenMP 5.1 [2.15.1, interop Construct, Restrictions] 15944 // Each interop-var may be specified for at most one action-clause of each 15945 // interop construct. 15946 llvm::SmallPtrSet<const VarDecl *, 4> InteropVars; 15947 for (const OMPClause *C : Clauses) { 15948 OpenMPClauseKind ClauseKind = C->getClauseKind(); 15949 const DeclRefExpr *DRE = nullptr; 15950 SourceLocation VarLoc; 15951 15952 if (ClauseKind == OMPC_init) { 15953 const auto *IC = cast<OMPInitClause>(C); 15954 VarLoc = IC->getVarLoc(); 15955 DRE = dyn_cast_or_null<DeclRefExpr>(IC->getInteropVar()); 15956 } else if (ClauseKind == OMPC_use) { 15957 const auto *UC = cast<OMPUseClause>(C); 15958 VarLoc = UC->getVarLoc(); 15959 DRE = dyn_cast_or_null<DeclRefExpr>(UC->getInteropVar()); 15960 } else if (ClauseKind == OMPC_destroy) { 15961 const auto *DC = cast<OMPDestroyClause>(C); 15962 VarLoc = DC->getVarLoc(); 15963 DRE = dyn_cast_or_null<DeclRefExpr>(DC->getInteropVar()); 15964 } 15965 15966 if (!DRE) 15967 continue; 15968 15969 if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) { 15970 if (!InteropVars.insert(VD->getCanonicalDecl()).second) { 15971 Diag(VarLoc, diag::err_omp_interop_var_multiple_actions) << VD; 15972 return StmtError(); 15973 } 15974 } 15975 } 15976 15977 return OMPInteropDirective::Create(Context, StartLoc, EndLoc, Clauses); 15978 } 15979 15980 static bool isValidInteropVariable(Sema &SemaRef, Expr *InteropVarExpr, 15981 SourceLocation VarLoc, 15982 OpenMPClauseKind Kind) { 15983 if (InteropVarExpr->isValueDependent() || InteropVarExpr->isTypeDependent() || 15984 InteropVarExpr->isInstantiationDependent() || 15985 InteropVarExpr->containsUnexpandedParameterPack()) 15986 return true; 15987 15988 const auto *DRE = dyn_cast<DeclRefExpr>(InteropVarExpr); 15989 if (!DRE || !isa<VarDecl>(DRE->getDecl())) { 15990 SemaRef.Diag(VarLoc, diag::err_omp_interop_variable_expected) << 0; 15991 return false; 15992 } 15993 15994 // Interop variable should be of type omp_interop_t. 15995 bool HasError = false; 15996 QualType InteropType; 15997 LookupResult Result(SemaRef, &SemaRef.Context.Idents.get("omp_interop_t"), 15998 VarLoc, Sema::LookupOrdinaryName); 15999 if (SemaRef.LookupName(Result, SemaRef.getCurScope())) { 16000 NamedDecl *ND = Result.getFoundDecl(); 16001 if (const auto *TD = dyn_cast<TypeDecl>(ND)) { 16002 InteropType = QualType(TD->getTypeForDecl(), 0); 16003 } else { 16004 HasError = true; 16005 } 16006 } else { 16007 HasError = true; 16008 } 16009 16010 if (HasError) { 16011 SemaRef.Diag(VarLoc, diag::err_omp_implied_type_not_found) 16012 << "omp_interop_t"; 16013 return false; 16014 } 16015 16016 QualType VarType = InteropVarExpr->getType().getUnqualifiedType(); 16017 if (!SemaRef.Context.hasSameType(InteropType, VarType)) { 16018 SemaRef.Diag(VarLoc, diag::err_omp_interop_variable_wrong_type); 16019 return false; 16020 } 16021 16022 // OpenMP 5.1 [2.15.1, interop Construct, Restrictions] 16023 // The interop-var passed to init or destroy must be non-const. 16024 if ((Kind == OMPC_init || Kind == OMPC_destroy) && 16025 isConstNotMutableType(SemaRef, InteropVarExpr->getType())) { 16026 SemaRef.Diag(VarLoc, diag::err_omp_interop_variable_expected) 16027 << /*non-const*/ 1; 16028 return false; 16029 } 16030 return true; 16031 } 16032 16033 OMPClause * 16034 Sema::ActOnOpenMPInitClause(Expr *InteropVar, ArrayRef<Expr *> PrefExprs, 16035 bool IsTarget, bool IsTargetSync, 16036 SourceLocation StartLoc, SourceLocation LParenLoc, 16037 SourceLocation VarLoc, SourceLocation EndLoc) { 16038 16039 if (!isValidInteropVariable(*this, InteropVar, VarLoc, OMPC_init)) 16040 return nullptr; 16041 16042 // Check prefer_type values. These foreign-runtime-id values are either 16043 // string literals or constant integral expressions. 16044 for (const Expr *E : PrefExprs) { 16045 if (E->isValueDependent() || E->isTypeDependent() || 16046 E->isInstantiationDependent() || E->containsUnexpandedParameterPack()) 16047 continue; 16048 if (E->isIntegerConstantExpr(Context)) 16049 continue; 16050 if (isa<StringLiteral>(E)) 16051 continue; 16052 Diag(E->getExprLoc(), diag::err_omp_interop_prefer_type); 16053 return nullptr; 16054 } 16055 16056 return OMPInitClause::Create(Context, InteropVar, PrefExprs, IsTarget, 16057 IsTargetSync, StartLoc, LParenLoc, VarLoc, 16058 EndLoc); 16059 } 16060 16061 OMPClause *Sema::ActOnOpenMPUseClause(Expr *InteropVar, SourceLocation StartLoc, 16062 SourceLocation LParenLoc, 16063 SourceLocation VarLoc, 16064 SourceLocation EndLoc) { 16065 16066 if (!isValidInteropVariable(*this, InteropVar, VarLoc, OMPC_use)) 16067 return nullptr; 16068 16069 return new (Context) 16070 OMPUseClause(InteropVar, StartLoc, LParenLoc, VarLoc, EndLoc); 16071 } 16072 16073 OMPClause *Sema::ActOnOpenMPDestroyClause(Expr *InteropVar, 16074 SourceLocation StartLoc, 16075 SourceLocation LParenLoc, 16076 SourceLocation VarLoc, 16077 SourceLocation EndLoc) { 16078 if (InteropVar && 16079 !isValidInteropVariable(*this, InteropVar, VarLoc, OMPC_destroy)) 16080 return nullptr; 16081 16082 return new (Context) 16083 OMPDestroyClause(InteropVar, StartLoc, LParenLoc, VarLoc, EndLoc); 16084 } 16085 16086 OMPClause *Sema::ActOnOpenMPNovariantsClause(Expr *Condition, 16087 SourceLocation StartLoc, 16088 SourceLocation LParenLoc, 16089 SourceLocation EndLoc) { 16090 Expr *ValExpr = Condition; 16091 Stmt *HelperValStmt = nullptr; 16092 OpenMPDirectiveKind CaptureRegion = OMPD_unknown; 16093 if (!Condition->isValueDependent() && !Condition->isTypeDependent() && 16094 !Condition->isInstantiationDependent() && 16095 !Condition->containsUnexpandedParameterPack()) { 16096 ExprResult Val = CheckBooleanCondition(StartLoc, Condition); 16097 if (Val.isInvalid()) 16098 return nullptr; 16099 16100 ValExpr = MakeFullExpr(Val.get()).get(); 16101 16102 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective(); 16103 CaptureRegion = getOpenMPCaptureRegionForClause(DKind, OMPC_novariants, 16104 LangOpts.OpenMP); 16105 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) { 16106 ValExpr = MakeFullExpr(ValExpr).get(); 16107 llvm::MapVector<const Expr *, DeclRefExpr *> Captures; 16108 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 16109 HelperValStmt = buildPreInits(Context, Captures); 16110 } 16111 } 16112 16113 return new (Context) OMPNovariantsClause( 16114 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc); 16115 } 16116 16117 OMPClause *Sema::ActOnOpenMPNocontextClause(Expr *Condition, 16118 SourceLocation StartLoc, 16119 SourceLocation LParenLoc, 16120 SourceLocation EndLoc) { 16121 Expr *ValExpr = Condition; 16122 Stmt *HelperValStmt = nullptr; 16123 OpenMPDirectiveKind CaptureRegion = OMPD_unknown; 16124 if (!Condition->isValueDependent() && !Condition->isTypeDependent() && 16125 !Condition->isInstantiationDependent() && 16126 !Condition->containsUnexpandedParameterPack()) { 16127 ExprResult Val = CheckBooleanCondition(StartLoc, Condition); 16128 if (Val.isInvalid()) 16129 return nullptr; 16130 16131 ValExpr = MakeFullExpr(Val.get()).get(); 16132 16133 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective(); 16134 CaptureRegion = 16135 getOpenMPCaptureRegionForClause(DKind, OMPC_nocontext, LangOpts.OpenMP); 16136 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) { 16137 ValExpr = MakeFullExpr(ValExpr).get(); 16138 llvm::MapVector<const Expr *, DeclRefExpr *> Captures; 16139 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 16140 HelperValStmt = buildPreInits(Context, Captures); 16141 } 16142 } 16143 16144 return new (Context) OMPNocontextClause(ValExpr, HelperValStmt, CaptureRegion, 16145 StartLoc, LParenLoc, EndLoc); 16146 } 16147 16148 OMPClause *Sema::ActOnOpenMPFilterClause(Expr *ThreadID, 16149 SourceLocation StartLoc, 16150 SourceLocation LParenLoc, 16151 SourceLocation EndLoc) { 16152 Expr *ValExpr = ThreadID; 16153 Stmt *HelperValStmt = nullptr; 16154 16155 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective(); 16156 OpenMPDirectiveKind CaptureRegion = 16157 getOpenMPCaptureRegionForClause(DKind, OMPC_filter, LangOpts.OpenMP); 16158 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) { 16159 ValExpr = MakeFullExpr(ValExpr).get(); 16160 llvm::MapVector<const Expr *, DeclRefExpr *> Captures; 16161 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 16162 HelperValStmt = buildPreInits(Context, Captures); 16163 } 16164 16165 return new (Context) OMPFilterClause(ValExpr, HelperValStmt, CaptureRegion, 16166 StartLoc, LParenLoc, EndLoc); 16167 } 16168 16169 OMPClause *Sema::ActOnOpenMPVarListClause( 16170 OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *DepModOrTailExpr, 16171 const OMPVarListLocTy &Locs, SourceLocation ColonLoc, 16172 CXXScopeSpec &ReductionOrMapperIdScopeSpec, 16173 DeclarationNameInfo &ReductionOrMapperId, int ExtraModifier, 16174 ArrayRef<OpenMPMapModifierKind> MapTypeModifiers, 16175 ArrayRef<SourceLocation> MapTypeModifiersLoc, bool IsMapTypeImplicit, 16176 SourceLocation ExtraModifierLoc, 16177 ArrayRef<OpenMPMotionModifierKind> MotionModifiers, 16178 ArrayRef<SourceLocation> MotionModifiersLoc) { 16179 SourceLocation StartLoc = Locs.StartLoc; 16180 SourceLocation LParenLoc = Locs.LParenLoc; 16181 SourceLocation EndLoc = Locs.EndLoc; 16182 OMPClause *Res = nullptr; 16183 switch (Kind) { 16184 case OMPC_private: 16185 Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc); 16186 break; 16187 case OMPC_firstprivate: 16188 Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc); 16189 break; 16190 case OMPC_lastprivate: 16191 assert(0 <= ExtraModifier && ExtraModifier <= OMPC_LASTPRIVATE_unknown && 16192 "Unexpected lastprivate modifier."); 16193 Res = ActOnOpenMPLastprivateClause( 16194 VarList, static_cast<OpenMPLastprivateModifier>(ExtraModifier), 16195 ExtraModifierLoc, ColonLoc, StartLoc, LParenLoc, EndLoc); 16196 break; 16197 case OMPC_shared: 16198 Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc); 16199 break; 16200 case OMPC_reduction: 16201 assert(0 <= ExtraModifier && ExtraModifier <= OMPC_REDUCTION_unknown && 16202 "Unexpected lastprivate modifier."); 16203 Res = ActOnOpenMPReductionClause( 16204 VarList, static_cast<OpenMPReductionClauseModifier>(ExtraModifier), 16205 StartLoc, LParenLoc, ExtraModifierLoc, ColonLoc, EndLoc, 16206 ReductionOrMapperIdScopeSpec, ReductionOrMapperId); 16207 break; 16208 case OMPC_task_reduction: 16209 Res = ActOnOpenMPTaskReductionClause(VarList, StartLoc, LParenLoc, ColonLoc, 16210 EndLoc, ReductionOrMapperIdScopeSpec, 16211 ReductionOrMapperId); 16212 break; 16213 case OMPC_in_reduction: 16214 Res = ActOnOpenMPInReductionClause(VarList, StartLoc, LParenLoc, ColonLoc, 16215 EndLoc, ReductionOrMapperIdScopeSpec, 16216 ReductionOrMapperId); 16217 break; 16218 case OMPC_linear: 16219 assert(0 <= ExtraModifier && ExtraModifier <= OMPC_LINEAR_unknown && 16220 "Unexpected linear modifier."); 16221 Res = ActOnOpenMPLinearClause( 16222 VarList, DepModOrTailExpr, StartLoc, LParenLoc, 16223 static_cast<OpenMPLinearClauseKind>(ExtraModifier), ExtraModifierLoc, 16224 ColonLoc, EndLoc); 16225 break; 16226 case OMPC_aligned: 16227 Res = ActOnOpenMPAlignedClause(VarList, DepModOrTailExpr, StartLoc, 16228 LParenLoc, ColonLoc, EndLoc); 16229 break; 16230 case OMPC_copyin: 16231 Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc); 16232 break; 16233 case OMPC_copyprivate: 16234 Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc); 16235 break; 16236 case OMPC_flush: 16237 Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc); 16238 break; 16239 case OMPC_depend: 16240 assert(0 <= ExtraModifier && ExtraModifier <= OMPC_DEPEND_unknown && 16241 "Unexpected depend modifier."); 16242 Res = ActOnOpenMPDependClause( 16243 DepModOrTailExpr, static_cast<OpenMPDependClauseKind>(ExtraModifier), 16244 ExtraModifierLoc, ColonLoc, VarList, StartLoc, LParenLoc, EndLoc); 16245 break; 16246 case OMPC_map: 16247 assert(0 <= ExtraModifier && ExtraModifier <= OMPC_MAP_unknown && 16248 "Unexpected map modifier."); 16249 Res = ActOnOpenMPMapClause( 16250 MapTypeModifiers, MapTypeModifiersLoc, ReductionOrMapperIdScopeSpec, 16251 ReductionOrMapperId, static_cast<OpenMPMapClauseKind>(ExtraModifier), 16252 IsMapTypeImplicit, ExtraModifierLoc, ColonLoc, VarList, Locs); 16253 break; 16254 case OMPC_to: 16255 Res = ActOnOpenMPToClause(MotionModifiers, MotionModifiersLoc, 16256 ReductionOrMapperIdScopeSpec, ReductionOrMapperId, 16257 ColonLoc, VarList, Locs); 16258 break; 16259 case OMPC_from: 16260 Res = ActOnOpenMPFromClause(MotionModifiers, MotionModifiersLoc, 16261 ReductionOrMapperIdScopeSpec, 16262 ReductionOrMapperId, ColonLoc, VarList, Locs); 16263 break; 16264 case OMPC_use_device_ptr: 16265 Res = ActOnOpenMPUseDevicePtrClause(VarList, Locs); 16266 break; 16267 case OMPC_use_device_addr: 16268 Res = ActOnOpenMPUseDeviceAddrClause(VarList, Locs); 16269 break; 16270 case OMPC_is_device_ptr: 16271 Res = ActOnOpenMPIsDevicePtrClause(VarList, Locs); 16272 break; 16273 case OMPC_allocate: 16274 Res = ActOnOpenMPAllocateClause(DepModOrTailExpr, VarList, StartLoc, 16275 LParenLoc, ColonLoc, EndLoc); 16276 break; 16277 case OMPC_nontemporal: 16278 Res = ActOnOpenMPNontemporalClause(VarList, StartLoc, LParenLoc, EndLoc); 16279 break; 16280 case OMPC_inclusive: 16281 Res = ActOnOpenMPInclusiveClause(VarList, StartLoc, LParenLoc, EndLoc); 16282 break; 16283 case OMPC_exclusive: 16284 Res = ActOnOpenMPExclusiveClause(VarList, StartLoc, LParenLoc, EndLoc); 16285 break; 16286 case OMPC_affinity: 16287 Res = ActOnOpenMPAffinityClause(StartLoc, LParenLoc, ColonLoc, EndLoc, 16288 DepModOrTailExpr, VarList); 16289 break; 16290 case OMPC_if: 16291 case OMPC_depobj: 16292 case OMPC_final: 16293 case OMPC_num_threads: 16294 case OMPC_safelen: 16295 case OMPC_simdlen: 16296 case OMPC_sizes: 16297 case OMPC_allocator: 16298 case OMPC_collapse: 16299 case OMPC_default: 16300 case OMPC_proc_bind: 16301 case OMPC_schedule: 16302 case OMPC_ordered: 16303 case OMPC_nowait: 16304 case OMPC_untied: 16305 case OMPC_mergeable: 16306 case OMPC_threadprivate: 16307 case OMPC_read: 16308 case OMPC_write: 16309 case OMPC_update: 16310 case OMPC_capture: 16311 case OMPC_compare: 16312 case OMPC_seq_cst: 16313 case OMPC_acq_rel: 16314 case OMPC_acquire: 16315 case OMPC_release: 16316 case OMPC_relaxed: 16317 case OMPC_device: 16318 case OMPC_threads: 16319 case OMPC_simd: 16320 case OMPC_num_teams: 16321 case OMPC_thread_limit: 16322 case OMPC_priority: 16323 case OMPC_grainsize: 16324 case OMPC_nogroup: 16325 case OMPC_num_tasks: 16326 case OMPC_hint: 16327 case OMPC_dist_schedule: 16328 case OMPC_defaultmap: 16329 case OMPC_unknown: 16330 case OMPC_uniform: 16331 case OMPC_unified_address: 16332 case OMPC_unified_shared_memory: 16333 case OMPC_reverse_offload: 16334 case OMPC_dynamic_allocators: 16335 case OMPC_atomic_default_mem_order: 16336 case OMPC_device_type: 16337 case OMPC_match: 16338 case OMPC_order: 16339 case OMPC_destroy: 16340 case OMPC_novariants: 16341 case OMPC_nocontext: 16342 case OMPC_detach: 16343 case OMPC_uses_allocators: 16344 case OMPC_when: 16345 case OMPC_bind: 16346 default: 16347 llvm_unreachable("Clause is not allowed."); 16348 } 16349 return Res; 16350 } 16351 16352 ExprResult Sema::getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK, 16353 ExprObjectKind OK, SourceLocation Loc) { 16354 ExprResult Res = BuildDeclRefExpr( 16355 Capture, Capture->getType().getNonReferenceType(), VK_LValue, Loc); 16356 if (!Res.isUsable()) 16357 return ExprError(); 16358 if (OK == OK_Ordinary && !getLangOpts().CPlusPlus) { 16359 Res = CreateBuiltinUnaryOp(Loc, UO_Deref, Res.get()); 16360 if (!Res.isUsable()) 16361 return ExprError(); 16362 } 16363 if (VK != VK_LValue && Res.get()->isGLValue()) { 16364 Res = DefaultLvalueConversion(Res.get()); 16365 if (!Res.isUsable()) 16366 return ExprError(); 16367 } 16368 return Res; 16369 } 16370 16371 OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList, 16372 SourceLocation StartLoc, 16373 SourceLocation LParenLoc, 16374 SourceLocation EndLoc) { 16375 SmallVector<Expr *, 8> Vars; 16376 SmallVector<Expr *, 8> PrivateCopies; 16377 for (Expr *RefExpr : VarList) { 16378 assert(RefExpr && "NULL expr in OpenMP private clause."); 16379 SourceLocation ELoc; 16380 SourceRange ERange; 16381 Expr *SimpleRefExpr = RefExpr; 16382 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 16383 if (Res.second) { 16384 // It will be analyzed later. 16385 Vars.push_back(RefExpr); 16386 PrivateCopies.push_back(nullptr); 16387 } 16388 ValueDecl *D = Res.first; 16389 if (!D) 16390 continue; 16391 16392 QualType Type = D->getType(); 16393 auto *VD = dyn_cast<VarDecl>(D); 16394 16395 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3] 16396 // A variable that appears in a private clause must not have an incomplete 16397 // type or a reference type. 16398 if (RequireCompleteType(ELoc, Type, diag::err_omp_private_incomplete_type)) 16399 continue; 16400 Type = Type.getNonReferenceType(); 16401 16402 // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions] 16403 // A variable that is privatized must not have a const-qualified type 16404 // unless it is of class type with a mutable member. This restriction does 16405 // not apply to the firstprivate clause. 16406 // 16407 // OpenMP 3.1 [2.9.3.3, private clause, Restrictions] 16408 // A variable that appears in a private clause must not have a 16409 // const-qualified type unless it is of class type with a mutable member. 16410 if (rejectConstNotMutableType(*this, D, Type, OMPC_private, ELoc)) 16411 continue; 16412 16413 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 16414 // in a Construct] 16415 // Variables with the predetermined data-sharing attributes may not be 16416 // listed in data-sharing attributes clauses, except for the cases 16417 // listed below. For these exceptions only, listing a predetermined 16418 // variable in a data-sharing attribute clause is allowed and overrides 16419 // the variable's predetermined data-sharing attributes. 16420 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false); 16421 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) { 16422 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind) 16423 << getOpenMPClauseName(OMPC_private); 16424 reportOriginalDsa(*this, DSAStack, D, DVar); 16425 continue; 16426 } 16427 16428 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective(); 16429 // Variably modified types are not supported for tasks. 16430 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() && 16431 isOpenMPTaskingDirective(CurrDir)) { 16432 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported) 16433 << getOpenMPClauseName(OMPC_private) << Type 16434 << getOpenMPDirectiveName(CurrDir); 16435 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) == 16436 VarDecl::DeclarationOnly; 16437 Diag(D->getLocation(), 16438 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 16439 << D; 16440 continue; 16441 } 16442 16443 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3] 16444 // A list item cannot appear in both a map clause and a data-sharing 16445 // attribute clause on the same construct 16446 // 16447 // OpenMP 5.0 [2.19.7.1, Restrictions, p.7] 16448 // A list item cannot appear in both a map clause and a data-sharing 16449 // attribute clause on the same construct unless the construct is a 16450 // combined construct. 16451 if ((LangOpts.OpenMP <= 45 && isOpenMPTargetExecutionDirective(CurrDir)) || 16452 CurrDir == OMPD_target) { 16453 OpenMPClauseKind ConflictKind; 16454 if (DSAStack->checkMappableExprComponentListsForDecl( 16455 VD, /*CurrentRegionOnly=*/true, 16456 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef, 16457 OpenMPClauseKind WhereFoundClauseKind) -> bool { 16458 ConflictKind = WhereFoundClauseKind; 16459 return true; 16460 })) { 16461 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa) 16462 << getOpenMPClauseName(OMPC_private) 16463 << getOpenMPClauseName(ConflictKind) 16464 << getOpenMPDirectiveName(CurrDir); 16465 reportOriginalDsa(*this, DSAStack, D, DVar); 16466 continue; 16467 } 16468 } 16469 16470 // OpenMP [2.9.3.3, Restrictions, C/C++, p.1] 16471 // A variable of class type (or array thereof) that appears in a private 16472 // clause requires an accessible, unambiguous default constructor for the 16473 // class type. 16474 // Generate helper private variable and initialize it with the default 16475 // value. The address of the original variable is replaced by the address of 16476 // the new private variable in CodeGen. This new variable is not added to 16477 // IdResolver, so the code in the OpenMP region uses original variable for 16478 // proper diagnostics. 16479 Type = Type.getUnqualifiedType(); 16480 VarDecl *VDPrivate = 16481 buildVarDecl(*this, ELoc, Type, D->getName(), 16482 D->hasAttrs() ? &D->getAttrs() : nullptr, 16483 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr); 16484 ActOnUninitializedDecl(VDPrivate); 16485 if (VDPrivate->isInvalidDecl()) 16486 continue; 16487 DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr( 16488 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc); 16489 16490 DeclRefExpr *Ref = nullptr; 16491 if (!VD && !CurContext->isDependentContext()) 16492 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false); 16493 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_private, Ref); 16494 Vars.push_back((VD || CurContext->isDependentContext()) 16495 ? RefExpr->IgnoreParens() 16496 : Ref); 16497 PrivateCopies.push_back(VDPrivateRefExpr); 16498 } 16499 16500 if (Vars.empty()) 16501 return nullptr; 16502 16503 return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars, 16504 PrivateCopies); 16505 } 16506 16507 OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList, 16508 SourceLocation StartLoc, 16509 SourceLocation LParenLoc, 16510 SourceLocation EndLoc) { 16511 SmallVector<Expr *, 8> Vars; 16512 SmallVector<Expr *, 8> PrivateCopies; 16513 SmallVector<Expr *, 8> Inits; 16514 SmallVector<Decl *, 4> ExprCaptures; 16515 bool IsImplicitClause = 16516 StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid(); 16517 SourceLocation ImplicitClauseLoc = DSAStack->getConstructLoc(); 16518 16519 for (Expr *RefExpr : VarList) { 16520 assert(RefExpr && "NULL expr in OpenMP firstprivate clause."); 16521 SourceLocation ELoc; 16522 SourceRange ERange; 16523 Expr *SimpleRefExpr = RefExpr; 16524 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 16525 if (Res.second) { 16526 // It will be analyzed later. 16527 Vars.push_back(RefExpr); 16528 PrivateCopies.push_back(nullptr); 16529 Inits.push_back(nullptr); 16530 } 16531 ValueDecl *D = Res.first; 16532 if (!D) 16533 continue; 16534 16535 ELoc = IsImplicitClause ? ImplicitClauseLoc : ELoc; 16536 QualType Type = D->getType(); 16537 auto *VD = dyn_cast<VarDecl>(D); 16538 16539 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3] 16540 // A variable that appears in a private clause must not have an incomplete 16541 // type or a reference type. 16542 if (RequireCompleteType(ELoc, Type, 16543 diag::err_omp_firstprivate_incomplete_type)) 16544 continue; 16545 Type = Type.getNonReferenceType(); 16546 16547 // OpenMP [2.9.3.4, Restrictions, C/C++, p.1] 16548 // A variable of class type (or array thereof) that appears in a private 16549 // clause requires an accessible, unambiguous copy constructor for the 16550 // class type. 16551 QualType ElemType = Context.getBaseElementType(Type).getNonReferenceType(); 16552 16553 // If an implicit firstprivate variable found it was checked already. 16554 DSAStackTy::DSAVarData TopDVar; 16555 if (!IsImplicitClause) { 16556 DSAStackTy::DSAVarData DVar = 16557 DSAStack->getTopDSA(D, /*FromParent=*/false); 16558 TopDVar = DVar; 16559 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective(); 16560 bool IsConstant = ElemType.isConstant(Context); 16561 // OpenMP [2.4.13, Data-sharing Attribute Clauses] 16562 // A list item that specifies a given variable may not appear in more 16563 // than one clause on the same directive, except that a variable may be 16564 // specified in both firstprivate and lastprivate clauses. 16565 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3] 16566 // A list item may appear in a firstprivate or lastprivate clause but not 16567 // both. 16568 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate && 16569 (isOpenMPDistributeDirective(CurrDir) || 16570 DVar.CKind != OMPC_lastprivate) && 16571 DVar.RefExpr) { 16572 Diag(ELoc, diag::err_omp_wrong_dsa) 16573 << getOpenMPClauseName(DVar.CKind) 16574 << getOpenMPClauseName(OMPC_firstprivate); 16575 reportOriginalDsa(*this, DSAStack, D, DVar); 16576 continue; 16577 } 16578 16579 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 16580 // in a Construct] 16581 // Variables with the predetermined data-sharing attributes may not be 16582 // listed in data-sharing attributes clauses, except for the cases 16583 // listed below. For these exceptions only, listing a predetermined 16584 // variable in a data-sharing attribute clause is allowed and overrides 16585 // the variable's predetermined data-sharing attributes. 16586 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 16587 // in a Construct, C/C++, p.2] 16588 // Variables with const-qualified type having no mutable member may be 16589 // listed in a firstprivate clause, even if they are static data members. 16590 if (!(IsConstant || (VD && VD->isStaticDataMember())) && !DVar.RefExpr && 16591 DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) { 16592 Diag(ELoc, diag::err_omp_wrong_dsa) 16593 << getOpenMPClauseName(DVar.CKind) 16594 << getOpenMPClauseName(OMPC_firstprivate); 16595 reportOriginalDsa(*this, DSAStack, D, DVar); 16596 continue; 16597 } 16598 16599 // OpenMP [2.9.3.4, Restrictions, p.2] 16600 // A list item that is private within a parallel region must not appear 16601 // in a firstprivate clause on a worksharing construct if any of the 16602 // worksharing regions arising from the worksharing construct ever bind 16603 // to any of the parallel regions arising from the parallel construct. 16604 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3] 16605 // A list item that is private within a teams region must not appear in a 16606 // firstprivate clause on a distribute construct if any of the distribute 16607 // regions arising from the distribute construct ever bind to any of the 16608 // teams regions arising from the teams construct. 16609 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3] 16610 // A list item that appears in a reduction clause of a teams construct 16611 // must not appear in a firstprivate clause on a distribute construct if 16612 // any of the distribute regions arising from the distribute construct 16613 // ever bind to any of the teams regions arising from the teams construct. 16614 if ((isOpenMPWorksharingDirective(CurrDir) || 16615 isOpenMPDistributeDirective(CurrDir)) && 16616 !isOpenMPParallelDirective(CurrDir) && 16617 !isOpenMPTeamsDirective(CurrDir)) { 16618 DVar = DSAStack->getImplicitDSA(D, true); 16619 if (DVar.CKind != OMPC_shared && 16620 (isOpenMPParallelDirective(DVar.DKind) || 16621 isOpenMPTeamsDirective(DVar.DKind) || 16622 DVar.DKind == OMPD_unknown)) { 16623 Diag(ELoc, diag::err_omp_required_access) 16624 << getOpenMPClauseName(OMPC_firstprivate) 16625 << getOpenMPClauseName(OMPC_shared); 16626 reportOriginalDsa(*this, DSAStack, D, DVar); 16627 continue; 16628 } 16629 } 16630 // OpenMP [2.9.3.4, Restrictions, p.3] 16631 // A list item that appears in a reduction clause of a parallel construct 16632 // must not appear in a firstprivate clause on a worksharing or task 16633 // construct if any of the worksharing or task regions arising from the 16634 // worksharing or task construct ever bind to any of the parallel regions 16635 // arising from the parallel construct. 16636 // OpenMP [2.9.3.4, Restrictions, p.4] 16637 // A list item that appears in a reduction clause in worksharing 16638 // construct must not appear in a firstprivate clause in a task construct 16639 // encountered during execution of any of the worksharing regions arising 16640 // from the worksharing construct. 16641 if (isOpenMPTaskingDirective(CurrDir)) { 16642 DVar = DSAStack->hasInnermostDSA( 16643 D, 16644 [](OpenMPClauseKind C, bool AppliedToPointee) { 16645 return C == OMPC_reduction && !AppliedToPointee; 16646 }, 16647 [](OpenMPDirectiveKind K) { 16648 return isOpenMPParallelDirective(K) || 16649 isOpenMPWorksharingDirective(K) || 16650 isOpenMPTeamsDirective(K); 16651 }, 16652 /*FromParent=*/true); 16653 if (DVar.CKind == OMPC_reduction && 16654 (isOpenMPParallelDirective(DVar.DKind) || 16655 isOpenMPWorksharingDirective(DVar.DKind) || 16656 isOpenMPTeamsDirective(DVar.DKind))) { 16657 Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate) 16658 << getOpenMPDirectiveName(DVar.DKind); 16659 reportOriginalDsa(*this, DSAStack, D, DVar); 16660 continue; 16661 } 16662 } 16663 16664 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3] 16665 // A list item cannot appear in both a map clause and a data-sharing 16666 // attribute clause on the same construct 16667 // 16668 // OpenMP 5.0 [2.19.7.1, Restrictions, p.7] 16669 // A list item cannot appear in both a map clause and a data-sharing 16670 // attribute clause on the same construct unless the construct is a 16671 // combined construct. 16672 if ((LangOpts.OpenMP <= 45 && 16673 isOpenMPTargetExecutionDirective(CurrDir)) || 16674 CurrDir == OMPD_target) { 16675 OpenMPClauseKind ConflictKind; 16676 if (DSAStack->checkMappableExprComponentListsForDecl( 16677 VD, /*CurrentRegionOnly=*/true, 16678 [&ConflictKind]( 16679 OMPClauseMappableExprCommon::MappableExprComponentListRef, 16680 OpenMPClauseKind WhereFoundClauseKind) { 16681 ConflictKind = WhereFoundClauseKind; 16682 return true; 16683 })) { 16684 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa) 16685 << getOpenMPClauseName(OMPC_firstprivate) 16686 << getOpenMPClauseName(ConflictKind) 16687 << getOpenMPDirectiveName(DSAStack->getCurrentDirective()); 16688 reportOriginalDsa(*this, DSAStack, D, DVar); 16689 continue; 16690 } 16691 } 16692 } 16693 16694 // Variably modified types are not supported for tasks. 16695 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() && 16696 isOpenMPTaskingDirective(DSAStack->getCurrentDirective())) { 16697 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported) 16698 << getOpenMPClauseName(OMPC_firstprivate) << Type 16699 << getOpenMPDirectiveName(DSAStack->getCurrentDirective()); 16700 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) == 16701 VarDecl::DeclarationOnly; 16702 Diag(D->getLocation(), 16703 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 16704 << D; 16705 continue; 16706 } 16707 16708 Type = Type.getUnqualifiedType(); 16709 VarDecl *VDPrivate = 16710 buildVarDecl(*this, ELoc, Type, D->getName(), 16711 D->hasAttrs() ? &D->getAttrs() : nullptr, 16712 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr); 16713 // Generate helper private variable and initialize it with the value of the 16714 // original variable. The address of the original variable is replaced by 16715 // the address of the new private variable in the CodeGen. This new variable 16716 // is not added to IdResolver, so the code in the OpenMP region uses 16717 // original variable for proper diagnostics and variable capturing. 16718 Expr *VDInitRefExpr = nullptr; 16719 // For arrays generate initializer for single element and replace it by the 16720 // original array element in CodeGen. 16721 if (Type->isArrayType()) { 16722 VarDecl *VDInit = 16723 buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, D->getName()); 16724 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc); 16725 Expr *Init = DefaultLvalueConversion(VDInitRefExpr).get(); 16726 ElemType = ElemType.getUnqualifiedType(); 16727 VarDecl *VDInitTemp = buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, 16728 ".firstprivate.temp"); 16729 InitializedEntity Entity = 16730 InitializedEntity::InitializeVariable(VDInitTemp); 16731 InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc); 16732 16733 InitializationSequence InitSeq(*this, Entity, Kind, Init); 16734 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init); 16735 if (Result.isInvalid()) 16736 VDPrivate->setInvalidDecl(); 16737 else 16738 VDPrivate->setInit(Result.getAs<Expr>()); 16739 // Remove temp variable declaration. 16740 Context.Deallocate(VDInitTemp); 16741 } else { 16742 VarDecl *VDInit = buildVarDecl(*this, RefExpr->getExprLoc(), Type, 16743 ".firstprivate.temp"); 16744 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(), 16745 RefExpr->getExprLoc()); 16746 AddInitializerToDecl(VDPrivate, 16747 DefaultLvalueConversion(VDInitRefExpr).get(), 16748 /*DirectInit=*/false); 16749 } 16750 if (VDPrivate->isInvalidDecl()) { 16751 if (IsImplicitClause) { 16752 Diag(RefExpr->getExprLoc(), 16753 diag::note_omp_task_predetermined_firstprivate_here); 16754 } 16755 continue; 16756 } 16757 CurContext->addDecl(VDPrivate); 16758 DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr( 16759 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), 16760 RefExpr->getExprLoc()); 16761 DeclRefExpr *Ref = nullptr; 16762 if (!VD && !CurContext->isDependentContext()) { 16763 if (TopDVar.CKind == OMPC_lastprivate) { 16764 Ref = TopDVar.PrivateCopy; 16765 } else { 16766 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true); 16767 if (!isOpenMPCapturedDecl(D)) 16768 ExprCaptures.push_back(Ref->getDecl()); 16769 } 16770 } 16771 if (!IsImplicitClause) 16772 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref); 16773 Vars.push_back((VD || CurContext->isDependentContext()) 16774 ? RefExpr->IgnoreParens() 16775 : Ref); 16776 PrivateCopies.push_back(VDPrivateRefExpr); 16777 Inits.push_back(VDInitRefExpr); 16778 } 16779 16780 if (Vars.empty()) 16781 return nullptr; 16782 16783 return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, 16784 Vars, PrivateCopies, Inits, 16785 buildPreInits(Context, ExprCaptures)); 16786 } 16787 16788 OMPClause *Sema::ActOnOpenMPLastprivateClause( 16789 ArrayRef<Expr *> VarList, OpenMPLastprivateModifier LPKind, 16790 SourceLocation LPKindLoc, SourceLocation ColonLoc, SourceLocation StartLoc, 16791 SourceLocation LParenLoc, SourceLocation EndLoc) { 16792 if (LPKind == OMPC_LASTPRIVATE_unknown && LPKindLoc.isValid()) { 16793 assert(ColonLoc.isValid() && "Colon location must be valid."); 16794 Diag(LPKindLoc, diag::err_omp_unexpected_clause_value) 16795 << getListOfPossibleValues(OMPC_lastprivate, /*First=*/0, 16796 /*Last=*/OMPC_LASTPRIVATE_unknown) 16797 << getOpenMPClauseName(OMPC_lastprivate); 16798 return nullptr; 16799 } 16800 16801 SmallVector<Expr *, 8> Vars; 16802 SmallVector<Expr *, 8> SrcExprs; 16803 SmallVector<Expr *, 8> DstExprs; 16804 SmallVector<Expr *, 8> AssignmentOps; 16805 SmallVector<Decl *, 4> ExprCaptures; 16806 SmallVector<Expr *, 4> ExprPostUpdates; 16807 for (Expr *RefExpr : VarList) { 16808 assert(RefExpr && "NULL expr in OpenMP lastprivate clause."); 16809 SourceLocation ELoc; 16810 SourceRange ERange; 16811 Expr *SimpleRefExpr = RefExpr; 16812 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 16813 if (Res.second) { 16814 // It will be analyzed later. 16815 Vars.push_back(RefExpr); 16816 SrcExprs.push_back(nullptr); 16817 DstExprs.push_back(nullptr); 16818 AssignmentOps.push_back(nullptr); 16819 } 16820 ValueDecl *D = Res.first; 16821 if (!D) 16822 continue; 16823 16824 QualType Type = D->getType(); 16825 auto *VD = dyn_cast<VarDecl>(D); 16826 16827 // OpenMP [2.14.3.5, Restrictions, C/C++, p.2] 16828 // A variable that appears in a lastprivate clause must not have an 16829 // incomplete type or a reference type. 16830 if (RequireCompleteType(ELoc, Type, 16831 diag::err_omp_lastprivate_incomplete_type)) 16832 continue; 16833 Type = Type.getNonReferenceType(); 16834 16835 // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions] 16836 // A variable that is privatized must not have a const-qualified type 16837 // unless it is of class type with a mutable member. This restriction does 16838 // not apply to the firstprivate clause. 16839 // 16840 // OpenMP 3.1 [2.9.3.5, lastprivate clause, Restrictions] 16841 // A variable that appears in a lastprivate clause must not have a 16842 // const-qualified type unless it is of class type with a mutable member. 16843 if (rejectConstNotMutableType(*this, D, Type, OMPC_lastprivate, ELoc)) 16844 continue; 16845 16846 // OpenMP 5.0 [2.19.4.5 lastprivate Clause, Restrictions] 16847 // A list item that appears in a lastprivate clause with the conditional 16848 // modifier must be a scalar variable. 16849 if (LPKind == OMPC_LASTPRIVATE_conditional && !Type->isScalarType()) { 16850 Diag(ELoc, diag::err_omp_lastprivate_conditional_non_scalar); 16851 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) == 16852 VarDecl::DeclarationOnly; 16853 Diag(D->getLocation(), 16854 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 16855 << D; 16856 continue; 16857 } 16858 16859 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective(); 16860 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced 16861 // in a Construct] 16862 // Variables with the predetermined data-sharing attributes may not be 16863 // listed in data-sharing attributes clauses, except for the cases 16864 // listed below. 16865 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3] 16866 // A list item may appear in a firstprivate or lastprivate clause but not 16867 // both. 16868 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false); 16869 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate && 16870 (isOpenMPDistributeDirective(CurrDir) || 16871 DVar.CKind != OMPC_firstprivate) && 16872 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) { 16873 Diag(ELoc, diag::err_omp_wrong_dsa) 16874 << getOpenMPClauseName(DVar.CKind) 16875 << getOpenMPClauseName(OMPC_lastprivate); 16876 reportOriginalDsa(*this, DSAStack, D, DVar); 16877 continue; 16878 } 16879 16880 // OpenMP [2.14.3.5, Restrictions, p.2] 16881 // A list item that is private within a parallel region, or that appears in 16882 // the reduction clause of a parallel construct, must not appear in a 16883 // lastprivate clause on a worksharing construct if any of the corresponding 16884 // worksharing regions ever binds to any of the corresponding parallel 16885 // regions. 16886 DSAStackTy::DSAVarData TopDVar = DVar; 16887 if (isOpenMPWorksharingDirective(CurrDir) && 16888 !isOpenMPParallelDirective(CurrDir) && 16889 !isOpenMPTeamsDirective(CurrDir)) { 16890 DVar = DSAStack->getImplicitDSA(D, true); 16891 if (DVar.CKind != OMPC_shared) { 16892 Diag(ELoc, diag::err_omp_required_access) 16893 << getOpenMPClauseName(OMPC_lastprivate) 16894 << getOpenMPClauseName(OMPC_shared); 16895 reportOriginalDsa(*this, DSAStack, D, DVar); 16896 continue; 16897 } 16898 } 16899 16900 // OpenMP [2.14.3.5, Restrictions, C++, p.1,2] 16901 // A variable of class type (or array thereof) that appears in a 16902 // lastprivate clause requires an accessible, unambiguous default 16903 // constructor for the class type, unless the list item is also specified 16904 // in a firstprivate clause. 16905 // A variable of class type (or array thereof) that appears in a 16906 // lastprivate clause requires an accessible, unambiguous copy assignment 16907 // operator for the class type. 16908 Type = Context.getBaseElementType(Type).getNonReferenceType(); 16909 VarDecl *SrcVD = buildVarDecl(*this, ERange.getBegin(), 16910 Type.getUnqualifiedType(), ".lastprivate.src", 16911 D->hasAttrs() ? &D->getAttrs() : nullptr); 16912 DeclRefExpr *PseudoSrcExpr = 16913 buildDeclRefExpr(*this, SrcVD, Type.getUnqualifiedType(), ELoc); 16914 VarDecl *DstVD = 16915 buildVarDecl(*this, ERange.getBegin(), Type, ".lastprivate.dst", 16916 D->hasAttrs() ? &D->getAttrs() : nullptr); 16917 DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc); 16918 // For arrays generate assignment operation for single element and replace 16919 // it by the original array element in CodeGen. 16920 ExprResult AssignmentOp = BuildBinOp(/*S=*/nullptr, ELoc, BO_Assign, 16921 PseudoDstExpr, PseudoSrcExpr); 16922 if (AssignmentOp.isInvalid()) 16923 continue; 16924 AssignmentOp = 16925 ActOnFinishFullExpr(AssignmentOp.get(), ELoc, /*DiscardedValue*/ false); 16926 if (AssignmentOp.isInvalid()) 16927 continue; 16928 16929 DeclRefExpr *Ref = nullptr; 16930 if (!VD && !CurContext->isDependentContext()) { 16931 if (TopDVar.CKind == OMPC_firstprivate) { 16932 Ref = TopDVar.PrivateCopy; 16933 } else { 16934 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false); 16935 if (!isOpenMPCapturedDecl(D)) 16936 ExprCaptures.push_back(Ref->getDecl()); 16937 } 16938 if ((TopDVar.CKind == OMPC_firstprivate && !TopDVar.PrivateCopy) || 16939 (!isOpenMPCapturedDecl(D) && 16940 Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>())) { 16941 ExprResult RefRes = DefaultLvalueConversion(Ref); 16942 if (!RefRes.isUsable()) 16943 continue; 16944 ExprResult PostUpdateRes = 16945 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr, 16946 RefRes.get()); 16947 if (!PostUpdateRes.isUsable()) 16948 continue; 16949 ExprPostUpdates.push_back( 16950 IgnoredValueConversions(PostUpdateRes.get()).get()); 16951 } 16952 } 16953 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_lastprivate, Ref); 16954 Vars.push_back((VD || CurContext->isDependentContext()) 16955 ? RefExpr->IgnoreParens() 16956 : Ref); 16957 SrcExprs.push_back(PseudoSrcExpr); 16958 DstExprs.push_back(PseudoDstExpr); 16959 AssignmentOps.push_back(AssignmentOp.get()); 16960 } 16961 16962 if (Vars.empty()) 16963 return nullptr; 16964 16965 return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, 16966 Vars, SrcExprs, DstExprs, AssignmentOps, 16967 LPKind, LPKindLoc, ColonLoc, 16968 buildPreInits(Context, ExprCaptures), 16969 buildPostUpdate(*this, ExprPostUpdates)); 16970 } 16971 16972 OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList, 16973 SourceLocation StartLoc, 16974 SourceLocation LParenLoc, 16975 SourceLocation EndLoc) { 16976 SmallVector<Expr *, 8> Vars; 16977 for (Expr *RefExpr : VarList) { 16978 assert(RefExpr && "NULL expr in OpenMP lastprivate clause."); 16979 SourceLocation ELoc; 16980 SourceRange ERange; 16981 Expr *SimpleRefExpr = RefExpr; 16982 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 16983 if (Res.second) { 16984 // It will be analyzed later. 16985 Vars.push_back(RefExpr); 16986 } 16987 ValueDecl *D = Res.first; 16988 if (!D) 16989 continue; 16990 16991 auto *VD = dyn_cast<VarDecl>(D); 16992 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 16993 // in a Construct] 16994 // Variables with the predetermined data-sharing attributes may not be 16995 // listed in data-sharing attributes clauses, except for the cases 16996 // listed below. For these exceptions only, listing a predetermined 16997 // variable in a data-sharing attribute clause is allowed and overrides 16998 // the variable's predetermined data-sharing attributes. 16999 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false); 17000 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared && 17001 DVar.RefExpr) { 17002 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind) 17003 << getOpenMPClauseName(OMPC_shared); 17004 reportOriginalDsa(*this, DSAStack, D, DVar); 17005 continue; 17006 } 17007 17008 DeclRefExpr *Ref = nullptr; 17009 if (!VD && isOpenMPCapturedDecl(D) && !CurContext->isDependentContext()) 17010 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true); 17011 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_shared, Ref); 17012 Vars.push_back((VD || !Ref || CurContext->isDependentContext()) 17013 ? RefExpr->IgnoreParens() 17014 : Ref); 17015 } 17016 17017 if (Vars.empty()) 17018 return nullptr; 17019 17020 return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars); 17021 } 17022 17023 namespace { 17024 class DSARefChecker : public StmtVisitor<DSARefChecker, bool> { 17025 DSAStackTy *Stack; 17026 17027 public: 17028 bool VisitDeclRefExpr(DeclRefExpr *E) { 17029 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) { 17030 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, /*FromParent=*/false); 17031 if (DVar.CKind == OMPC_shared && !DVar.RefExpr) 17032 return false; 17033 if (DVar.CKind != OMPC_unknown) 17034 return true; 17035 DSAStackTy::DSAVarData DVarPrivate = Stack->hasDSA( 17036 VD, 17037 [](OpenMPClauseKind C, bool AppliedToPointee) { 17038 return isOpenMPPrivate(C) && !AppliedToPointee; 17039 }, 17040 [](OpenMPDirectiveKind) { return true; }, 17041 /*FromParent=*/true); 17042 return DVarPrivate.CKind != OMPC_unknown; 17043 } 17044 return false; 17045 } 17046 bool VisitStmt(Stmt *S) { 17047 for (Stmt *Child : S->children()) { 17048 if (Child && Visit(Child)) 17049 return true; 17050 } 17051 return false; 17052 } 17053 explicit DSARefChecker(DSAStackTy *S) : Stack(S) {} 17054 }; 17055 } // namespace 17056 17057 namespace { 17058 // Transform MemberExpression for specified FieldDecl of current class to 17059 // DeclRefExpr to specified OMPCapturedExprDecl. 17060 class TransformExprToCaptures : public TreeTransform<TransformExprToCaptures> { 17061 typedef TreeTransform<TransformExprToCaptures> BaseTransform; 17062 ValueDecl *Field = nullptr; 17063 DeclRefExpr *CapturedExpr = nullptr; 17064 17065 public: 17066 TransformExprToCaptures(Sema &SemaRef, ValueDecl *FieldDecl) 17067 : BaseTransform(SemaRef), Field(FieldDecl), CapturedExpr(nullptr) {} 17068 17069 ExprResult TransformMemberExpr(MemberExpr *E) { 17070 if (isa<CXXThisExpr>(E->getBase()->IgnoreParenImpCasts()) && 17071 E->getMemberDecl() == Field) { 17072 CapturedExpr = buildCapture(SemaRef, Field, E, /*WithInit=*/false); 17073 return CapturedExpr; 17074 } 17075 return BaseTransform::TransformMemberExpr(E); 17076 } 17077 DeclRefExpr *getCapturedExpr() { return CapturedExpr; } 17078 }; 17079 } // namespace 17080 17081 template <typename T, typename U> 17082 static T filterLookupForUDReductionAndMapper( 17083 SmallVectorImpl<U> &Lookups, const llvm::function_ref<T(ValueDecl *)> Gen) { 17084 for (U &Set : Lookups) { 17085 for (auto *D : Set) { 17086 if (T Res = Gen(cast<ValueDecl>(D))) 17087 return Res; 17088 } 17089 } 17090 return T(); 17091 } 17092 17093 static NamedDecl *findAcceptableDecl(Sema &SemaRef, NamedDecl *D) { 17094 assert(!LookupResult::isVisible(SemaRef, D) && "not in slow case"); 17095 17096 for (auto RD : D->redecls()) { 17097 // Don't bother with extra checks if we already know this one isn't visible. 17098 if (RD == D) 17099 continue; 17100 17101 auto ND = cast<NamedDecl>(RD); 17102 if (LookupResult::isVisible(SemaRef, ND)) 17103 return ND; 17104 } 17105 17106 return nullptr; 17107 } 17108 17109 static void 17110 argumentDependentLookup(Sema &SemaRef, const DeclarationNameInfo &Id, 17111 SourceLocation Loc, QualType Ty, 17112 SmallVectorImpl<UnresolvedSet<8>> &Lookups) { 17113 // Find all of the associated namespaces and classes based on the 17114 // arguments we have. 17115 Sema::AssociatedNamespaceSet AssociatedNamespaces; 17116 Sema::AssociatedClassSet AssociatedClasses; 17117 OpaqueValueExpr OVE(Loc, Ty, VK_LValue); 17118 SemaRef.FindAssociatedClassesAndNamespaces(Loc, &OVE, AssociatedNamespaces, 17119 AssociatedClasses); 17120 17121 // C++ [basic.lookup.argdep]p3: 17122 // Let X be the lookup set produced by unqualified lookup (3.4.1) 17123 // and let Y be the lookup set produced by argument dependent 17124 // lookup (defined as follows). If X contains [...] then Y is 17125 // empty. Otherwise Y is the set of declarations found in the 17126 // namespaces associated with the argument types as described 17127 // below. The set of declarations found by the lookup of the name 17128 // is the union of X and Y. 17129 // 17130 // Here, we compute Y and add its members to the overloaded 17131 // candidate set. 17132 for (auto *NS : AssociatedNamespaces) { 17133 // When considering an associated namespace, the lookup is the 17134 // same as the lookup performed when the associated namespace is 17135 // used as a qualifier (3.4.3.2) except that: 17136 // 17137 // -- Any using-directives in the associated namespace are 17138 // ignored. 17139 // 17140 // -- Any namespace-scope friend functions declared in 17141 // associated classes are visible within their respective 17142 // namespaces even if they are not visible during an ordinary 17143 // lookup (11.4). 17144 DeclContext::lookup_result R = NS->lookup(Id.getName()); 17145 for (auto *D : R) { 17146 auto *Underlying = D; 17147 if (auto *USD = dyn_cast<UsingShadowDecl>(D)) 17148 Underlying = USD->getTargetDecl(); 17149 17150 if (!isa<OMPDeclareReductionDecl>(Underlying) && 17151 !isa<OMPDeclareMapperDecl>(Underlying)) 17152 continue; 17153 17154 if (!SemaRef.isVisible(D)) { 17155 D = findAcceptableDecl(SemaRef, D); 17156 if (!D) 17157 continue; 17158 if (auto *USD = dyn_cast<UsingShadowDecl>(D)) 17159 Underlying = USD->getTargetDecl(); 17160 } 17161 Lookups.emplace_back(); 17162 Lookups.back().addDecl(Underlying); 17163 } 17164 } 17165 } 17166 17167 static ExprResult 17168 buildDeclareReductionRef(Sema &SemaRef, SourceLocation Loc, SourceRange Range, 17169 Scope *S, CXXScopeSpec &ReductionIdScopeSpec, 17170 const DeclarationNameInfo &ReductionId, QualType Ty, 17171 CXXCastPath &BasePath, Expr *UnresolvedReduction) { 17172 if (ReductionIdScopeSpec.isInvalid()) 17173 return ExprError(); 17174 SmallVector<UnresolvedSet<8>, 4> Lookups; 17175 if (S) { 17176 LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName); 17177 Lookup.suppressDiagnostics(); 17178 while (S && SemaRef.LookupParsedName(Lookup, S, &ReductionIdScopeSpec)) { 17179 NamedDecl *D = Lookup.getRepresentativeDecl(); 17180 do { 17181 S = S->getParent(); 17182 } while (S && !S->isDeclScope(D)); 17183 if (S) 17184 S = S->getParent(); 17185 Lookups.emplace_back(); 17186 Lookups.back().append(Lookup.begin(), Lookup.end()); 17187 Lookup.clear(); 17188 } 17189 } else if (auto *ULE = 17190 cast_or_null<UnresolvedLookupExpr>(UnresolvedReduction)) { 17191 Lookups.push_back(UnresolvedSet<8>()); 17192 Decl *PrevD = nullptr; 17193 for (NamedDecl *D : ULE->decls()) { 17194 if (D == PrevD) 17195 Lookups.push_back(UnresolvedSet<8>()); 17196 else if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(D)) 17197 Lookups.back().addDecl(DRD); 17198 PrevD = D; 17199 } 17200 } 17201 if (SemaRef.CurContext->isDependentContext() || Ty->isDependentType() || 17202 Ty->isInstantiationDependentType() || 17203 Ty->containsUnexpandedParameterPack() || 17204 filterLookupForUDReductionAndMapper<bool>(Lookups, [](ValueDecl *D) { 17205 return !D->isInvalidDecl() && 17206 (D->getType()->isDependentType() || 17207 D->getType()->isInstantiationDependentType() || 17208 D->getType()->containsUnexpandedParameterPack()); 17209 })) { 17210 UnresolvedSet<8> ResSet; 17211 for (const UnresolvedSet<8> &Set : Lookups) { 17212 if (Set.empty()) 17213 continue; 17214 ResSet.append(Set.begin(), Set.end()); 17215 // The last item marks the end of all declarations at the specified scope. 17216 ResSet.addDecl(Set[Set.size() - 1]); 17217 } 17218 return UnresolvedLookupExpr::Create( 17219 SemaRef.Context, /*NamingClass=*/nullptr, 17220 ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), ReductionId, 17221 /*ADL=*/true, /*Overloaded=*/true, ResSet.begin(), ResSet.end()); 17222 } 17223 // Lookup inside the classes. 17224 // C++ [over.match.oper]p3: 17225 // For a unary operator @ with an operand of a type whose 17226 // cv-unqualified version is T1, and for a binary operator @ with 17227 // a left operand of a type whose cv-unqualified version is T1 and 17228 // a right operand of a type whose cv-unqualified version is T2, 17229 // three sets of candidate functions, designated member 17230 // candidates, non-member candidates and built-in candidates, are 17231 // constructed as follows: 17232 // -- If T1 is a complete class type or a class currently being 17233 // defined, the set of member candidates is the result of the 17234 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise, 17235 // the set of member candidates is empty. 17236 LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName); 17237 Lookup.suppressDiagnostics(); 17238 if (const auto *TyRec = Ty->getAs<RecordType>()) { 17239 // Complete the type if it can be completed. 17240 // If the type is neither complete nor being defined, bail out now. 17241 if (SemaRef.isCompleteType(Loc, Ty) || TyRec->isBeingDefined() || 17242 TyRec->getDecl()->getDefinition()) { 17243 Lookup.clear(); 17244 SemaRef.LookupQualifiedName(Lookup, TyRec->getDecl()); 17245 if (Lookup.empty()) { 17246 Lookups.emplace_back(); 17247 Lookups.back().append(Lookup.begin(), Lookup.end()); 17248 } 17249 } 17250 } 17251 // Perform ADL. 17252 if (SemaRef.getLangOpts().CPlusPlus) 17253 argumentDependentLookup(SemaRef, ReductionId, Loc, Ty, Lookups); 17254 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>( 17255 Lookups, [&SemaRef, Ty](ValueDecl *D) -> ValueDecl * { 17256 if (!D->isInvalidDecl() && 17257 SemaRef.Context.hasSameType(D->getType(), Ty)) 17258 return D; 17259 return nullptr; 17260 })) 17261 return SemaRef.BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(), 17262 VK_LValue, Loc); 17263 if (SemaRef.getLangOpts().CPlusPlus) { 17264 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>( 17265 Lookups, [&SemaRef, Ty, Loc](ValueDecl *D) -> ValueDecl * { 17266 if (!D->isInvalidDecl() && 17267 SemaRef.IsDerivedFrom(Loc, Ty, D->getType()) && 17268 !Ty.isMoreQualifiedThan(D->getType())) 17269 return D; 17270 return nullptr; 17271 })) { 17272 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 17273 /*DetectVirtual=*/false); 17274 if (SemaRef.IsDerivedFrom(Loc, Ty, VD->getType(), Paths)) { 17275 if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType( 17276 VD->getType().getUnqualifiedType()))) { 17277 if (SemaRef.CheckBaseClassAccess( 17278 Loc, VD->getType(), Ty, Paths.front(), 17279 /*DiagID=*/0) != Sema::AR_inaccessible) { 17280 SemaRef.BuildBasePathArray(Paths, BasePath); 17281 return SemaRef.BuildDeclRefExpr( 17282 VD, VD->getType().getNonReferenceType(), VK_LValue, Loc); 17283 } 17284 } 17285 } 17286 } 17287 } 17288 if (ReductionIdScopeSpec.isSet()) { 17289 SemaRef.Diag(Loc, diag::err_omp_not_resolved_reduction_identifier) 17290 << Ty << Range; 17291 return ExprError(); 17292 } 17293 return ExprEmpty(); 17294 } 17295 17296 namespace { 17297 /// Data for the reduction-based clauses. 17298 struct ReductionData { 17299 /// List of original reduction items. 17300 SmallVector<Expr *, 8> Vars; 17301 /// List of private copies of the reduction items. 17302 SmallVector<Expr *, 8> Privates; 17303 /// LHS expressions for the reduction_op expressions. 17304 SmallVector<Expr *, 8> LHSs; 17305 /// RHS expressions for the reduction_op expressions. 17306 SmallVector<Expr *, 8> RHSs; 17307 /// Reduction operation expression. 17308 SmallVector<Expr *, 8> ReductionOps; 17309 /// inscan copy operation expressions. 17310 SmallVector<Expr *, 8> InscanCopyOps; 17311 /// inscan copy temp array expressions for prefix sums. 17312 SmallVector<Expr *, 8> InscanCopyArrayTemps; 17313 /// inscan copy temp array element expressions for prefix sums. 17314 SmallVector<Expr *, 8> InscanCopyArrayElems; 17315 /// Taskgroup descriptors for the corresponding reduction items in 17316 /// in_reduction clauses. 17317 SmallVector<Expr *, 8> TaskgroupDescriptors; 17318 /// List of captures for clause. 17319 SmallVector<Decl *, 4> ExprCaptures; 17320 /// List of postupdate expressions. 17321 SmallVector<Expr *, 4> ExprPostUpdates; 17322 /// Reduction modifier. 17323 unsigned RedModifier = 0; 17324 ReductionData() = delete; 17325 /// Reserves required memory for the reduction data. 17326 ReductionData(unsigned Size, unsigned Modifier = 0) : RedModifier(Modifier) { 17327 Vars.reserve(Size); 17328 Privates.reserve(Size); 17329 LHSs.reserve(Size); 17330 RHSs.reserve(Size); 17331 ReductionOps.reserve(Size); 17332 if (RedModifier == OMPC_REDUCTION_inscan) { 17333 InscanCopyOps.reserve(Size); 17334 InscanCopyArrayTemps.reserve(Size); 17335 InscanCopyArrayElems.reserve(Size); 17336 } 17337 TaskgroupDescriptors.reserve(Size); 17338 ExprCaptures.reserve(Size); 17339 ExprPostUpdates.reserve(Size); 17340 } 17341 /// Stores reduction item and reduction operation only (required for dependent 17342 /// reduction item). 17343 void push(Expr *Item, Expr *ReductionOp) { 17344 Vars.emplace_back(Item); 17345 Privates.emplace_back(nullptr); 17346 LHSs.emplace_back(nullptr); 17347 RHSs.emplace_back(nullptr); 17348 ReductionOps.emplace_back(ReductionOp); 17349 TaskgroupDescriptors.emplace_back(nullptr); 17350 if (RedModifier == OMPC_REDUCTION_inscan) { 17351 InscanCopyOps.push_back(nullptr); 17352 InscanCopyArrayTemps.push_back(nullptr); 17353 InscanCopyArrayElems.push_back(nullptr); 17354 } 17355 } 17356 /// Stores reduction data. 17357 void push(Expr *Item, Expr *Private, Expr *LHS, Expr *RHS, Expr *ReductionOp, 17358 Expr *TaskgroupDescriptor, Expr *CopyOp, Expr *CopyArrayTemp, 17359 Expr *CopyArrayElem) { 17360 Vars.emplace_back(Item); 17361 Privates.emplace_back(Private); 17362 LHSs.emplace_back(LHS); 17363 RHSs.emplace_back(RHS); 17364 ReductionOps.emplace_back(ReductionOp); 17365 TaskgroupDescriptors.emplace_back(TaskgroupDescriptor); 17366 if (RedModifier == OMPC_REDUCTION_inscan) { 17367 InscanCopyOps.push_back(CopyOp); 17368 InscanCopyArrayTemps.push_back(CopyArrayTemp); 17369 InscanCopyArrayElems.push_back(CopyArrayElem); 17370 } else { 17371 assert(CopyOp == nullptr && CopyArrayTemp == nullptr && 17372 CopyArrayElem == nullptr && 17373 "Copy operation must be used for inscan reductions only."); 17374 } 17375 } 17376 }; 17377 } // namespace 17378 17379 static bool checkOMPArraySectionConstantForReduction( 17380 ASTContext &Context, const OMPArraySectionExpr *OASE, bool &SingleElement, 17381 SmallVectorImpl<llvm::APSInt> &ArraySizes) { 17382 const Expr *Length = OASE->getLength(); 17383 if (Length == nullptr) { 17384 // For array sections of the form [1:] or [:], we would need to analyze 17385 // the lower bound... 17386 if (OASE->getColonLocFirst().isValid()) 17387 return false; 17388 17389 // This is an array subscript which has implicit length 1! 17390 SingleElement = true; 17391 ArraySizes.push_back(llvm::APSInt::get(1)); 17392 } else { 17393 Expr::EvalResult Result; 17394 if (!Length->EvaluateAsInt(Result, Context)) 17395 return false; 17396 17397 llvm::APSInt ConstantLengthValue = Result.Val.getInt(); 17398 SingleElement = (ConstantLengthValue.getSExtValue() == 1); 17399 ArraySizes.push_back(ConstantLengthValue); 17400 } 17401 17402 // Get the base of this array section and walk up from there. 17403 const Expr *Base = OASE->getBase()->IgnoreParenImpCasts(); 17404 17405 // We require length = 1 for all array sections except the right-most to 17406 // guarantee that the memory region is contiguous and has no holes in it. 17407 while (const auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base)) { 17408 Length = TempOASE->getLength(); 17409 if (Length == nullptr) { 17410 // For array sections of the form [1:] or [:], we would need to analyze 17411 // the lower bound... 17412 if (OASE->getColonLocFirst().isValid()) 17413 return false; 17414 17415 // This is an array subscript which has implicit length 1! 17416 ArraySizes.push_back(llvm::APSInt::get(1)); 17417 } else { 17418 Expr::EvalResult Result; 17419 if (!Length->EvaluateAsInt(Result, Context)) 17420 return false; 17421 17422 llvm::APSInt ConstantLengthValue = Result.Val.getInt(); 17423 if (ConstantLengthValue.getSExtValue() != 1) 17424 return false; 17425 17426 ArraySizes.push_back(ConstantLengthValue); 17427 } 17428 Base = TempOASE->getBase()->IgnoreParenImpCasts(); 17429 } 17430 17431 // If we have a single element, we don't need to add the implicit lengths. 17432 if (!SingleElement) { 17433 while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) { 17434 // Has implicit length 1! 17435 ArraySizes.push_back(llvm::APSInt::get(1)); 17436 Base = TempASE->getBase()->IgnoreParenImpCasts(); 17437 } 17438 } 17439 17440 // This array section can be privatized as a single value or as a constant 17441 // sized array. 17442 return true; 17443 } 17444 17445 static BinaryOperatorKind 17446 getRelatedCompoundReductionOp(BinaryOperatorKind BOK) { 17447 if (BOK == BO_Add) 17448 return BO_AddAssign; 17449 if (BOK == BO_Mul) 17450 return BO_MulAssign; 17451 if (BOK == BO_And) 17452 return BO_AndAssign; 17453 if (BOK == BO_Or) 17454 return BO_OrAssign; 17455 if (BOK == BO_Xor) 17456 return BO_XorAssign; 17457 return BOK; 17458 } 17459 17460 static bool actOnOMPReductionKindClause( 17461 Sema &S, DSAStackTy *Stack, OpenMPClauseKind ClauseKind, 17462 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, 17463 SourceLocation ColonLoc, SourceLocation EndLoc, 17464 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId, 17465 ArrayRef<Expr *> UnresolvedReductions, ReductionData &RD) { 17466 DeclarationName DN = ReductionId.getName(); 17467 OverloadedOperatorKind OOK = DN.getCXXOverloadedOperator(); 17468 BinaryOperatorKind BOK = BO_Comma; 17469 17470 ASTContext &Context = S.Context; 17471 // OpenMP [2.14.3.6, reduction clause] 17472 // C 17473 // reduction-identifier is either an identifier or one of the following 17474 // operators: +, -, *, &, |, ^, && and || 17475 // C++ 17476 // reduction-identifier is either an id-expression or one of the following 17477 // operators: +, -, *, &, |, ^, && and || 17478 switch (OOK) { 17479 case OO_Plus: 17480 case OO_Minus: 17481 BOK = BO_Add; 17482 break; 17483 case OO_Star: 17484 BOK = BO_Mul; 17485 break; 17486 case OO_Amp: 17487 BOK = BO_And; 17488 break; 17489 case OO_Pipe: 17490 BOK = BO_Or; 17491 break; 17492 case OO_Caret: 17493 BOK = BO_Xor; 17494 break; 17495 case OO_AmpAmp: 17496 BOK = BO_LAnd; 17497 break; 17498 case OO_PipePipe: 17499 BOK = BO_LOr; 17500 break; 17501 case OO_New: 17502 case OO_Delete: 17503 case OO_Array_New: 17504 case OO_Array_Delete: 17505 case OO_Slash: 17506 case OO_Percent: 17507 case OO_Tilde: 17508 case OO_Exclaim: 17509 case OO_Equal: 17510 case OO_Less: 17511 case OO_Greater: 17512 case OO_LessEqual: 17513 case OO_GreaterEqual: 17514 case OO_PlusEqual: 17515 case OO_MinusEqual: 17516 case OO_StarEqual: 17517 case OO_SlashEqual: 17518 case OO_PercentEqual: 17519 case OO_CaretEqual: 17520 case OO_AmpEqual: 17521 case OO_PipeEqual: 17522 case OO_LessLess: 17523 case OO_GreaterGreater: 17524 case OO_LessLessEqual: 17525 case OO_GreaterGreaterEqual: 17526 case OO_EqualEqual: 17527 case OO_ExclaimEqual: 17528 case OO_Spaceship: 17529 case OO_PlusPlus: 17530 case OO_MinusMinus: 17531 case OO_Comma: 17532 case OO_ArrowStar: 17533 case OO_Arrow: 17534 case OO_Call: 17535 case OO_Subscript: 17536 case OO_Conditional: 17537 case OO_Coawait: 17538 case NUM_OVERLOADED_OPERATORS: 17539 llvm_unreachable("Unexpected reduction identifier"); 17540 case OO_None: 17541 if (IdentifierInfo *II = DN.getAsIdentifierInfo()) { 17542 if (II->isStr("max")) 17543 BOK = BO_GT; 17544 else if (II->isStr("min")) 17545 BOK = BO_LT; 17546 } 17547 break; 17548 } 17549 SourceRange ReductionIdRange; 17550 if (ReductionIdScopeSpec.isValid()) 17551 ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc()); 17552 else 17553 ReductionIdRange.setBegin(ReductionId.getBeginLoc()); 17554 ReductionIdRange.setEnd(ReductionId.getEndLoc()); 17555 17556 auto IR = UnresolvedReductions.begin(), ER = UnresolvedReductions.end(); 17557 bool FirstIter = true; 17558 for (Expr *RefExpr : VarList) { 17559 assert(RefExpr && "nullptr expr in OpenMP reduction clause."); 17560 // OpenMP [2.1, C/C++] 17561 // A list item is a variable or array section, subject to the restrictions 17562 // specified in Section 2.4 on page 42 and in each of the sections 17563 // describing clauses and directives for which a list appears. 17564 // OpenMP [2.14.3.3, Restrictions, p.1] 17565 // A variable that is part of another variable (as an array or 17566 // structure element) cannot appear in a private clause. 17567 if (!FirstIter && IR != ER) 17568 ++IR; 17569 FirstIter = false; 17570 SourceLocation ELoc; 17571 SourceRange ERange; 17572 Expr *SimpleRefExpr = RefExpr; 17573 auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange, 17574 /*AllowArraySection=*/true); 17575 if (Res.second) { 17576 // Try to find 'declare reduction' corresponding construct before using 17577 // builtin/overloaded operators. 17578 QualType Type = Context.DependentTy; 17579 CXXCastPath BasePath; 17580 ExprResult DeclareReductionRef = buildDeclareReductionRef( 17581 S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec, 17582 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR); 17583 Expr *ReductionOp = nullptr; 17584 if (S.CurContext->isDependentContext() && 17585 (DeclareReductionRef.isUnset() || 17586 isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) 17587 ReductionOp = DeclareReductionRef.get(); 17588 // It will be analyzed later. 17589 RD.push(RefExpr, ReductionOp); 17590 } 17591 ValueDecl *D = Res.first; 17592 if (!D) 17593 continue; 17594 17595 Expr *TaskgroupDescriptor = nullptr; 17596 QualType Type; 17597 auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr->IgnoreParens()); 17598 auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr->IgnoreParens()); 17599 if (ASE) { 17600 Type = ASE->getType().getNonReferenceType(); 17601 } else if (OASE) { 17602 QualType BaseType = 17603 OMPArraySectionExpr::getBaseOriginalType(OASE->getBase()); 17604 if (const auto *ATy = BaseType->getAsArrayTypeUnsafe()) 17605 Type = ATy->getElementType(); 17606 else 17607 Type = BaseType->getPointeeType(); 17608 Type = Type.getNonReferenceType(); 17609 } else { 17610 Type = Context.getBaseElementType(D->getType().getNonReferenceType()); 17611 } 17612 auto *VD = dyn_cast<VarDecl>(D); 17613 17614 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3] 17615 // A variable that appears in a private clause must not have an incomplete 17616 // type or a reference type. 17617 if (S.RequireCompleteType(ELoc, D->getType(), 17618 diag::err_omp_reduction_incomplete_type)) 17619 continue; 17620 // OpenMP [2.14.3.6, reduction clause, Restrictions] 17621 // A list item that appears in a reduction clause must not be 17622 // const-qualified. 17623 if (rejectConstNotMutableType(S, D, Type, ClauseKind, ELoc, 17624 /*AcceptIfMutable*/ false, ASE || OASE)) 17625 continue; 17626 17627 OpenMPDirectiveKind CurrDir = Stack->getCurrentDirective(); 17628 // OpenMP [2.9.3.6, Restrictions, C/C++, p.4] 17629 // If a list-item is a reference type then it must bind to the same object 17630 // for all threads of the team. 17631 if (!ASE && !OASE) { 17632 if (VD) { 17633 VarDecl *VDDef = VD->getDefinition(); 17634 if (VD->getType()->isReferenceType() && VDDef && VDDef->hasInit()) { 17635 DSARefChecker Check(Stack); 17636 if (Check.Visit(VDDef->getInit())) { 17637 S.Diag(ELoc, diag::err_omp_reduction_ref_type_arg) 17638 << getOpenMPClauseName(ClauseKind) << ERange; 17639 S.Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef; 17640 continue; 17641 } 17642 } 17643 } 17644 17645 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced 17646 // in a Construct] 17647 // Variables with the predetermined data-sharing attributes may not be 17648 // listed in data-sharing attributes clauses, except for the cases 17649 // listed below. For these exceptions only, listing a predetermined 17650 // variable in a data-sharing attribute clause is allowed and overrides 17651 // the variable's predetermined data-sharing attributes. 17652 // OpenMP [2.14.3.6, Restrictions, p.3] 17653 // Any number of reduction clauses can be specified on the directive, 17654 // but a list item can appear only once in the reduction clauses for that 17655 // directive. 17656 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(D, /*FromParent=*/false); 17657 if (DVar.CKind == OMPC_reduction) { 17658 S.Diag(ELoc, diag::err_omp_once_referenced) 17659 << getOpenMPClauseName(ClauseKind); 17660 if (DVar.RefExpr) 17661 S.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced); 17662 continue; 17663 } 17664 if (DVar.CKind != OMPC_unknown) { 17665 S.Diag(ELoc, diag::err_omp_wrong_dsa) 17666 << getOpenMPClauseName(DVar.CKind) 17667 << getOpenMPClauseName(OMPC_reduction); 17668 reportOriginalDsa(S, Stack, D, DVar); 17669 continue; 17670 } 17671 17672 // OpenMP [2.14.3.6, Restrictions, p.1] 17673 // A list item that appears in a reduction clause of a worksharing 17674 // construct must be shared in the parallel regions to which any of the 17675 // worksharing regions arising from the worksharing construct bind. 17676 if (isOpenMPWorksharingDirective(CurrDir) && 17677 !isOpenMPParallelDirective(CurrDir) && 17678 !isOpenMPTeamsDirective(CurrDir)) { 17679 DVar = Stack->getImplicitDSA(D, true); 17680 if (DVar.CKind != OMPC_shared) { 17681 S.Diag(ELoc, diag::err_omp_required_access) 17682 << getOpenMPClauseName(OMPC_reduction) 17683 << getOpenMPClauseName(OMPC_shared); 17684 reportOriginalDsa(S, Stack, D, DVar); 17685 continue; 17686 } 17687 } 17688 } else { 17689 // Threadprivates cannot be shared between threads, so dignose if the base 17690 // is a threadprivate variable. 17691 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(D, /*FromParent=*/false); 17692 if (DVar.CKind == OMPC_threadprivate) { 17693 S.Diag(ELoc, diag::err_omp_wrong_dsa) 17694 << getOpenMPClauseName(DVar.CKind) 17695 << getOpenMPClauseName(OMPC_reduction); 17696 reportOriginalDsa(S, Stack, D, DVar); 17697 continue; 17698 } 17699 } 17700 17701 // Try to find 'declare reduction' corresponding construct before using 17702 // builtin/overloaded operators. 17703 CXXCastPath BasePath; 17704 ExprResult DeclareReductionRef = buildDeclareReductionRef( 17705 S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec, 17706 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR); 17707 if (DeclareReductionRef.isInvalid()) 17708 continue; 17709 if (S.CurContext->isDependentContext() && 17710 (DeclareReductionRef.isUnset() || 17711 isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) { 17712 RD.push(RefExpr, DeclareReductionRef.get()); 17713 continue; 17714 } 17715 if (BOK == BO_Comma && DeclareReductionRef.isUnset()) { 17716 // Not allowed reduction identifier is found. 17717 S.Diag(ReductionId.getBeginLoc(), 17718 diag::err_omp_unknown_reduction_identifier) 17719 << Type << ReductionIdRange; 17720 continue; 17721 } 17722 17723 // OpenMP [2.14.3.6, reduction clause, Restrictions] 17724 // The type of a list item that appears in a reduction clause must be valid 17725 // for the reduction-identifier. For a max or min reduction in C, the type 17726 // of the list item must be an allowed arithmetic data type: char, int, 17727 // float, double, or _Bool, possibly modified with long, short, signed, or 17728 // unsigned. For a max or min reduction in C++, the type of the list item 17729 // must be an allowed arithmetic data type: char, wchar_t, int, float, 17730 // double, or bool, possibly modified with long, short, signed, or unsigned. 17731 if (DeclareReductionRef.isUnset()) { 17732 if ((BOK == BO_GT || BOK == BO_LT) && 17733 !(Type->isScalarType() || 17734 (S.getLangOpts().CPlusPlus && Type->isArithmeticType()))) { 17735 S.Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg) 17736 << getOpenMPClauseName(ClauseKind) << S.getLangOpts().CPlusPlus; 17737 if (!ASE && !OASE) { 17738 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) == 17739 VarDecl::DeclarationOnly; 17740 S.Diag(D->getLocation(), 17741 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 17742 << D; 17743 } 17744 continue; 17745 } 17746 if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) && 17747 !S.getLangOpts().CPlusPlus && Type->isFloatingType()) { 17748 S.Diag(ELoc, diag::err_omp_clause_floating_type_arg) 17749 << getOpenMPClauseName(ClauseKind); 17750 if (!ASE && !OASE) { 17751 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) == 17752 VarDecl::DeclarationOnly; 17753 S.Diag(D->getLocation(), 17754 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 17755 << D; 17756 } 17757 continue; 17758 } 17759 } 17760 17761 Type = Type.getNonLValueExprType(Context).getUnqualifiedType(); 17762 VarDecl *LHSVD = buildVarDecl(S, ELoc, Type, ".reduction.lhs", 17763 D->hasAttrs() ? &D->getAttrs() : nullptr); 17764 VarDecl *RHSVD = buildVarDecl(S, ELoc, Type, D->getName(), 17765 D->hasAttrs() ? &D->getAttrs() : nullptr); 17766 QualType PrivateTy = Type; 17767 17768 // Try if we can determine constant lengths for all array sections and avoid 17769 // the VLA. 17770 bool ConstantLengthOASE = false; 17771 if (OASE) { 17772 bool SingleElement; 17773 llvm::SmallVector<llvm::APSInt, 4> ArraySizes; 17774 ConstantLengthOASE = checkOMPArraySectionConstantForReduction( 17775 Context, OASE, SingleElement, ArraySizes); 17776 17777 // If we don't have a single element, we must emit a constant array type. 17778 if (ConstantLengthOASE && !SingleElement) { 17779 for (llvm::APSInt &Size : ArraySizes) 17780 PrivateTy = Context.getConstantArrayType(PrivateTy, Size, nullptr, 17781 ArrayType::Normal, 17782 /*IndexTypeQuals=*/0); 17783 } 17784 } 17785 17786 if ((OASE && !ConstantLengthOASE) || 17787 (!OASE && !ASE && 17788 D->getType().getNonReferenceType()->isVariablyModifiedType())) { 17789 if (!Context.getTargetInfo().isVLASupported()) { 17790 if (isOpenMPTargetExecutionDirective(Stack->getCurrentDirective())) { 17791 S.Diag(ELoc, diag::err_omp_reduction_vla_unsupported) << !!OASE; 17792 S.Diag(ELoc, diag::note_vla_unsupported); 17793 continue; 17794 } else { 17795 S.targetDiag(ELoc, diag::err_omp_reduction_vla_unsupported) << !!OASE; 17796 S.targetDiag(ELoc, diag::note_vla_unsupported); 17797 } 17798 } 17799 // For arrays/array sections only: 17800 // Create pseudo array type for private copy. The size for this array will 17801 // be generated during codegen. 17802 // For array subscripts or single variables Private Ty is the same as Type 17803 // (type of the variable or single array element). 17804 PrivateTy = Context.getVariableArrayType( 17805 Type, 17806 new (Context) 17807 OpaqueValueExpr(ELoc, Context.getSizeType(), VK_PRValue), 17808 ArrayType::Normal, /*IndexTypeQuals=*/0, SourceRange()); 17809 } else if (!ASE && !OASE && 17810 Context.getAsArrayType(D->getType().getNonReferenceType())) { 17811 PrivateTy = D->getType().getNonReferenceType(); 17812 } 17813 // Private copy. 17814 VarDecl *PrivateVD = 17815 buildVarDecl(S, ELoc, PrivateTy, D->getName(), 17816 D->hasAttrs() ? &D->getAttrs() : nullptr, 17817 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr); 17818 // Add initializer for private variable. 17819 Expr *Init = nullptr; 17820 DeclRefExpr *LHSDRE = buildDeclRefExpr(S, LHSVD, Type, ELoc); 17821 DeclRefExpr *RHSDRE = buildDeclRefExpr(S, RHSVD, Type, ELoc); 17822 if (DeclareReductionRef.isUsable()) { 17823 auto *DRDRef = DeclareReductionRef.getAs<DeclRefExpr>(); 17824 auto *DRD = cast<OMPDeclareReductionDecl>(DRDRef->getDecl()); 17825 if (DRD->getInitializer()) { 17826 Init = DRDRef; 17827 RHSVD->setInit(DRDRef); 17828 RHSVD->setInitStyle(VarDecl::CallInit); 17829 } 17830 } else { 17831 switch (BOK) { 17832 case BO_Add: 17833 case BO_Xor: 17834 case BO_Or: 17835 case BO_LOr: 17836 // '+', '-', '^', '|', '||' reduction ops - initializer is '0'. 17837 if (Type->isScalarType() || Type->isAnyComplexType()) 17838 Init = S.ActOnIntegerConstant(ELoc, /*Val=*/0).get(); 17839 break; 17840 case BO_Mul: 17841 case BO_LAnd: 17842 if (Type->isScalarType() || Type->isAnyComplexType()) { 17843 // '*' and '&&' reduction ops - initializer is '1'. 17844 Init = S.ActOnIntegerConstant(ELoc, /*Val=*/1).get(); 17845 } 17846 break; 17847 case BO_And: { 17848 // '&' reduction op - initializer is '~0'. 17849 QualType OrigType = Type; 17850 if (auto *ComplexTy = OrigType->getAs<ComplexType>()) 17851 Type = ComplexTy->getElementType(); 17852 if (Type->isRealFloatingType()) { 17853 llvm::APFloat InitValue = llvm::APFloat::getAllOnesValue( 17854 Context.getFloatTypeSemantics(Type)); 17855 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true, 17856 Type, ELoc); 17857 } else if (Type->isScalarType()) { 17858 uint64_t Size = Context.getTypeSize(Type); 17859 QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0); 17860 llvm::APInt InitValue = llvm::APInt::getAllOnes(Size); 17861 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc); 17862 } 17863 if (Init && OrigType->isAnyComplexType()) { 17864 // Init = 0xFFFF + 0xFFFFi; 17865 auto *Im = new (Context) ImaginaryLiteral(Init, OrigType); 17866 Init = S.CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get(); 17867 } 17868 Type = OrigType; 17869 break; 17870 } 17871 case BO_LT: 17872 case BO_GT: { 17873 // 'min' reduction op - initializer is 'Largest representable number in 17874 // the reduction list item type'. 17875 // 'max' reduction op - initializer is 'Least representable number in 17876 // the reduction list item type'. 17877 if (Type->isIntegerType() || Type->isPointerType()) { 17878 bool IsSigned = Type->hasSignedIntegerRepresentation(); 17879 uint64_t Size = Context.getTypeSize(Type); 17880 QualType IntTy = 17881 Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned); 17882 llvm::APInt InitValue = 17883 (BOK != BO_LT) ? IsSigned ? llvm::APInt::getSignedMinValue(Size) 17884 : llvm::APInt::getMinValue(Size) 17885 : IsSigned ? llvm::APInt::getSignedMaxValue(Size) 17886 : llvm::APInt::getMaxValue(Size); 17887 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc); 17888 if (Type->isPointerType()) { 17889 // Cast to pointer type. 17890 ExprResult CastExpr = S.BuildCStyleCastExpr( 17891 ELoc, Context.getTrivialTypeSourceInfo(Type, ELoc), ELoc, Init); 17892 if (CastExpr.isInvalid()) 17893 continue; 17894 Init = CastExpr.get(); 17895 } 17896 } else if (Type->isRealFloatingType()) { 17897 llvm::APFloat InitValue = llvm::APFloat::getLargest( 17898 Context.getFloatTypeSemantics(Type), BOK != BO_LT); 17899 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true, 17900 Type, ELoc); 17901 } 17902 break; 17903 } 17904 case BO_PtrMemD: 17905 case BO_PtrMemI: 17906 case BO_MulAssign: 17907 case BO_Div: 17908 case BO_Rem: 17909 case BO_Sub: 17910 case BO_Shl: 17911 case BO_Shr: 17912 case BO_LE: 17913 case BO_GE: 17914 case BO_EQ: 17915 case BO_NE: 17916 case BO_Cmp: 17917 case BO_AndAssign: 17918 case BO_XorAssign: 17919 case BO_OrAssign: 17920 case BO_Assign: 17921 case BO_AddAssign: 17922 case BO_SubAssign: 17923 case BO_DivAssign: 17924 case BO_RemAssign: 17925 case BO_ShlAssign: 17926 case BO_ShrAssign: 17927 case BO_Comma: 17928 llvm_unreachable("Unexpected reduction operation"); 17929 } 17930 } 17931 if (Init && DeclareReductionRef.isUnset()) { 17932 S.AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false); 17933 // Store initializer for single element in private copy. Will be used 17934 // during codegen. 17935 PrivateVD->setInit(RHSVD->getInit()); 17936 PrivateVD->setInitStyle(RHSVD->getInitStyle()); 17937 } else if (!Init) { 17938 S.ActOnUninitializedDecl(RHSVD); 17939 // Store initializer for single element in private copy. Will be used 17940 // during codegen. 17941 PrivateVD->setInit(RHSVD->getInit()); 17942 PrivateVD->setInitStyle(RHSVD->getInitStyle()); 17943 } 17944 if (RHSVD->isInvalidDecl()) 17945 continue; 17946 if (!RHSVD->hasInit() && DeclareReductionRef.isUnset()) { 17947 S.Diag(ELoc, diag::err_omp_reduction_id_not_compatible) 17948 << Type << ReductionIdRange; 17949 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) == 17950 VarDecl::DeclarationOnly; 17951 S.Diag(D->getLocation(), 17952 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 17953 << D; 17954 continue; 17955 } 17956 DeclRefExpr *PrivateDRE = buildDeclRefExpr(S, PrivateVD, PrivateTy, ELoc); 17957 ExprResult ReductionOp; 17958 if (DeclareReductionRef.isUsable()) { 17959 QualType RedTy = DeclareReductionRef.get()->getType(); 17960 QualType PtrRedTy = Context.getPointerType(RedTy); 17961 ExprResult LHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, LHSDRE); 17962 ExprResult RHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RHSDRE); 17963 if (!BasePath.empty()) { 17964 LHS = S.DefaultLvalueConversion(LHS.get()); 17965 RHS = S.DefaultLvalueConversion(RHS.get()); 17966 LHS = ImplicitCastExpr::Create( 17967 Context, PtrRedTy, CK_UncheckedDerivedToBase, LHS.get(), &BasePath, 17968 LHS.get()->getValueKind(), FPOptionsOverride()); 17969 RHS = ImplicitCastExpr::Create( 17970 Context, PtrRedTy, CK_UncheckedDerivedToBase, RHS.get(), &BasePath, 17971 RHS.get()->getValueKind(), FPOptionsOverride()); 17972 } 17973 FunctionProtoType::ExtProtoInfo EPI; 17974 QualType Params[] = {PtrRedTy, PtrRedTy}; 17975 QualType FnTy = Context.getFunctionType(Context.VoidTy, Params, EPI); 17976 auto *OVE = new (Context) OpaqueValueExpr( 17977 ELoc, Context.getPointerType(FnTy), VK_PRValue, OK_Ordinary, 17978 S.DefaultLvalueConversion(DeclareReductionRef.get()).get()); 17979 Expr *Args[] = {LHS.get(), RHS.get()}; 17980 ReductionOp = 17981 CallExpr::Create(Context, OVE, Args, Context.VoidTy, VK_PRValue, ELoc, 17982 S.CurFPFeatureOverrides()); 17983 } else { 17984 BinaryOperatorKind CombBOK = getRelatedCompoundReductionOp(BOK); 17985 if (Type->isRecordType() && CombBOK != BOK) { 17986 Sema::TentativeAnalysisScope Trap(S); 17987 ReductionOp = 17988 S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(), 17989 CombBOK, LHSDRE, RHSDRE); 17990 } 17991 if (!ReductionOp.isUsable()) { 17992 ReductionOp = 17993 S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(), BOK, 17994 LHSDRE, RHSDRE); 17995 if (ReductionOp.isUsable()) { 17996 if (BOK != BO_LT && BOK != BO_GT) { 17997 ReductionOp = 17998 S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(), 17999 BO_Assign, LHSDRE, ReductionOp.get()); 18000 } else { 18001 auto *ConditionalOp = new (Context) 18002 ConditionalOperator(ReductionOp.get(), ELoc, LHSDRE, ELoc, 18003 RHSDRE, Type, VK_LValue, OK_Ordinary); 18004 ReductionOp = 18005 S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(), 18006 BO_Assign, LHSDRE, ConditionalOp); 18007 } 18008 } 18009 } 18010 if (ReductionOp.isUsable()) 18011 ReductionOp = S.ActOnFinishFullExpr(ReductionOp.get(), 18012 /*DiscardedValue*/ false); 18013 if (!ReductionOp.isUsable()) 18014 continue; 18015 } 18016 18017 // Add copy operations for inscan reductions. 18018 // LHS = RHS; 18019 ExprResult CopyOpRes, TempArrayRes, TempArrayElem; 18020 if (ClauseKind == OMPC_reduction && 18021 RD.RedModifier == OMPC_REDUCTION_inscan) { 18022 ExprResult RHS = S.DefaultLvalueConversion(RHSDRE); 18023 CopyOpRes = S.BuildBinOp(Stack->getCurScope(), ELoc, BO_Assign, LHSDRE, 18024 RHS.get()); 18025 if (!CopyOpRes.isUsable()) 18026 continue; 18027 CopyOpRes = 18028 S.ActOnFinishFullExpr(CopyOpRes.get(), /*DiscardedValue=*/true); 18029 if (!CopyOpRes.isUsable()) 18030 continue; 18031 // For simd directive and simd-based directives in simd mode no need to 18032 // construct temp array, need just a single temp element. 18033 if (Stack->getCurrentDirective() == OMPD_simd || 18034 (S.getLangOpts().OpenMPSimd && 18035 isOpenMPSimdDirective(Stack->getCurrentDirective()))) { 18036 VarDecl *TempArrayVD = 18037 buildVarDecl(S, ELoc, PrivateTy, D->getName(), 18038 D->hasAttrs() ? &D->getAttrs() : nullptr); 18039 // Add a constructor to the temp decl. 18040 S.ActOnUninitializedDecl(TempArrayVD); 18041 TempArrayRes = buildDeclRefExpr(S, TempArrayVD, PrivateTy, ELoc); 18042 } else { 18043 // Build temp array for prefix sum. 18044 auto *Dim = new (S.Context) 18045 OpaqueValueExpr(ELoc, S.Context.getSizeType(), VK_PRValue); 18046 QualType ArrayTy = 18047 S.Context.getVariableArrayType(PrivateTy, Dim, ArrayType::Normal, 18048 /*IndexTypeQuals=*/0, {ELoc, ELoc}); 18049 VarDecl *TempArrayVD = 18050 buildVarDecl(S, ELoc, ArrayTy, D->getName(), 18051 D->hasAttrs() ? &D->getAttrs() : nullptr); 18052 // Add a constructor to the temp decl. 18053 S.ActOnUninitializedDecl(TempArrayVD); 18054 TempArrayRes = buildDeclRefExpr(S, TempArrayVD, ArrayTy, ELoc); 18055 TempArrayElem = 18056 S.DefaultFunctionArrayLvalueConversion(TempArrayRes.get()); 18057 auto *Idx = new (S.Context) 18058 OpaqueValueExpr(ELoc, S.Context.getSizeType(), VK_PRValue); 18059 TempArrayElem = S.CreateBuiltinArraySubscriptExpr(TempArrayElem.get(), 18060 ELoc, Idx, ELoc); 18061 } 18062 } 18063 18064 // OpenMP [2.15.4.6, Restrictions, p.2] 18065 // A list item that appears in an in_reduction clause of a task construct 18066 // must appear in a task_reduction clause of a construct associated with a 18067 // taskgroup region that includes the participating task in its taskgroup 18068 // set. The construct associated with the innermost region that meets this 18069 // condition must specify the same reduction-identifier as the in_reduction 18070 // clause. 18071 if (ClauseKind == OMPC_in_reduction) { 18072 SourceRange ParentSR; 18073 BinaryOperatorKind ParentBOK; 18074 const Expr *ParentReductionOp = nullptr; 18075 Expr *ParentBOKTD = nullptr, *ParentReductionOpTD = nullptr; 18076 DSAStackTy::DSAVarData ParentBOKDSA = 18077 Stack->getTopMostTaskgroupReductionData(D, ParentSR, ParentBOK, 18078 ParentBOKTD); 18079 DSAStackTy::DSAVarData ParentReductionOpDSA = 18080 Stack->getTopMostTaskgroupReductionData( 18081 D, ParentSR, ParentReductionOp, ParentReductionOpTD); 18082 bool IsParentBOK = ParentBOKDSA.DKind != OMPD_unknown; 18083 bool IsParentReductionOp = ParentReductionOpDSA.DKind != OMPD_unknown; 18084 if ((DeclareReductionRef.isUnset() && IsParentReductionOp) || 18085 (DeclareReductionRef.isUsable() && IsParentBOK) || 18086 (IsParentBOK && BOK != ParentBOK) || IsParentReductionOp) { 18087 bool EmitError = true; 18088 if (IsParentReductionOp && DeclareReductionRef.isUsable()) { 18089 llvm::FoldingSetNodeID RedId, ParentRedId; 18090 ParentReductionOp->Profile(ParentRedId, Context, /*Canonical=*/true); 18091 DeclareReductionRef.get()->Profile(RedId, Context, 18092 /*Canonical=*/true); 18093 EmitError = RedId != ParentRedId; 18094 } 18095 if (EmitError) { 18096 S.Diag(ReductionId.getBeginLoc(), 18097 diag::err_omp_reduction_identifier_mismatch) 18098 << ReductionIdRange << RefExpr->getSourceRange(); 18099 S.Diag(ParentSR.getBegin(), 18100 diag::note_omp_previous_reduction_identifier) 18101 << ParentSR 18102 << (IsParentBOK ? ParentBOKDSA.RefExpr 18103 : ParentReductionOpDSA.RefExpr) 18104 ->getSourceRange(); 18105 continue; 18106 } 18107 } 18108 TaskgroupDescriptor = IsParentBOK ? ParentBOKTD : ParentReductionOpTD; 18109 } 18110 18111 DeclRefExpr *Ref = nullptr; 18112 Expr *VarsExpr = RefExpr->IgnoreParens(); 18113 if (!VD && !S.CurContext->isDependentContext()) { 18114 if (ASE || OASE) { 18115 TransformExprToCaptures RebuildToCapture(S, D); 18116 VarsExpr = 18117 RebuildToCapture.TransformExpr(RefExpr->IgnoreParens()).get(); 18118 Ref = RebuildToCapture.getCapturedExpr(); 18119 } else { 18120 VarsExpr = Ref = buildCapture(S, D, SimpleRefExpr, /*WithInit=*/false); 18121 } 18122 if (!S.isOpenMPCapturedDecl(D)) { 18123 RD.ExprCaptures.emplace_back(Ref->getDecl()); 18124 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) { 18125 ExprResult RefRes = S.DefaultLvalueConversion(Ref); 18126 if (!RefRes.isUsable()) 18127 continue; 18128 ExprResult PostUpdateRes = 18129 S.BuildBinOp(Stack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr, 18130 RefRes.get()); 18131 if (!PostUpdateRes.isUsable()) 18132 continue; 18133 if (isOpenMPTaskingDirective(Stack->getCurrentDirective()) || 18134 Stack->getCurrentDirective() == OMPD_taskgroup) { 18135 S.Diag(RefExpr->getExprLoc(), 18136 diag::err_omp_reduction_non_addressable_expression) 18137 << RefExpr->getSourceRange(); 18138 continue; 18139 } 18140 RD.ExprPostUpdates.emplace_back( 18141 S.IgnoredValueConversions(PostUpdateRes.get()).get()); 18142 } 18143 } 18144 } 18145 // All reduction items are still marked as reduction (to do not increase 18146 // code base size). 18147 unsigned Modifier = RD.RedModifier; 18148 // Consider task_reductions as reductions with task modifier. Required for 18149 // correct analysis of in_reduction clauses. 18150 if (CurrDir == OMPD_taskgroup && ClauseKind == OMPC_task_reduction) 18151 Modifier = OMPC_REDUCTION_task; 18152 Stack->addDSA(D, RefExpr->IgnoreParens(), OMPC_reduction, Ref, Modifier, 18153 ASE || OASE); 18154 if (Modifier == OMPC_REDUCTION_task && 18155 (CurrDir == OMPD_taskgroup || 18156 ((isOpenMPParallelDirective(CurrDir) || 18157 isOpenMPWorksharingDirective(CurrDir)) && 18158 !isOpenMPSimdDirective(CurrDir)))) { 18159 if (DeclareReductionRef.isUsable()) 18160 Stack->addTaskgroupReductionData(D, ReductionIdRange, 18161 DeclareReductionRef.get()); 18162 else 18163 Stack->addTaskgroupReductionData(D, ReductionIdRange, BOK); 18164 } 18165 RD.push(VarsExpr, PrivateDRE, LHSDRE, RHSDRE, ReductionOp.get(), 18166 TaskgroupDescriptor, CopyOpRes.get(), TempArrayRes.get(), 18167 TempArrayElem.get()); 18168 } 18169 return RD.Vars.empty(); 18170 } 18171 18172 OMPClause *Sema::ActOnOpenMPReductionClause( 18173 ArrayRef<Expr *> VarList, OpenMPReductionClauseModifier Modifier, 18174 SourceLocation StartLoc, SourceLocation LParenLoc, 18175 SourceLocation ModifierLoc, SourceLocation ColonLoc, SourceLocation EndLoc, 18176 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId, 18177 ArrayRef<Expr *> UnresolvedReductions) { 18178 if (ModifierLoc.isValid() && Modifier == OMPC_REDUCTION_unknown) { 18179 Diag(LParenLoc, diag::err_omp_unexpected_clause_value) 18180 << getListOfPossibleValues(OMPC_reduction, /*First=*/0, 18181 /*Last=*/OMPC_REDUCTION_unknown) 18182 << getOpenMPClauseName(OMPC_reduction); 18183 return nullptr; 18184 } 18185 // OpenMP 5.0, 2.19.5.4 reduction Clause, Restrictions 18186 // A reduction clause with the inscan reduction-modifier may only appear on a 18187 // worksharing-loop construct, a worksharing-loop SIMD construct, a simd 18188 // construct, a parallel worksharing-loop construct or a parallel 18189 // worksharing-loop SIMD construct. 18190 if (Modifier == OMPC_REDUCTION_inscan && 18191 (DSAStack->getCurrentDirective() != OMPD_for && 18192 DSAStack->getCurrentDirective() != OMPD_for_simd && 18193 DSAStack->getCurrentDirective() != OMPD_simd && 18194 DSAStack->getCurrentDirective() != OMPD_parallel_for && 18195 DSAStack->getCurrentDirective() != OMPD_parallel_for_simd)) { 18196 Diag(ModifierLoc, diag::err_omp_wrong_inscan_reduction); 18197 return nullptr; 18198 } 18199 18200 ReductionData RD(VarList.size(), Modifier); 18201 if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_reduction, VarList, 18202 StartLoc, LParenLoc, ColonLoc, EndLoc, 18203 ReductionIdScopeSpec, ReductionId, 18204 UnresolvedReductions, RD)) 18205 return nullptr; 18206 18207 return OMPReductionClause::Create( 18208 Context, StartLoc, LParenLoc, ModifierLoc, ColonLoc, EndLoc, Modifier, 18209 RD.Vars, ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId, 18210 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, RD.InscanCopyOps, 18211 RD.InscanCopyArrayTemps, RD.InscanCopyArrayElems, 18212 buildPreInits(Context, RD.ExprCaptures), 18213 buildPostUpdate(*this, RD.ExprPostUpdates)); 18214 } 18215 18216 OMPClause *Sema::ActOnOpenMPTaskReductionClause( 18217 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, 18218 SourceLocation ColonLoc, SourceLocation EndLoc, 18219 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId, 18220 ArrayRef<Expr *> UnresolvedReductions) { 18221 ReductionData RD(VarList.size()); 18222 if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_task_reduction, VarList, 18223 StartLoc, LParenLoc, ColonLoc, EndLoc, 18224 ReductionIdScopeSpec, ReductionId, 18225 UnresolvedReductions, RD)) 18226 return nullptr; 18227 18228 return OMPTaskReductionClause::Create( 18229 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars, 18230 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId, 18231 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, 18232 buildPreInits(Context, RD.ExprCaptures), 18233 buildPostUpdate(*this, RD.ExprPostUpdates)); 18234 } 18235 18236 OMPClause *Sema::ActOnOpenMPInReductionClause( 18237 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, 18238 SourceLocation ColonLoc, SourceLocation EndLoc, 18239 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId, 18240 ArrayRef<Expr *> UnresolvedReductions) { 18241 ReductionData RD(VarList.size()); 18242 if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_in_reduction, VarList, 18243 StartLoc, LParenLoc, ColonLoc, EndLoc, 18244 ReductionIdScopeSpec, ReductionId, 18245 UnresolvedReductions, RD)) 18246 return nullptr; 18247 18248 return OMPInReductionClause::Create( 18249 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars, 18250 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId, 18251 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, RD.TaskgroupDescriptors, 18252 buildPreInits(Context, RD.ExprCaptures), 18253 buildPostUpdate(*this, RD.ExprPostUpdates)); 18254 } 18255 18256 bool Sema::CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind, 18257 SourceLocation LinLoc) { 18258 if ((!LangOpts.CPlusPlus && LinKind != OMPC_LINEAR_val) || 18259 LinKind == OMPC_LINEAR_unknown) { 18260 Diag(LinLoc, diag::err_omp_wrong_linear_modifier) << LangOpts.CPlusPlus; 18261 return true; 18262 } 18263 return false; 18264 } 18265 18266 bool Sema::CheckOpenMPLinearDecl(const ValueDecl *D, SourceLocation ELoc, 18267 OpenMPLinearClauseKind LinKind, QualType Type, 18268 bool IsDeclareSimd) { 18269 const auto *VD = dyn_cast_or_null<VarDecl>(D); 18270 // A variable must not have an incomplete type or a reference type. 18271 if (RequireCompleteType(ELoc, Type, diag::err_omp_linear_incomplete_type)) 18272 return true; 18273 if ((LinKind == OMPC_LINEAR_uval || LinKind == OMPC_LINEAR_ref) && 18274 !Type->isReferenceType()) { 18275 Diag(ELoc, diag::err_omp_wrong_linear_modifier_non_reference) 18276 << Type << getOpenMPSimpleClauseTypeName(OMPC_linear, LinKind); 18277 return true; 18278 } 18279 Type = Type.getNonReferenceType(); 18280 18281 // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions] 18282 // A variable that is privatized must not have a const-qualified type 18283 // unless it is of class type with a mutable member. This restriction does 18284 // not apply to the firstprivate clause, nor to the linear clause on 18285 // declarative directives (like declare simd). 18286 if (!IsDeclareSimd && 18287 rejectConstNotMutableType(*this, D, Type, OMPC_linear, ELoc)) 18288 return true; 18289 18290 // A list item must be of integral or pointer type. 18291 Type = Type.getUnqualifiedType().getCanonicalType(); 18292 const auto *Ty = Type.getTypePtrOrNull(); 18293 if (!Ty || (LinKind != OMPC_LINEAR_ref && !Ty->isDependentType() && 18294 !Ty->isIntegralType(Context) && !Ty->isPointerType())) { 18295 Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << Type; 18296 if (D) { 18297 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) == 18298 VarDecl::DeclarationOnly; 18299 Diag(D->getLocation(), 18300 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 18301 << D; 18302 } 18303 return true; 18304 } 18305 return false; 18306 } 18307 18308 OMPClause *Sema::ActOnOpenMPLinearClause( 18309 ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc, 18310 SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind, 18311 SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc) { 18312 SmallVector<Expr *, 8> Vars; 18313 SmallVector<Expr *, 8> Privates; 18314 SmallVector<Expr *, 8> Inits; 18315 SmallVector<Decl *, 4> ExprCaptures; 18316 SmallVector<Expr *, 4> ExprPostUpdates; 18317 if (CheckOpenMPLinearModifier(LinKind, LinLoc)) 18318 LinKind = OMPC_LINEAR_val; 18319 for (Expr *RefExpr : VarList) { 18320 assert(RefExpr && "NULL expr in OpenMP linear clause."); 18321 SourceLocation ELoc; 18322 SourceRange ERange; 18323 Expr *SimpleRefExpr = RefExpr; 18324 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 18325 if (Res.second) { 18326 // It will be analyzed later. 18327 Vars.push_back(RefExpr); 18328 Privates.push_back(nullptr); 18329 Inits.push_back(nullptr); 18330 } 18331 ValueDecl *D = Res.first; 18332 if (!D) 18333 continue; 18334 18335 QualType Type = D->getType(); 18336 auto *VD = dyn_cast<VarDecl>(D); 18337 18338 // OpenMP [2.14.3.7, linear clause] 18339 // A list-item cannot appear in more than one linear clause. 18340 // A list-item that appears in a linear clause cannot appear in any 18341 // other data-sharing attribute clause. 18342 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false); 18343 if (DVar.RefExpr) { 18344 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind) 18345 << getOpenMPClauseName(OMPC_linear); 18346 reportOriginalDsa(*this, DSAStack, D, DVar); 18347 continue; 18348 } 18349 18350 if (CheckOpenMPLinearDecl(D, ELoc, LinKind, Type)) 18351 continue; 18352 Type = Type.getNonReferenceType().getUnqualifiedType().getCanonicalType(); 18353 18354 // Build private copy of original var. 18355 VarDecl *Private = 18356 buildVarDecl(*this, ELoc, Type, D->getName(), 18357 D->hasAttrs() ? &D->getAttrs() : nullptr, 18358 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr); 18359 DeclRefExpr *PrivateRef = buildDeclRefExpr(*this, Private, Type, ELoc); 18360 // Build var to save initial value. 18361 VarDecl *Init = buildVarDecl(*this, ELoc, Type, ".linear.start"); 18362 Expr *InitExpr; 18363 DeclRefExpr *Ref = nullptr; 18364 if (!VD && !CurContext->isDependentContext()) { 18365 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false); 18366 if (!isOpenMPCapturedDecl(D)) { 18367 ExprCaptures.push_back(Ref->getDecl()); 18368 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) { 18369 ExprResult RefRes = DefaultLvalueConversion(Ref); 18370 if (!RefRes.isUsable()) 18371 continue; 18372 ExprResult PostUpdateRes = 18373 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, 18374 SimpleRefExpr, RefRes.get()); 18375 if (!PostUpdateRes.isUsable()) 18376 continue; 18377 ExprPostUpdates.push_back( 18378 IgnoredValueConversions(PostUpdateRes.get()).get()); 18379 } 18380 } 18381 } 18382 if (LinKind == OMPC_LINEAR_uval) 18383 InitExpr = VD ? VD->getInit() : SimpleRefExpr; 18384 else 18385 InitExpr = VD ? SimpleRefExpr : Ref; 18386 AddInitializerToDecl(Init, DefaultLvalueConversion(InitExpr).get(), 18387 /*DirectInit=*/false); 18388 DeclRefExpr *InitRef = buildDeclRefExpr(*this, Init, Type, ELoc); 18389 18390 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_linear, Ref); 18391 Vars.push_back((VD || CurContext->isDependentContext()) 18392 ? RefExpr->IgnoreParens() 18393 : Ref); 18394 Privates.push_back(PrivateRef); 18395 Inits.push_back(InitRef); 18396 } 18397 18398 if (Vars.empty()) 18399 return nullptr; 18400 18401 Expr *StepExpr = Step; 18402 Expr *CalcStepExpr = nullptr; 18403 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() && 18404 !Step->isInstantiationDependent() && 18405 !Step->containsUnexpandedParameterPack()) { 18406 SourceLocation StepLoc = Step->getBeginLoc(); 18407 ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step); 18408 if (Val.isInvalid()) 18409 return nullptr; 18410 StepExpr = Val.get(); 18411 18412 // Build var to save the step value. 18413 VarDecl *SaveVar = 18414 buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step"); 18415 ExprResult SaveRef = 18416 buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc); 18417 ExprResult CalcStep = 18418 BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr); 18419 CalcStep = ActOnFinishFullExpr(CalcStep.get(), /*DiscardedValue*/ false); 18420 18421 // Warn about zero linear step (it would be probably better specified as 18422 // making corresponding variables 'const'). 18423 if (Optional<llvm::APSInt> Result = 18424 StepExpr->getIntegerConstantExpr(Context)) { 18425 if (!Result->isNegative() && !Result->isStrictlyPositive()) 18426 Diag(StepLoc, diag::warn_omp_linear_step_zero) 18427 << Vars[0] << (Vars.size() > 1); 18428 } else if (CalcStep.isUsable()) { 18429 // Calculate the step beforehand instead of doing this on each iteration. 18430 // (This is not used if the number of iterations may be kfold-ed). 18431 CalcStepExpr = CalcStep.get(); 18432 } 18433 } 18434 18435 return OMPLinearClause::Create(Context, StartLoc, LParenLoc, LinKind, LinLoc, 18436 ColonLoc, EndLoc, Vars, Privates, Inits, 18437 StepExpr, CalcStepExpr, 18438 buildPreInits(Context, ExprCaptures), 18439 buildPostUpdate(*this, ExprPostUpdates)); 18440 } 18441 18442 static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV, 18443 Expr *NumIterations, Sema &SemaRef, 18444 Scope *S, DSAStackTy *Stack) { 18445 // Walk the vars and build update/final expressions for the CodeGen. 18446 SmallVector<Expr *, 8> Updates; 18447 SmallVector<Expr *, 8> Finals; 18448 SmallVector<Expr *, 8> UsedExprs; 18449 Expr *Step = Clause.getStep(); 18450 Expr *CalcStep = Clause.getCalcStep(); 18451 // OpenMP [2.14.3.7, linear clause] 18452 // If linear-step is not specified it is assumed to be 1. 18453 if (!Step) 18454 Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get(); 18455 else if (CalcStep) 18456 Step = cast<BinaryOperator>(CalcStep)->getLHS(); 18457 bool HasErrors = false; 18458 auto CurInit = Clause.inits().begin(); 18459 auto CurPrivate = Clause.privates().begin(); 18460 OpenMPLinearClauseKind LinKind = Clause.getModifier(); 18461 for (Expr *RefExpr : Clause.varlists()) { 18462 SourceLocation ELoc; 18463 SourceRange ERange; 18464 Expr *SimpleRefExpr = RefExpr; 18465 auto Res = getPrivateItem(SemaRef, SimpleRefExpr, ELoc, ERange); 18466 ValueDecl *D = Res.first; 18467 if (Res.second || !D) { 18468 Updates.push_back(nullptr); 18469 Finals.push_back(nullptr); 18470 HasErrors = true; 18471 continue; 18472 } 18473 auto &&Info = Stack->isLoopControlVariable(D); 18474 // OpenMP [2.15.11, distribute simd Construct] 18475 // A list item may not appear in a linear clause, unless it is the loop 18476 // iteration variable. 18477 if (isOpenMPDistributeDirective(Stack->getCurrentDirective()) && 18478 isOpenMPSimdDirective(Stack->getCurrentDirective()) && !Info.first) { 18479 SemaRef.Diag(ELoc, 18480 diag::err_omp_linear_distribute_var_non_loop_iteration); 18481 Updates.push_back(nullptr); 18482 Finals.push_back(nullptr); 18483 HasErrors = true; 18484 continue; 18485 } 18486 Expr *InitExpr = *CurInit; 18487 18488 // Build privatized reference to the current linear var. 18489 auto *DE = cast<DeclRefExpr>(SimpleRefExpr); 18490 Expr *CapturedRef; 18491 if (LinKind == OMPC_LINEAR_uval) 18492 CapturedRef = cast<VarDecl>(DE->getDecl())->getInit(); 18493 else 18494 CapturedRef = 18495 buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()), 18496 DE->getType().getUnqualifiedType(), DE->getExprLoc(), 18497 /*RefersToCapture=*/true); 18498 18499 // Build update: Var = InitExpr + IV * Step 18500 ExprResult Update; 18501 if (!Info.first) 18502 Update = buildCounterUpdate( 18503 SemaRef, S, RefExpr->getExprLoc(), *CurPrivate, InitExpr, IV, Step, 18504 /*Subtract=*/false, /*IsNonRectangularLB=*/false); 18505 else 18506 Update = *CurPrivate; 18507 Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getBeginLoc(), 18508 /*DiscardedValue*/ false); 18509 18510 // Build final: Var = PrivCopy; 18511 ExprResult Final; 18512 if (!Info.first) 18513 Final = SemaRef.BuildBinOp( 18514 S, RefExpr->getExprLoc(), BO_Assign, CapturedRef, 18515 SemaRef.DefaultLvalueConversion(*CurPrivate).get()); 18516 else 18517 Final = *CurPrivate; 18518 Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getBeginLoc(), 18519 /*DiscardedValue*/ false); 18520 18521 if (!Update.isUsable() || !Final.isUsable()) { 18522 Updates.push_back(nullptr); 18523 Finals.push_back(nullptr); 18524 UsedExprs.push_back(nullptr); 18525 HasErrors = true; 18526 } else { 18527 Updates.push_back(Update.get()); 18528 Finals.push_back(Final.get()); 18529 if (!Info.first) 18530 UsedExprs.push_back(SimpleRefExpr); 18531 } 18532 ++CurInit; 18533 ++CurPrivate; 18534 } 18535 if (Expr *S = Clause.getStep()) 18536 UsedExprs.push_back(S); 18537 // Fill the remaining part with the nullptr. 18538 UsedExprs.append(Clause.varlist_size() + 1 - UsedExprs.size(), nullptr); 18539 Clause.setUpdates(Updates); 18540 Clause.setFinals(Finals); 18541 Clause.setUsedExprs(UsedExprs); 18542 return HasErrors; 18543 } 18544 18545 OMPClause *Sema::ActOnOpenMPAlignedClause( 18546 ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc, 18547 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) { 18548 SmallVector<Expr *, 8> Vars; 18549 for (Expr *RefExpr : VarList) { 18550 assert(RefExpr && "NULL expr in OpenMP linear clause."); 18551 SourceLocation ELoc; 18552 SourceRange ERange; 18553 Expr *SimpleRefExpr = RefExpr; 18554 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 18555 if (Res.second) { 18556 // It will be analyzed later. 18557 Vars.push_back(RefExpr); 18558 } 18559 ValueDecl *D = Res.first; 18560 if (!D) 18561 continue; 18562 18563 QualType QType = D->getType(); 18564 auto *VD = dyn_cast<VarDecl>(D); 18565 18566 // OpenMP [2.8.1, simd construct, Restrictions] 18567 // The type of list items appearing in the aligned clause must be 18568 // array, pointer, reference to array, or reference to pointer. 18569 QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType(); 18570 const Type *Ty = QType.getTypePtrOrNull(); 18571 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) { 18572 Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr) 18573 << QType << getLangOpts().CPlusPlus << ERange; 18574 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) == 18575 VarDecl::DeclarationOnly; 18576 Diag(D->getLocation(), 18577 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 18578 << D; 18579 continue; 18580 } 18581 18582 // OpenMP [2.8.1, simd construct, Restrictions] 18583 // A list-item cannot appear in more than one aligned clause. 18584 if (const Expr *PrevRef = DSAStack->addUniqueAligned(D, SimpleRefExpr)) { 18585 Diag(ELoc, diag::err_omp_used_in_clause_twice) 18586 << 0 << getOpenMPClauseName(OMPC_aligned) << ERange; 18587 Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa) 18588 << getOpenMPClauseName(OMPC_aligned); 18589 continue; 18590 } 18591 18592 DeclRefExpr *Ref = nullptr; 18593 if (!VD && isOpenMPCapturedDecl(D)) 18594 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true); 18595 Vars.push_back(DefaultFunctionArrayConversion( 18596 (VD || !Ref) ? RefExpr->IgnoreParens() : Ref) 18597 .get()); 18598 } 18599 18600 // OpenMP [2.8.1, simd construct, Description] 18601 // The parameter of the aligned clause, alignment, must be a constant 18602 // positive integer expression. 18603 // If no optional parameter is specified, implementation-defined default 18604 // alignments for SIMD instructions on the target platforms are assumed. 18605 if (Alignment != nullptr) { 18606 ExprResult AlignResult = 18607 VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned); 18608 if (AlignResult.isInvalid()) 18609 return nullptr; 18610 Alignment = AlignResult.get(); 18611 } 18612 if (Vars.empty()) 18613 return nullptr; 18614 18615 return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc, 18616 EndLoc, Vars, Alignment); 18617 } 18618 18619 OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList, 18620 SourceLocation StartLoc, 18621 SourceLocation LParenLoc, 18622 SourceLocation EndLoc) { 18623 SmallVector<Expr *, 8> Vars; 18624 SmallVector<Expr *, 8> SrcExprs; 18625 SmallVector<Expr *, 8> DstExprs; 18626 SmallVector<Expr *, 8> AssignmentOps; 18627 for (Expr *RefExpr : VarList) { 18628 assert(RefExpr && "NULL expr in OpenMP copyin clause."); 18629 if (isa<DependentScopeDeclRefExpr>(RefExpr)) { 18630 // It will be analyzed later. 18631 Vars.push_back(RefExpr); 18632 SrcExprs.push_back(nullptr); 18633 DstExprs.push_back(nullptr); 18634 AssignmentOps.push_back(nullptr); 18635 continue; 18636 } 18637 18638 SourceLocation ELoc = RefExpr->getExprLoc(); 18639 // OpenMP [2.1, C/C++] 18640 // A list item is a variable name. 18641 // OpenMP [2.14.4.1, Restrictions, p.1] 18642 // A list item that appears in a copyin clause must be threadprivate. 18643 auto *DE = dyn_cast<DeclRefExpr>(RefExpr); 18644 if (!DE || !isa<VarDecl>(DE->getDecl())) { 18645 Diag(ELoc, diag::err_omp_expected_var_name_member_expr) 18646 << 0 << RefExpr->getSourceRange(); 18647 continue; 18648 } 18649 18650 Decl *D = DE->getDecl(); 18651 auto *VD = cast<VarDecl>(D); 18652 18653 QualType Type = VD->getType(); 18654 if (Type->isDependentType() || Type->isInstantiationDependentType()) { 18655 // It will be analyzed later. 18656 Vars.push_back(DE); 18657 SrcExprs.push_back(nullptr); 18658 DstExprs.push_back(nullptr); 18659 AssignmentOps.push_back(nullptr); 18660 continue; 18661 } 18662 18663 // OpenMP [2.14.4.1, Restrictions, C/C++, p.1] 18664 // A list item that appears in a copyin clause must be threadprivate. 18665 if (!DSAStack->isThreadPrivate(VD)) { 18666 Diag(ELoc, diag::err_omp_required_access) 18667 << getOpenMPClauseName(OMPC_copyin) 18668 << getOpenMPDirectiveName(OMPD_threadprivate); 18669 continue; 18670 } 18671 18672 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2] 18673 // A variable of class type (or array thereof) that appears in a 18674 // copyin clause requires an accessible, unambiguous copy assignment 18675 // operator for the class type. 18676 QualType ElemType = Context.getBaseElementType(Type).getNonReferenceType(); 18677 VarDecl *SrcVD = 18678 buildVarDecl(*this, DE->getBeginLoc(), ElemType.getUnqualifiedType(), 18679 ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr); 18680 DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr( 18681 *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc()); 18682 VarDecl *DstVD = 18683 buildVarDecl(*this, DE->getBeginLoc(), ElemType, ".copyin.dst", 18684 VD->hasAttrs() ? &VD->getAttrs() : nullptr); 18685 DeclRefExpr *PseudoDstExpr = 18686 buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc()); 18687 // For arrays generate assignment operation for single element and replace 18688 // it by the original array element in CodeGen. 18689 ExprResult AssignmentOp = 18690 BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign, PseudoDstExpr, 18691 PseudoSrcExpr); 18692 if (AssignmentOp.isInvalid()) 18693 continue; 18694 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(), 18695 /*DiscardedValue*/ false); 18696 if (AssignmentOp.isInvalid()) 18697 continue; 18698 18699 DSAStack->addDSA(VD, DE, OMPC_copyin); 18700 Vars.push_back(DE); 18701 SrcExprs.push_back(PseudoSrcExpr); 18702 DstExprs.push_back(PseudoDstExpr); 18703 AssignmentOps.push_back(AssignmentOp.get()); 18704 } 18705 18706 if (Vars.empty()) 18707 return nullptr; 18708 18709 return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars, 18710 SrcExprs, DstExprs, AssignmentOps); 18711 } 18712 18713 OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList, 18714 SourceLocation StartLoc, 18715 SourceLocation LParenLoc, 18716 SourceLocation EndLoc) { 18717 SmallVector<Expr *, 8> Vars; 18718 SmallVector<Expr *, 8> SrcExprs; 18719 SmallVector<Expr *, 8> DstExprs; 18720 SmallVector<Expr *, 8> AssignmentOps; 18721 for (Expr *RefExpr : VarList) { 18722 assert(RefExpr && "NULL expr in OpenMP linear clause."); 18723 SourceLocation ELoc; 18724 SourceRange ERange; 18725 Expr *SimpleRefExpr = RefExpr; 18726 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 18727 if (Res.second) { 18728 // It will be analyzed later. 18729 Vars.push_back(RefExpr); 18730 SrcExprs.push_back(nullptr); 18731 DstExprs.push_back(nullptr); 18732 AssignmentOps.push_back(nullptr); 18733 } 18734 ValueDecl *D = Res.first; 18735 if (!D) 18736 continue; 18737 18738 QualType Type = D->getType(); 18739 auto *VD = dyn_cast<VarDecl>(D); 18740 18741 // OpenMP [2.14.4.2, Restrictions, p.2] 18742 // A list item that appears in a copyprivate clause may not appear in a 18743 // private or firstprivate clause on the single construct. 18744 if (!VD || !DSAStack->isThreadPrivate(VD)) { 18745 DSAStackTy::DSAVarData DVar = 18746 DSAStack->getTopDSA(D, /*FromParent=*/false); 18747 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate && 18748 DVar.RefExpr) { 18749 Diag(ELoc, diag::err_omp_wrong_dsa) 18750 << getOpenMPClauseName(DVar.CKind) 18751 << getOpenMPClauseName(OMPC_copyprivate); 18752 reportOriginalDsa(*this, DSAStack, D, DVar); 18753 continue; 18754 } 18755 18756 // OpenMP [2.11.4.2, Restrictions, p.1] 18757 // All list items that appear in a copyprivate clause must be either 18758 // threadprivate or private in the enclosing context. 18759 if (DVar.CKind == OMPC_unknown) { 18760 DVar = DSAStack->getImplicitDSA(D, false); 18761 if (DVar.CKind == OMPC_shared) { 18762 Diag(ELoc, diag::err_omp_required_access) 18763 << getOpenMPClauseName(OMPC_copyprivate) 18764 << "threadprivate or private in the enclosing context"; 18765 reportOriginalDsa(*this, DSAStack, D, DVar); 18766 continue; 18767 } 18768 } 18769 } 18770 18771 // Variably modified types are not supported. 18772 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) { 18773 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported) 18774 << getOpenMPClauseName(OMPC_copyprivate) << Type 18775 << getOpenMPDirectiveName(DSAStack->getCurrentDirective()); 18776 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) == 18777 VarDecl::DeclarationOnly; 18778 Diag(D->getLocation(), 18779 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 18780 << D; 18781 continue; 18782 } 18783 18784 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2] 18785 // A variable of class type (or array thereof) that appears in a 18786 // copyin clause requires an accessible, unambiguous copy assignment 18787 // operator for the class type. 18788 Type = Context.getBaseElementType(Type.getNonReferenceType()) 18789 .getUnqualifiedType(); 18790 VarDecl *SrcVD = 18791 buildVarDecl(*this, RefExpr->getBeginLoc(), Type, ".copyprivate.src", 18792 D->hasAttrs() ? &D->getAttrs() : nullptr); 18793 DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr(*this, SrcVD, Type, ELoc); 18794 VarDecl *DstVD = 18795 buildVarDecl(*this, RefExpr->getBeginLoc(), Type, ".copyprivate.dst", 18796 D->hasAttrs() ? &D->getAttrs() : nullptr); 18797 DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc); 18798 ExprResult AssignmentOp = BuildBinOp( 18799 DSAStack->getCurScope(), ELoc, BO_Assign, PseudoDstExpr, PseudoSrcExpr); 18800 if (AssignmentOp.isInvalid()) 18801 continue; 18802 AssignmentOp = 18803 ActOnFinishFullExpr(AssignmentOp.get(), ELoc, /*DiscardedValue*/ false); 18804 if (AssignmentOp.isInvalid()) 18805 continue; 18806 18807 // No need to mark vars as copyprivate, they are already threadprivate or 18808 // implicitly private. 18809 assert(VD || isOpenMPCapturedDecl(D)); 18810 Vars.push_back( 18811 VD ? RefExpr->IgnoreParens() 18812 : buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false)); 18813 SrcExprs.push_back(PseudoSrcExpr); 18814 DstExprs.push_back(PseudoDstExpr); 18815 AssignmentOps.push_back(AssignmentOp.get()); 18816 } 18817 18818 if (Vars.empty()) 18819 return nullptr; 18820 18821 return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, 18822 Vars, SrcExprs, DstExprs, AssignmentOps); 18823 } 18824 18825 OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList, 18826 SourceLocation StartLoc, 18827 SourceLocation LParenLoc, 18828 SourceLocation EndLoc) { 18829 if (VarList.empty()) 18830 return nullptr; 18831 18832 return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList); 18833 } 18834 18835 /// Tries to find omp_depend_t. type. 18836 static bool findOMPDependT(Sema &S, SourceLocation Loc, DSAStackTy *Stack, 18837 bool Diagnose = true) { 18838 QualType OMPDependT = Stack->getOMPDependT(); 18839 if (!OMPDependT.isNull()) 18840 return true; 18841 IdentifierInfo *II = &S.PP.getIdentifierTable().get("omp_depend_t"); 18842 ParsedType PT = S.getTypeName(*II, Loc, S.getCurScope()); 18843 if (!PT.getAsOpaquePtr() || PT.get().isNull()) { 18844 if (Diagnose) 18845 S.Diag(Loc, diag::err_omp_implied_type_not_found) << "omp_depend_t"; 18846 return false; 18847 } 18848 Stack->setOMPDependT(PT.get()); 18849 return true; 18850 } 18851 18852 OMPClause *Sema::ActOnOpenMPDepobjClause(Expr *Depobj, SourceLocation StartLoc, 18853 SourceLocation LParenLoc, 18854 SourceLocation EndLoc) { 18855 if (!Depobj) 18856 return nullptr; 18857 18858 bool OMPDependTFound = findOMPDependT(*this, StartLoc, DSAStack); 18859 18860 // OpenMP 5.0, 2.17.10.1 depobj Construct 18861 // depobj is an lvalue expression of type omp_depend_t. 18862 if (!Depobj->isTypeDependent() && !Depobj->isValueDependent() && 18863 !Depobj->isInstantiationDependent() && 18864 !Depobj->containsUnexpandedParameterPack() && 18865 (OMPDependTFound && 18866 !Context.typesAreCompatible(DSAStack->getOMPDependT(), Depobj->getType(), 18867 /*CompareUnqualified=*/true))) { 18868 Diag(Depobj->getExprLoc(), diag::err_omp_expected_omp_depend_t_lvalue) 18869 << 0 << Depobj->getType() << Depobj->getSourceRange(); 18870 } 18871 18872 if (!Depobj->isLValue()) { 18873 Diag(Depobj->getExprLoc(), diag::err_omp_expected_omp_depend_t_lvalue) 18874 << 1 << Depobj->getSourceRange(); 18875 } 18876 18877 return OMPDepobjClause::Create(Context, StartLoc, LParenLoc, EndLoc, Depobj); 18878 } 18879 18880 OMPClause * 18881 Sema::ActOnOpenMPDependClause(Expr *DepModifier, OpenMPDependClauseKind DepKind, 18882 SourceLocation DepLoc, SourceLocation ColonLoc, 18883 ArrayRef<Expr *> VarList, SourceLocation StartLoc, 18884 SourceLocation LParenLoc, SourceLocation EndLoc) { 18885 if (DSAStack->getCurrentDirective() == OMPD_ordered && 18886 DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink) { 18887 Diag(DepLoc, diag::err_omp_unexpected_clause_value) 18888 << "'source' or 'sink'" << getOpenMPClauseName(OMPC_depend); 18889 return nullptr; 18890 } 18891 if (DSAStack->getCurrentDirective() == OMPD_taskwait && 18892 DepKind == OMPC_DEPEND_mutexinoutset) { 18893 Diag(DepLoc, diag::err_omp_taskwait_depend_mutexinoutset_not_allowed); 18894 return nullptr; 18895 } 18896 if ((DSAStack->getCurrentDirective() != OMPD_ordered || 18897 DSAStack->getCurrentDirective() == OMPD_depobj) && 18898 (DepKind == OMPC_DEPEND_unknown || DepKind == OMPC_DEPEND_source || 18899 DepKind == OMPC_DEPEND_sink || 18900 ((LangOpts.OpenMP < 50 || 18901 DSAStack->getCurrentDirective() == OMPD_depobj) && 18902 DepKind == OMPC_DEPEND_depobj))) { 18903 SmallVector<unsigned, 3> Except; 18904 Except.push_back(OMPC_DEPEND_source); 18905 Except.push_back(OMPC_DEPEND_sink); 18906 if (LangOpts.OpenMP < 50 || DSAStack->getCurrentDirective() == OMPD_depobj) 18907 Except.push_back(OMPC_DEPEND_depobj); 18908 if (LangOpts.OpenMP < 51) 18909 Except.push_back(OMPC_DEPEND_inoutset); 18910 std::string Expected = (LangOpts.OpenMP >= 50 && !DepModifier) 18911 ? "depend modifier(iterator) or " 18912 : ""; 18913 Diag(DepLoc, diag::err_omp_unexpected_clause_value) 18914 << Expected + getListOfPossibleValues(OMPC_depend, /*First=*/0, 18915 /*Last=*/OMPC_DEPEND_unknown, 18916 Except) 18917 << getOpenMPClauseName(OMPC_depend); 18918 return nullptr; 18919 } 18920 if (DepModifier && 18921 (DepKind == OMPC_DEPEND_source || DepKind == OMPC_DEPEND_sink)) { 18922 Diag(DepModifier->getExprLoc(), 18923 diag::err_omp_depend_sink_source_with_modifier); 18924 return nullptr; 18925 } 18926 if (DepModifier && 18927 !DepModifier->getType()->isSpecificBuiltinType(BuiltinType::OMPIterator)) 18928 Diag(DepModifier->getExprLoc(), diag::err_omp_depend_modifier_not_iterator); 18929 18930 SmallVector<Expr *, 8> Vars; 18931 DSAStackTy::OperatorOffsetTy OpsOffs; 18932 llvm::APSInt DepCounter(/*BitWidth=*/32); 18933 llvm::APSInt TotalDepCount(/*BitWidth=*/32); 18934 if (DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) { 18935 if (const Expr *OrderedCountExpr = 18936 DSAStack->getParentOrderedRegionParam().first) { 18937 TotalDepCount = OrderedCountExpr->EvaluateKnownConstInt(Context); 18938 TotalDepCount.setIsUnsigned(/*Val=*/true); 18939 } 18940 } 18941 for (Expr *RefExpr : VarList) { 18942 assert(RefExpr && "NULL expr in OpenMP shared clause."); 18943 if (isa<DependentScopeDeclRefExpr>(RefExpr)) { 18944 // It will be analyzed later. 18945 Vars.push_back(RefExpr); 18946 continue; 18947 } 18948 18949 SourceLocation ELoc = RefExpr->getExprLoc(); 18950 Expr *SimpleExpr = RefExpr->IgnoreParenCasts(); 18951 if (DepKind == OMPC_DEPEND_sink) { 18952 if (DSAStack->getParentOrderedRegionParam().first && 18953 DepCounter >= TotalDepCount) { 18954 Diag(ELoc, diag::err_omp_depend_sink_unexpected_expr); 18955 continue; 18956 } 18957 ++DepCounter; 18958 // OpenMP [2.13.9, Summary] 18959 // depend(dependence-type : vec), where dependence-type is: 18960 // 'sink' and where vec is the iteration vector, which has the form: 18961 // x1 [+- d1], x2 [+- d2 ], . . . , xn [+- dn] 18962 // where n is the value specified by the ordered clause in the loop 18963 // directive, xi denotes the loop iteration variable of the i-th nested 18964 // loop associated with the loop directive, and di is a constant 18965 // non-negative integer. 18966 if (CurContext->isDependentContext()) { 18967 // It will be analyzed later. 18968 Vars.push_back(RefExpr); 18969 continue; 18970 } 18971 SimpleExpr = SimpleExpr->IgnoreImplicit(); 18972 OverloadedOperatorKind OOK = OO_None; 18973 SourceLocation OOLoc; 18974 Expr *LHS = SimpleExpr; 18975 Expr *RHS = nullptr; 18976 if (auto *BO = dyn_cast<BinaryOperator>(SimpleExpr)) { 18977 OOK = BinaryOperator::getOverloadedOperator(BO->getOpcode()); 18978 OOLoc = BO->getOperatorLoc(); 18979 LHS = BO->getLHS()->IgnoreParenImpCasts(); 18980 RHS = BO->getRHS()->IgnoreParenImpCasts(); 18981 } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(SimpleExpr)) { 18982 OOK = OCE->getOperator(); 18983 OOLoc = OCE->getOperatorLoc(); 18984 LHS = OCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts(); 18985 RHS = OCE->getArg(/*Arg=*/1)->IgnoreParenImpCasts(); 18986 } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SimpleExpr)) { 18987 OOK = MCE->getMethodDecl() 18988 ->getNameInfo() 18989 .getName() 18990 .getCXXOverloadedOperator(); 18991 OOLoc = MCE->getCallee()->getExprLoc(); 18992 LHS = MCE->getImplicitObjectArgument()->IgnoreParenImpCasts(); 18993 RHS = MCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts(); 18994 } 18995 SourceLocation ELoc; 18996 SourceRange ERange; 18997 auto Res = getPrivateItem(*this, LHS, ELoc, ERange); 18998 if (Res.second) { 18999 // It will be analyzed later. 19000 Vars.push_back(RefExpr); 19001 } 19002 ValueDecl *D = Res.first; 19003 if (!D) 19004 continue; 19005 19006 if (OOK != OO_Plus && OOK != OO_Minus && (RHS || OOK != OO_None)) { 19007 Diag(OOLoc, diag::err_omp_depend_sink_expected_plus_minus); 19008 continue; 19009 } 19010 if (RHS) { 19011 ExprResult RHSRes = VerifyPositiveIntegerConstantInClause( 19012 RHS, OMPC_depend, /*StrictlyPositive=*/false); 19013 if (RHSRes.isInvalid()) 19014 continue; 19015 } 19016 if (!CurContext->isDependentContext() && 19017 DSAStack->getParentOrderedRegionParam().first && 19018 DepCounter != DSAStack->isParentLoopControlVariable(D).first) { 19019 const ValueDecl *VD = 19020 DSAStack->getParentLoopControlVariable(DepCounter.getZExtValue()); 19021 if (VD) 19022 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration) 19023 << 1 << VD; 19024 else 19025 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration) << 0; 19026 continue; 19027 } 19028 OpsOffs.emplace_back(RHS, OOK); 19029 } else { 19030 bool OMPDependTFound = LangOpts.OpenMP >= 50; 19031 if (OMPDependTFound) 19032 OMPDependTFound = findOMPDependT(*this, StartLoc, DSAStack, 19033 DepKind == OMPC_DEPEND_depobj); 19034 if (DepKind == OMPC_DEPEND_depobj) { 19035 // OpenMP 5.0, 2.17.11 depend Clause, Restrictions, C/C++ 19036 // List items used in depend clauses with the depobj dependence type 19037 // must be expressions of the omp_depend_t type. 19038 if (!RefExpr->isValueDependent() && !RefExpr->isTypeDependent() && 19039 !RefExpr->isInstantiationDependent() && 19040 !RefExpr->containsUnexpandedParameterPack() && 19041 (OMPDependTFound && 19042 !Context.hasSameUnqualifiedType(DSAStack->getOMPDependT(), 19043 RefExpr->getType()))) { 19044 Diag(ELoc, diag::err_omp_expected_omp_depend_t_lvalue) 19045 << 0 << RefExpr->getType() << RefExpr->getSourceRange(); 19046 continue; 19047 } 19048 if (!RefExpr->isLValue()) { 19049 Diag(ELoc, diag::err_omp_expected_omp_depend_t_lvalue) 19050 << 1 << RefExpr->getType() << RefExpr->getSourceRange(); 19051 continue; 19052 } 19053 } else { 19054 // OpenMP 5.0 [2.17.11, Restrictions] 19055 // List items used in depend clauses cannot be zero-length array 19056 // sections. 19057 QualType ExprTy = RefExpr->getType().getNonReferenceType(); 19058 const auto *OASE = dyn_cast<OMPArraySectionExpr>(SimpleExpr); 19059 if (OASE) { 19060 QualType BaseType = 19061 OMPArraySectionExpr::getBaseOriginalType(OASE->getBase()); 19062 if (const auto *ATy = BaseType->getAsArrayTypeUnsafe()) 19063 ExprTy = ATy->getElementType(); 19064 else 19065 ExprTy = BaseType->getPointeeType(); 19066 ExprTy = ExprTy.getNonReferenceType(); 19067 const Expr *Length = OASE->getLength(); 19068 Expr::EvalResult Result; 19069 if (Length && !Length->isValueDependent() && 19070 Length->EvaluateAsInt(Result, Context) && 19071 Result.Val.getInt().isZero()) { 19072 Diag(ELoc, 19073 diag::err_omp_depend_zero_length_array_section_not_allowed) 19074 << SimpleExpr->getSourceRange(); 19075 continue; 19076 } 19077 } 19078 19079 // OpenMP 5.0, 2.17.11 depend Clause, Restrictions, C/C++ 19080 // List items used in depend clauses with the in, out, inout, 19081 // inoutset, or mutexinoutset dependence types cannot be 19082 // expressions of the omp_depend_t type. 19083 if (!RefExpr->isValueDependent() && !RefExpr->isTypeDependent() && 19084 !RefExpr->isInstantiationDependent() && 19085 !RefExpr->containsUnexpandedParameterPack() && 19086 (!RefExpr->IgnoreParenImpCasts()->isLValue() || 19087 (OMPDependTFound && 19088 DSAStack->getOMPDependT().getTypePtr() == ExprTy.getTypePtr()))) { 19089 Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item) 19090 << (LangOpts.OpenMP >= 50 ? 1 : 0) 19091 << (LangOpts.OpenMP >= 50 ? 1 : 0) << RefExpr->getSourceRange(); 19092 continue; 19093 } 19094 19095 auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr); 19096 if (ASE && !ASE->getBase()->isTypeDependent() && 19097 !ASE->getBase()->getType().getNonReferenceType()->isPointerType() && 19098 !ASE->getBase()->getType().getNonReferenceType()->isArrayType()) { 19099 Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item) 19100 << (LangOpts.OpenMP >= 50 ? 1 : 0) 19101 << (LangOpts.OpenMP >= 50 ? 1 : 0) << RefExpr->getSourceRange(); 19102 continue; 19103 } 19104 19105 ExprResult Res; 19106 { 19107 Sema::TentativeAnalysisScope Trap(*this); 19108 Res = CreateBuiltinUnaryOp(ELoc, UO_AddrOf, 19109 RefExpr->IgnoreParenImpCasts()); 19110 } 19111 if (!Res.isUsable() && !isa<OMPArraySectionExpr>(SimpleExpr) && 19112 !isa<OMPArrayShapingExpr>(SimpleExpr)) { 19113 Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item) 19114 << (LangOpts.OpenMP >= 50 ? 1 : 0) 19115 << (LangOpts.OpenMP >= 50 ? 1 : 0) << RefExpr->getSourceRange(); 19116 continue; 19117 } 19118 } 19119 } 19120 Vars.push_back(RefExpr->IgnoreParenImpCasts()); 19121 } 19122 19123 if (!CurContext->isDependentContext() && DepKind == OMPC_DEPEND_sink && 19124 TotalDepCount > VarList.size() && 19125 DSAStack->getParentOrderedRegionParam().first && 19126 DSAStack->getParentLoopControlVariable(VarList.size() + 1)) { 19127 Diag(EndLoc, diag::err_omp_depend_sink_expected_loop_iteration) 19128 << 1 << DSAStack->getParentLoopControlVariable(VarList.size() + 1); 19129 } 19130 if (DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink && 19131 Vars.empty()) 19132 return nullptr; 19133 19134 auto *C = OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc, 19135 DepModifier, DepKind, DepLoc, ColonLoc, 19136 Vars, TotalDepCount.getZExtValue()); 19137 if ((DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) && 19138 DSAStack->isParentOrderedRegion()) 19139 DSAStack->addDoacrossDependClause(C, OpsOffs); 19140 return C; 19141 } 19142 19143 OMPClause *Sema::ActOnOpenMPDeviceClause(OpenMPDeviceClauseModifier Modifier, 19144 Expr *Device, SourceLocation StartLoc, 19145 SourceLocation LParenLoc, 19146 SourceLocation ModifierLoc, 19147 SourceLocation EndLoc) { 19148 assert((ModifierLoc.isInvalid() || LangOpts.OpenMP >= 50) && 19149 "Unexpected device modifier in OpenMP < 50."); 19150 19151 bool ErrorFound = false; 19152 if (ModifierLoc.isValid() && Modifier == OMPC_DEVICE_unknown) { 19153 std::string Values = 19154 getListOfPossibleValues(OMPC_device, /*First=*/0, OMPC_DEVICE_unknown); 19155 Diag(ModifierLoc, diag::err_omp_unexpected_clause_value) 19156 << Values << getOpenMPClauseName(OMPC_device); 19157 ErrorFound = true; 19158 } 19159 19160 Expr *ValExpr = Device; 19161 Stmt *HelperValStmt = nullptr; 19162 19163 // OpenMP [2.9.1, Restrictions] 19164 // The device expression must evaluate to a non-negative integer value. 19165 ErrorFound = !isNonNegativeIntegerValue(ValExpr, *this, OMPC_device, 19166 /*StrictlyPositive=*/false) || 19167 ErrorFound; 19168 if (ErrorFound) 19169 return nullptr; 19170 19171 // OpenMP 5.0 [2.12.5, Restrictions] 19172 // In case of ancestor device-modifier, a requires directive with 19173 // the reverse_offload clause must be specified. 19174 if (Modifier == OMPC_DEVICE_ancestor) { 19175 if (!DSAStack->hasRequiresDeclWithClause<OMPReverseOffloadClause>()) { 19176 targetDiag( 19177 StartLoc, 19178 diag::err_omp_device_ancestor_without_requires_reverse_offload); 19179 ErrorFound = true; 19180 } 19181 } 19182 19183 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective(); 19184 OpenMPDirectiveKind CaptureRegion = 19185 getOpenMPCaptureRegionForClause(DKind, OMPC_device, LangOpts.OpenMP); 19186 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) { 19187 ValExpr = MakeFullExpr(ValExpr).get(); 19188 llvm::MapVector<const Expr *, DeclRefExpr *> Captures; 19189 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 19190 HelperValStmt = buildPreInits(Context, Captures); 19191 } 19192 19193 return new (Context) 19194 OMPDeviceClause(Modifier, ValExpr, HelperValStmt, CaptureRegion, StartLoc, 19195 LParenLoc, ModifierLoc, EndLoc); 19196 } 19197 19198 static bool checkTypeMappable(SourceLocation SL, SourceRange SR, Sema &SemaRef, 19199 DSAStackTy *Stack, QualType QTy, 19200 bool FullCheck = true) { 19201 if (SemaRef.RequireCompleteType(SL, QTy, diag::err_incomplete_type)) 19202 return false; 19203 if (FullCheck && !SemaRef.CurContext->isDependentContext() && 19204 !QTy.isTriviallyCopyableType(SemaRef.Context)) 19205 SemaRef.Diag(SL, diag::warn_omp_non_trivial_type_mapped) << QTy << SR; 19206 return true; 19207 } 19208 19209 /// Return true if it can be proven that the provided array expression 19210 /// (array section or array subscript) does NOT specify the whole size of the 19211 /// array whose base type is \a BaseQTy. 19212 static bool checkArrayExpressionDoesNotReferToWholeSize(Sema &SemaRef, 19213 const Expr *E, 19214 QualType BaseQTy) { 19215 const auto *OASE = dyn_cast<OMPArraySectionExpr>(E); 19216 19217 // If this is an array subscript, it refers to the whole size if the size of 19218 // the dimension is constant and equals 1. Also, an array section assumes the 19219 // format of an array subscript if no colon is used. 19220 if (isa<ArraySubscriptExpr>(E) || 19221 (OASE && OASE->getColonLocFirst().isInvalid())) { 19222 if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr())) 19223 return ATy->getSize().getSExtValue() != 1; 19224 // Size can't be evaluated statically. 19225 return false; 19226 } 19227 19228 assert(OASE && "Expecting array section if not an array subscript."); 19229 const Expr *LowerBound = OASE->getLowerBound(); 19230 const Expr *Length = OASE->getLength(); 19231 19232 // If there is a lower bound that does not evaluates to zero, we are not 19233 // covering the whole dimension. 19234 if (LowerBound) { 19235 Expr::EvalResult Result; 19236 if (!LowerBound->EvaluateAsInt(Result, SemaRef.getASTContext())) 19237 return false; // Can't get the integer value as a constant. 19238 19239 llvm::APSInt ConstLowerBound = Result.Val.getInt(); 19240 if (ConstLowerBound.getSExtValue()) 19241 return true; 19242 } 19243 19244 // If we don't have a length we covering the whole dimension. 19245 if (!Length) 19246 return false; 19247 19248 // If the base is a pointer, we don't have a way to get the size of the 19249 // pointee. 19250 if (BaseQTy->isPointerType()) 19251 return false; 19252 19253 // We can only check if the length is the same as the size of the dimension 19254 // if we have a constant array. 19255 const auto *CATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()); 19256 if (!CATy) 19257 return false; 19258 19259 Expr::EvalResult Result; 19260 if (!Length->EvaluateAsInt(Result, SemaRef.getASTContext())) 19261 return false; // Can't get the integer value as a constant. 19262 19263 llvm::APSInt ConstLength = Result.Val.getInt(); 19264 return CATy->getSize().getSExtValue() != ConstLength.getSExtValue(); 19265 } 19266 19267 // Return true if it can be proven that the provided array expression (array 19268 // section or array subscript) does NOT specify a single element of the array 19269 // whose base type is \a BaseQTy. 19270 static bool checkArrayExpressionDoesNotReferToUnitySize(Sema &SemaRef, 19271 const Expr *E, 19272 QualType BaseQTy) { 19273 const auto *OASE = dyn_cast<OMPArraySectionExpr>(E); 19274 19275 // An array subscript always refer to a single element. Also, an array section 19276 // assumes the format of an array subscript if no colon is used. 19277 if (isa<ArraySubscriptExpr>(E) || 19278 (OASE && OASE->getColonLocFirst().isInvalid())) 19279 return false; 19280 19281 assert(OASE && "Expecting array section if not an array subscript."); 19282 const Expr *Length = OASE->getLength(); 19283 19284 // If we don't have a length we have to check if the array has unitary size 19285 // for this dimension. Also, we should always expect a length if the base type 19286 // is pointer. 19287 if (!Length) { 19288 if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr())) 19289 return ATy->getSize().getSExtValue() != 1; 19290 // We cannot assume anything. 19291 return false; 19292 } 19293 19294 // Check if the length evaluates to 1. 19295 Expr::EvalResult Result; 19296 if (!Length->EvaluateAsInt(Result, SemaRef.getASTContext())) 19297 return false; // Can't get the integer value as a constant. 19298 19299 llvm::APSInt ConstLength = Result.Val.getInt(); 19300 return ConstLength.getSExtValue() != 1; 19301 } 19302 19303 // The base of elements of list in a map clause have to be either: 19304 // - a reference to variable or field. 19305 // - a member expression. 19306 // - an array expression. 19307 // 19308 // E.g. if we have the expression 'r.S.Arr[:12]', we want to retrieve the 19309 // reference to 'r'. 19310 // 19311 // If we have: 19312 // 19313 // struct SS { 19314 // Bla S; 19315 // foo() { 19316 // #pragma omp target map (S.Arr[:12]); 19317 // } 19318 // } 19319 // 19320 // We want to retrieve the member expression 'this->S'; 19321 19322 // OpenMP 5.0 [2.19.7.1, map Clause, Restrictions, p.2] 19323 // If a list item is an array section, it must specify contiguous storage. 19324 // 19325 // For this restriction it is sufficient that we make sure only references 19326 // to variables or fields and array expressions, and that no array sections 19327 // exist except in the rightmost expression (unless they cover the whole 19328 // dimension of the array). E.g. these would be invalid: 19329 // 19330 // r.ArrS[3:5].Arr[6:7] 19331 // 19332 // r.ArrS[3:5].x 19333 // 19334 // but these would be valid: 19335 // r.ArrS[3].Arr[6:7] 19336 // 19337 // r.ArrS[3].x 19338 namespace { 19339 class MapBaseChecker final : public StmtVisitor<MapBaseChecker, bool> { 19340 Sema &SemaRef; 19341 OpenMPClauseKind CKind = OMPC_unknown; 19342 OpenMPDirectiveKind DKind = OMPD_unknown; 19343 OMPClauseMappableExprCommon::MappableExprComponentList &Components; 19344 bool IsNonContiguous = false; 19345 bool NoDiagnose = false; 19346 const Expr *RelevantExpr = nullptr; 19347 bool AllowUnitySizeArraySection = true; 19348 bool AllowWholeSizeArraySection = true; 19349 bool AllowAnotherPtr = true; 19350 SourceLocation ELoc; 19351 SourceRange ERange; 19352 19353 void emitErrorMsg() { 19354 // If nothing else worked, this is not a valid map clause expression. 19355 if (SemaRef.getLangOpts().OpenMP < 50) { 19356 SemaRef.Diag(ELoc, 19357 diag::err_omp_expected_named_var_member_or_array_expression) 19358 << ERange; 19359 } else { 19360 SemaRef.Diag(ELoc, diag::err_omp_non_lvalue_in_map_or_motion_clauses) 19361 << getOpenMPClauseName(CKind) << ERange; 19362 } 19363 } 19364 19365 public: 19366 bool VisitDeclRefExpr(DeclRefExpr *DRE) { 19367 if (!isa<VarDecl>(DRE->getDecl())) { 19368 emitErrorMsg(); 19369 return false; 19370 } 19371 assert(!RelevantExpr && "RelevantExpr is expected to be nullptr"); 19372 RelevantExpr = DRE; 19373 // Record the component. 19374 Components.emplace_back(DRE, DRE->getDecl(), IsNonContiguous); 19375 return true; 19376 } 19377 19378 bool VisitMemberExpr(MemberExpr *ME) { 19379 Expr *E = ME; 19380 Expr *BaseE = ME->getBase()->IgnoreParenCasts(); 19381 19382 if (isa<CXXThisExpr>(BaseE)) { 19383 assert(!RelevantExpr && "RelevantExpr is expected to be nullptr"); 19384 // We found a base expression: this->Val. 19385 RelevantExpr = ME; 19386 } else { 19387 E = BaseE; 19388 } 19389 19390 if (!isa<FieldDecl>(ME->getMemberDecl())) { 19391 if (!NoDiagnose) { 19392 SemaRef.Diag(ELoc, diag::err_omp_expected_access_to_data_field) 19393 << ME->getSourceRange(); 19394 return false; 19395 } 19396 if (RelevantExpr) 19397 return false; 19398 return Visit(E); 19399 } 19400 19401 auto *FD = cast<FieldDecl>(ME->getMemberDecl()); 19402 19403 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3] 19404 // A bit-field cannot appear in a map clause. 19405 // 19406 if (FD->isBitField()) { 19407 if (!NoDiagnose) { 19408 SemaRef.Diag(ELoc, diag::err_omp_bit_fields_forbidden_in_clause) 19409 << ME->getSourceRange() << getOpenMPClauseName(CKind); 19410 return false; 19411 } 19412 if (RelevantExpr) 19413 return false; 19414 return Visit(E); 19415 } 19416 19417 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1] 19418 // If the type of a list item is a reference to a type T then the type 19419 // will be considered to be T for all purposes of this clause. 19420 QualType CurType = BaseE->getType().getNonReferenceType(); 19421 19422 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.2] 19423 // A list item cannot be a variable that is a member of a structure with 19424 // a union type. 19425 // 19426 if (CurType->isUnionType()) { 19427 if (!NoDiagnose) { 19428 SemaRef.Diag(ELoc, diag::err_omp_union_type_not_allowed) 19429 << ME->getSourceRange(); 19430 return false; 19431 } 19432 return RelevantExpr || Visit(E); 19433 } 19434 19435 // If we got a member expression, we should not expect any array section 19436 // before that: 19437 // 19438 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.7] 19439 // If a list item is an element of a structure, only the rightmost symbol 19440 // of the variable reference can be an array section. 19441 // 19442 AllowUnitySizeArraySection = false; 19443 AllowWholeSizeArraySection = false; 19444 19445 // Record the component. 19446 Components.emplace_back(ME, FD, IsNonContiguous); 19447 return RelevantExpr || Visit(E); 19448 } 19449 19450 bool VisitArraySubscriptExpr(ArraySubscriptExpr *AE) { 19451 Expr *E = AE->getBase()->IgnoreParenImpCasts(); 19452 19453 if (!E->getType()->isAnyPointerType() && !E->getType()->isArrayType()) { 19454 if (!NoDiagnose) { 19455 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name) 19456 << 0 << AE->getSourceRange(); 19457 return false; 19458 } 19459 return RelevantExpr || Visit(E); 19460 } 19461 19462 // If we got an array subscript that express the whole dimension we 19463 // can have any array expressions before. If it only expressing part of 19464 // the dimension, we can only have unitary-size array expressions. 19465 if (checkArrayExpressionDoesNotReferToWholeSize(SemaRef, AE, E->getType())) 19466 AllowWholeSizeArraySection = false; 19467 19468 if (const auto *TE = dyn_cast<CXXThisExpr>(E->IgnoreParenCasts())) { 19469 Expr::EvalResult Result; 19470 if (!AE->getIdx()->isValueDependent() && 19471 AE->getIdx()->EvaluateAsInt(Result, SemaRef.getASTContext()) && 19472 !Result.Val.getInt().isZero()) { 19473 SemaRef.Diag(AE->getIdx()->getExprLoc(), 19474 diag::err_omp_invalid_map_this_expr); 19475 SemaRef.Diag(AE->getIdx()->getExprLoc(), 19476 diag::note_omp_invalid_subscript_on_this_ptr_map); 19477 } 19478 assert(!RelevantExpr && "RelevantExpr is expected to be nullptr"); 19479 RelevantExpr = TE; 19480 } 19481 19482 // Record the component - we don't have any declaration associated. 19483 Components.emplace_back(AE, nullptr, IsNonContiguous); 19484 19485 return RelevantExpr || Visit(E); 19486 } 19487 19488 bool VisitOMPArraySectionExpr(OMPArraySectionExpr *OASE) { 19489 // After OMP 5.0 Array section in reduction clause will be implicitly 19490 // mapped 19491 assert(!(SemaRef.getLangOpts().OpenMP < 50 && NoDiagnose) && 19492 "Array sections cannot be implicitly mapped."); 19493 Expr *E = OASE->getBase()->IgnoreParenImpCasts(); 19494 QualType CurType = 19495 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType(); 19496 19497 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1] 19498 // If the type of a list item is a reference to a type T then the type 19499 // will be considered to be T for all purposes of this clause. 19500 if (CurType->isReferenceType()) 19501 CurType = CurType->getPointeeType(); 19502 19503 bool IsPointer = CurType->isAnyPointerType(); 19504 19505 if (!IsPointer && !CurType->isArrayType()) { 19506 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name) 19507 << 0 << OASE->getSourceRange(); 19508 return false; 19509 } 19510 19511 bool NotWhole = 19512 checkArrayExpressionDoesNotReferToWholeSize(SemaRef, OASE, CurType); 19513 bool NotUnity = 19514 checkArrayExpressionDoesNotReferToUnitySize(SemaRef, OASE, CurType); 19515 19516 if (AllowWholeSizeArraySection) { 19517 // Any array section is currently allowed. Allowing a whole size array 19518 // section implies allowing a unity array section as well. 19519 // 19520 // If this array section refers to the whole dimension we can still 19521 // accept other array sections before this one, except if the base is a 19522 // pointer. Otherwise, only unitary sections are accepted. 19523 if (NotWhole || IsPointer) 19524 AllowWholeSizeArraySection = false; 19525 } else if (DKind == OMPD_target_update && 19526 SemaRef.getLangOpts().OpenMP >= 50) { 19527 if (IsPointer && !AllowAnotherPtr) 19528 SemaRef.Diag(ELoc, diag::err_omp_section_length_undefined) 19529 << /*array of unknown bound */ 1; 19530 else 19531 IsNonContiguous = true; 19532 } else if (AllowUnitySizeArraySection && NotUnity) { 19533 // A unity or whole array section is not allowed and that is not 19534 // compatible with the properties of the current array section. 19535 if (NoDiagnose) 19536 return false; 19537 SemaRef.Diag(ELoc, 19538 diag::err_array_section_does_not_specify_contiguous_storage) 19539 << OASE->getSourceRange(); 19540 return false; 19541 } 19542 19543 if (IsPointer) 19544 AllowAnotherPtr = false; 19545 19546 if (const auto *TE = dyn_cast<CXXThisExpr>(E)) { 19547 Expr::EvalResult ResultR; 19548 Expr::EvalResult ResultL; 19549 if (!OASE->getLength()->isValueDependent() && 19550 OASE->getLength()->EvaluateAsInt(ResultR, SemaRef.getASTContext()) && 19551 !ResultR.Val.getInt().isOne()) { 19552 SemaRef.Diag(OASE->getLength()->getExprLoc(), 19553 diag::err_omp_invalid_map_this_expr); 19554 SemaRef.Diag(OASE->getLength()->getExprLoc(), 19555 diag::note_omp_invalid_length_on_this_ptr_mapping); 19556 } 19557 if (OASE->getLowerBound() && !OASE->getLowerBound()->isValueDependent() && 19558 OASE->getLowerBound()->EvaluateAsInt(ResultL, 19559 SemaRef.getASTContext()) && 19560 !ResultL.Val.getInt().isZero()) { 19561 SemaRef.Diag(OASE->getLowerBound()->getExprLoc(), 19562 diag::err_omp_invalid_map_this_expr); 19563 SemaRef.Diag(OASE->getLowerBound()->getExprLoc(), 19564 diag::note_omp_invalid_lower_bound_on_this_ptr_mapping); 19565 } 19566 assert(!RelevantExpr && "RelevantExpr is expected to be nullptr"); 19567 RelevantExpr = TE; 19568 } 19569 19570 // Record the component - we don't have any declaration associated. 19571 Components.emplace_back(OASE, nullptr, /*IsNonContiguous=*/false); 19572 return RelevantExpr || Visit(E); 19573 } 19574 bool VisitOMPArrayShapingExpr(OMPArrayShapingExpr *E) { 19575 Expr *Base = E->getBase(); 19576 19577 // Record the component - we don't have any declaration associated. 19578 Components.emplace_back(E, nullptr, IsNonContiguous); 19579 19580 return Visit(Base->IgnoreParenImpCasts()); 19581 } 19582 19583 bool VisitUnaryOperator(UnaryOperator *UO) { 19584 if (SemaRef.getLangOpts().OpenMP < 50 || !UO->isLValue() || 19585 UO->getOpcode() != UO_Deref) { 19586 emitErrorMsg(); 19587 return false; 19588 } 19589 if (!RelevantExpr) { 19590 // Record the component if haven't found base decl. 19591 Components.emplace_back(UO, nullptr, /*IsNonContiguous=*/false); 19592 } 19593 return RelevantExpr || Visit(UO->getSubExpr()->IgnoreParenImpCasts()); 19594 } 19595 bool VisitBinaryOperator(BinaryOperator *BO) { 19596 if (SemaRef.getLangOpts().OpenMP < 50 || !BO->getType()->isPointerType()) { 19597 emitErrorMsg(); 19598 return false; 19599 } 19600 19601 // Pointer arithmetic is the only thing we expect to happen here so after we 19602 // make sure the binary operator is a pointer type, the we only thing need 19603 // to to is to visit the subtree that has the same type as root (so that we 19604 // know the other subtree is just an offset) 19605 Expr *LE = BO->getLHS()->IgnoreParenImpCasts(); 19606 Expr *RE = BO->getRHS()->IgnoreParenImpCasts(); 19607 Components.emplace_back(BO, nullptr, false); 19608 assert((LE->getType().getTypePtr() == BO->getType().getTypePtr() || 19609 RE->getType().getTypePtr() == BO->getType().getTypePtr()) && 19610 "Either LHS or RHS have base decl inside"); 19611 if (BO->getType().getTypePtr() == LE->getType().getTypePtr()) 19612 return RelevantExpr || Visit(LE); 19613 return RelevantExpr || Visit(RE); 19614 } 19615 bool VisitCXXThisExpr(CXXThisExpr *CTE) { 19616 assert(!RelevantExpr && "RelevantExpr is expected to be nullptr"); 19617 RelevantExpr = CTE; 19618 Components.emplace_back(CTE, nullptr, IsNonContiguous); 19619 return true; 19620 } 19621 bool VisitCXXOperatorCallExpr(CXXOperatorCallExpr *COCE) { 19622 assert(!RelevantExpr && "RelevantExpr is expected to be nullptr"); 19623 Components.emplace_back(COCE, nullptr, IsNonContiguous); 19624 return true; 19625 } 19626 bool VisitOpaqueValueExpr(OpaqueValueExpr *E) { 19627 Expr *Source = E->getSourceExpr(); 19628 if (!Source) { 19629 emitErrorMsg(); 19630 return false; 19631 } 19632 return Visit(Source); 19633 } 19634 bool VisitStmt(Stmt *) { 19635 emitErrorMsg(); 19636 return false; 19637 } 19638 const Expr *getFoundBase() const { return RelevantExpr; } 19639 explicit MapBaseChecker( 19640 Sema &SemaRef, OpenMPClauseKind CKind, OpenMPDirectiveKind DKind, 19641 OMPClauseMappableExprCommon::MappableExprComponentList &Components, 19642 bool NoDiagnose, SourceLocation &ELoc, SourceRange &ERange) 19643 : SemaRef(SemaRef), CKind(CKind), DKind(DKind), Components(Components), 19644 NoDiagnose(NoDiagnose), ELoc(ELoc), ERange(ERange) {} 19645 }; 19646 } // namespace 19647 19648 /// Return the expression of the base of the mappable expression or null if it 19649 /// cannot be determined and do all the necessary checks to see if the 19650 /// expression is valid as a standalone mappable expression. In the process, 19651 /// record all the components of the expression. 19652 static const Expr *checkMapClauseExpressionBase( 19653 Sema &SemaRef, Expr *E, 19654 OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents, 19655 OpenMPClauseKind CKind, OpenMPDirectiveKind DKind, bool NoDiagnose) { 19656 SourceLocation ELoc = E->getExprLoc(); 19657 SourceRange ERange = E->getSourceRange(); 19658 MapBaseChecker Checker(SemaRef, CKind, DKind, CurComponents, NoDiagnose, ELoc, 19659 ERange); 19660 if (Checker.Visit(E->IgnoreParens())) { 19661 // Check if the highest dimension array section has length specified 19662 if (SemaRef.getLangOpts().OpenMP >= 50 && !CurComponents.empty() && 19663 (CKind == OMPC_to || CKind == OMPC_from)) { 19664 auto CI = CurComponents.rbegin(); 19665 auto CE = CurComponents.rend(); 19666 for (; CI != CE; ++CI) { 19667 const auto *OASE = 19668 dyn_cast<OMPArraySectionExpr>(CI->getAssociatedExpression()); 19669 if (!OASE) 19670 continue; 19671 if (OASE && OASE->getLength()) 19672 break; 19673 SemaRef.Diag(ELoc, diag::err_array_section_does_not_specify_length) 19674 << ERange; 19675 } 19676 } 19677 return Checker.getFoundBase(); 19678 } 19679 return nullptr; 19680 } 19681 19682 // Return true if expression E associated with value VD has conflicts with other 19683 // map information. 19684 static bool checkMapConflicts( 19685 Sema &SemaRef, DSAStackTy *DSAS, const ValueDecl *VD, const Expr *E, 19686 bool CurrentRegionOnly, 19687 OMPClauseMappableExprCommon::MappableExprComponentListRef CurComponents, 19688 OpenMPClauseKind CKind) { 19689 assert(VD && E); 19690 SourceLocation ELoc = E->getExprLoc(); 19691 SourceRange ERange = E->getSourceRange(); 19692 19693 // In order to easily check the conflicts we need to match each component of 19694 // the expression under test with the components of the expressions that are 19695 // already in the stack. 19696 19697 assert(!CurComponents.empty() && "Map clause expression with no components!"); 19698 assert(CurComponents.back().getAssociatedDeclaration() == VD && 19699 "Map clause expression with unexpected base!"); 19700 19701 // Variables to help detecting enclosing problems in data environment nests. 19702 bool IsEnclosedByDataEnvironmentExpr = false; 19703 const Expr *EnclosingExpr = nullptr; 19704 19705 bool FoundError = DSAS->checkMappableExprComponentListsForDecl( 19706 VD, CurrentRegionOnly, 19707 [&IsEnclosedByDataEnvironmentExpr, &SemaRef, VD, CurrentRegionOnly, ELoc, 19708 ERange, CKind, &EnclosingExpr, 19709 CurComponents](OMPClauseMappableExprCommon::MappableExprComponentListRef 19710 StackComponents, 19711 OpenMPClauseKind Kind) { 19712 if (CKind == Kind && SemaRef.LangOpts.OpenMP >= 50) 19713 return false; 19714 assert(!StackComponents.empty() && 19715 "Map clause expression with no components!"); 19716 assert(StackComponents.back().getAssociatedDeclaration() == VD && 19717 "Map clause expression with unexpected base!"); 19718 (void)VD; 19719 19720 // The whole expression in the stack. 19721 const Expr *RE = StackComponents.front().getAssociatedExpression(); 19722 19723 // Expressions must start from the same base. Here we detect at which 19724 // point both expressions diverge from each other and see if we can 19725 // detect if the memory referred to both expressions is contiguous and 19726 // do not overlap. 19727 auto CI = CurComponents.rbegin(); 19728 auto CE = CurComponents.rend(); 19729 auto SI = StackComponents.rbegin(); 19730 auto SE = StackComponents.rend(); 19731 for (; CI != CE && SI != SE; ++CI, ++SI) { 19732 19733 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.3] 19734 // At most one list item can be an array item derived from a given 19735 // variable in map clauses of the same construct. 19736 if (CurrentRegionOnly && 19737 (isa<ArraySubscriptExpr>(CI->getAssociatedExpression()) || 19738 isa<OMPArraySectionExpr>(CI->getAssociatedExpression()) || 19739 isa<OMPArrayShapingExpr>(CI->getAssociatedExpression())) && 19740 (isa<ArraySubscriptExpr>(SI->getAssociatedExpression()) || 19741 isa<OMPArraySectionExpr>(SI->getAssociatedExpression()) || 19742 isa<OMPArrayShapingExpr>(SI->getAssociatedExpression()))) { 19743 SemaRef.Diag(CI->getAssociatedExpression()->getExprLoc(), 19744 diag::err_omp_multiple_array_items_in_map_clause) 19745 << CI->getAssociatedExpression()->getSourceRange(); 19746 SemaRef.Diag(SI->getAssociatedExpression()->getExprLoc(), 19747 diag::note_used_here) 19748 << SI->getAssociatedExpression()->getSourceRange(); 19749 return true; 19750 } 19751 19752 // Do both expressions have the same kind? 19753 if (CI->getAssociatedExpression()->getStmtClass() != 19754 SI->getAssociatedExpression()->getStmtClass()) 19755 break; 19756 19757 // Are we dealing with different variables/fields? 19758 if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration()) 19759 break; 19760 } 19761 // Check if the extra components of the expressions in the enclosing 19762 // data environment are redundant for the current base declaration. 19763 // If they are, the maps completely overlap, which is legal. 19764 for (; SI != SE; ++SI) { 19765 QualType Type; 19766 if (const auto *ASE = 19767 dyn_cast<ArraySubscriptExpr>(SI->getAssociatedExpression())) { 19768 Type = ASE->getBase()->IgnoreParenImpCasts()->getType(); 19769 } else if (const auto *OASE = dyn_cast<OMPArraySectionExpr>( 19770 SI->getAssociatedExpression())) { 19771 const Expr *E = OASE->getBase()->IgnoreParenImpCasts(); 19772 Type = 19773 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType(); 19774 } else if (const auto *OASE = dyn_cast<OMPArrayShapingExpr>( 19775 SI->getAssociatedExpression())) { 19776 Type = OASE->getBase()->getType()->getPointeeType(); 19777 } 19778 if (Type.isNull() || Type->isAnyPointerType() || 19779 checkArrayExpressionDoesNotReferToWholeSize( 19780 SemaRef, SI->getAssociatedExpression(), Type)) 19781 break; 19782 } 19783 19784 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4] 19785 // List items of map clauses in the same construct must not share 19786 // original storage. 19787 // 19788 // If the expressions are exactly the same or one is a subset of the 19789 // other, it means they are sharing storage. 19790 if (CI == CE && SI == SE) { 19791 if (CurrentRegionOnly) { 19792 if (CKind == OMPC_map) { 19793 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange; 19794 } else { 19795 assert(CKind == OMPC_to || CKind == OMPC_from); 19796 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update) 19797 << ERange; 19798 } 19799 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here) 19800 << RE->getSourceRange(); 19801 return true; 19802 } 19803 // If we find the same expression in the enclosing data environment, 19804 // that is legal. 19805 IsEnclosedByDataEnvironmentExpr = true; 19806 return false; 19807 } 19808 19809 QualType DerivedType = 19810 std::prev(CI)->getAssociatedDeclaration()->getType(); 19811 SourceLocation DerivedLoc = 19812 std::prev(CI)->getAssociatedExpression()->getExprLoc(); 19813 19814 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1] 19815 // If the type of a list item is a reference to a type T then the type 19816 // will be considered to be T for all purposes of this clause. 19817 DerivedType = DerivedType.getNonReferenceType(); 19818 19819 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.1] 19820 // A variable for which the type is pointer and an array section 19821 // derived from that variable must not appear as list items of map 19822 // clauses of the same construct. 19823 // 19824 // Also, cover one of the cases in: 19825 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5] 19826 // If any part of the original storage of a list item has corresponding 19827 // storage in the device data environment, all of the original storage 19828 // must have corresponding storage in the device data environment. 19829 // 19830 if (DerivedType->isAnyPointerType()) { 19831 if (CI == CE || SI == SE) { 19832 SemaRef.Diag( 19833 DerivedLoc, 19834 diag::err_omp_pointer_mapped_along_with_derived_section) 19835 << DerivedLoc; 19836 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here) 19837 << RE->getSourceRange(); 19838 return true; 19839 } 19840 if (CI->getAssociatedExpression()->getStmtClass() != 19841 SI->getAssociatedExpression()->getStmtClass() || 19842 CI->getAssociatedDeclaration()->getCanonicalDecl() == 19843 SI->getAssociatedDeclaration()->getCanonicalDecl()) { 19844 assert(CI != CE && SI != SE); 19845 SemaRef.Diag(DerivedLoc, diag::err_omp_same_pointer_dereferenced) 19846 << DerivedLoc; 19847 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here) 19848 << RE->getSourceRange(); 19849 return true; 19850 } 19851 } 19852 19853 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4] 19854 // List items of map clauses in the same construct must not share 19855 // original storage. 19856 // 19857 // An expression is a subset of the other. 19858 if (CurrentRegionOnly && (CI == CE || SI == SE)) { 19859 if (CKind == OMPC_map) { 19860 if (CI != CE || SI != SE) { 19861 // Allow constructs like this: map(s, s.ptr[0:1]), where s.ptr is 19862 // a pointer. 19863 auto Begin = 19864 CI != CE ? CurComponents.begin() : StackComponents.begin(); 19865 auto End = CI != CE ? CurComponents.end() : StackComponents.end(); 19866 auto It = Begin; 19867 while (It != End && !It->getAssociatedDeclaration()) 19868 std::advance(It, 1); 19869 assert(It != End && 19870 "Expected at least one component with the declaration."); 19871 if (It != Begin && It->getAssociatedDeclaration() 19872 ->getType() 19873 .getCanonicalType() 19874 ->isAnyPointerType()) { 19875 IsEnclosedByDataEnvironmentExpr = false; 19876 EnclosingExpr = nullptr; 19877 return false; 19878 } 19879 } 19880 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange; 19881 } else { 19882 assert(CKind == OMPC_to || CKind == OMPC_from); 19883 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update) 19884 << ERange; 19885 } 19886 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here) 19887 << RE->getSourceRange(); 19888 return true; 19889 } 19890 19891 // The current expression uses the same base as other expression in the 19892 // data environment but does not contain it completely. 19893 if (!CurrentRegionOnly && SI != SE) 19894 EnclosingExpr = RE; 19895 19896 // The current expression is a subset of the expression in the data 19897 // environment. 19898 IsEnclosedByDataEnvironmentExpr |= 19899 (!CurrentRegionOnly && CI != CE && SI == SE); 19900 19901 return false; 19902 }); 19903 19904 if (CurrentRegionOnly) 19905 return FoundError; 19906 19907 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5] 19908 // If any part of the original storage of a list item has corresponding 19909 // storage in the device data environment, all of the original storage must 19910 // have corresponding storage in the device data environment. 19911 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.6] 19912 // If a list item is an element of a structure, and a different element of 19913 // the structure has a corresponding list item in the device data environment 19914 // prior to a task encountering the construct associated with the map clause, 19915 // then the list item must also have a corresponding list item in the device 19916 // data environment prior to the task encountering the construct. 19917 // 19918 if (EnclosingExpr && !IsEnclosedByDataEnvironmentExpr) { 19919 SemaRef.Diag(ELoc, 19920 diag::err_omp_original_storage_is_shared_and_does_not_contain) 19921 << ERange; 19922 SemaRef.Diag(EnclosingExpr->getExprLoc(), diag::note_used_here) 19923 << EnclosingExpr->getSourceRange(); 19924 return true; 19925 } 19926 19927 return FoundError; 19928 } 19929 19930 // Look up the user-defined mapper given the mapper name and mapped type, and 19931 // build a reference to it. 19932 static ExprResult buildUserDefinedMapperRef(Sema &SemaRef, Scope *S, 19933 CXXScopeSpec &MapperIdScopeSpec, 19934 const DeclarationNameInfo &MapperId, 19935 QualType Type, 19936 Expr *UnresolvedMapper) { 19937 if (MapperIdScopeSpec.isInvalid()) 19938 return ExprError(); 19939 // Get the actual type for the array type. 19940 if (Type->isArrayType()) { 19941 assert(Type->getAsArrayTypeUnsafe() && "Expect to get a valid array type"); 19942 Type = Type->getAsArrayTypeUnsafe()->getElementType().getCanonicalType(); 19943 } 19944 // Find all user-defined mappers with the given MapperId. 19945 SmallVector<UnresolvedSet<8>, 4> Lookups; 19946 LookupResult Lookup(SemaRef, MapperId, Sema::LookupOMPMapperName); 19947 Lookup.suppressDiagnostics(); 19948 if (S) { 19949 while (S && SemaRef.LookupParsedName(Lookup, S, &MapperIdScopeSpec)) { 19950 NamedDecl *D = Lookup.getRepresentativeDecl(); 19951 while (S && !S->isDeclScope(D)) 19952 S = S->getParent(); 19953 if (S) 19954 S = S->getParent(); 19955 Lookups.emplace_back(); 19956 Lookups.back().append(Lookup.begin(), Lookup.end()); 19957 Lookup.clear(); 19958 } 19959 } else if (auto *ULE = cast_or_null<UnresolvedLookupExpr>(UnresolvedMapper)) { 19960 // Extract the user-defined mappers with the given MapperId. 19961 Lookups.push_back(UnresolvedSet<8>()); 19962 for (NamedDecl *D : ULE->decls()) { 19963 auto *DMD = cast<OMPDeclareMapperDecl>(D); 19964 assert(DMD && "Expect valid OMPDeclareMapperDecl during instantiation."); 19965 Lookups.back().addDecl(DMD); 19966 } 19967 } 19968 // Defer the lookup for dependent types. The results will be passed through 19969 // UnresolvedMapper on instantiation. 19970 if (SemaRef.CurContext->isDependentContext() || Type->isDependentType() || 19971 Type->isInstantiationDependentType() || 19972 Type->containsUnexpandedParameterPack() || 19973 filterLookupForUDReductionAndMapper<bool>(Lookups, [](ValueDecl *D) { 19974 return !D->isInvalidDecl() && 19975 (D->getType()->isDependentType() || 19976 D->getType()->isInstantiationDependentType() || 19977 D->getType()->containsUnexpandedParameterPack()); 19978 })) { 19979 UnresolvedSet<8> URS; 19980 for (const UnresolvedSet<8> &Set : Lookups) { 19981 if (Set.empty()) 19982 continue; 19983 URS.append(Set.begin(), Set.end()); 19984 } 19985 return UnresolvedLookupExpr::Create( 19986 SemaRef.Context, /*NamingClass=*/nullptr, 19987 MapperIdScopeSpec.getWithLocInContext(SemaRef.Context), MapperId, 19988 /*ADL=*/false, /*Overloaded=*/true, URS.begin(), URS.end()); 19989 } 19990 SourceLocation Loc = MapperId.getLoc(); 19991 // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions 19992 // The type must be of struct, union or class type in C and C++ 19993 if (!Type->isStructureOrClassType() && !Type->isUnionType() && 19994 (MapperIdScopeSpec.isSet() || MapperId.getAsString() != "default")) { 19995 SemaRef.Diag(Loc, diag::err_omp_mapper_wrong_type); 19996 return ExprError(); 19997 } 19998 // Perform argument dependent lookup. 19999 if (SemaRef.getLangOpts().CPlusPlus && !MapperIdScopeSpec.isSet()) 20000 argumentDependentLookup(SemaRef, MapperId, Loc, Type, Lookups); 20001 // Return the first user-defined mapper with the desired type. 20002 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>( 20003 Lookups, [&SemaRef, Type](ValueDecl *D) -> ValueDecl * { 20004 if (!D->isInvalidDecl() && 20005 SemaRef.Context.hasSameType(D->getType(), Type)) 20006 return D; 20007 return nullptr; 20008 })) 20009 return SemaRef.BuildDeclRefExpr(VD, Type, VK_LValue, Loc); 20010 // Find the first user-defined mapper with a type derived from the desired 20011 // type. 20012 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>( 20013 Lookups, [&SemaRef, Type, Loc](ValueDecl *D) -> ValueDecl * { 20014 if (!D->isInvalidDecl() && 20015 SemaRef.IsDerivedFrom(Loc, Type, D->getType()) && 20016 !Type.isMoreQualifiedThan(D->getType())) 20017 return D; 20018 return nullptr; 20019 })) { 20020 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 20021 /*DetectVirtual=*/false); 20022 if (SemaRef.IsDerivedFrom(Loc, Type, VD->getType(), Paths)) { 20023 if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType( 20024 VD->getType().getUnqualifiedType()))) { 20025 if (SemaRef.CheckBaseClassAccess( 20026 Loc, VD->getType(), Type, Paths.front(), 20027 /*DiagID=*/0) != Sema::AR_inaccessible) { 20028 return SemaRef.BuildDeclRefExpr(VD, Type, VK_LValue, Loc); 20029 } 20030 } 20031 } 20032 } 20033 // Report error if a mapper is specified, but cannot be found. 20034 if (MapperIdScopeSpec.isSet() || MapperId.getAsString() != "default") { 20035 SemaRef.Diag(Loc, diag::err_omp_invalid_mapper) 20036 << Type << MapperId.getName(); 20037 return ExprError(); 20038 } 20039 return ExprEmpty(); 20040 } 20041 20042 namespace { 20043 // Utility struct that gathers all the related lists associated with a mappable 20044 // expression. 20045 struct MappableVarListInfo { 20046 // The list of expressions. 20047 ArrayRef<Expr *> VarList; 20048 // The list of processed expressions. 20049 SmallVector<Expr *, 16> ProcessedVarList; 20050 // The mappble components for each expression. 20051 OMPClauseMappableExprCommon::MappableExprComponentLists VarComponents; 20052 // The base declaration of the variable. 20053 SmallVector<ValueDecl *, 16> VarBaseDeclarations; 20054 // The reference to the user-defined mapper associated with every expression. 20055 SmallVector<Expr *, 16> UDMapperList; 20056 20057 MappableVarListInfo(ArrayRef<Expr *> VarList) : VarList(VarList) { 20058 // We have a list of components and base declarations for each entry in the 20059 // variable list. 20060 VarComponents.reserve(VarList.size()); 20061 VarBaseDeclarations.reserve(VarList.size()); 20062 } 20063 }; 20064 } // namespace 20065 20066 // Check the validity of the provided variable list for the provided clause kind 20067 // \a CKind. In the check process the valid expressions, mappable expression 20068 // components, variables, and user-defined mappers are extracted and used to 20069 // fill \a ProcessedVarList, \a VarComponents, \a VarBaseDeclarations, and \a 20070 // UDMapperList in MVLI. \a MapType, \a IsMapTypeImplicit, \a MapperIdScopeSpec, 20071 // and \a MapperId are expected to be valid if the clause kind is 'map'. 20072 static void checkMappableExpressionList( 20073 Sema &SemaRef, DSAStackTy *DSAS, OpenMPClauseKind CKind, 20074 MappableVarListInfo &MVLI, SourceLocation StartLoc, 20075 CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo MapperId, 20076 ArrayRef<Expr *> UnresolvedMappers, 20077 OpenMPMapClauseKind MapType = OMPC_MAP_unknown, 20078 ArrayRef<OpenMPMapModifierKind> Modifiers = None, 20079 bool IsMapTypeImplicit = false, bool NoDiagnose = false) { 20080 // We only expect mappable expressions in 'to', 'from', and 'map' clauses. 20081 assert((CKind == OMPC_map || CKind == OMPC_to || CKind == OMPC_from) && 20082 "Unexpected clause kind with mappable expressions!"); 20083 20084 // If the identifier of user-defined mapper is not specified, it is "default". 20085 // We do not change the actual name in this clause to distinguish whether a 20086 // mapper is specified explicitly, i.e., it is not explicitly specified when 20087 // MapperId.getName() is empty. 20088 if (!MapperId.getName() || MapperId.getName().isEmpty()) { 20089 auto &DeclNames = SemaRef.getASTContext().DeclarationNames; 20090 MapperId.setName(DeclNames.getIdentifier( 20091 &SemaRef.getASTContext().Idents.get("default"))); 20092 MapperId.setLoc(StartLoc); 20093 } 20094 20095 // Iterators to find the current unresolved mapper expression. 20096 auto UMIt = UnresolvedMappers.begin(), UMEnd = UnresolvedMappers.end(); 20097 bool UpdateUMIt = false; 20098 Expr *UnresolvedMapper = nullptr; 20099 20100 bool HasHoldModifier = 20101 llvm::is_contained(Modifiers, OMPC_MAP_MODIFIER_ompx_hold); 20102 20103 // Keep track of the mappable components and base declarations in this clause. 20104 // Each entry in the list is going to have a list of components associated. We 20105 // record each set of the components so that we can build the clause later on. 20106 // In the end we should have the same amount of declarations and component 20107 // lists. 20108 20109 for (Expr *RE : MVLI.VarList) { 20110 assert(RE && "Null expr in omp to/from/map clause"); 20111 SourceLocation ELoc = RE->getExprLoc(); 20112 20113 // Find the current unresolved mapper expression. 20114 if (UpdateUMIt && UMIt != UMEnd) { 20115 UMIt++; 20116 assert( 20117 UMIt != UMEnd && 20118 "Expect the size of UnresolvedMappers to match with that of VarList"); 20119 } 20120 UpdateUMIt = true; 20121 if (UMIt != UMEnd) 20122 UnresolvedMapper = *UMIt; 20123 20124 const Expr *VE = RE->IgnoreParenLValueCasts(); 20125 20126 if (VE->isValueDependent() || VE->isTypeDependent() || 20127 VE->isInstantiationDependent() || 20128 VE->containsUnexpandedParameterPack()) { 20129 // Try to find the associated user-defined mapper. 20130 ExprResult ER = buildUserDefinedMapperRef( 20131 SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId, 20132 VE->getType().getCanonicalType(), UnresolvedMapper); 20133 if (ER.isInvalid()) 20134 continue; 20135 MVLI.UDMapperList.push_back(ER.get()); 20136 // We can only analyze this information once the missing information is 20137 // resolved. 20138 MVLI.ProcessedVarList.push_back(RE); 20139 continue; 20140 } 20141 20142 Expr *SimpleExpr = RE->IgnoreParenCasts(); 20143 20144 if (!RE->isLValue()) { 20145 if (SemaRef.getLangOpts().OpenMP < 50) { 20146 SemaRef.Diag( 20147 ELoc, diag::err_omp_expected_named_var_member_or_array_expression) 20148 << RE->getSourceRange(); 20149 } else { 20150 SemaRef.Diag(ELoc, diag::err_omp_non_lvalue_in_map_or_motion_clauses) 20151 << getOpenMPClauseName(CKind) << RE->getSourceRange(); 20152 } 20153 continue; 20154 } 20155 20156 OMPClauseMappableExprCommon::MappableExprComponentList CurComponents; 20157 ValueDecl *CurDeclaration = nullptr; 20158 20159 // Obtain the array or member expression bases if required. Also, fill the 20160 // components array with all the components identified in the process. 20161 const Expr *BE = 20162 checkMapClauseExpressionBase(SemaRef, SimpleExpr, CurComponents, CKind, 20163 DSAS->getCurrentDirective(), NoDiagnose); 20164 if (!BE) 20165 continue; 20166 20167 assert(!CurComponents.empty() && 20168 "Invalid mappable expression information."); 20169 20170 if (const auto *TE = dyn_cast<CXXThisExpr>(BE)) { 20171 // Add store "this" pointer to class in DSAStackTy for future checking 20172 DSAS->addMappedClassesQualTypes(TE->getType()); 20173 // Try to find the associated user-defined mapper. 20174 ExprResult ER = buildUserDefinedMapperRef( 20175 SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId, 20176 VE->getType().getCanonicalType(), UnresolvedMapper); 20177 if (ER.isInvalid()) 20178 continue; 20179 MVLI.UDMapperList.push_back(ER.get()); 20180 // Skip restriction checking for variable or field declarations 20181 MVLI.ProcessedVarList.push_back(RE); 20182 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1); 20183 MVLI.VarComponents.back().append(CurComponents.begin(), 20184 CurComponents.end()); 20185 MVLI.VarBaseDeclarations.push_back(nullptr); 20186 continue; 20187 } 20188 20189 // For the following checks, we rely on the base declaration which is 20190 // expected to be associated with the last component. The declaration is 20191 // expected to be a variable or a field (if 'this' is being mapped). 20192 CurDeclaration = CurComponents.back().getAssociatedDeclaration(); 20193 assert(CurDeclaration && "Null decl on map clause."); 20194 assert( 20195 CurDeclaration->isCanonicalDecl() && 20196 "Expecting components to have associated only canonical declarations."); 20197 20198 auto *VD = dyn_cast<VarDecl>(CurDeclaration); 20199 const auto *FD = dyn_cast<FieldDecl>(CurDeclaration); 20200 20201 assert((VD || FD) && "Only variables or fields are expected here!"); 20202 (void)FD; 20203 20204 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.10] 20205 // threadprivate variables cannot appear in a map clause. 20206 // OpenMP 4.5 [2.10.5, target update Construct] 20207 // threadprivate variables cannot appear in a from clause. 20208 if (VD && DSAS->isThreadPrivate(VD)) { 20209 if (NoDiagnose) 20210 continue; 20211 DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false); 20212 SemaRef.Diag(ELoc, diag::err_omp_threadprivate_in_clause) 20213 << getOpenMPClauseName(CKind); 20214 reportOriginalDsa(SemaRef, DSAS, VD, DVar); 20215 continue; 20216 } 20217 20218 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9] 20219 // A list item cannot appear in both a map clause and a data-sharing 20220 // attribute clause on the same construct. 20221 20222 // Check conflicts with other map clause expressions. We check the conflicts 20223 // with the current construct separately from the enclosing data 20224 // environment, because the restrictions are different. We only have to 20225 // check conflicts across regions for the map clauses. 20226 if (checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr, 20227 /*CurrentRegionOnly=*/true, CurComponents, CKind)) 20228 break; 20229 if (CKind == OMPC_map && 20230 (SemaRef.getLangOpts().OpenMP <= 45 || StartLoc.isValid()) && 20231 checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr, 20232 /*CurrentRegionOnly=*/false, CurComponents, CKind)) 20233 break; 20234 20235 // OpenMP 4.5 [2.10.5, target update Construct] 20236 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1] 20237 // If the type of a list item is a reference to a type T then the type will 20238 // be considered to be T for all purposes of this clause. 20239 auto I = llvm::find_if( 20240 CurComponents, 20241 [](const OMPClauseMappableExprCommon::MappableComponent &MC) { 20242 return MC.getAssociatedDeclaration(); 20243 }); 20244 assert(I != CurComponents.end() && "Null decl on map clause."); 20245 (void)I; 20246 QualType Type; 20247 auto *ASE = dyn_cast<ArraySubscriptExpr>(VE->IgnoreParens()); 20248 auto *OASE = dyn_cast<OMPArraySectionExpr>(VE->IgnoreParens()); 20249 auto *OAShE = dyn_cast<OMPArrayShapingExpr>(VE->IgnoreParens()); 20250 if (ASE) { 20251 Type = ASE->getType().getNonReferenceType(); 20252 } else if (OASE) { 20253 QualType BaseType = 20254 OMPArraySectionExpr::getBaseOriginalType(OASE->getBase()); 20255 if (const auto *ATy = BaseType->getAsArrayTypeUnsafe()) 20256 Type = ATy->getElementType(); 20257 else 20258 Type = BaseType->getPointeeType(); 20259 Type = Type.getNonReferenceType(); 20260 } else if (OAShE) { 20261 Type = OAShE->getBase()->getType()->getPointeeType(); 20262 } else { 20263 Type = VE->getType(); 20264 } 20265 20266 // OpenMP 4.5 [2.10.5, target update Construct, Restrictions, p.4] 20267 // A list item in a to or from clause must have a mappable type. 20268 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9] 20269 // A list item must have a mappable type. 20270 if (!checkTypeMappable(VE->getExprLoc(), VE->getSourceRange(), SemaRef, 20271 DSAS, Type, /*FullCheck=*/true)) 20272 continue; 20273 20274 if (CKind == OMPC_map) { 20275 // target enter data 20276 // OpenMP [2.10.2, Restrictions, p. 99] 20277 // A map-type must be specified in all map clauses and must be either 20278 // to or alloc. 20279 OpenMPDirectiveKind DKind = DSAS->getCurrentDirective(); 20280 if (DKind == OMPD_target_enter_data && 20281 !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_alloc)) { 20282 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive) 20283 << (IsMapTypeImplicit ? 1 : 0) 20284 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType) 20285 << getOpenMPDirectiveName(DKind); 20286 continue; 20287 } 20288 20289 // target exit_data 20290 // OpenMP [2.10.3, Restrictions, p. 102] 20291 // A map-type must be specified in all map clauses and must be either 20292 // from, release, or delete. 20293 if (DKind == OMPD_target_exit_data && 20294 !(MapType == OMPC_MAP_from || MapType == OMPC_MAP_release || 20295 MapType == OMPC_MAP_delete)) { 20296 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive) 20297 << (IsMapTypeImplicit ? 1 : 0) 20298 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType) 20299 << getOpenMPDirectiveName(DKind); 20300 continue; 20301 } 20302 20303 // The 'ompx_hold' modifier is specifically intended to be used on a 20304 // 'target' or 'target data' directive to prevent data from being unmapped 20305 // during the associated statement. It is not permitted on a 'target 20306 // enter data' or 'target exit data' directive, which have no associated 20307 // statement. 20308 if ((DKind == OMPD_target_enter_data || DKind == OMPD_target_exit_data) && 20309 HasHoldModifier) { 20310 SemaRef.Diag(StartLoc, 20311 diag::err_omp_invalid_map_type_modifier_for_directive) 20312 << getOpenMPSimpleClauseTypeName(OMPC_map, 20313 OMPC_MAP_MODIFIER_ompx_hold) 20314 << getOpenMPDirectiveName(DKind); 20315 continue; 20316 } 20317 20318 // target, target data 20319 // OpenMP 5.0 [2.12.2, Restrictions, p. 163] 20320 // OpenMP 5.0 [2.12.5, Restrictions, p. 174] 20321 // A map-type in a map clause must be to, from, tofrom or alloc 20322 if ((DKind == OMPD_target_data || 20323 isOpenMPTargetExecutionDirective(DKind)) && 20324 !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_from || 20325 MapType == OMPC_MAP_tofrom || MapType == OMPC_MAP_alloc)) { 20326 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive) 20327 << (IsMapTypeImplicit ? 1 : 0) 20328 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType) 20329 << getOpenMPDirectiveName(DKind); 20330 continue; 20331 } 20332 20333 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3] 20334 // A list item cannot appear in both a map clause and a data-sharing 20335 // attribute clause on the same construct 20336 // 20337 // OpenMP 5.0 [2.19.7.1, Restrictions, p.7] 20338 // A list item cannot appear in both a map clause and a data-sharing 20339 // attribute clause on the same construct unless the construct is a 20340 // combined construct. 20341 if (VD && ((SemaRef.LangOpts.OpenMP <= 45 && 20342 isOpenMPTargetExecutionDirective(DKind)) || 20343 DKind == OMPD_target)) { 20344 DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false); 20345 if (isOpenMPPrivate(DVar.CKind)) { 20346 SemaRef.Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa) 20347 << getOpenMPClauseName(DVar.CKind) 20348 << getOpenMPClauseName(OMPC_map) 20349 << getOpenMPDirectiveName(DSAS->getCurrentDirective()); 20350 reportOriginalDsa(SemaRef, DSAS, CurDeclaration, DVar); 20351 continue; 20352 } 20353 } 20354 } 20355 20356 // Try to find the associated user-defined mapper. 20357 ExprResult ER = buildUserDefinedMapperRef( 20358 SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId, 20359 Type.getCanonicalType(), UnresolvedMapper); 20360 if (ER.isInvalid()) 20361 continue; 20362 MVLI.UDMapperList.push_back(ER.get()); 20363 20364 // Save the current expression. 20365 MVLI.ProcessedVarList.push_back(RE); 20366 20367 // Store the components in the stack so that they can be used to check 20368 // against other clauses later on. 20369 DSAS->addMappableExpressionComponents(CurDeclaration, CurComponents, 20370 /*WhereFoundClauseKind=*/OMPC_map); 20371 20372 // Save the components and declaration to create the clause. For purposes of 20373 // the clause creation, any component list that has has base 'this' uses 20374 // null as base declaration. 20375 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1); 20376 MVLI.VarComponents.back().append(CurComponents.begin(), 20377 CurComponents.end()); 20378 MVLI.VarBaseDeclarations.push_back(isa<MemberExpr>(BE) ? nullptr 20379 : CurDeclaration); 20380 } 20381 } 20382 20383 OMPClause *Sema::ActOnOpenMPMapClause( 20384 ArrayRef<OpenMPMapModifierKind> MapTypeModifiers, 20385 ArrayRef<SourceLocation> MapTypeModifiersLoc, 20386 CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo &MapperId, 20387 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit, SourceLocation MapLoc, 20388 SourceLocation ColonLoc, ArrayRef<Expr *> VarList, 20389 const OMPVarListLocTy &Locs, bool NoDiagnose, 20390 ArrayRef<Expr *> UnresolvedMappers) { 20391 OpenMPMapModifierKind Modifiers[] = { 20392 OMPC_MAP_MODIFIER_unknown, OMPC_MAP_MODIFIER_unknown, 20393 OMPC_MAP_MODIFIER_unknown, OMPC_MAP_MODIFIER_unknown, 20394 OMPC_MAP_MODIFIER_unknown}; 20395 SourceLocation ModifiersLoc[NumberOfOMPMapClauseModifiers]; 20396 20397 // Process map-type-modifiers, flag errors for duplicate modifiers. 20398 unsigned Count = 0; 20399 for (unsigned I = 0, E = MapTypeModifiers.size(); I < E; ++I) { 20400 if (MapTypeModifiers[I] != OMPC_MAP_MODIFIER_unknown && 20401 llvm::is_contained(Modifiers, MapTypeModifiers[I])) { 20402 Diag(MapTypeModifiersLoc[I], diag::err_omp_duplicate_map_type_modifier); 20403 continue; 20404 } 20405 assert(Count < NumberOfOMPMapClauseModifiers && 20406 "Modifiers exceed the allowed number of map type modifiers"); 20407 Modifiers[Count] = MapTypeModifiers[I]; 20408 ModifiersLoc[Count] = MapTypeModifiersLoc[I]; 20409 ++Count; 20410 } 20411 20412 MappableVarListInfo MVLI(VarList); 20413 checkMappableExpressionList(*this, DSAStack, OMPC_map, MVLI, Locs.StartLoc, 20414 MapperIdScopeSpec, MapperId, UnresolvedMappers, 20415 MapType, Modifiers, IsMapTypeImplicit, 20416 NoDiagnose); 20417 20418 // We need to produce a map clause even if we don't have variables so that 20419 // other diagnostics related with non-existing map clauses are accurate. 20420 return OMPMapClause::Create(Context, Locs, MVLI.ProcessedVarList, 20421 MVLI.VarBaseDeclarations, MVLI.VarComponents, 20422 MVLI.UDMapperList, Modifiers, ModifiersLoc, 20423 MapperIdScopeSpec.getWithLocInContext(Context), 20424 MapperId, MapType, IsMapTypeImplicit, MapLoc); 20425 } 20426 20427 QualType Sema::ActOnOpenMPDeclareReductionType(SourceLocation TyLoc, 20428 TypeResult ParsedType) { 20429 assert(ParsedType.isUsable()); 20430 20431 QualType ReductionType = GetTypeFromParser(ParsedType.get()); 20432 if (ReductionType.isNull()) 20433 return QualType(); 20434 20435 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions, C\C++ 20436 // A type name in a declare reduction directive cannot be a function type, an 20437 // array type, a reference type, or a type qualified with const, volatile or 20438 // restrict. 20439 if (ReductionType.hasQualifiers()) { 20440 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 0; 20441 return QualType(); 20442 } 20443 20444 if (ReductionType->isFunctionType()) { 20445 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 1; 20446 return QualType(); 20447 } 20448 if (ReductionType->isReferenceType()) { 20449 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 2; 20450 return QualType(); 20451 } 20452 if (ReductionType->isArrayType()) { 20453 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 3; 20454 return QualType(); 20455 } 20456 return ReductionType; 20457 } 20458 20459 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveStart( 20460 Scope *S, DeclContext *DC, DeclarationName Name, 20461 ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes, 20462 AccessSpecifier AS, Decl *PrevDeclInScope) { 20463 SmallVector<Decl *, 8> Decls; 20464 Decls.reserve(ReductionTypes.size()); 20465 20466 LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPReductionName, 20467 forRedeclarationInCurContext()); 20468 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions 20469 // A reduction-identifier may not be re-declared in the current scope for the 20470 // same type or for a type that is compatible according to the base language 20471 // rules. 20472 llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes; 20473 OMPDeclareReductionDecl *PrevDRD = nullptr; 20474 bool InCompoundScope = true; 20475 if (S != nullptr) { 20476 // Find previous declaration with the same name not referenced in other 20477 // declarations. 20478 FunctionScopeInfo *ParentFn = getEnclosingFunction(); 20479 InCompoundScope = 20480 (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty(); 20481 LookupName(Lookup, S); 20482 FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false, 20483 /*AllowInlineNamespace=*/false); 20484 llvm::DenseMap<OMPDeclareReductionDecl *, bool> UsedAsPrevious; 20485 LookupResult::Filter Filter = Lookup.makeFilter(); 20486 while (Filter.hasNext()) { 20487 auto *PrevDecl = cast<OMPDeclareReductionDecl>(Filter.next()); 20488 if (InCompoundScope) { 20489 auto I = UsedAsPrevious.find(PrevDecl); 20490 if (I == UsedAsPrevious.end()) 20491 UsedAsPrevious[PrevDecl] = false; 20492 if (OMPDeclareReductionDecl *D = PrevDecl->getPrevDeclInScope()) 20493 UsedAsPrevious[D] = true; 20494 } 20495 PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] = 20496 PrevDecl->getLocation(); 20497 } 20498 Filter.done(); 20499 if (InCompoundScope) { 20500 for (const auto &PrevData : UsedAsPrevious) { 20501 if (!PrevData.second) { 20502 PrevDRD = PrevData.first; 20503 break; 20504 } 20505 } 20506 } 20507 } else if (PrevDeclInScope != nullptr) { 20508 auto *PrevDRDInScope = PrevDRD = 20509 cast<OMPDeclareReductionDecl>(PrevDeclInScope); 20510 do { 20511 PreviousRedeclTypes[PrevDRDInScope->getType().getCanonicalType()] = 20512 PrevDRDInScope->getLocation(); 20513 PrevDRDInScope = PrevDRDInScope->getPrevDeclInScope(); 20514 } while (PrevDRDInScope != nullptr); 20515 } 20516 for (const auto &TyData : ReductionTypes) { 20517 const auto I = PreviousRedeclTypes.find(TyData.first.getCanonicalType()); 20518 bool Invalid = false; 20519 if (I != PreviousRedeclTypes.end()) { 20520 Diag(TyData.second, diag::err_omp_declare_reduction_redefinition) 20521 << TyData.first; 20522 Diag(I->second, diag::note_previous_definition); 20523 Invalid = true; 20524 } 20525 PreviousRedeclTypes[TyData.first.getCanonicalType()] = TyData.second; 20526 auto *DRD = OMPDeclareReductionDecl::Create(Context, DC, TyData.second, 20527 Name, TyData.first, PrevDRD); 20528 DC->addDecl(DRD); 20529 DRD->setAccess(AS); 20530 Decls.push_back(DRD); 20531 if (Invalid) 20532 DRD->setInvalidDecl(); 20533 else 20534 PrevDRD = DRD; 20535 } 20536 20537 return DeclGroupPtrTy::make( 20538 DeclGroupRef::Create(Context, Decls.begin(), Decls.size())); 20539 } 20540 20541 void Sema::ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D) { 20542 auto *DRD = cast<OMPDeclareReductionDecl>(D); 20543 20544 // Enter new function scope. 20545 PushFunctionScope(); 20546 setFunctionHasBranchProtectedScope(); 20547 getCurFunction()->setHasOMPDeclareReductionCombiner(); 20548 20549 if (S != nullptr) 20550 PushDeclContext(S, DRD); 20551 else 20552 CurContext = DRD; 20553 20554 PushExpressionEvaluationContext( 20555 ExpressionEvaluationContext::PotentiallyEvaluated); 20556 20557 QualType ReductionType = DRD->getType(); 20558 // Create 'T* omp_parm;T omp_in;'. All references to 'omp_in' will 20559 // be replaced by '*omp_parm' during codegen. This required because 'omp_in' 20560 // uses semantics of argument handles by value, but it should be passed by 20561 // reference. C lang does not support references, so pass all parameters as 20562 // pointers. 20563 // Create 'T omp_in;' variable. 20564 VarDecl *OmpInParm = 20565 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_in"); 20566 // Create 'T* omp_parm;T omp_out;'. All references to 'omp_out' will 20567 // be replaced by '*omp_parm' during codegen. This required because 'omp_out' 20568 // uses semantics of argument handles by value, but it should be passed by 20569 // reference. C lang does not support references, so pass all parameters as 20570 // pointers. 20571 // Create 'T omp_out;' variable. 20572 VarDecl *OmpOutParm = 20573 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_out"); 20574 if (S != nullptr) { 20575 PushOnScopeChains(OmpInParm, S); 20576 PushOnScopeChains(OmpOutParm, S); 20577 } else { 20578 DRD->addDecl(OmpInParm); 20579 DRD->addDecl(OmpOutParm); 20580 } 20581 Expr *InE = 20582 ::buildDeclRefExpr(*this, OmpInParm, ReductionType, D->getLocation()); 20583 Expr *OutE = 20584 ::buildDeclRefExpr(*this, OmpOutParm, ReductionType, D->getLocation()); 20585 DRD->setCombinerData(InE, OutE); 20586 } 20587 20588 void Sema::ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner) { 20589 auto *DRD = cast<OMPDeclareReductionDecl>(D); 20590 DiscardCleanupsInEvaluationContext(); 20591 PopExpressionEvaluationContext(); 20592 20593 PopDeclContext(); 20594 PopFunctionScopeInfo(); 20595 20596 if (Combiner != nullptr) 20597 DRD->setCombiner(Combiner); 20598 else 20599 DRD->setInvalidDecl(); 20600 } 20601 20602 VarDecl *Sema::ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D) { 20603 auto *DRD = cast<OMPDeclareReductionDecl>(D); 20604 20605 // Enter new function scope. 20606 PushFunctionScope(); 20607 setFunctionHasBranchProtectedScope(); 20608 20609 if (S != nullptr) 20610 PushDeclContext(S, DRD); 20611 else 20612 CurContext = DRD; 20613 20614 PushExpressionEvaluationContext( 20615 ExpressionEvaluationContext::PotentiallyEvaluated); 20616 20617 QualType ReductionType = DRD->getType(); 20618 // Create 'T* omp_parm;T omp_priv;'. All references to 'omp_priv' will 20619 // be replaced by '*omp_parm' during codegen. This required because 'omp_priv' 20620 // uses semantics of argument handles by value, but it should be passed by 20621 // reference. C lang does not support references, so pass all parameters as 20622 // pointers. 20623 // Create 'T omp_priv;' variable. 20624 VarDecl *OmpPrivParm = 20625 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_priv"); 20626 // Create 'T* omp_parm;T omp_orig;'. All references to 'omp_orig' will 20627 // be replaced by '*omp_parm' during codegen. This required because 'omp_orig' 20628 // uses semantics of argument handles by value, but it should be passed by 20629 // reference. C lang does not support references, so pass all parameters as 20630 // pointers. 20631 // Create 'T omp_orig;' variable. 20632 VarDecl *OmpOrigParm = 20633 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_orig"); 20634 if (S != nullptr) { 20635 PushOnScopeChains(OmpPrivParm, S); 20636 PushOnScopeChains(OmpOrigParm, S); 20637 } else { 20638 DRD->addDecl(OmpPrivParm); 20639 DRD->addDecl(OmpOrigParm); 20640 } 20641 Expr *OrigE = 20642 ::buildDeclRefExpr(*this, OmpOrigParm, ReductionType, D->getLocation()); 20643 Expr *PrivE = 20644 ::buildDeclRefExpr(*this, OmpPrivParm, ReductionType, D->getLocation()); 20645 DRD->setInitializerData(OrigE, PrivE); 20646 return OmpPrivParm; 20647 } 20648 20649 void Sema::ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer, 20650 VarDecl *OmpPrivParm) { 20651 auto *DRD = cast<OMPDeclareReductionDecl>(D); 20652 DiscardCleanupsInEvaluationContext(); 20653 PopExpressionEvaluationContext(); 20654 20655 PopDeclContext(); 20656 PopFunctionScopeInfo(); 20657 20658 if (Initializer != nullptr) { 20659 DRD->setInitializer(Initializer, OMPDeclareReductionDecl::CallInit); 20660 } else if (OmpPrivParm->hasInit()) { 20661 DRD->setInitializer(OmpPrivParm->getInit(), 20662 OmpPrivParm->isDirectInit() 20663 ? OMPDeclareReductionDecl::DirectInit 20664 : OMPDeclareReductionDecl::CopyInit); 20665 } else { 20666 DRD->setInvalidDecl(); 20667 } 20668 } 20669 20670 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveEnd( 20671 Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid) { 20672 for (Decl *D : DeclReductions.get()) { 20673 if (IsValid) { 20674 if (S) 20675 PushOnScopeChains(cast<OMPDeclareReductionDecl>(D), S, 20676 /*AddToContext=*/false); 20677 } else { 20678 D->setInvalidDecl(); 20679 } 20680 } 20681 return DeclReductions; 20682 } 20683 20684 TypeResult Sema::ActOnOpenMPDeclareMapperVarDecl(Scope *S, Declarator &D) { 20685 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 20686 QualType T = TInfo->getType(); 20687 if (D.isInvalidType()) 20688 return true; 20689 20690 if (getLangOpts().CPlusPlus) { 20691 // Check that there are no default arguments (C++ only). 20692 CheckExtraCXXDefaultArguments(D); 20693 } 20694 20695 return CreateParsedType(T, TInfo); 20696 } 20697 20698 QualType Sema::ActOnOpenMPDeclareMapperType(SourceLocation TyLoc, 20699 TypeResult ParsedType) { 20700 assert(ParsedType.isUsable() && "Expect usable parsed mapper type"); 20701 20702 QualType MapperType = GetTypeFromParser(ParsedType.get()); 20703 assert(!MapperType.isNull() && "Expect valid mapper type"); 20704 20705 // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions 20706 // The type must be of struct, union or class type in C and C++ 20707 if (!MapperType->isStructureOrClassType() && !MapperType->isUnionType()) { 20708 Diag(TyLoc, diag::err_omp_mapper_wrong_type); 20709 return QualType(); 20710 } 20711 return MapperType; 20712 } 20713 20714 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareMapperDirective( 20715 Scope *S, DeclContext *DC, DeclarationName Name, QualType MapperType, 20716 SourceLocation StartLoc, DeclarationName VN, AccessSpecifier AS, 20717 Expr *MapperVarRef, ArrayRef<OMPClause *> Clauses, Decl *PrevDeclInScope) { 20718 LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPMapperName, 20719 forRedeclarationInCurContext()); 20720 // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions 20721 // A mapper-identifier may not be redeclared in the current scope for the 20722 // same type or for a type that is compatible according to the base language 20723 // rules. 20724 llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes; 20725 OMPDeclareMapperDecl *PrevDMD = nullptr; 20726 bool InCompoundScope = true; 20727 if (S != nullptr) { 20728 // Find previous declaration with the same name not referenced in other 20729 // declarations. 20730 FunctionScopeInfo *ParentFn = getEnclosingFunction(); 20731 InCompoundScope = 20732 (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty(); 20733 LookupName(Lookup, S); 20734 FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false, 20735 /*AllowInlineNamespace=*/false); 20736 llvm::DenseMap<OMPDeclareMapperDecl *, bool> UsedAsPrevious; 20737 LookupResult::Filter Filter = Lookup.makeFilter(); 20738 while (Filter.hasNext()) { 20739 auto *PrevDecl = cast<OMPDeclareMapperDecl>(Filter.next()); 20740 if (InCompoundScope) { 20741 auto I = UsedAsPrevious.find(PrevDecl); 20742 if (I == UsedAsPrevious.end()) 20743 UsedAsPrevious[PrevDecl] = false; 20744 if (OMPDeclareMapperDecl *D = PrevDecl->getPrevDeclInScope()) 20745 UsedAsPrevious[D] = true; 20746 } 20747 PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] = 20748 PrevDecl->getLocation(); 20749 } 20750 Filter.done(); 20751 if (InCompoundScope) { 20752 for (const auto &PrevData : UsedAsPrevious) { 20753 if (!PrevData.second) { 20754 PrevDMD = PrevData.first; 20755 break; 20756 } 20757 } 20758 } 20759 } else if (PrevDeclInScope) { 20760 auto *PrevDMDInScope = PrevDMD = 20761 cast<OMPDeclareMapperDecl>(PrevDeclInScope); 20762 do { 20763 PreviousRedeclTypes[PrevDMDInScope->getType().getCanonicalType()] = 20764 PrevDMDInScope->getLocation(); 20765 PrevDMDInScope = PrevDMDInScope->getPrevDeclInScope(); 20766 } while (PrevDMDInScope != nullptr); 20767 } 20768 const auto I = PreviousRedeclTypes.find(MapperType.getCanonicalType()); 20769 bool Invalid = false; 20770 if (I != PreviousRedeclTypes.end()) { 20771 Diag(StartLoc, diag::err_omp_declare_mapper_redefinition) 20772 << MapperType << Name; 20773 Diag(I->second, diag::note_previous_definition); 20774 Invalid = true; 20775 } 20776 // Build expressions for implicit maps of data members with 'default' 20777 // mappers. 20778 SmallVector<OMPClause *, 4> ClausesWithImplicit(Clauses.begin(), 20779 Clauses.end()); 20780 if (LangOpts.OpenMP >= 50) 20781 processImplicitMapsWithDefaultMappers(*this, DSAStack, ClausesWithImplicit); 20782 auto *DMD = 20783 OMPDeclareMapperDecl::Create(Context, DC, StartLoc, Name, MapperType, VN, 20784 ClausesWithImplicit, PrevDMD); 20785 if (S) 20786 PushOnScopeChains(DMD, S); 20787 else 20788 DC->addDecl(DMD); 20789 DMD->setAccess(AS); 20790 if (Invalid) 20791 DMD->setInvalidDecl(); 20792 20793 auto *VD = cast<DeclRefExpr>(MapperVarRef)->getDecl(); 20794 VD->setDeclContext(DMD); 20795 VD->setLexicalDeclContext(DMD); 20796 DMD->addDecl(VD); 20797 DMD->setMapperVarRef(MapperVarRef); 20798 20799 return DeclGroupPtrTy::make(DeclGroupRef(DMD)); 20800 } 20801 20802 ExprResult 20803 Sema::ActOnOpenMPDeclareMapperDirectiveVarDecl(Scope *S, QualType MapperType, 20804 SourceLocation StartLoc, 20805 DeclarationName VN) { 20806 TypeSourceInfo *TInfo = 20807 Context.getTrivialTypeSourceInfo(MapperType, StartLoc); 20808 auto *VD = VarDecl::Create(Context, Context.getTranslationUnitDecl(), 20809 StartLoc, StartLoc, VN.getAsIdentifierInfo(), 20810 MapperType, TInfo, SC_None); 20811 if (S) 20812 PushOnScopeChains(VD, S, /*AddToContext=*/false); 20813 Expr *E = buildDeclRefExpr(*this, VD, MapperType, StartLoc); 20814 DSAStack->addDeclareMapperVarRef(E); 20815 return E; 20816 } 20817 20818 bool Sema::isOpenMPDeclareMapperVarDeclAllowed(const VarDecl *VD) const { 20819 assert(LangOpts.OpenMP && "Expected OpenMP mode."); 20820 const Expr *Ref = DSAStack->getDeclareMapperVarRef(); 20821 if (const auto *DRE = cast_or_null<DeclRefExpr>(Ref)) { 20822 if (VD->getCanonicalDecl() == DRE->getDecl()->getCanonicalDecl()) 20823 return true; 20824 if (VD->isUsableInConstantExpressions(Context)) 20825 return true; 20826 return false; 20827 } 20828 return true; 20829 } 20830 20831 const ValueDecl *Sema::getOpenMPDeclareMapperVarName() const { 20832 assert(LangOpts.OpenMP && "Expected OpenMP mode."); 20833 return cast<DeclRefExpr>(DSAStack->getDeclareMapperVarRef())->getDecl(); 20834 } 20835 20836 OMPClause *Sema::ActOnOpenMPNumTeamsClause(Expr *NumTeams, 20837 SourceLocation StartLoc, 20838 SourceLocation LParenLoc, 20839 SourceLocation EndLoc) { 20840 Expr *ValExpr = NumTeams; 20841 Stmt *HelperValStmt = nullptr; 20842 20843 // OpenMP [teams Constrcut, Restrictions] 20844 // The num_teams expression must evaluate to a positive integer value. 20845 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_teams, 20846 /*StrictlyPositive=*/true)) 20847 return nullptr; 20848 20849 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective(); 20850 OpenMPDirectiveKind CaptureRegion = 20851 getOpenMPCaptureRegionForClause(DKind, OMPC_num_teams, LangOpts.OpenMP); 20852 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) { 20853 ValExpr = MakeFullExpr(ValExpr).get(); 20854 llvm::MapVector<const Expr *, DeclRefExpr *> Captures; 20855 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 20856 HelperValStmt = buildPreInits(Context, Captures); 20857 } 20858 20859 return new (Context) OMPNumTeamsClause(ValExpr, HelperValStmt, CaptureRegion, 20860 StartLoc, LParenLoc, EndLoc); 20861 } 20862 20863 OMPClause *Sema::ActOnOpenMPThreadLimitClause(Expr *ThreadLimit, 20864 SourceLocation StartLoc, 20865 SourceLocation LParenLoc, 20866 SourceLocation EndLoc) { 20867 Expr *ValExpr = ThreadLimit; 20868 Stmt *HelperValStmt = nullptr; 20869 20870 // OpenMP [teams Constrcut, Restrictions] 20871 // The thread_limit expression must evaluate to a positive integer value. 20872 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_thread_limit, 20873 /*StrictlyPositive=*/true)) 20874 return nullptr; 20875 20876 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective(); 20877 OpenMPDirectiveKind CaptureRegion = getOpenMPCaptureRegionForClause( 20878 DKind, OMPC_thread_limit, LangOpts.OpenMP); 20879 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) { 20880 ValExpr = MakeFullExpr(ValExpr).get(); 20881 llvm::MapVector<const Expr *, DeclRefExpr *> Captures; 20882 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 20883 HelperValStmt = buildPreInits(Context, Captures); 20884 } 20885 20886 return new (Context) OMPThreadLimitClause( 20887 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc); 20888 } 20889 20890 OMPClause *Sema::ActOnOpenMPPriorityClause(Expr *Priority, 20891 SourceLocation StartLoc, 20892 SourceLocation LParenLoc, 20893 SourceLocation EndLoc) { 20894 Expr *ValExpr = Priority; 20895 Stmt *HelperValStmt = nullptr; 20896 OpenMPDirectiveKind CaptureRegion = OMPD_unknown; 20897 20898 // OpenMP [2.9.1, task Constrcut] 20899 // The priority-value is a non-negative numerical scalar expression. 20900 if (!isNonNegativeIntegerValue( 20901 ValExpr, *this, OMPC_priority, 20902 /*StrictlyPositive=*/false, /*BuildCapture=*/true, 20903 DSAStack->getCurrentDirective(), &CaptureRegion, &HelperValStmt)) 20904 return nullptr; 20905 20906 return new (Context) OMPPriorityClause(ValExpr, HelperValStmt, CaptureRegion, 20907 StartLoc, LParenLoc, EndLoc); 20908 } 20909 20910 OMPClause *Sema::ActOnOpenMPGrainsizeClause(Expr *Grainsize, 20911 SourceLocation StartLoc, 20912 SourceLocation LParenLoc, 20913 SourceLocation EndLoc) { 20914 Expr *ValExpr = Grainsize; 20915 Stmt *HelperValStmt = nullptr; 20916 OpenMPDirectiveKind CaptureRegion = OMPD_unknown; 20917 20918 // OpenMP [2.9.2, taskloop Constrcut] 20919 // The parameter of the grainsize clause must be a positive integer 20920 // expression. 20921 if (!isNonNegativeIntegerValue( 20922 ValExpr, *this, OMPC_grainsize, 20923 /*StrictlyPositive=*/true, /*BuildCapture=*/true, 20924 DSAStack->getCurrentDirective(), &CaptureRegion, &HelperValStmt)) 20925 return nullptr; 20926 20927 return new (Context) OMPGrainsizeClause(ValExpr, HelperValStmt, CaptureRegion, 20928 StartLoc, LParenLoc, EndLoc); 20929 } 20930 20931 OMPClause *Sema::ActOnOpenMPNumTasksClause(Expr *NumTasks, 20932 SourceLocation StartLoc, 20933 SourceLocation LParenLoc, 20934 SourceLocation EndLoc) { 20935 Expr *ValExpr = NumTasks; 20936 Stmt *HelperValStmt = nullptr; 20937 OpenMPDirectiveKind CaptureRegion = OMPD_unknown; 20938 20939 // OpenMP [2.9.2, taskloop Constrcut] 20940 // The parameter of the num_tasks clause must be a positive integer 20941 // expression. 20942 if (!isNonNegativeIntegerValue( 20943 ValExpr, *this, OMPC_num_tasks, 20944 /*StrictlyPositive=*/true, /*BuildCapture=*/true, 20945 DSAStack->getCurrentDirective(), &CaptureRegion, &HelperValStmt)) 20946 return nullptr; 20947 20948 return new (Context) OMPNumTasksClause(ValExpr, HelperValStmt, CaptureRegion, 20949 StartLoc, LParenLoc, EndLoc); 20950 } 20951 20952 OMPClause *Sema::ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc, 20953 SourceLocation LParenLoc, 20954 SourceLocation EndLoc) { 20955 // OpenMP [2.13.2, critical construct, Description] 20956 // ... where hint-expression is an integer constant expression that evaluates 20957 // to a valid lock hint. 20958 ExprResult HintExpr = VerifyPositiveIntegerConstantInClause(Hint, OMPC_hint); 20959 if (HintExpr.isInvalid()) 20960 return nullptr; 20961 return new (Context) 20962 OMPHintClause(HintExpr.get(), StartLoc, LParenLoc, EndLoc); 20963 } 20964 20965 /// Tries to find omp_event_handle_t type. 20966 static bool findOMPEventHandleT(Sema &S, SourceLocation Loc, 20967 DSAStackTy *Stack) { 20968 QualType OMPEventHandleT = Stack->getOMPEventHandleT(); 20969 if (!OMPEventHandleT.isNull()) 20970 return true; 20971 IdentifierInfo *II = &S.PP.getIdentifierTable().get("omp_event_handle_t"); 20972 ParsedType PT = S.getTypeName(*II, Loc, S.getCurScope()); 20973 if (!PT.getAsOpaquePtr() || PT.get().isNull()) { 20974 S.Diag(Loc, diag::err_omp_implied_type_not_found) << "omp_event_handle_t"; 20975 return false; 20976 } 20977 Stack->setOMPEventHandleT(PT.get()); 20978 return true; 20979 } 20980 20981 OMPClause *Sema::ActOnOpenMPDetachClause(Expr *Evt, SourceLocation StartLoc, 20982 SourceLocation LParenLoc, 20983 SourceLocation EndLoc) { 20984 if (!Evt->isValueDependent() && !Evt->isTypeDependent() && 20985 !Evt->isInstantiationDependent() && 20986 !Evt->containsUnexpandedParameterPack()) { 20987 if (!findOMPEventHandleT(*this, Evt->getExprLoc(), DSAStack)) 20988 return nullptr; 20989 // OpenMP 5.0, 2.10.1 task Construct. 20990 // event-handle is a variable of the omp_event_handle_t type. 20991 auto *Ref = dyn_cast<DeclRefExpr>(Evt->IgnoreParenImpCasts()); 20992 if (!Ref) { 20993 Diag(Evt->getExprLoc(), diag::err_omp_var_expected) 20994 << "omp_event_handle_t" << 0 << Evt->getSourceRange(); 20995 return nullptr; 20996 } 20997 auto *VD = dyn_cast_or_null<VarDecl>(Ref->getDecl()); 20998 if (!VD) { 20999 Diag(Evt->getExprLoc(), diag::err_omp_var_expected) 21000 << "omp_event_handle_t" << 0 << Evt->getSourceRange(); 21001 return nullptr; 21002 } 21003 if (!Context.hasSameUnqualifiedType(DSAStack->getOMPEventHandleT(), 21004 VD->getType()) || 21005 VD->getType().isConstant(Context)) { 21006 Diag(Evt->getExprLoc(), diag::err_omp_var_expected) 21007 << "omp_event_handle_t" << 1 << VD->getType() 21008 << Evt->getSourceRange(); 21009 return nullptr; 21010 } 21011 // OpenMP 5.0, 2.10.1 task Construct 21012 // [detach clause]... The event-handle will be considered as if it was 21013 // specified on a firstprivate clause. 21014 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, /*FromParent=*/false); 21015 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate && 21016 DVar.RefExpr) { 21017 Diag(Evt->getExprLoc(), diag::err_omp_wrong_dsa) 21018 << getOpenMPClauseName(DVar.CKind) 21019 << getOpenMPClauseName(OMPC_firstprivate); 21020 reportOriginalDsa(*this, DSAStack, VD, DVar); 21021 return nullptr; 21022 } 21023 } 21024 21025 return new (Context) OMPDetachClause(Evt, StartLoc, LParenLoc, EndLoc); 21026 } 21027 21028 OMPClause *Sema::ActOnOpenMPDistScheduleClause( 21029 OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc, 21030 SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc, 21031 SourceLocation EndLoc) { 21032 if (Kind == OMPC_DIST_SCHEDULE_unknown) { 21033 std::string Values; 21034 Values += "'"; 21035 Values += getOpenMPSimpleClauseTypeName(OMPC_dist_schedule, 0); 21036 Values += "'"; 21037 Diag(KindLoc, diag::err_omp_unexpected_clause_value) 21038 << Values << getOpenMPClauseName(OMPC_dist_schedule); 21039 return nullptr; 21040 } 21041 Expr *ValExpr = ChunkSize; 21042 Stmt *HelperValStmt = nullptr; 21043 if (ChunkSize) { 21044 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() && 21045 !ChunkSize->isInstantiationDependent() && 21046 !ChunkSize->containsUnexpandedParameterPack()) { 21047 SourceLocation ChunkSizeLoc = ChunkSize->getBeginLoc(); 21048 ExprResult Val = 21049 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize); 21050 if (Val.isInvalid()) 21051 return nullptr; 21052 21053 ValExpr = Val.get(); 21054 21055 // OpenMP [2.7.1, Restrictions] 21056 // chunk_size must be a loop invariant integer expression with a positive 21057 // value. 21058 if (Optional<llvm::APSInt> Result = 21059 ValExpr->getIntegerConstantExpr(Context)) { 21060 if (Result->isSigned() && !Result->isStrictlyPositive()) { 21061 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause) 21062 << "dist_schedule" << ChunkSize->getSourceRange(); 21063 return nullptr; 21064 } 21065 } else if (getOpenMPCaptureRegionForClause( 21066 DSAStack->getCurrentDirective(), OMPC_dist_schedule, 21067 LangOpts.OpenMP) != OMPD_unknown && 21068 !CurContext->isDependentContext()) { 21069 ValExpr = MakeFullExpr(ValExpr).get(); 21070 llvm::MapVector<const Expr *, DeclRefExpr *> Captures; 21071 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 21072 HelperValStmt = buildPreInits(Context, Captures); 21073 } 21074 } 21075 } 21076 21077 return new (Context) 21078 OMPDistScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, 21079 Kind, ValExpr, HelperValStmt); 21080 } 21081 21082 OMPClause *Sema::ActOnOpenMPDefaultmapClause( 21083 OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind, 21084 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc, 21085 SourceLocation KindLoc, SourceLocation EndLoc) { 21086 if (getLangOpts().OpenMP < 50) { 21087 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom || 21088 Kind != OMPC_DEFAULTMAP_scalar) { 21089 std::string Value; 21090 SourceLocation Loc; 21091 Value += "'"; 21092 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom) { 21093 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap, 21094 OMPC_DEFAULTMAP_MODIFIER_tofrom); 21095 Loc = MLoc; 21096 } else { 21097 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap, 21098 OMPC_DEFAULTMAP_scalar); 21099 Loc = KindLoc; 21100 } 21101 Value += "'"; 21102 Diag(Loc, diag::err_omp_unexpected_clause_value) 21103 << Value << getOpenMPClauseName(OMPC_defaultmap); 21104 return nullptr; 21105 } 21106 } else { 21107 bool isDefaultmapModifier = (M != OMPC_DEFAULTMAP_MODIFIER_unknown); 21108 bool isDefaultmapKind = (Kind != OMPC_DEFAULTMAP_unknown) || 21109 (LangOpts.OpenMP >= 50 && KindLoc.isInvalid()); 21110 if (!isDefaultmapKind || !isDefaultmapModifier) { 21111 StringRef KindValue = "'scalar', 'aggregate', 'pointer'"; 21112 if (LangOpts.OpenMP == 50) { 21113 StringRef ModifierValue = "'alloc', 'from', 'to', 'tofrom', " 21114 "'firstprivate', 'none', 'default'"; 21115 if (!isDefaultmapKind && isDefaultmapModifier) { 21116 Diag(KindLoc, diag::err_omp_unexpected_clause_value) 21117 << KindValue << getOpenMPClauseName(OMPC_defaultmap); 21118 } else if (isDefaultmapKind && !isDefaultmapModifier) { 21119 Diag(MLoc, diag::err_omp_unexpected_clause_value) 21120 << ModifierValue << getOpenMPClauseName(OMPC_defaultmap); 21121 } else { 21122 Diag(MLoc, diag::err_omp_unexpected_clause_value) 21123 << ModifierValue << getOpenMPClauseName(OMPC_defaultmap); 21124 Diag(KindLoc, diag::err_omp_unexpected_clause_value) 21125 << KindValue << getOpenMPClauseName(OMPC_defaultmap); 21126 } 21127 } else { 21128 StringRef ModifierValue = 21129 "'alloc', 'from', 'to', 'tofrom', " 21130 "'firstprivate', 'none', 'default', 'present'"; 21131 if (!isDefaultmapKind && isDefaultmapModifier) { 21132 Diag(KindLoc, diag::err_omp_unexpected_clause_value) 21133 << KindValue << getOpenMPClauseName(OMPC_defaultmap); 21134 } else if (isDefaultmapKind && !isDefaultmapModifier) { 21135 Diag(MLoc, diag::err_omp_unexpected_clause_value) 21136 << ModifierValue << getOpenMPClauseName(OMPC_defaultmap); 21137 } else { 21138 Diag(MLoc, diag::err_omp_unexpected_clause_value) 21139 << ModifierValue << getOpenMPClauseName(OMPC_defaultmap); 21140 Diag(KindLoc, diag::err_omp_unexpected_clause_value) 21141 << KindValue << getOpenMPClauseName(OMPC_defaultmap); 21142 } 21143 } 21144 return nullptr; 21145 } 21146 21147 // OpenMP [5.0, 2.12.5, Restrictions, p. 174] 21148 // At most one defaultmap clause for each category can appear on the 21149 // directive. 21150 if (DSAStack->checkDefaultmapCategory(Kind)) { 21151 Diag(StartLoc, diag::err_omp_one_defaultmap_each_category); 21152 return nullptr; 21153 } 21154 } 21155 if (Kind == OMPC_DEFAULTMAP_unknown) { 21156 // Variable category is not specified - mark all categories. 21157 DSAStack->setDefaultDMAAttr(M, OMPC_DEFAULTMAP_aggregate, StartLoc); 21158 DSAStack->setDefaultDMAAttr(M, OMPC_DEFAULTMAP_scalar, StartLoc); 21159 DSAStack->setDefaultDMAAttr(M, OMPC_DEFAULTMAP_pointer, StartLoc); 21160 } else { 21161 DSAStack->setDefaultDMAAttr(M, Kind, StartLoc); 21162 } 21163 21164 return new (Context) 21165 OMPDefaultmapClause(StartLoc, LParenLoc, MLoc, KindLoc, EndLoc, Kind, M); 21166 } 21167 21168 bool Sema::ActOnStartOpenMPDeclareTargetContext( 21169 DeclareTargetContextInfo &DTCI) { 21170 DeclContext *CurLexicalContext = getCurLexicalContext(); 21171 if (!CurLexicalContext->isFileContext() && 21172 !CurLexicalContext->isExternCContext() && 21173 !CurLexicalContext->isExternCXXContext() && 21174 !isa<CXXRecordDecl>(CurLexicalContext) && 21175 !isa<ClassTemplateDecl>(CurLexicalContext) && 21176 !isa<ClassTemplatePartialSpecializationDecl>(CurLexicalContext) && 21177 !isa<ClassTemplateSpecializationDecl>(CurLexicalContext)) { 21178 Diag(DTCI.Loc, diag::err_omp_region_not_file_context); 21179 return false; 21180 } 21181 DeclareTargetNesting.push_back(DTCI); 21182 return true; 21183 } 21184 21185 const Sema::DeclareTargetContextInfo 21186 Sema::ActOnOpenMPEndDeclareTargetDirective() { 21187 assert(!DeclareTargetNesting.empty() && 21188 "check isInOpenMPDeclareTargetContext() first!"); 21189 return DeclareTargetNesting.pop_back_val(); 21190 } 21191 21192 void Sema::ActOnFinishedOpenMPDeclareTargetContext( 21193 DeclareTargetContextInfo &DTCI) { 21194 for (auto &It : DTCI.ExplicitlyMapped) 21195 ActOnOpenMPDeclareTargetName(It.first, It.second.Loc, It.second.MT, DTCI); 21196 } 21197 21198 NamedDecl *Sema::lookupOpenMPDeclareTargetName(Scope *CurScope, 21199 CXXScopeSpec &ScopeSpec, 21200 const DeclarationNameInfo &Id) { 21201 LookupResult Lookup(*this, Id, LookupOrdinaryName); 21202 LookupParsedName(Lookup, CurScope, &ScopeSpec, true); 21203 21204 if (Lookup.isAmbiguous()) 21205 return nullptr; 21206 Lookup.suppressDiagnostics(); 21207 21208 if (!Lookup.isSingleResult()) { 21209 VarOrFuncDeclFilterCCC CCC(*this); 21210 if (TypoCorrection Corrected = 21211 CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr, CCC, 21212 CTK_ErrorRecovery)) { 21213 diagnoseTypo(Corrected, PDiag(diag::err_undeclared_var_use_suggest) 21214 << Id.getName()); 21215 checkDeclIsAllowedInOpenMPTarget(nullptr, Corrected.getCorrectionDecl()); 21216 return nullptr; 21217 } 21218 21219 Diag(Id.getLoc(), diag::err_undeclared_var_use) << Id.getName(); 21220 return nullptr; 21221 } 21222 21223 NamedDecl *ND = Lookup.getAsSingle<NamedDecl>(); 21224 if (!isa<VarDecl>(ND) && !isa<FunctionDecl>(ND) && 21225 !isa<FunctionTemplateDecl>(ND)) { 21226 Diag(Id.getLoc(), diag::err_omp_invalid_target_decl) << Id.getName(); 21227 return nullptr; 21228 } 21229 return ND; 21230 } 21231 21232 void Sema::ActOnOpenMPDeclareTargetName(NamedDecl *ND, SourceLocation Loc, 21233 OMPDeclareTargetDeclAttr::MapTypeTy MT, 21234 DeclareTargetContextInfo &DTCI) { 21235 assert((isa<VarDecl>(ND) || isa<FunctionDecl>(ND) || 21236 isa<FunctionTemplateDecl>(ND)) && 21237 "Expected variable, function or function template."); 21238 21239 // Diagnose marking after use as it may lead to incorrect diagnosis and 21240 // codegen. 21241 if (LangOpts.OpenMP >= 50 && 21242 (ND->isUsed(/*CheckUsedAttr=*/false) || ND->isReferenced())) 21243 Diag(Loc, diag::warn_omp_declare_target_after_first_use); 21244 21245 // Explicit declare target lists have precedence. 21246 const unsigned Level = -1; 21247 21248 auto *VD = cast<ValueDecl>(ND); 21249 llvm::Optional<OMPDeclareTargetDeclAttr *> ActiveAttr = 21250 OMPDeclareTargetDeclAttr::getActiveAttr(VD); 21251 if (ActiveAttr.hasValue() && ActiveAttr.getValue()->getDevType() != DTCI.DT && 21252 ActiveAttr.getValue()->getLevel() == Level) { 21253 Diag(Loc, diag::err_omp_device_type_mismatch) 21254 << OMPDeclareTargetDeclAttr::ConvertDevTypeTyToStr(DTCI.DT) 21255 << OMPDeclareTargetDeclAttr::ConvertDevTypeTyToStr( 21256 ActiveAttr.getValue()->getDevType()); 21257 return; 21258 } 21259 if (ActiveAttr.hasValue() && ActiveAttr.getValue()->getMapType() != MT && 21260 ActiveAttr.getValue()->getLevel() == Level) { 21261 Diag(Loc, diag::err_omp_declare_target_to_and_link) << ND; 21262 return; 21263 } 21264 21265 if (ActiveAttr.hasValue() && ActiveAttr.getValue()->getLevel() == Level) 21266 return; 21267 21268 Expr *IndirectE = nullptr; 21269 bool IsIndirect = false; 21270 if (DTCI.Indirect.hasValue()) { 21271 IndirectE = DTCI.Indirect.getValue(); 21272 if (!IndirectE) 21273 IsIndirect = true; 21274 } 21275 auto *A = OMPDeclareTargetDeclAttr::CreateImplicit( 21276 Context, MT, DTCI.DT, IndirectE, IsIndirect, Level, 21277 SourceRange(Loc, Loc)); 21278 ND->addAttr(A); 21279 if (ASTMutationListener *ML = Context.getASTMutationListener()) 21280 ML->DeclarationMarkedOpenMPDeclareTarget(ND, A); 21281 checkDeclIsAllowedInOpenMPTarget(nullptr, ND, Loc); 21282 } 21283 21284 static void checkDeclInTargetContext(SourceLocation SL, SourceRange SR, 21285 Sema &SemaRef, Decl *D) { 21286 if (!D || !isa<VarDecl>(D)) 21287 return; 21288 auto *VD = cast<VarDecl>(D); 21289 Optional<OMPDeclareTargetDeclAttr::MapTypeTy> MapTy = 21290 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD); 21291 if (SemaRef.LangOpts.OpenMP >= 50 && 21292 (SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true) || 21293 SemaRef.getCurBlock() || SemaRef.getCurCapturedRegion()) && 21294 VD->hasGlobalStorage()) { 21295 if (!MapTy || *MapTy != OMPDeclareTargetDeclAttr::MT_To) { 21296 // OpenMP 5.0, 2.12.7 declare target Directive, Restrictions 21297 // If a lambda declaration and definition appears between a 21298 // declare target directive and the matching end declare target 21299 // directive, all variables that are captured by the lambda 21300 // expression must also appear in a to clause. 21301 SemaRef.Diag(VD->getLocation(), 21302 diag::err_omp_lambda_capture_in_declare_target_not_to); 21303 SemaRef.Diag(SL, diag::note_var_explicitly_captured_here) 21304 << VD << 0 << SR; 21305 return; 21306 } 21307 } 21308 if (MapTy.hasValue()) 21309 return; 21310 SemaRef.Diag(VD->getLocation(), diag::warn_omp_not_in_target_context); 21311 SemaRef.Diag(SL, diag::note_used_here) << SR; 21312 } 21313 21314 static bool checkValueDeclInTarget(SourceLocation SL, SourceRange SR, 21315 Sema &SemaRef, DSAStackTy *Stack, 21316 ValueDecl *VD) { 21317 return OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD) || 21318 checkTypeMappable(SL, SR, SemaRef, Stack, VD->getType(), 21319 /*FullCheck=*/false); 21320 } 21321 21322 void Sema::checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D, 21323 SourceLocation IdLoc) { 21324 if (!D || D->isInvalidDecl()) 21325 return; 21326 SourceRange SR = E ? E->getSourceRange() : D->getSourceRange(); 21327 SourceLocation SL = E ? E->getBeginLoc() : D->getLocation(); 21328 if (auto *VD = dyn_cast<VarDecl>(D)) { 21329 // Only global variables can be marked as declare target. 21330 if (!VD->isFileVarDecl() && !VD->isStaticLocal() && 21331 !VD->isStaticDataMember()) 21332 return; 21333 // 2.10.6: threadprivate variable cannot appear in a declare target 21334 // directive. 21335 if (DSAStack->isThreadPrivate(VD)) { 21336 Diag(SL, diag::err_omp_threadprivate_in_target); 21337 reportOriginalDsa(*this, DSAStack, VD, DSAStack->getTopDSA(VD, false)); 21338 return; 21339 } 21340 } 21341 if (const auto *FTD = dyn_cast<FunctionTemplateDecl>(D)) 21342 D = FTD->getTemplatedDecl(); 21343 if (auto *FD = dyn_cast<FunctionDecl>(D)) { 21344 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res = 21345 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(FD); 21346 if (IdLoc.isValid() && Res && *Res == OMPDeclareTargetDeclAttr::MT_Link) { 21347 Diag(IdLoc, diag::err_omp_function_in_link_clause); 21348 Diag(FD->getLocation(), diag::note_defined_here) << FD; 21349 return; 21350 } 21351 } 21352 if (auto *VD = dyn_cast<ValueDecl>(D)) { 21353 // Problem if any with var declared with incomplete type will be reported 21354 // as normal, so no need to check it here. 21355 if ((E || !VD->getType()->isIncompleteType()) && 21356 !checkValueDeclInTarget(SL, SR, *this, DSAStack, VD)) 21357 return; 21358 if (!E && isInOpenMPDeclareTargetContext()) { 21359 // Checking declaration inside declare target region. 21360 if (isa<VarDecl>(D) || isa<FunctionDecl>(D) || 21361 isa<FunctionTemplateDecl>(D)) { 21362 llvm::Optional<OMPDeclareTargetDeclAttr *> ActiveAttr = 21363 OMPDeclareTargetDeclAttr::getActiveAttr(VD); 21364 unsigned Level = DeclareTargetNesting.size(); 21365 if (ActiveAttr.hasValue() && ActiveAttr.getValue()->getLevel() >= Level) 21366 return; 21367 DeclareTargetContextInfo &DTCI = DeclareTargetNesting.back(); 21368 Expr *IndirectE = nullptr; 21369 bool IsIndirect = false; 21370 if (DTCI.Indirect.hasValue()) { 21371 IndirectE = DTCI.Indirect.getValue(); 21372 if (!IndirectE) 21373 IsIndirect = true; 21374 } 21375 auto *A = OMPDeclareTargetDeclAttr::CreateImplicit( 21376 Context, OMPDeclareTargetDeclAttr::MT_To, DTCI.DT, IndirectE, 21377 IsIndirect, Level, SourceRange(DTCI.Loc, DTCI.Loc)); 21378 D->addAttr(A); 21379 if (ASTMutationListener *ML = Context.getASTMutationListener()) 21380 ML->DeclarationMarkedOpenMPDeclareTarget(D, A); 21381 } 21382 return; 21383 } 21384 } 21385 if (!E) 21386 return; 21387 checkDeclInTargetContext(E->getExprLoc(), E->getSourceRange(), *this, D); 21388 } 21389 21390 OMPClause *Sema::ActOnOpenMPToClause( 21391 ArrayRef<OpenMPMotionModifierKind> MotionModifiers, 21392 ArrayRef<SourceLocation> MotionModifiersLoc, 21393 CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo &MapperId, 21394 SourceLocation ColonLoc, ArrayRef<Expr *> VarList, 21395 const OMPVarListLocTy &Locs, ArrayRef<Expr *> UnresolvedMappers) { 21396 OpenMPMotionModifierKind Modifiers[] = {OMPC_MOTION_MODIFIER_unknown, 21397 OMPC_MOTION_MODIFIER_unknown}; 21398 SourceLocation ModifiersLoc[NumberOfOMPMotionModifiers]; 21399 21400 // Process motion-modifiers, flag errors for duplicate modifiers. 21401 unsigned Count = 0; 21402 for (unsigned I = 0, E = MotionModifiers.size(); I < E; ++I) { 21403 if (MotionModifiers[I] != OMPC_MOTION_MODIFIER_unknown && 21404 llvm::is_contained(Modifiers, MotionModifiers[I])) { 21405 Diag(MotionModifiersLoc[I], diag::err_omp_duplicate_motion_modifier); 21406 continue; 21407 } 21408 assert(Count < NumberOfOMPMotionModifiers && 21409 "Modifiers exceed the allowed number of motion modifiers"); 21410 Modifiers[Count] = MotionModifiers[I]; 21411 ModifiersLoc[Count] = MotionModifiersLoc[I]; 21412 ++Count; 21413 } 21414 21415 MappableVarListInfo MVLI(VarList); 21416 checkMappableExpressionList(*this, DSAStack, OMPC_to, MVLI, Locs.StartLoc, 21417 MapperIdScopeSpec, MapperId, UnresolvedMappers); 21418 if (MVLI.ProcessedVarList.empty()) 21419 return nullptr; 21420 21421 return OMPToClause::Create( 21422 Context, Locs, MVLI.ProcessedVarList, MVLI.VarBaseDeclarations, 21423 MVLI.VarComponents, MVLI.UDMapperList, Modifiers, ModifiersLoc, 21424 MapperIdScopeSpec.getWithLocInContext(Context), MapperId); 21425 } 21426 21427 OMPClause *Sema::ActOnOpenMPFromClause( 21428 ArrayRef<OpenMPMotionModifierKind> MotionModifiers, 21429 ArrayRef<SourceLocation> MotionModifiersLoc, 21430 CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo &MapperId, 21431 SourceLocation ColonLoc, ArrayRef<Expr *> VarList, 21432 const OMPVarListLocTy &Locs, ArrayRef<Expr *> UnresolvedMappers) { 21433 OpenMPMotionModifierKind Modifiers[] = {OMPC_MOTION_MODIFIER_unknown, 21434 OMPC_MOTION_MODIFIER_unknown}; 21435 SourceLocation ModifiersLoc[NumberOfOMPMotionModifiers]; 21436 21437 // Process motion-modifiers, flag errors for duplicate modifiers. 21438 unsigned Count = 0; 21439 for (unsigned I = 0, E = MotionModifiers.size(); I < E; ++I) { 21440 if (MotionModifiers[I] != OMPC_MOTION_MODIFIER_unknown && 21441 llvm::is_contained(Modifiers, MotionModifiers[I])) { 21442 Diag(MotionModifiersLoc[I], diag::err_omp_duplicate_motion_modifier); 21443 continue; 21444 } 21445 assert(Count < NumberOfOMPMotionModifiers && 21446 "Modifiers exceed the allowed number of motion modifiers"); 21447 Modifiers[Count] = MotionModifiers[I]; 21448 ModifiersLoc[Count] = MotionModifiersLoc[I]; 21449 ++Count; 21450 } 21451 21452 MappableVarListInfo MVLI(VarList); 21453 checkMappableExpressionList(*this, DSAStack, OMPC_from, MVLI, Locs.StartLoc, 21454 MapperIdScopeSpec, MapperId, UnresolvedMappers); 21455 if (MVLI.ProcessedVarList.empty()) 21456 return nullptr; 21457 21458 return OMPFromClause::Create( 21459 Context, Locs, MVLI.ProcessedVarList, MVLI.VarBaseDeclarations, 21460 MVLI.VarComponents, MVLI.UDMapperList, Modifiers, ModifiersLoc, 21461 MapperIdScopeSpec.getWithLocInContext(Context), MapperId); 21462 } 21463 21464 OMPClause *Sema::ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList, 21465 const OMPVarListLocTy &Locs) { 21466 MappableVarListInfo MVLI(VarList); 21467 SmallVector<Expr *, 8> PrivateCopies; 21468 SmallVector<Expr *, 8> Inits; 21469 21470 for (Expr *RefExpr : VarList) { 21471 assert(RefExpr && "NULL expr in OpenMP use_device_ptr clause."); 21472 SourceLocation ELoc; 21473 SourceRange ERange; 21474 Expr *SimpleRefExpr = RefExpr; 21475 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 21476 if (Res.second) { 21477 // It will be analyzed later. 21478 MVLI.ProcessedVarList.push_back(RefExpr); 21479 PrivateCopies.push_back(nullptr); 21480 Inits.push_back(nullptr); 21481 } 21482 ValueDecl *D = Res.first; 21483 if (!D) 21484 continue; 21485 21486 QualType Type = D->getType(); 21487 Type = Type.getNonReferenceType().getUnqualifiedType(); 21488 21489 auto *VD = dyn_cast<VarDecl>(D); 21490 21491 // Item should be a pointer or reference to pointer. 21492 if (!Type->isPointerType()) { 21493 Diag(ELoc, diag::err_omp_usedeviceptr_not_a_pointer) 21494 << 0 << RefExpr->getSourceRange(); 21495 continue; 21496 } 21497 21498 // Build the private variable and the expression that refers to it. 21499 auto VDPrivate = 21500 buildVarDecl(*this, ELoc, Type, D->getName(), 21501 D->hasAttrs() ? &D->getAttrs() : nullptr, 21502 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr); 21503 if (VDPrivate->isInvalidDecl()) 21504 continue; 21505 21506 CurContext->addDecl(VDPrivate); 21507 DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr( 21508 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc); 21509 21510 // Add temporary variable to initialize the private copy of the pointer. 21511 VarDecl *VDInit = 21512 buildVarDecl(*this, RefExpr->getExprLoc(), Type, ".devptr.temp"); 21513 DeclRefExpr *VDInitRefExpr = buildDeclRefExpr( 21514 *this, VDInit, RefExpr->getType(), RefExpr->getExprLoc()); 21515 AddInitializerToDecl(VDPrivate, 21516 DefaultLvalueConversion(VDInitRefExpr).get(), 21517 /*DirectInit=*/false); 21518 21519 // If required, build a capture to implement the privatization initialized 21520 // with the current list item value. 21521 DeclRefExpr *Ref = nullptr; 21522 if (!VD) 21523 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true); 21524 MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref); 21525 PrivateCopies.push_back(VDPrivateRefExpr); 21526 Inits.push_back(VDInitRefExpr); 21527 21528 // We need to add a data sharing attribute for this variable to make sure it 21529 // is correctly captured. A variable that shows up in a use_device_ptr has 21530 // similar properties of a first private variable. 21531 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref); 21532 21533 // Create a mappable component for the list item. List items in this clause 21534 // only need a component. 21535 MVLI.VarBaseDeclarations.push_back(D); 21536 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1); 21537 MVLI.VarComponents.back().emplace_back(SimpleRefExpr, D, 21538 /*IsNonContiguous=*/false); 21539 } 21540 21541 if (MVLI.ProcessedVarList.empty()) 21542 return nullptr; 21543 21544 return OMPUseDevicePtrClause::Create( 21545 Context, Locs, MVLI.ProcessedVarList, PrivateCopies, Inits, 21546 MVLI.VarBaseDeclarations, MVLI.VarComponents); 21547 } 21548 21549 OMPClause *Sema::ActOnOpenMPUseDeviceAddrClause(ArrayRef<Expr *> VarList, 21550 const OMPVarListLocTy &Locs) { 21551 MappableVarListInfo MVLI(VarList); 21552 21553 for (Expr *RefExpr : VarList) { 21554 assert(RefExpr && "NULL expr in OpenMP use_device_addr clause."); 21555 SourceLocation ELoc; 21556 SourceRange ERange; 21557 Expr *SimpleRefExpr = RefExpr; 21558 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange, 21559 /*AllowArraySection=*/true); 21560 if (Res.second) { 21561 // It will be analyzed later. 21562 MVLI.ProcessedVarList.push_back(RefExpr); 21563 } 21564 ValueDecl *D = Res.first; 21565 if (!D) 21566 continue; 21567 auto *VD = dyn_cast<VarDecl>(D); 21568 21569 // If required, build a capture to implement the privatization initialized 21570 // with the current list item value. 21571 DeclRefExpr *Ref = nullptr; 21572 if (!VD) 21573 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true); 21574 MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref); 21575 21576 // We need to add a data sharing attribute for this variable to make sure it 21577 // is correctly captured. A variable that shows up in a use_device_addr has 21578 // similar properties of a first private variable. 21579 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref); 21580 21581 // Create a mappable component for the list item. List items in this clause 21582 // only need a component. 21583 MVLI.VarBaseDeclarations.push_back(D); 21584 MVLI.VarComponents.emplace_back(); 21585 Expr *Component = SimpleRefExpr; 21586 if (VD && (isa<OMPArraySectionExpr>(RefExpr->IgnoreParenImpCasts()) || 21587 isa<ArraySubscriptExpr>(RefExpr->IgnoreParenImpCasts()))) 21588 Component = DefaultFunctionArrayLvalueConversion(SimpleRefExpr).get(); 21589 MVLI.VarComponents.back().emplace_back(Component, D, 21590 /*IsNonContiguous=*/false); 21591 } 21592 21593 if (MVLI.ProcessedVarList.empty()) 21594 return nullptr; 21595 21596 return OMPUseDeviceAddrClause::Create(Context, Locs, MVLI.ProcessedVarList, 21597 MVLI.VarBaseDeclarations, 21598 MVLI.VarComponents); 21599 } 21600 21601 OMPClause *Sema::ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList, 21602 const OMPVarListLocTy &Locs) { 21603 MappableVarListInfo MVLI(VarList); 21604 for (Expr *RefExpr : VarList) { 21605 assert(RefExpr && "NULL expr in OpenMP is_device_ptr clause."); 21606 SourceLocation ELoc; 21607 SourceRange ERange; 21608 Expr *SimpleRefExpr = RefExpr; 21609 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 21610 if (Res.second) { 21611 // It will be analyzed later. 21612 MVLI.ProcessedVarList.push_back(RefExpr); 21613 } 21614 ValueDecl *D = Res.first; 21615 if (!D) 21616 continue; 21617 21618 QualType Type = D->getType(); 21619 // item should be a pointer or array or reference to pointer or array 21620 if (!Type.getNonReferenceType()->isPointerType() && 21621 !Type.getNonReferenceType()->isArrayType()) { 21622 Diag(ELoc, diag::err_omp_argument_type_isdeviceptr) 21623 << 0 << RefExpr->getSourceRange(); 21624 continue; 21625 } 21626 21627 // Check if the declaration in the clause does not show up in any data 21628 // sharing attribute. 21629 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false); 21630 if (isOpenMPPrivate(DVar.CKind)) { 21631 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa) 21632 << getOpenMPClauseName(DVar.CKind) 21633 << getOpenMPClauseName(OMPC_is_device_ptr) 21634 << getOpenMPDirectiveName(DSAStack->getCurrentDirective()); 21635 reportOriginalDsa(*this, DSAStack, D, DVar); 21636 continue; 21637 } 21638 21639 const Expr *ConflictExpr; 21640 if (DSAStack->checkMappableExprComponentListsForDecl( 21641 D, /*CurrentRegionOnly=*/true, 21642 [&ConflictExpr]( 21643 OMPClauseMappableExprCommon::MappableExprComponentListRef R, 21644 OpenMPClauseKind) -> bool { 21645 ConflictExpr = R.front().getAssociatedExpression(); 21646 return true; 21647 })) { 21648 Diag(ELoc, diag::err_omp_map_shared_storage) << RefExpr->getSourceRange(); 21649 Diag(ConflictExpr->getExprLoc(), diag::note_used_here) 21650 << ConflictExpr->getSourceRange(); 21651 continue; 21652 } 21653 21654 // Store the components in the stack so that they can be used to check 21655 // against other clauses later on. 21656 OMPClauseMappableExprCommon::MappableComponent MC( 21657 SimpleRefExpr, D, /*IsNonContiguous=*/false); 21658 DSAStack->addMappableExpressionComponents( 21659 D, MC, /*WhereFoundClauseKind=*/OMPC_is_device_ptr); 21660 21661 // Record the expression we've just processed. 21662 MVLI.ProcessedVarList.push_back(SimpleRefExpr); 21663 21664 // Create a mappable component for the list item. List items in this clause 21665 // only need a component. We use a null declaration to signal fields in 21666 // 'this'. 21667 assert((isa<DeclRefExpr>(SimpleRefExpr) || 21668 isa<CXXThisExpr>(cast<MemberExpr>(SimpleRefExpr)->getBase())) && 21669 "Unexpected device pointer expression!"); 21670 MVLI.VarBaseDeclarations.push_back( 21671 isa<DeclRefExpr>(SimpleRefExpr) ? D : nullptr); 21672 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1); 21673 MVLI.VarComponents.back().push_back(MC); 21674 } 21675 21676 if (MVLI.ProcessedVarList.empty()) 21677 return nullptr; 21678 21679 return OMPIsDevicePtrClause::Create(Context, Locs, MVLI.ProcessedVarList, 21680 MVLI.VarBaseDeclarations, 21681 MVLI.VarComponents); 21682 } 21683 21684 OMPClause *Sema::ActOnOpenMPAllocateClause( 21685 Expr *Allocator, ArrayRef<Expr *> VarList, SourceLocation StartLoc, 21686 SourceLocation ColonLoc, SourceLocation LParenLoc, SourceLocation EndLoc) { 21687 if (Allocator) { 21688 // OpenMP [2.11.4 allocate Clause, Description] 21689 // allocator is an expression of omp_allocator_handle_t type. 21690 if (!findOMPAllocatorHandleT(*this, Allocator->getExprLoc(), DSAStack)) 21691 return nullptr; 21692 21693 ExprResult AllocatorRes = DefaultLvalueConversion(Allocator); 21694 if (AllocatorRes.isInvalid()) 21695 return nullptr; 21696 AllocatorRes = PerformImplicitConversion(AllocatorRes.get(), 21697 DSAStack->getOMPAllocatorHandleT(), 21698 Sema::AA_Initializing, 21699 /*AllowExplicit=*/true); 21700 if (AllocatorRes.isInvalid()) 21701 return nullptr; 21702 Allocator = AllocatorRes.get(); 21703 } else { 21704 // OpenMP 5.0, 2.11.4 allocate Clause, Restrictions. 21705 // allocate clauses that appear on a target construct or on constructs in a 21706 // target region must specify an allocator expression unless a requires 21707 // directive with the dynamic_allocators clause is present in the same 21708 // compilation unit. 21709 if (LangOpts.OpenMPIsDevice && 21710 !DSAStack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>()) 21711 targetDiag(StartLoc, diag::err_expected_allocator_expression); 21712 } 21713 // Analyze and build list of variables. 21714 SmallVector<Expr *, 8> Vars; 21715 for (Expr *RefExpr : VarList) { 21716 assert(RefExpr && "NULL expr in OpenMP private clause."); 21717 SourceLocation ELoc; 21718 SourceRange ERange; 21719 Expr *SimpleRefExpr = RefExpr; 21720 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 21721 if (Res.second) { 21722 // It will be analyzed later. 21723 Vars.push_back(RefExpr); 21724 } 21725 ValueDecl *D = Res.first; 21726 if (!D) 21727 continue; 21728 21729 auto *VD = dyn_cast<VarDecl>(D); 21730 DeclRefExpr *Ref = nullptr; 21731 if (!VD && !CurContext->isDependentContext()) 21732 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false); 21733 Vars.push_back((VD || CurContext->isDependentContext()) 21734 ? RefExpr->IgnoreParens() 21735 : Ref); 21736 } 21737 21738 if (Vars.empty()) 21739 return nullptr; 21740 21741 if (Allocator) 21742 DSAStack->addInnerAllocatorExpr(Allocator); 21743 return OMPAllocateClause::Create(Context, StartLoc, LParenLoc, Allocator, 21744 ColonLoc, EndLoc, Vars); 21745 } 21746 21747 OMPClause *Sema::ActOnOpenMPNontemporalClause(ArrayRef<Expr *> VarList, 21748 SourceLocation StartLoc, 21749 SourceLocation LParenLoc, 21750 SourceLocation EndLoc) { 21751 SmallVector<Expr *, 8> Vars; 21752 for (Expr *RefExpr : VarList) { 21753 assert(RefExpr && "NULL expr in OpenMP nontemporal clause."); 21754 SourceLocation ELoc; 21755 SourceRange ERange; 21756 Expr *SimpleRefExpr = RefExpr; 21757 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 21758 if (Res.second) 21759 // It will be analyzed later. 21760 Vars.push_back(RefExpr); 21761 ValueDecl *D = Res.first; 21762 if (!D) 21763 continue; 21764 21765 // OpenMP 5.0, 2.9.3.1 simd Construct, Restrictions. 21766 // A list-item cannot appear in more than one nontemporal clause. 21767 if (const Expr *PrevRef = 21768 DSAStack->addUniqueNontemporal(D, SimpleRefExpr)) { 21769 Diag(ELoc, diag::err_omp_used_in_clause_twice) 21770 << 0 << getOpenMPClauseName(OMPC_nontemporal) << ERange; 21771 Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa) 21772 << getOpenMPClauseName(OMPC_nontemporal); 21773 continue; 21774 } 21775 21776 Vars.push_back(RefExpr); 21777 } 21778 21779 if (Vars.empty()) 21780 return nullptr; 21781 21782 return OMPNontemporalClause::Create(Context, StartLoc, LParenLoc, EndLoc, 21783 Vars); 21784 } 21785 21786 OMPClause *Sema::ActOnOpenMPInclusiveClause(ArrayRef<Expr *> VarList, 21787 SourceLocation StartLoc, 21788 SourceLocation LParenLoc, 21789 SourceLocation EndLoc) { 21790 SmallVector<Expr *, 8> Vars; 21791 for (Expr *RefExpr : VarList) { 21792 assert(RefExpr && "NULL expr in OpenMP nontemporal clause."); 21793 SourceLocation ELoc; 21794 SourceRange ERange; 21795 Expr *SimpleRefExpr = RefExpr; 21796 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange, 21797 /*AllowArraySection=*/true); 21798 if (Res.second) 21799 // It will be analyzed later. 21800 Vars.push_back(RefExpr); 21801 ValueDecl *D = Res.first; 21802 if (!D) 21803 continue; 21804 21805 const DSAStackTy::DSAVarData DVar = 21806 DSAStack->getTopDSA(D, /*FromParent=*/true); 21807 // OpenMP 5.0, 2.9.6, scan Directive, Restrictions. 21808 // A list item that appears in the inclusive or exclusive clause must appear 21809 // in a reduction clause with the inscan modifier on the enclosing 21810 // worksharing-loop, worksharing-loop SIMD, or simd construct. 21811 if (DVar.CKind != OMPC_reduction || DVar.Modifier != OMPC_REDUCTION_inscan) 21812 Diag(ELoc, diag::err_omp_inclusive_exclusive_not_reduction) 21813 << RefExpr->getSourceRange(); 21814 21815 if (DSAStack->getParentDirective() != OMPD_unknown) 21816 DSAStack->markDeclAsUsedInScanDirective(D); 21817 Vars.push_back(RefExpr); 21818 } 21819 21820 if (Vars.empty()) 21821 return nullptr; 21822 21823 return OMPInclusiveClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars); 21824 } 21825 21826 OMPClause *Sema::ActOnOpenMPExclusiveClause(ArrayRef<Expr *> VarList, 21827 SourceLocation StartLoc, 21828 SourceLocation LParenLoc, 21829 SourceLocation EndLoc) { 21830 SmallVector<Expr *, 8> Vars; 21831 for (Expr *RefExpr : VarList) { 21832 assert(RefExpr && "NULL expr in OpenMP nontemporal clause."); 21833 SourceLocation ELoc; 21834 SourceRange ERange; 21835 Expr *SimpleRefExpr = RefExpr; 21836 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange, 21837 /*AllowArraySection=*/true); 21838 if (Res.second) 21839 // It will be analyzed later. 21840 Vars.push_back(RefExpr); 21841 ValueDecl *D = Res.first; 21842 if (!D) 21843 continue; 21844 21845 OpenMPDirectiveKind ParentDirective = DSAStack->getParentDirective(); 21846 DSAStackTy::DSAVarData DVar; 21847 if (ParentDirective != OMPD_unknown) 21848 DVar = DSAStack->getTopDSA(D, /*FromParent=*/true); 21849 // OpenMP 5.0, 2.9.6, scan Directive, Restrictions. 21850 // A list item that appears in the inclusive or exclusive clause must appear 21851 // in a reduction clause with the inscan modifier on the enclosing 21852 // worksharing-loop, worksharing-loop SIMD, or simd construct. 21853 if (ParentDirective == OMPD_unknown || DVar.CKind != OMPC_reduction || 21854 DVar.Modifier != OMPC_REDUCTION_inscan) { 21855 Diag(ELoc, diag::err_omp_inclusive_exclusive_not_reduction) 21856 << RefExpr->getSourceRange(); 21857 } else { 21858 DSAStack->markDeclAsUsedInScanDirective(D); 21859 } 21860 Vars.push_back(RefExpr); 21861 } 21862 21863 if (Vars.empty()) 21864 return nullptr; 21865 21866 return OMPExclusiveClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars); 21867 } 21868 21869 /// Tries to find omp_alloctrait_t type. 21870 static bool findOMPAlloctraitT(Sema &S, SourceLocation Loc, DSAStackTy *Stack) { 21871 QualType OMPAlloctraitT = Stack->getOMPAlloctraitT(); 21872 if (!OMPAlloctraitT.isNull()) 21873 return true; 21874 IdentifierInfo &II = S.PP.getIdentifierTable().get("omp_alloctrait_t"); 21875 ParsedType PT = S.getTypeName(II, Loc, S.getCurScope()); 21876 if (!PT.getAsOpaquePtr() || PT.get().isNull()) { 21877 S.Diag(Loc, diag::err_omp_implied_type_not_found) << "omp_alloctrait_t"; 21878 return false; 21879 } 21880 Stack->setOMPAlloctraitT(PT.get()); 21881 return true; 21882 } 21883 21884 OMPClause *Sema::ActOnOpenMPUsesAllocatorClause( 21885 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc, 21886 ArrayRef<UsesAllocatorsData> Data) { 21887 // OpenMP [2.12.5, target Construct] 21888 // allocator is an identifier of omp_allocator_handle_t type. 21889 if (!findOMPAllocatorHandleT(*this, StartLoc, DSAStack)) 21890 return nullptr; 21891 // OpenMP [2.12.5, target Construct] 21892 // allocator-traits-array is an identifier of const omp_alloctrait_t * type. 21893 if (llvm::any_of( 21894 Data, 21895 [](const UsesAllocatorsData &D) { return D.AllocatorTraits; }) && 21896 !findOMPAlloctraitT(*this, StartLoc, DSAStack)) 21897 return nullptr; 21898 llvm::SmallPtrSet<CanonicalDeclPtr<Decl>, 4> PredefinedAllocators; 21899 for (int I = 0; I < OMPAllocateDeclAttr::OMPUserDefinedMemAlloc; ++I) { 21900 auto AllocatorKind = static_cast<OMPAllocateDeclAttr::AllocatorTypeTy>(I); 21901 StringRef Allocator = 21902 OMPAllocateDeclAttr::ConvertAllocatorTypeTyToStr(AllocatorKind); 21903 DeclarationName AllocatorName = &Context.Idents.get(Allocator); 21904 PredefinedAllocators.insert(LookupSingleName( 21905 TUScope, AllocatorName, StartLoc, Sema::LookupAnyName)); 21906 } 21907 21908 SmallVector<OMPUsesAllocatorsClause::Data, 4> NewData; 21909 for (const UsesAllocatorsData &D : Data) { 21910 Expr *AllocatorExpr = nullptr; 21911 // Check allocator expression. 21912 if (D.Allocator->isTypeDependent()) { 21913 AllocatorExpr = D.Allocator; 21914 } else { 21915 // Traits were specified - need to assign new allocator to the specified 21916 // allocator, so it must be an lvalue. 21917 AllocatorExpr = D.Allocator->IgnoreParenImpCasts(); 21918 auto *DRE = dyn_cast<DeclRefExpr>(AllocatorExpr); 21919 bool IsPredefinedAllocator = false; 21920 if (DRE) 21921 IsPredefinedAllocator = PredefinedAllocators.count(DRE->getDecl()); 21922 if (!DRE || 21923 !(Context.hasSameUnqualifiedType( 21924 AllocatorExpr->getType(), DSAStack->getOMPAllocatorHandleT()) || 21925 Context.typesAreCompatible(AllocatorExpr->getType(), 21926 DSAStack->getOMPAllocatorHandleT(), 21927 /*CompareUnqualified=*/true)) || 21928 (!IsPredefinedAllocator && 21929 (AllocatorExpr->getType().isConstant(Context) || 21930 !AllocatorExpr->isLValue()))) { 21931 Diag(D.Allocator->getExprLoc(), diag::err_omp_var_expected) 21932 << "omp_allocator_handle_t" << (DRE ? 1 : 0) 21933 << AllocatorExpr->getType() << D.Allocator->getSourceRange(); 21934 continue; 21935 } 21936 // OpenMP [2.12.5, target Construct] 21937 // Predefined allocators appearing in a uses_allocators clause cannot have 21938 // traits specified. 21939 if (IsPredefinedAllocator && D.AllocatorTraits) { 21940 Diag(D.AllocatorTraits->getExprLoc(), 21941 diag::err_omp_predefined_allocator_with_traits) 21942 << D.AllocatorTraits->getSourceRange(); 21943 Diag(D.Allocator->getExprLoc(), diag::note_omp_predefined_allocator) 21944 << cast<NamedDecl>(DRE->getDecl())->getName() 21945 << D.Allocator->getSourceRange(); 21946 continue; 21947 } 21948 // OpenMP [2.12.5, target Construct] 21949 // Non-predefined allocators appearing in a uses_allocators clause must 21950 // have traits specified. 21951 if (!IsPredefinedAllocator && !D.AllocatorTraits) { 21952 Diag(D.Allocator->getExprLoc(), 21953 diag::err_omp_nonpredefined_allocator_without_traits); 21954 continue; 21955 } 21956 // No allocator traits - just convert it to rvalue. 21957 if (!D.AllocatorTraits) 21958 AllocatorExpr = DefaultLvalueConversion(AllocatorExpr).get(); 21959 DSAStack->addUsesAllocatorsDecl( 21960 DRE->getDecl(), 21961 IsPredefinedAllocator 21962 ? DSAStackTy::UsesAllocatorsDeclKind::PredefinedAllocator 21963 : DSAStackTy::UsesAllocatorsDeclKind::UserDefinedAllocator); 21964 } 21965 Expr *AllocatorTraitsExpr = nullptr; 21966 if (D.AllocatorTraits) { 21967 if (D.AllocatorTraits->isTypeDependent()) { 21968 AllocatorTraitsExpr = D.AllocatorTraits; 21969 } else { 21970 // OpenMP [2.12.5, target Construct] 21971 // Arrays that contain allocator traits that appear in a uses_allocators 21972 // clause must be constant arrays, have constant values and be defined 21973 // in the same scope as the construct in which the clause appears. 21974 AllocatorTraitsExpr = D.AllocatorTraits->IgnoreParenImpCasts(); 21975 // Check that traits expr is a constant array. 21976 QualType TraitTy; 21977 if (const ArrayType *Ty = 21978 AllocatorTraitsExpr->getType()->getAsArrayTypeUnsafe()) 21979 if (const auto *ConstArrayTy = dyn_cast<ConstantArrayType>(Ty)) 21980 TraitTy = ConstArrayTy->getElementType(); 21981 if (TraitTy.isNull() || 21982 !(Context.hasSameUnqualifiedType(TraitTy, 21983 DSAStack->getOMPAlloctraitT()) || 21984 Context.typesAreCompatible(TraitTy, DSAStack->getOMPAlloctraitT(), 21985 /*CompareUnqualified=*/true))) { 21986 Diag(D.AllocatorTraits->getExprLoc(), 21987 diag::err_omp_expected_array_alloctraits) 21988 << AllocatorTraitsExpr->getType(); 21989 continue; 21990 } 21991 // Do not map by default allocator traits if it is a standalone 21992 // variable. 21993 if (auto *DRE = dyn_cast<DeclRefExpr>(AllocatorTraitsExpr)) 21994 DSAStack->addUsesAllocatorsDecl( 21995 DRE->getDecl(), 21996 DSAStackTy::UsesAllocatorsDeclKind::AllocatorTrait); 21997 } 21998 } 21999 OMPUsesAllocatorsClause::Data &NewD = NewData.emplace_back(); 22000 NewD.Allocator = AllocatorExpr; 22001 NewD.AllocatorTraits = AllocatorTraitsExpr; 22002 NewD.LParenLoc = D.LParenLoc; 22003 NewD.RParenLoc = D.RParenLoc; 22004 } 22005 return OMPUsesAllocatorsClause::Create(Context, StartLoc, LParenLoc, EndLoc, 22006 NewData); 22007 } 22008 22009 OMPClause *Sema::ActOnOpenMPAffinityClause( 22010 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc, 22011 SourceLocation EndLoc, Expr *Modifier, ArrayRef<Expr *> Locators) { 22012 SmallVector<Expr *, 8> Vars; 22013 for (Expr *RefExpr : Locators) { 22014 assert(RefExpr && "NULL expr in OpenMP shared clause."); 22015 if (isa<DependentScopeDeclRefExpr>(RefExpr) || RefExpr->isTypeDependent()) { 22016 // It will be analyzed later. 22017 Vars.push_back(RefExpr); 22018 continue; 22019 } 22020 22021 SourceLocation ELoc = RefExpr->getExprLoc(); 22022 Expr *SimpleExpr = RefExpr->IgnoreParenImpCasts(); 22023 22024 if (!SimpleExpr->isLValue()) { 22025 Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item) 22026 << 1 << 0 << RefExpr->getSourceRange(); 22027 continue; 22028 } 22029 22030 ExprResult Res; 22031 { 22032 Sema::TentativeAnalysisScope Trap(*this); 22033 Res = CreateBuiltinUnaryOp(ELoc, UO_AddrOf, SimpleExpr); 22034 } 22035 if (!Res.isUsable() && !isa<OMPArraySectionExpr>(SimpleExpr) && 22036 !isa<OMPArrayShapingExpr>(SimpleExpr)) { 22037 Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item) 22038 << 1 << 0 << RefExpr->getSourceRange(); 22039 continue; 22040 } 22041 Vars.push_back(SimpleExpr); 22042 } 22043 22044 return OMPAffinityClause::Create(Context, StartLoc, LParenLoc, ColonLoc, 22045 EndLoc, Modifier, Vars); 22046 } 22047 22048 OMPClause *Sema::ActOnOpenMPBindClause(OpenMPBindClauseKind Kind, 22049 SourceLocation KindLoc, 22050 SourceLocation StartLoc, 22051 SourceLocation LParenLoc, 22052 SourceLocation EndLoc) { 22053 if (Kind == OMPC_BIND_unknown) { 22054 Diag(KindLoc, diag::err_omp_unexpected_clause_value) 22055 << getListOfPossibleValues(OMPC_bind, /*First=*/0, 22056 /*Last=*/unsigned(OMPC_BIND_unknown)) 22057 << getOpenMPClauseName(OMPC_bind); 22058 return nullptr; 22059 } 22060 22061 return OMPBindClause::Create(Context, Kind, KindLoc, StartLoc, LParenLoc, 22062 EndLoc); 22063 } 22064