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/Frontend/OpenMP/OMPConstants.h"
39 #include <set>
40 
41 using namespace clang;
42 using namespace llvm::omp;
43 
44 //===----------------------------------------------------------------------===//
45 // Stack of data-sharing attributes for variables
46 //===----------------------------------------------------------------------===//
47 
48 static const Expr *checkMapClauseExpressionBase(
49     Sema &SemaRef, Expr *E,
50     OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
51     OpenMPClauseKind CKind, bool NoDiagnose);
52 
53 namespace {
54 /// Default data sharing attributes, which can be applied to directive.
55 enum DefaultDataSharingAttributes {
56   DSA_unspecified = 0, /// Data sharing attribute not specified.
57   DSA_none = 1 << 0,   /// Default data sharing attribute 'none'.
58   DSA_shared = 1 << 1, /// Default data sharing attribute 'shared'.
59 };
60 
61 /// Stack for tracking declarations used in OpenMP directives and
62 /// clauses and their data-sharing attributes.
63 class DSAStackTy {
64 public:
65   struct DSAVarData {
66     OpenMPDirectiveKind DKind = OMPD_unknown;
67     OpenMPClauseKind CKind = OMPC_unknown;
68     unsigned Modifier = 0;
69     const Expr *RefExpr = nullptr;
70     DeclRefExpr *PrivateCopy = nullptr;
71     SourceLocation ImplicitDSALoc;
72     DSAVarData() = default;
73     DSAVarData(OpenMPDirectiveKind DKind, OpenMPClauseKind CKind,
74                const Expr *RefExpr, DeclRefExpr *PrivateCopy,
75                SourceLocation ImplicitDSALoc, unsigned Modifier)
76         : DKind(DKind), CKind(CKind), Modifier(Modifier), RefExpr(RefExpr),
77           PrivateCopy(PrivateCopy), ImplicitDSALoc(ImplicitDSALoc) {}
78   };
79   using OperatorOffsetTy =
80       llvm::SmallVector<std::pair<Expr *, OverloadedOperatorKind>, 4>;
81   using DoacrossDependMapTy =
82       llvm::DenseMap<OMPDependClause *, OperatorOffsetTy>;
83   /// Kind of the declaration used in the uses_allocators clauses.
84   enum class UsesAllocatorsDeclKind {
85     /// Predefined allocator
86     PredefinedAllocator,
87     /// User-defined allocator
88     UserDefinedAllocator,
89     /// The declaration that represent allocator trait
90     AllocatorTrait,
91   };
92 
93 private:
94   struct DSAInfo {
95     OpenMPClauseKind Attributes = OMPC_unknown;
96     unsigned Modifier = 0;
97     /// Pointer to a reference expression and a flag which shows that the
98     /// variable is marked as lastprivate(true) or not (false).
99     llvm::PointerIntPair<const Expr *, 1, bool> RefExpr;
100     DeclRefExpr *PrivateCopy = nullptr;
101   };
102   using DeclSAMapTy = llvm::SmallDenseMap<const ValueDecl *, DSAInfo, 8>;
103   using UsedRefMapTy = llvm::SmallDenseMap<const ValueDecl *, const Expr *, 8>;
104   using LCDeclInfo = std::pair<unsigned, VarDecl *>;
105   using LoopControlVariablesMapTy =
106       llvm::SmallDenseMap<const ValueDecl *, LCDeclInfo, 8>;
107   /// Struct that associates a component with the clause kind where they are
108   /// found.
109   struct MappedExprComponentTy {
110     OMPClauseMappableExprCommon::MappableExprComponentLists Components;
111     OpenMPClauseKind Kind = OMPC_unknown;
112   };
113   using MappedExprComponentsTy =
114       llvm::DenseMap<const ValueDecl *, MappedExprComponentTy>;
115   using CriticalsWithHintsTy =
116       llvm::StringMap<std::pair<const OMPCriticalDirective *, llvm::APSInt>>;
117   struct ReductionData {
118     using BOKPtrType = llvm::PointerEmbeddedInt<BinaryOperatorKind, 16>;
119     SourceRange ReductionRange;
120     llvm::PointerUnion<const Expr *, BOKPtrType> ReductionOp;
121     ReductionData() = default;
122     void set(BinaryOperatorKind BO, SourceRange RR) {
123       ReductionRange = RR;
124       ReductionOp = BO;
125     }
126     void set(const Expr *RefExpr, SourceRange RR) {
127       ReductionRange = RR;
128       ReductionOp = RefExpr;
129     }
130   };
131   using DeclReductionMapTy =
132       llvm::SmallDenseMap<const ValueDecl *, ReductionData, 4>;
133   struct DefaultmapInfo {
134     OpenMPDefaultmapClauseModifier ImplicitBehavior =
135         OMPC_DEFAULTMAP_MODIFIER_unknown;
136     SourceLocation SLoc;
137     DefaultmapInfo() = default;
138     DefaultmapInfo(OpenMPDefaultmapClauseModifier M, SourceLocation Loc)
139         : ImplicitBehavior(M), SLoc(Loc) {}
140   };
141 
142   struct SharingMapTy {
143     DeclSAMapTy SharingMap;
144     DeclReductionMapTy ReductionMap;
145     UsedRefMapTy AlignedMap;
146     UsedRefMapTy NontemporalMap;
147     MappedExprComponentsTy MappedExprComponents;
148     LoopControlVariablesMapTy LCVMap;
149     DefaultDataSharingAttributes DefaultAttr = DSA_unspecified;
150     SourceLocation DefaultAttrLoc;
151     DefaultmapInfo DefaultmapMap[OMPC_DEFAULTMAP_unknown];
152     OpenMPDirectiveKind Directive = OMPD_unknown;
153     DeclarationNameInfo DirectiveName;
154     Scope *CurScope = nullptr;
155     SourceLocation ConstructLoc;
156     /// Set of 'depend' clauses with 'sink|source' dependence kind. Required to
157     /// get the data (loop counters etc.) about enclosing loop-based construct.
158     /// This data is required during codegen.
159     DoacrossDependMapTy DoacrossDepends;
160     /// First argument (Expr *) contains optional argument of the
161     /// 'ordered' clause, the second one is true if the regions has 'ordered'
162     /// clause, false otherwise.
163     llvm::Optional<std::pair<const Expr *, OMPOrderedClause *>> OrderedRegion;
164     unsigned AssociatedLoops = 1;
165     bool HasMutipleLoops = false;
166     const Decl *PossiblyLoopCounter = nullptr;
167     bool NowaitRegion = false;
168     bool CancelRegion = false;
169     bool LoopStart = false;
170     bool BodyComplete = false;
171     SourceLocation PrevScanLocation;
172     SourceLocation PrevOrderedLocation;
173     SourceLocation InnerTeamsRegionLoc;
174     /// Reference to the taskgroup task_reduction reference expression.
175     Expr *TaskgroupReductionRef = nullptr;
176     llvm::DenseSet<QualType> MappedClassesQualTypes;
177     SmallVector<Expr *, 4> InnerUsedAllocators;
178     llvm::DenseSet<CanonicalDeclPtr<Decl>> ImplicitTaskFirstprivates;
179     /// List of globals marked as declare target link in this target region
180     /// (isOpenMPTargetExecutionDirective(Directive) == true).
181     llvm::SmallVector<DeclRefExpr *, 4> DeclareTargetLinkVarDecls;
182     /// List of decls used in inclusive/exclusive clauses of the scan directive.
183     llvm::DenseSet<CanonicalDeclPtr<Decl>> UsedInScanDirective;
184     llvm::DenseMap<CanonicalDeclPtr<const Decl>, UsesAllocatorsDeclKind>
185         UsesAllocatorsDecls;
186     SharingMapTy(OpenMPDirectiveKind DKind, DeclarationNameInfo Name,
187                  Scope *CurScope, SourceLocation Loc)
188         : Directive(DKind), DirectiveName(Name), CurScope(CurScope),
189           ConstructLoc(Loc) {}
190     SharingMapTy() = default;
191   };
192 
193   using StackTy = SmallVector<SharingMapTy, 4>;
194 
195   /// Stack of used declaration and their data-sharing attributes.
196   DeclSAMapTy Threadprivates;
197   const FunctionScopeInfo *CurrentNonCapturingFunctionScope = nullptr;
198   SmallVector<std::pair<StackTy, const FunctionScopeInfo *>, 4> Stack;
199   /// true, if check for DSA must be from parent directive, false, if
200   /// from current directive.
201   OpenMPClauseKind ClauseKindMode = OMPC_unknown;
202   Sema &SemaRef;
203   bool ForceCapturing = false;
204   /// true if all the variables in the target executable directives must be
205   /// captured by reference.
206   bool ForceCaptureByReferenceInTargetExecutable = false;
207   CriticalsWithHintsTy Criticals;
208   unsigned IgnoredStackElements = 0;
209 
210   /// Iterators over the stack iterate in order from innermost to outermost
211   /// directive.
212   using const_iterator = StackTy::const_reverse_iterator;
213   const_iterator begin() const {
214     return Stack.empty() ? const_iterator()
215                          : Stack.back().first.rbegin() + IgnoredStackElements;
216   }
217   const_iterator end() const {
218     return Stack.empty() ? const_iterator() : Stack.back().first.rend();
219   }
220   using iterator = StackTy::reverse_iterator;
221   iterator begin() {
222     return Stack.empty() ? iterator()
223                          : Stack.back().first.rbegin() + IgnoredStackElements;
224   }
225   iterator end() {
226     return Stack.empty() ? iterator() : Stack.back().first.rend();
227   }
228 
229   // Convenience operations to get at the elements of the stack.
230 
231   bool isStackEmpty() const {
232     return Stack.empty() ||
233            Stack.back().second != CurrentNonCapturingFunctionScope ||
234            Stack.back().first.size() <= IgnoredStackElements;
235   }
236   size_t getStackSize() const {
237     return isStackEmpty() ? 0
238                           : Stack.back().first.size() - IgnoredStackElements;
239   }
240 
241   SharingMapTy *getTopOfStackOrNull() {
242     size_t Size = getStackSize();
243     if (Size == 0)
244       return nullptr;
245     return &Stack.back().first[Size - 1];
246   }
247   const SharingMapTy *getTopOfStackOrNull() const {
248     return const_cast<DSAStackTy&>(*this).getTopOfStackOrNull();
249   }
250   SharingMapTy &getTopOfStack() {
251     assert(!isStackEmpty() && "no current directive");
252     return *getTopOfStackOrNull();
253   }
254   const SharingMapTy &getTopOfStack() const {
255     return const_cast<DSAStackTy&>(*this).getTopOfStack();
256   }
257 
258   SharingMapTy *getSecondOnStackOrNull() {
259     size_t Size = getStackSize();
260     if (Size <= 1)
261       return nullptr;
262     return &Stack.back().first[Size - 2];
263   }
264   const SharingMapTy *getSecondOnStackOrNull() const {
265     return const_cast<DSAStackTy&>(*this).getSecondOnStackOrNull();
266   }
267 
268   /// Get the stack element at a certain level (previously returned by
269   /// \c getNestingLevel).
270   ///
271   /// Note that nesting levels count from outermost to innermost, and this is
272   /// the reverse of our iteration order where new inner levels are pushed at
273   /// the front of the stack.
274   SharingMapTy &getStackElemAtLevel(unsigned Level) {
275     assert(Level < getStackSize() && "no such stack element");
276     return Stack.back().first[Level];
277   }
278   const SharingMapTy &getStackElemAtLevel(unsigned Level) const {
279     return const_cast<DSAStackTy&>(*this).getStackElemAtLevel(Level);
280   }
281 
282   DSAVarData getDSA(const_iterator &Iter, ValueDecl *D) const;
283 
284   /// Checks if the variable is a local for OpenMP region.
285   bool isOpenMPLocal(VarDecl *D, const_iterator Iter) const;
286 
287   /// Vector of previously declared requires directives
288   SmallVector<const OMPRequiresDecl *, 2> RequiresDecls;
289   /// omp_allocator_handle_t type.
290   QualType OMPAllocatorHandleT;
291   /// omp_depend_t type.
292   QualType OMPDependT;
293   /// omp_event_handle_t type.
294   QualType OMPEventHandleT;
295   /// omp_alloctrait_t type.
296   QualType OMPAlloctraitT;
297   /// Expression for the predefined allocators.
298   Expr *OMPPredefinedAllocators[OMPAllocateDeclAttr::OMPUserDefinedMemAlloc] = {
299       nullptr};
300   /// Vector of previously encountered target directives
301   SmallVector<SourceLocation, 2> TargetLocations;
302   SourceLocation AtomicLocation;
303 
304 public:
305   explicit DSAStackTy(Sema &S) : SemaRef(S) {}
306 
307   /// Sets omp_allocator_handle_t type.
308   void setOMPAllocatorHandleT(QualType Ty) { OMPAllocatorHandleT = Ty; }
309   /// Gets omp_allocator_handle_t type.
310   QualType getOMPAllocatorHandleT() const { return OMPAllocatorHandleT; }
311   /// Sets omp_alloctrait_t type.
312   void setOMPAlloctraitT(QualType Ty) { OMPAlloctraitT = Ty; }
313   /// Gets omp_alloctrait_t type.
314   QualType getOMPAlloctraitT() const { return OMPAlloctraitT; }
315   /// Sets the given default allocator.
316   void setAllocator(OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind,
317                     Expr *Allocator) {
318     OMPPredefinedAllocators[AllocatorKind] = Allocator;
319   }
320   /// Returns the specified default allocator.
321   Expr *getAllocator(OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind) const {
322     return OMPPredefinedAllocators[AllocatorKind];
323   }
324   /// Sets omp_depend_t type.
325   void setOMPDependT(QualType Ty) { OMPDependT = Ty; }
326   /// Gets omp_depend_t type.
327   QualType getOMPDependT() const { return OMPDependT; }
328 
329   /// Sets omp_event_handle_t type.
330   void setOMPEventHandleT(QualType Ty) { OMPEventHandleT = Ty; }
331   /// Gets omp_event_handle_t type.
332   QualType getOMPEventHandleT() const { return OMPEventHandleT; }
333 
334   bool isClauseParsingMode() const { return ClauseKindMode != OMPC_unknown; }
335   OpenMPClauseKind getClauseParsingMode() const {
336     assert(isClauseParsingMode() && "Must be in clause parsing mode.");
337     return ClauseKindMode;
338   }
339   void setClauseParsingMode(OpenMPClauseKind K) { ClauseKindMode = K; }
340 
341   bool isBodyComplete() const {
342     const SharingMapTy *Top = getTopOfStackOrNull();
343     return Top && Top->BodyComplete;
344   }
345   void setBodyComplete() {
346     getTopOfStack().BodyComplete = true;
347   }
348 
349   bool isForceVarCapturing() const { return ForceCapturing; }
350   void setForceVarCapturing(bool V) { ForceCapturing = V; }
351 
352   void setForceCaptureByReferenceInTargetExecutable(bool V) {
353     ForceCaptureByReferenceInTargetExecutable = V;
354   }
355   bool isForceCaptureByReferenceInTargetExecutable() const {
356     return ForceCaptureByReferenceInTargetExecutable;
357   }
358 
359   void push(OpenMPDirectiveKind DKind, const DeclarationNameInfo &DirName,
360             Scope *CurScope, SourceLocation Loc) {
361     assert(!IgnoredStackElements &&
362            "cannot change stack while ignoring elements");
363     if (Stack.empty() ||
364         Stack.back().second != CurrentNonCapturingFunctionScope)
365       Stack.emplace_back(StackTy(), CurrentNonCapturingFunctionScope);
366     Stack.back().first.emplace_back(DKind, DirName, CurScope, Loc);
367     Stack.back().first.back().DefaultAttrLoc = Loc;
368   }
369 
370   void pop() {
371     assert(!IgnoredStackElements &&
372            "cannot change stack while ignoring elements");
373     assert(!Stack.back().first.empty() &&
374            "Data-sharing attributes stack is empty!");
375     Stack.back().first.pop_back();
376   }
377 
378   /// RAII object to temporarily leave the scope of a directive when we want to
379   /// logically operate in its parent.
380   class ParentDirectiveScope {
381     DSAStackTy &Self;
382     bool Active;
383   public:
384     ParentDirectiveScope(DSAStackTy &Self, bool Activate)
385         : Self(Self), Active(false) {
386       if (Activate)
387         enable();
388     }
389     ~ParentDirectiveScope() { disable(); }
390     void disable() {
391       if (Active) {
392         --Self.IgnoredStackElements;
393         Active = false;
394       }
395     }
396     void enable() {
397       if (!Active) {
398         ++Self.IgnoredStackElements;
399         Active = true;
400       }
401     }
402   };
403 
404   /// Marks that we're started loop parsing.
405   void loopInit() {
406     assert(isOpenMPLoopDirective(getCurrentDirective()) &&
407            "Expected loop-based directive.");
408     getTopOfStack().LoopStart = true;
409   }
410   /// Start capturing of the variables in the loop context.
411   void loopStart() {
412     assert(isOpenMPLoopDirective(getCurrentDirective()) &&
413            "Expected loop-based directive.");
414     getTopOfStack().LoopStart = false;
415   }
416   /// true, if variables are captured, false otherwise.
417   bool isLoopStarted() const {
418     assert(isOpenMPLoopDirective(getCurrentDirective()) &&
419            "Expected loop-based directive.");
420     return !getTopOfStack().LoopStart;
421   }
422   /// Marks (or clears) declaration as possibly loop counter.
423   void resetPossibleLoopCounter(const Decl *D = nullptr) {
424     getTopOfStack().PossiblyLoopCounter =
425         D ? D->getCanonicalDecl() : D;
426   }
427   /// Gets the possible loop counter decl.
428   const Decl *getPossiblyLoopCunter() const {
429     return getTopOfStack().PossiblyLoopCounter;
430   }
431   /// Start new OpenMP region stack in new non-capturing function.
432   void pushFunction() {
433     assert(!IgnoredStackElements &&
434            "cannot change stack while ignoring elements");
435     const FunctionScopeInfo *CurFnScope = SemaRef.getCurFunction();
436     assert(!isa<CapturingScopeInfo>(CurFnScope));
437     CurrentNonCapturingFunctionScope = CurFnScope;
438   }
439   /// Pop region stack for non-capturing function.
440   void popFunction(const FunctionScopeInfo *OldFSI) {
441     assert(!IgnoredStackElements &&
442            "cannot change stack while ignoring elements");
443     if (!Stack.empty() && Stack.back().second == OldFSI) {
444       assert(Stack.back().first.empty());
445       Stack.pop_back();
446     }
447     CurrentNonCapturingFunctionScope = nullptr;
448     for (const FunctionScopeInfo *FSI : llvm::reverse(SemaRef.FunctionScopes)) {
449       if (!isa<CapturingScopeInfo>(FSI)) {
450         CurrentNonCapturingFunctionScope = FSI;
451         break;
452       }
453     }
454   }
455 
456   void addCriticalWithHint(const OMPCriticalDirective *D, llvm::APSInt Hint) {
457     Criticals.try_emplace(D->getDirectiveName().getAsString(), D, Hint);
458   }
459   const std::pair<const OMPCriticalDirective *, llvm::APSInt>
460   getCriticalWithHint(const DeclarationNameInfo &Name) const {
461     auto I = Criticals.find(Name.getAsString());
462     if (I != Criticals.end())
463       return I->second;
464     return std::make_pair(nullptr, llvm::APSInt());
465   }
466   /// If 'aligned' declaration for given variable \a D was not seen yet,
467   /// add it and return NULL; otherwise return previous occurrence's expression
468   /// for diagnostics.
469   const Expr *addUniqueAligned(const ValueDecl *D, const Expr *NewDE);
470   /// If 'nontemporal' declaration for given variable \a D was not seen yet,
471   /// add it and return NULL; otherwise return previous occurrence's expression
472   /// for diagnostics.
473   const Expr *addUniqueNontemporal(const ValueDecl *D, const Expr *NewDE);
474 
475   /// Register specified variable as loop control variable.
476   void addLoopControlVariable(const ValueDecl *D, VarDecl *Capture);
477   /// Check if the specified variable is a loop control variable for
478   /// current region.
479   /// \return The index of the loop control variable in the list of associated
480   /// for-loops (from outer to inner).
481   const LCDeclInfo isLoopControlVariable(const ValueDecl *D) const;
482   /// Check if the specified variable is a loop control variable for
483   /// parent region.
484   /// \return The index of the loop control variable in the list of associated
485   /// for-loops (from outer to inner).
486   const LCDeclInfo isParentLoopControlVariable(const ValueDecl *D) const;
487   /// Check if the specified variable is a loop control variable for
488   /// current region.
489   /// \return The index of the loop control variable in the list of associated
490   /// for-loops (from outer to inner).
491   const LCDeclInfo isLoopControlVariable(const ValueDecl *D,
492                                          unsigned Level) const;
493   /// Get the loop control variable for the I-th loop (or nullptr) in
494   /// parent directive.
495   const ValueDecl *getParentLoopControlVariable(unsigned I) const;
496 
497   /// Marks the specified decl \p D as used in scan directive.
498   void markDeclAsUsedInScanDirective(ValueDecl *D) {
499     if (SharingMapTy *Stack = getSecondOnStackOrNull())
500       Stack->UsedInScanDirective.insert(D);
501   }
502 
503   /// Checks if the specified declaration was used in the inner scan directive.
504   bool isUsedInScanDirective(ValueDecl *D) const {
505     if (const SharingMapTy *Stack = getTopOfStackOrNull())
506       return Stack->UsedInScanDirective.count(D) > 0;
507     return false;
508   }
509 
510   /// Adds explicit data sharing attribute to the specified declaration.
511   void addDSA(const ValueDecl *D, const Expr *E, OpenMPClauseKind A,
512               DeclRefExpr *PrivateCopy = nullptr, unsigned Modifier = 0);
513 
514   /// Adds additional information for the reduction items with the reduction id
515   /// represented as an operator.
516   void addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
517                                  BinaryOperatorKind BOK);
518   /// Adds additional information for the reduction items with the reduction id
519   /// represented as reduction identifier.
520   void addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
521                                  const Expr *ReductionRef);
522   /// Returns the location and reduction operation from the innermost parent
523   /// region for the given \p D.
524   const DSAVarData
525   getTopMostTaskgroupReductionData(const ValueDecl *D, SourceRange &SR,
526                                    BinaryOperatorKind &BOK,
527                                    Expr *&TaskgroupDescriptor) const;
528   /// Returns the location and reduction operation from the innermost parent
529   /// region for the given \p D.
530   const DSAVarData
531   getTopMostTaskgroupReductionData(const ValueDecl *D, SourceRange &SR,
532                                    const Expr *&ReductionRef,
533                                    Expr *&TaskgroupDescriptor) const;
534   /// Return reduction reference expression for the current taskgroup or
535   /// parallel/worksharing directives with task reductions.
536   Expr *getTaskgroupReductionRef() const {
537     assert((getTopOfStack().Directive == OMPD_taskgroup ||
538             ((isOpenMPParallelDirective(getTopOfStack().Directive) ||
539               isOpenMPWorksharingDirective(getTopOfStack().Directive)) &&
540              !isOpenMPSimdDirective(getTopOfStack().Directive))) &&
541            "taskgroup reference expression requested for non taskgroup or "
542            "parallel/worksharing directive.");
543     return getTopOfStack().TaskgroupReductionRef;
544   }
545   /// Checks if the given \p VD declaration is actually a taskgroup reduction
546   /// descriptor variable at the \p Level of OpenMP regions.
547   bool isTaskgroupReductionRef(const ValueDecl *VD, unsigned Level) const {
548     return getStackElemAtLevel(Level).TaskgroupReductionRef &&
549            cast<DeclRefExpr>(getStackElemAtLevel(Level).TaskgroupReductionRef)
550                    ->getDecl() == VD;
551   }
552 
553   /// Returns data sharing attributes from top of the stack for the
554   /// specified declaration.
555   const DSAVarData getTopDSA(ValueDecl *D, bool FromParent);
556   /// Returns data-sharing attributes for the specified declaration.
557   const DSAVarData getImplicitDSA(ValueDecl *D, bool FromParent) const;
558   /// Returns data-sharing attributes for the specified declaration.
559   const DSAVarData getImplicitDSA(ValueDecl *D, unsigned Level) const;
560   /// Checks if the specified variables has data-sharing attributes which
561   /// match specified \a CPred predicate in any directive which matches \a DPred
562   /// predicate.
563   const DSAVarData
564   hasDSA(ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
565          const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
566          bool FromParent) const;
567   /// Checks if the specified variables has data-sharing attributes which
568   /// match specified \a CPred predicate in any innermost directive which
569   /// matches \a DPred predicate.
570   const DSAVarData
571   hasInnermostDSA(ValueDecl *D,
572                   const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
573                   const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
574                   bool FromParent) const;
575   /// Checks if the specified variables has explicit data-sharing
576   /// attributes which match specified \a CPred predicate at the specified
577   /// OpenMP region.
578   bool hasExplicitDSA(const ValueDecl *D,
579                       const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
580                       unsigned Level, bool NotLastprivate = false) const;
581 
582   /// Returns true if the directive at level \Level matches in the
583   /// specified \a DPred predicate.
584   bool hasExplicitDirective(
585       const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
586       unsigned Level) const;
587 
588   /// Finds a directive which matches specified \a DPred predicate.
589   bool hasDirective(
590       const llvm::function_ref<bool(
591           OpenMPDirectiveKind, const DeclarationNameInfo &, SourceLocation)>
592           DPred,
593       bool FromParent) const;
594 
595   /// Returns currently analyzed directive.
596   OpenMPDirectiveKind getCurrentDirective() const {
597     const SharingMapTy *Top = getTopOfStackOrNull();
598     return Top ? Top->Directive : OMPD_unknown;
599   }
600   /// Returns directive kind at specified level.
601   OpenMPDirectiveKind getDirective(unsigned Level) const {
602     assert(!isStackEmpty() && "No directive at specified level.");
603     return getStackElemAtLevel(Level).Directive;
604   }
605   /// Returns the capture region at the specified level.
606   OpenMPDirectiveKind getCaptureRegion(unsigned Level,
607                                        unsigned OpenMPCaptureLevel) const {
608     SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
609     getOpenMPCaptureRegions(CaptureRegions, getDirective(Level));
610     return CaptureRegions[OpenMPCaptureLevel];
611   }
612   /// Returns parent directive.
613   OpenMPDirectiveKind getParentDirective() const {
614     const SharingMapTy *Parent = getSecondOnStackOrNull();
615     return Parent ? Parent->Directive : OMPD_unknown;
616   }
617 
618   /// Add requires decl to internal vector
619   void addRequiresDecl(OMPRequiresDecl *RD) {
620     RequiresDecls.push_back(RD);
621   }
622 
623   /// Checks if the defined 'requires' directive has specified type of clause.
624   template <typename ClauseType>
625   bool hasRequiresDeclWithClause() const {
626     return llvm::any_of(RequiresDecls, [](const OMPRequiresDecl *D) {
627       return llvm::any_of(D->clauselists(), [](const OMPClause *C) {
628         return isa<ClauseType>(C);
629       });
630     });
631   }
632 
633   /// Checks for a duplicate clause amongst previously declared requires
634   /// directives
635   bool hasDuplicateRequiresClause(ArrayRef<OMPClause *> ClauseList) const {
636     bool IsDuplicate = false;
637     for (OMPClause *CNew : ClauseList) {
638       for (const OMPRequiresDecl *D : RequiresDecls) {
639         for (const OMPClause *CPrev : D->clauselists()) {
640           if (CNew->getClauseKind() == CPrev->getClauseKind()) {
641             SemaRef.Diag(CNew->getBeginLoc(),
642                          diag::err_omp_requires_clause_redeclaration)
643                 << getOpenMPClauseName(CNew->getClauseKind());
644             SemaRef.Diag(CPrev->getBeginLoc(),
645                          diag::note_omp_requires_previous_clause)
646                 << getOpenMPClauseName(CPrev->getClauseKind());
647             IsDuplicate = true;
648           }
649         }
650       }
651     }
652     return IsDuplicate;
653   }
654 
655   /// Add location of previously encountered target to internal vector
656   void addTargetDirLocation(SourceLocation LocStart) {
657     TargetLocations.push_back(LocStart);
658   }
659 
660   /// Add location for the first encountered atomicc directive.
661   void addAtomicDirectiveLoc(SourceLocation Loc) {
662     if (AtomicLocation.isInvalid())
663       AtomicLocation = Loc;
664   }
665 
666   /// Returns the location of the first encountered atomic directive in the
667   /// module.
668   SourceLocation getAtomicDirectiveLoc() const {
669     return AtomicLocation;
670   }
671 
672   // Return previously encountered target region locations.
673   ArrayRef<SourceLocation> getEncounteredTargetLocs() const {
674     return TargetLocations;
675   }
676 
677   /// Set default data sharing attribute to none.
678   void setDefaultDSANone(SourceLocation Loc) {
679     getTopOfStack().DefaultAttr = DSA_none;
680     getTopOfStack().DefaultAttrLoc = Loc;
681   }
682   /// Set default data sharing attribute to shared.
683   void setDefaultDSAShared(SourceLocation Loc) {
684     getTopOfStack().DefaultAttr = DSA_shared;
685     getTopOfStack().DefaultAttrLoc = Loc;
686   }
687   /// Set default data mapping attribute to Modifier:Kind
688   void setDefaultDMAAttr(OpenMPDefaultmapClauseModifier M,
689                          OpenMPDefaultmapClauseKind Kind,
690                          SourceLocation Loc) {
691     DefaultmapInfo &DMI = getTopOfStack().DefaultmapMap[Kind];
692     DMI.ImplicitBehavior = M;
693     DMI.SLoc = Loc;
694   }
695   /// Check whether the implicit-behavior has been set in defaultmap
696   bool checkDefaultmapCategory(OpenMPDefaultmapClauseKind VariableCategory) {
697     if (VariableCategory == OMPC_DEFAULTMAP_unknown)
698       return getTopOfStack()
699                      .DefaultmapMap[OMPC_DEFAULTMAP_aggregate]
700                      .ImplicitBehavior != OMPC_DEFAULTMAP_MODIFIER_unknown ||
701              getTopOfStack()
702                      .DefaultmapMap[OMPC_DEFAULTMAP_scalar]
703                      .ImplicitBehavior != OMPC_DEFAULTMAP_MODIFIER_unknown ||
704              getTopOfStack()
705                      .DefaultmapMap[OMPC_DEFAULTMAP_pointer]
706                      .ImplicitBehavior != OMPC_DEFAULTMAP_MODIFIER_unknown;
707     return getTopOfStack().DefaultmapMap[VariableCategory].ImplicitBehavior !=
708            OMPC_DEFAULTMAP_MODIFIER_unknown;
709   }
710 
711   DefaultDataSharingAttributes getDefaultDSA(unsigned Level) const {
712     return getStackSize() <= Level ? DSA_unspecified
713                                    : getStackElemAtLevel(Level).DefaultAttr;
714   }
715   DefaultDataSharingAttributes getDefaultDSA() const {
716     return isStackEmpty() ? DSA_unspecified
717                           : getTopOfStack().DefaultAttr;
718   }
719   SourceLocation getDefaultDSALocation() const {
720     return isStackEmpty() ? SourceLocation()
721                           : getTopOfStack().DefaultAttrLoc;
722   }
723   OpenMPDefaultmapClauseModifier
724   getDefaultmapModifier(OpenMPDefaultmapClauseKind Kind) const {
725     return isStackEmpty()
726                ? OMPC_DEFAULTMAP_MODIFIER_unknown
727                : getTopOfStack().DefaultmapMap[Kind].ImplicitBehavior;
728   }
729   OpenMPDefaultmapClauseModifier
730   getDefaultmapModifierAtLevel(unsigned Level,
731                                OpenMPDefaultmapClauseKind Kind) const {
732     return getStackElemAtLevel(Level).DefaultmapMap[Kind].ImplicitBehavior;
733   }
734   bool isDefaultmapCapturedByRef(unsigned Level,
735                                  OpenMPDefaultmapClauseKind Kind) const {
736     OpenMPDefaultmapClauseModifier M =
737         getDefaultmapModifierAtLevel(Level, Kind);
738     if (Kind == OMPC_DEFAULTMAP_scalar || Kind == OMPC_DEFAULTMAP_pointer) {
739       return (M == OMPC_DEFAULTMAP_MODIFIER_alloc) ||
740              (M == OMPC_DEFAULTMAP_MODIFIER_to) ||
741              (M == OMPC_DEFAULTMAP_MODIFIER_from) ||
742              (M == OMPC_DEFAULTMAP_MODIFIER_tofrom);
743     }
744     return true;
745   }
746   static bool mustBeFirstprivateBase(OpenMPDefaultmapClauseModifier M,
747                                      OpenMPDefaultmapClauseKind Kind) {
748     switch (Kind) {
749     case OMPC_DEFAULTMAP_scalar:
750     case OMPC_DEFAULTMAP_pointer:
751       return (M == OMPC_DEFAULTMAP_MODIFIER_unknown) ||
752              (M == OMPC_DEFAULTMAP_MODIFIER_firstprivate) ||
753              (M == OMPC_DEFAULTMAP_MODIFIER_default);
754     case OMPC_DEFAULTMAP_aggregate:
755       return M == OMPC_DEFAULTMAP_MODIFIER_firstprivate;
756     default:
757       break;
758     }
759     llvm_unreachable("Unexpected OpenMPDefaultmapClauseKind enum");
760   }
761   bool mustBeFirstprivateAtLevel(unsigned Level,
762                                  OpenMPDefaultmapClauseKind Kind) const {
763     OpenMPDefaultmapClauseModifier M =
764         getDefaultmapModifierAtLevel(Level, Kind);
765     return mustBeFirstprivateBase(M, Kind);
766   }
767   bool mustBeFirstprivate(OpenMPDefaultmapClauseKind Kind) const {
768     OpenMPDefaultmapClauseModifier M = getDefaultmapModifier(Kind);
769     return mustBeFirstprivateBase(M, Kind);
770   }
771 
772   /// Checks if the specified variable is a threadprivate.
773   bool isThreadPrivate(VarDecl *D) {
774     const DSAVarData DVar = getTopDSA(D, false);
775     return isOpenMPThreadPrivate(DVar.CKind);
776   }
777 
778   /// Marks current region as ordered (it has an 'ordered' clause).
779   void setOrderedRegion(bool IsOrdered, const Expr *Param,
780                         OMPOrderedClause *Clause) {
781     if (IsOrdered)
782       getTopOfStack().OrderedRegion.emplace(Param, Clause);
783     else
784       getTopOfStack().OrderedRegion.reset();
785   }
786   /// Returns true, if region is ordered (has associated 'ordered' clause),
787   /// false - otherwise.
788   bool isOrderedRegion() const {
789     if (const SharingMapTy *Top = getTopOfStackOrNull())
790       return Top->OrderedRegion.hasValue();
791     return false;
792   }
793   /// Returns optional parameter for the ordered region.
794   std::pair<const Expr *, OMPOrderedClause *> getOrderedRegionParam() const {
795     if (const SharingMapTy *Top = getTopOfStackOrNull())
796       if (Top->OrderedRegion.hasValue())
797         return Top->OrderedRegion.getValue();
798     return std::make_pair(nullptr, nullptr);
799   }
800   /// Returns true, if parent region is ordered (has associated
801   /// 'ordered' clause), false - otherwise.
802   bool isParentOrderedRegion() const {
803     if (const SharingMapTy *Parent = getSecondOnStackOrNull())
804       return Parent->OrderedRegion.hasValue();
805     return false;
806   }
807   /// Returns optional parameter for the ordered region.
808   std::pair<const Expr *, OMPOrderedClause *>
809   getParentOrderedRegionParam() const {
810     if (const SharingMapTy *Parent = getSecondOnStackOrNull())
811       if (Parent->OrderedRegion.hasValue())
812         return Parent->OrderedRegion.getValue();
813     return std::make_pair(nullptr, nullptr);
814   }
815   /// Marks current region as nowait (it has a 'nowait' clause).
816   void setNowaitRegion(bool IsNowait = true) {
817     getTopOfStack().NowaitRegion = IsNowait;
818   }
819   /// Returns true, if parent region is nowait (has associated
820   /// 'nowait' clause), false - otherwise.
821   bool isParentNowaitRegion() const {
822     if (const SharingMapTy *Parent = getSecondOnStackOrNull())
823       return Parent->NowaitRegion;
824     return false;
825   }
826   /// Marks parent region as cancel region.
827   void setParentCancelRegion(bool Cancel = true) {
828     if (SharingMapTy *Parent = getSecondOnStackOrNull())
829       Parent->CancelRegion |= Cancel;
830   }
831   /// Return true if current region has inner cancel construct.
832   bool isCancelRegion() const {
833     const SharingMapTy *Top = getTopOfStackOrNull();
834     return Top ? Top->CancelRegion : false;
835   }
836 
837   /// Mark that parent region already has scan directive.
838   void setParentHasScanDirective(SourceLocation Loc) {
839     if (SharingMapTy *Parent = getSecondOnStackOrNull())
840       Parent->PrevScanLocation = Loc;
841   }
842   /// Return true if current region has inner cancel construct.
843   bool doesParentHasScanDirective() const {
844     const SharingMapTy *Top = getSecondOnStackOrNull();
845     return Top ? Top->PrevScanLocation.isValid() : false;
846   }
847   /// Return true if current region has inner cancel construct.
848   SourceLocation getParentScanDirectiveLoc() const {
849     const SharingMapTy *Top = getSecondOnStackOrNull();
850     return Top ? Top->PrevScanLocation : SourceLocation();
851   }
852   /// Mark that parent region already has ordered directive.
853   void setParentHasOrderedDirective(SourceLocation Loc) {
854     if (SharingMapTy *Parent = getSecondOnStackOrNull())
855       Parent->PrevOrderedLocation = Loc;
856   }
857   /// Return true if current region has inner ordered construct.
858   bool doesParentHasOrderedDirective() const {
859     const SharingMapTy *Top = getSecondOnStackOrNull();
860     return Top ? Top->PrevOrderedLocation.isValid() : false;
861   }
862   /// Returns the location of the previously specified ordered directive.
863   SourceLocation getParentOrderedDirectiveLoc() const {
864     const SharingMapTy *Top = getSecondOnStackOrNull();
865     return Top ? Top->PrevOrderedLocation : SourceLocation();
866   }
867 
868   /// Set collapse value for the region.
869   void setAssociatedLoops(unsigned Val) {
870     getTopOfStack().AssociatedLoops = Val;
871     if (Val > 1)
872       getTopOfStack().HasMutipleLoops = true;
873   }
874   /// Return collapse value for region.
875   unsigned getAssociatedLoops() const {
876     const SharingMapTy *Top = getTopOfStackOrNull();
877     return Top ? Top->AssociatedLoops : 0;
878   }
879   /// Returns true if the construct is associated with multiple loops.
880   bool hasMutipleLoops() const {
881     const SharingMapTy *Top = getTopOfStackOrNull();
882     return Top ? Top->HasMutipleLoops : false;
883   }
884 
885   /// Marks current target region as one with closely nested teams
886   /// region.
887   void setParentTeamsRegionLoc(SourceLocation TeamsRegionLoc) {
888     if (SharingMapTy *Parent = getSecondOnStackOrNull())
889       Parent->InnerTeamsRegionLoc = TeamsRegionLoc;
890   }
891   /// Returns true, if current region has closely nested teams region.
892   bool hasInnerTeamsRegion() const {
893     return getInnerTeamsRegionLoc().isValid();
894   }
895   /// Returns location of the nested teams region (if any).
896   SourceLocation getInnerTeamsRegionLoc() const {
897     const SharingMapTy *Top = getTopOfStackOrNull();
898     return Top ? Top->InnerTeamsRegionLoc : SourceLocation();
899   }
900 
901   Scope *getCurScope() const {
902     const SharingMapTy *Top = getTopOfStackOrNull();
903     return Top ? Top->CurScope : nullptr;
904   }
905   SourceLocation getConstructLoc() const {
906     const SharingMapTy *Top = getTopOfStackOrNull();
907     return Top ? Top->ConstructLoc : SourceLocation();
908   }
909 
910   /// Do the check specified in \a Check to all component lists and return true
911   /// if any issue is found.
912   bool checkMappableExprComponentListsForDecl(
913       const ValueDecl *VD, bool CurrentRegionOnly,
914       const llvm::function_ref<
915           bool(OMPClauseMappableExprCommon::MappableExprComponentListRef,
916                OpenMPClauseKind)>
917           Check) const {
918     if (isStackEmpty())
919       return false;
920     auto SI = begin();
921     auto SE = end();
922 
923     if (SI == SE)
924       return false;
925 
926     if (CurrentRegionOnly)
927       SE = std::next(SI);
928     else
929       std::advance(SI, 1);
930 
931     for (; SI != SE; ++SI) {
932       auto MI = SI->MappedExprComponents.find(VD);
933       if (MI != SI->MappedExprComponents.end())
934         for (OMPClauseMappableExprCommon::MappableExprComponentListRef L :
935              MI->second.Components)
936           if (Check(L, MI->second.Kind))
937             return true;
938     }
939     return false;
940   }
941 
942   /// Do the check specified in \a Check to all component lists at a given level
943   /// and return true if any issue is found.
944   bool checkMappableExprComponentListsForDeclAtLevel(
945       const ValueDecl *VD, unsigned Level,
946       const llvm::function_ref<
947           bool(OMPClauseMappableExprCommon::MappableExprComponentListRef,
948                OpenMPClauseKind)>
949           Check) const {
950     if (getStackSize() <= Level)
951       return false;
952 
953     const SharingMapTy &StackElem = getStackElemAtLevel(Level);
954     auto MI = StackElem.MappedExprComponents.find(VD);
955     if (MI != StackElem.MappedExprComponents.end())
956       for (OMPClauseMappableExprCommon::MappableExprComponentListRef L :
957            MI->second.Components)
958         if (Check(L, MI->second.Kind))
959           return true;
960     return false;
961   }
962 
963   /// Create a new mappable expression component list associated with a given
964   /// declaration and initialize it with the provided list of components.
965   void addMappableExpressionComponents(
966       const ValueDecl *VD,
967       OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
968       OpenMPClauseKind WhereFoundClauseKind) {
969     MappedExprComponentTy &MEC = getTopOfStack().MappedExprComponents[VD];
970     // Create new entry and append the new components there.
971     MEC.Components.resize(MEC.Components.size() + 1);
972     MEC.Components.back().append(Components.begin(), Components.end());
973     MEC.Kind = WhereFoundClauseKind;
974   }
975 
976   unsigned getNestingLevel() const {
977     assert(!isStackEmpty());
978     return getStackSize() - 1;
979   }
980   void addDoacrossDependClause(OMPDependClause *C,
981                                const OperatorOffsetTy &OpsOffs) {
982     SharingMapTy *Parent = getSecondOnStackOrNull();
983     assert(Parent && isOpenMPWorksharingDirective(Parent->Directive));
984     Parent->DoacrossDepends.try_emplace(C, OpsOffs);
985   }
986   llvm::iterator_range<DoacrossDependMapTy::const_iterator>
987   getDoacrossDependClauses() const {
988     const SharingMapTy &StackElem = getTopOfStack();
989     if (isOpenMPWorksharingDirective(StackElem.Directive)) {
990       const DoacrossDependMapTy &Ref = StackElem.DoacrossDepends;
991       return llvm::make_range(Ref.begin(), Ref.end());
992     }
993     return llvm::make_range(StackElem.DoacrossDepends.end(),
994                             StackElem.DoacrossDepends.end());
995   }
996 
997   // Store types of classes which have been explicitly mapped
998   void addMappedClassesQualTypes(QualType QT) {
999     SharingMapTy &StackElem = getTopOfStack();
1000     StackElem.MappedClassesQualTypes.insert(QT);
1001   }
1002 
1003   // Return set of mapped classes types
1004   bool isClassPreviouslyMapped(QualType QT) const {
1005     const SharingMapTy &StackElem = getTopOfStack();
1006     return StackElem.MappedClassesQualTypes.count(QT) != 0;
1007   }
1008 
1009   /// Adds global declare target to the parent target region.
1010   void addToParentTargetRegionLinkGlobals(DeclRefExpr *E) {
1011     assert(*OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(
1012                E->getDecl()) == OMPDeclareTargetDeclAttr::MT_Link &&
1013            "Expected declare target link global.");
1014     for (auto &Elem : *this) {
1015       if (isOpenMPTargetExecutionDirective(Elem.Directive)) {
1016         Elem.DeclareTargetLinkVarDecls.push_back(E);
1017         return;
1018       }
1019     }
1020   }
1021 
1022   /// Returns the list of globals with declare target link if current directive
1023   /// is target.
1024   ArrayRef<DeclRefExpr *> getLinkGlobals() const {
1025     assert(isOpenMPTargetExecutionDirective(getCurrentDirective()) &&
1026            "Expected target executable directive.");
1027     return getTopOfStack().DeclareTargetLinkVarDecls;
1028   }
1029 
1030   /// Adds list of allocators expressions.
1031   void addInnerAllocatorExpr(Expr *E) {
1032     getTopOfStack().InnerUsedAllocators.push_back(E);
1033   }
1034   /// Return list of used allocators.
1035   ArrayRef<Expr *> getInnerAllocators() const {
1036     return getTopOfStack().InnerUsedAllocators;
1037   }
1038   /// Marks the declaration as implicitly firstprivate nin the task-based
1039   /// regions.
1040   void addImplicitTaskFirstprivate(unsigned Level, Decl *D) {
1041     getStackElemAtLevel(Level).ImplicitTaskFirstprivates.insert(D);
1042   }
1043   /// Checks if the decl is implicitly firstprivate in the task-based region.
1044   bool isImplicitTaskFirstprivate(Decl *D) const {
1045     return getTopOfStack().ImplicitTaskFirstprivates.count(D) > 0;
1046   }
1047 
1048   /// Marks decl as used in uses_allocators clause as the allocator.
1049   void addUsesAllocatorsDecl(const Decl *D, UsesAllocatorsDeclKind Kind) {
1050     getTopOfStack().UsesAllocatorsDecls.try_emplace(D, Kind);
1051   }
1052   /// Checks if specified decl is used in uses allocator clause as the
1053   /// allocator.
1054   Optional<UsesAllocatorsDeclKind> isUsesAllocatorsDecl(unsigned Level,
1055                                                         const Decl *D) const {
1056     const SharingMapTy &StackElem = getTopOfStack();
1057     auto I = StackElem.UsesAllocatorsDecls.find(D);
1058     if (I == StackElem.UsesAllocatorsDecls.end())
1059       return None;
1060     return I->getSecond();
1061   }
1062   Optional<UsesAllocatorsDeclKind> isUsesAllocatorsDecl(const Decl *D) const {
1063     const SharingMapTy &StackElem = getTopOfStack();
1064     auto I = StackElem.UsesAllocatorsDecls.find(D);
1065     if (I == StackElem.UsesAllocatorsDecls.end())
1066       return None;
1067     return I->getSecond();
1068   }
1069 };
1070 
1071 bool isImplicitTaskingRegion(OpenMPDirectiveKind DKind) {
1072   return isOpenMPParallelDirective(DKind) || isOpenMPTeamsDirective(DKind);
1073 }
1074 
1075 bool isImplicitOrExplicitTaskingRegion(OpenMPDirectiveKind DKind) {
1076   return isImplicitTaskingRegion(DKind) || isOpenMPTaskingDirective(DKind) ||
1077          DKind == OMPD_unknown;
1078 }
1079 
1080 } // namespace
1081 
1082 static const Expr *getExprAsWritten(const Expr *E) {
1083   if (const auto *FE = dyn_cast<FullExpr>(E))
1084     E = FE->getSubExpr();
1085 
1086   if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))
1087     E = MTE->getSubExpr();
1088 
1089   while (const auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E))
1090     E = Binder->getSubExpr();
1091 
1092   if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
1093     E = ICE->getSubExprAsWritten();
1094   return E->IgnoreParens();
1095 }
1096 
1097 static Expr *getExprAsWritten(Expr *E) {
1098   return const_cast<Expr *>(getExprAsWritten(const_cast<const Expr *>(E)));
1099 }
1100 
1101 static const ValueDecl *getCanonicalDecl(const ValueDecl *D) {
1102   if (const auto *CED = dyn_cast<OMPCapturedExprDecl>(D))
1103     if (const auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
1104       D = ME->getMemberDecl();
1105   const auto *VD = dyn_cast<VarDecl>(D);
1106   const auto *FD = dyn_cast<FieldDecl>(D);
1107   if (VD != nullptr) {
1108     VD = VD->getCanonicalDecl();
1109     D = VD;
1110   } else {
1111     assert(FD);
1112     FD = FD->getCanonicalDecl();
1113     D = FD;
1114   }
1115   return D;
1116 }
1117 
1118 static ValueDecl *getCanonicalDecl(ValueDecl *D) {
1119   return const_cast<ValueDecl *>(
1120       getCanonicalDecl(const_cast<const ValueDecl *>(D)));
1121 }
1122 
1123 DSAStackTy::DSAVarData DSAStackTy::getDSA(const_iterator &Iter,
1124                                           ValueDecl *D) const {
1125   D = getCanonicalDecl(D);
1126   auto *VD = dyn_cast<VarDecl>(D);
1127   const auto *FD = dyn_cast<FieldDecl>(D);
1128   DSAVarData DVar;
1129   if (Iter == end()) {
1130     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1131     // in a region but not in construct]
1132     //  File-scope or namespace-scope variables referenced in called routines
1133     //  in the region are shared unless they appear in a threadprivate
1134     //  directive.
1135     if (VD && !VD->isFunctionOrMethodVarDecl() && !isa<ParmVarDecl>(VD))
1136       DVar.CKind = OMPC_shared;
1137 
1138     // OpenMP [2.9.1.2, Data-sharing Attribute Rules for Variables Referenced
1139     // in a region but not in construct]
1140     //  Variables with static storage duration that are declared in called
1141     //  routines in the region are shared.
1142     if (VD && VD->hasGlobalStorage())
1143       DVar.CKind = OMPC_shared;
1144 
1145     // Non-static data members are shared by default.
1146     if (FD)
1147       DVar.CKind = OMPC_shared;
1148 
1149     return DVar;
1150   }
1151 
1152   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1153   // in a Construct, C/C++, predetermined, p.1]
1154   // Variables with automatic storage duration that are declared in a scope
1155   // inside the construct are private.
1156   if (VD && isOpenMPLocal(VD, Iter) && VD->isLocalVarDecl() &&
1157       (VD->getStorageClass() == SC_Auto || VD->getStorageClass() == SC_None)) {
1158     DVar.CKind = OMPC_private;
1159     return DVar;
1160   }
1161 
1162   DVar.DKind = Iter->Directive;
1163   // Explicitly specified attributes and local variables with predetermined
1164   // attributes.
1165   if (Iter->SharingMap.count(D)) {
1166     const DSAInfo &Data = Iter->SharingMap.lookup(D);
1167     DVar.RefExpr = Data.RefExpr.getPointer();
1168     DVar.PrivateCopy = Data.PrivateCopy;
1169     DVar.CKind = Data.Attributes;
1170     DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
1171     DVar.Modifier = Data.Modifier;
1172     return DVar;
1173   }
1174 
1175   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1176   // in a Construct, C/C++, implicitly determined, p.1]
1177   //  In a parallel or task construct, the data-sharing attributes of these
1178   //  variables are determined by the default clause, if present.
1179   switch (Iter->DefaultAttr) {
1180   case DSA_shared:
1181     DVar.CKind = OMPC_shared;
1182     DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
1183     return DVar;
1184   case DSA_none:
1185     return DVar;
1186   case DSA_unspecified:
1187     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1188     // in a Construct, implicitly determined, p.2]
1189     //  In a parallel construct, if no default clause is present, these
1190     //  variables are shared.
1191     DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
1192     if ((isOpenMPParallelDirective(DVar.DKind) &&
1193          !isOpenMPTaskLoopDirective(DVar.DKind)) ||
1194         isOpenMPTeamsDirective(DVar.DKind)) {
1195       DVar.CKind = OMPC_shared;
1196       return DVar;
1197     }
1198 
1199     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1200     // in a Construct, implicitly determined, p.4]
1201     //  In a task construct, if no default clause is present, a variable that in
1202     //  the enclosing context is determined to be shared by all implicit tasks
1203     //  bound to the current team is shared.
1204     if (isOpenMPTaskingDirective(DVar.DKind)) {
1205       DSAVarData DVarTemp;
1206       const_iterator I = Iter, E = end();
1207       do {
1208         ++I;
1209         // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables
1210         // Referenced in a Construct, implicitly determined, p.6]
1211         //  In a task construct, if no default clause is present, a variable
1212         //  whose data-sharing attribute is not determined by the rules above is
1213         //  firstprivate.
1214         DVarTemp = getDSA(I, D);
1215         if (DVarTemp.CKind != OMPC_shared) {
1216           DVar.RefExpr = nullptr;
1217           DVar.CKind = OMPC_firstprivate;
1218           return DVar;
1219         }
1220       } while (I != E && !isImplicitTaskingRegion(I->Directive));
1221       DVar.CKind =
1222           (DVarTemp.CKind == OMPC_unknown) ? OMPC_firstprivate : OMPC_shared;
1223       return DVar;
1224     }
1225   }
1226   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1227   // in a Construct, implicitly determined, p.3]
1228   //  For constructs other than task, if no default clause is present, these
1229   //  variables inherit their data-sharing attributes from the enclosing
1230   //  context.
1231   return getDSA(++Iter, D);
1232 }
1233 
1234 const Expr *DSAStackTy::addUniqueAligned(const ValueDecl *D,
1235                                          const Expr *NewDE) {
1236   assert(!isStackEmpty() && "Data sharing attributes stack is empty");
1237   D = getCanonicalDecl(D);
1238   SharingMapTy &StackElem = getTopOfStack();
1239   auto It = StackElem.AlignedMap.find(D);
1240   if (It == StackElem.AlignedMap.end()) {
1241     assert(NewDE && "Unexpected nullptr expr to be added into aligned map");
1242     StackElem.AlignedMap[D] = NewDE;
1243     return nullptr;
1244   }
1245   assert(It->second && "Unexpected nullptr expr in the aligned map");
1246   return It->second;
1247 }
1248 
1249 const Expr *DSAStackTy::addUniqueNontemporal(const ValueDecl *D,
1250                                              const Expr *NewDE) {
1251   assert(!isStackEmpty() && "Data sharing attributes stack is empty");
1252   D = getCanonicalDecl(D);
1253   SharingMapTy &StackElem = getTopOfStack();
1254   auto It = StackElem.NontemporalMap.find(D);
1255   if (It == StackElem.NontemporalMap.end()) {
1256     assert(NewDE && "Unexpected nullptr expr to be added into aligned map");
1257     StackElem.NontemporalMap[D] = NewDE;
1258     return nullptr;
1259   }
1260   assert(It->second && "Unexpected nullptr expr in the aligned map");
1261   return It->second;
1262 }
1263 
1264 void DSAStackTy::addLoopControlVariable(const ValueDecl *D, VarDecl *Capture) {
1265   assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
1266   D = getCanonicalDecl(D);
1267   SharingMapTy &StackElem = getTopOfStack();
1268   StackElem.LCVMap.try_emplace(
1269       D, LCDeclInfo(StackElem.LCVMap.size() + 1, Capture));
1270 }
1271 
1272 const DSAStackTy::LCDeclInfo
1273 DSAStackTy::isLoopControlVariable(const ValueDecl *D) const {
1274   assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
1275   D = getCanonicalDecl(D);
1276   const SharingMapTy &StackElem = getTopOfStack();
1277   auto It = StackElem.LCVMap.find(D);
1278   if (It != StackElem.LCVMap.end())
1279     return It->second;
1280   return {0, nullptr};
1281 }
1282 
1283 const DSAStackTy::LCDeclInfo
1284 DSAStackTy::isLoopControlVariable(const ValueDecl *D, unsigned Level) const {
1285   assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
1286   D = getCanonicalDecl(D);
1287   for (unsigned I = Level + 1; I > 0; --I) {
1288     const SharingMapTy &StackElem = getStackElemAtLevel(I - 1);
1289     auto It = StackElem.LCVMap.find(D);
1290     if (It != StackElem.LCVMap.end())
1291       return It->second;
1292   }
1293   return {0, nullptr};
1294 }
1295 
1296 const DSAStackTy::LCDeclInfo
1297 DSAStackTy::isParentLoopControlVariable(const ValueDecl *D) const {
1298   const SharingMapTy *Parent = getSecondOnStackOrNull();
1299   assert(Parent && "Data-sharing attributes stack is empty");
1300   D = getCanonicalDecl(D);
1301   auto It = Parent->LCVMap.find(D);
1302   if (It != Parent->LCVMap.end())
1303     return It->second;
1304   return {0, nullptr};
1305 }
1306 
1307 const ValueDecl *DSAStackTy::getParentLoopControlVariable(unsigned I) const {
1308   const SharingMapTy *Parent = getSecondOnStackOrNull();
1309   assert(Parent && "Data-sharing attributes stack is empty");
1310   if (Parent->LCVMap.size() < I)
1311     return nullptr;
1312   for (const auto &Pair : Parent->LCVMap)
1313     if (Pair.second.first == I)
1314       return Pair.first;
1315   return nullptr;
1316 }
1317 
1318 void DSAStackTy::addDSA(const ValueDecl *D, const Expr *E, OpenMPClauseKind A,
1319                         DeclRefExpr *PrivateCopy, unsigned Modifier) {
1320   D = getCanonicalDecl(D);
1321   if (A == OMPC_threadprivate) {
1322     DSAInfo &Data = Threadprivates[D];
1323     Data.Attributes = A;
1324     Data.RefExpr.setPointer(E);
1325     Data.PrivateCopy = nullptr;
1326     Data.Modifier = Modifier;
1327   } else {
1328     DSAInfo &Data = getTopOfStack().SharingMap[D];
1329     assert(Data.Attributes == OMPC_unknown || (A == Data.Attributes) ||
1330            (A == OMPC_firstprivate && Data.Attributes == OMPC_lastprivate) ||
1331            (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) ||
1332            (isLoopControlVariable(D).first && A == OMPC_private));
1333     Data.Modifier = Modifier;
1334     if (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) {
1335       Data.RefExpr.setInt(/*IntVal=*/true);
1336       return;
1337     }
1338     const bool IsLastprivate =
1339         A == OMPC_lastprivate || Data.Attributes == OMPC_lastprivate;
1340     Data.Attributes = A;
1341     Data.RefExpr.setPointerAndInt(E, IsLastprivate);
1342     Data.PrivateCopy = PrivateCopy;
1343     if (PrivateCopy) {
1344       DSAInfo &Data = getTopOfStack().SharingMap[PrivateCopy->getDecl()];
1345       Data.Modifier = Modifier;
1346       Data.Attributes = A;
1347       Data.RefExpr.setPointerAndInt(PrivateCopy, IsLastprivate);
1348       Data.PrivateCopy = nullptr;
1349     }
1350   }
1351 }
1352 
1353 /// Build a variable declaration for OpenMP loop iteration variable.
1354 static VarDecl *buildVarDecl(Sema &SemaRef, SourceLocation Loc, QualType Type,
1355                              StringRef Name, const AttrVec *Attrs = nullptr,
1356                              DeclRefExpr *OrigRef = nullptr) {
1357   DeclContext *DC = SemaRef.CurContext;
1358   IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
1359   TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
1360   auto *Decl =
1361       VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, TInfo, SC_None);
1362   if (Attrs) {
1363     for (specific_attr_iterator<AlignedAttr> I(Attrs->begin()), E(Attrs->end());
1364          I != E; ++I)
1365       Decl->addAttr(*I);
1366   }
1367   Decl->setImplicit();
1368   if (OrigRef) {
1369     Decl->addAttr(
1370         OMPReferencedVarAttr::CreateImplicit(SemaRef.Context, OrigRef));
1371   }
1372   return Decl;
1373 }
1374 
1375 static DeclRefExpr *buildDeclRefExpr(Sema &S, VarDecl *D, QualType Ty,
1376                                      SourceLocation Loc,
1377                                      bool RefersToCapture = false) {
1378   D->setReferenced();
1379   D->markUsed(S.Context);
1380   return DeclRefExpr::Create(S.getASTContext(), NestedNameSpecifierLoc(),
1381                              SourceLocation(), D, RefersToCapture, Loc, Ty,
1382                              VK_LValue);
1383 }
1384 
1385 void DSAStackTy::addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
1386                                            BinaryOperatorKind BOK) {
1387   D = getCanonicalDecl(D);
1388   assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
1389   assert(
1390       getTopOfStack().SharingMap[D].Attributes == OMPC_reduction &&
1391       "Additional reduction info may be specified only for reduction items.");
1392   ReductionData &ReductionData = getTopOfStack().ReductionMap[D];
1393   assert(ReductionData.ReductionRange.isInvalid() &&
1394          (getTopOfStack().Directive == OMPD_taskgroup ||
1395           ((isOpenMPParallelDirective(getTopOfStack().Directive) ||
1396             isOpenMPWorksharingDirective(getTopOfStack().Directive)) &&
1397            !isOpenMPSimdDirective(getTopOfStack().Directive))) &&
1398          "Additional reduction info may be specified only once for reduction "
1399          "items.");
1400   ReductionData.set(BOK, SR);
1401   Expr *&TaskgroupReductionRef =
1402       getTopOfStack().TaskgroupReductionRef;
1403   if (!TaskgroupReductionRef) {
1404     VarDecl *VD = buildVarDecl(SemaRef, SR.getBegin(),
1405                                SemaRef.Context.VoidPtrTy, ".task_red.");
1406     TaskgroupReductionRef =
1407         buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin());
1408   }
1409 }
1410 
1411 void DSAStackTy::addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
1412                                            const Expr *ReductionRef) {
1413   D = getCanonicalDecl(D);
1414   assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
1415   assert(
1416       getTopOfStack().SharingMap[D].Attributes == OMPC_reduction &&
1417       "Additional reduction info may be specified only for reduction items.");
1418   ReductionData &ReductionData = getTopOfStack().ReductionMap[D];
1419   assert(ReductionData.ReductionRange.isInvalid() &&
1420          (getTopOfStack().Directive == OMPD_taskgroup ||
1421           ((isOpenMPParallelDirective(getTopOfStack().Directive) ||
1422             isOpenMPWorksharingDirective(getTopOfStack().Directive)) &&
1423            !isOpenMPSimdDirective(getTopOfStack().Directive))) &&
1424          "Additional reduction info may be specified only once for reduction "
1425          "items.");
1426   ReductionData.set(ReductionRef, SR);
1427   Expr *&TaskgroupReductionRef =
1428       getTopOfStack().TaskgroupReductionRef;
1429   if (!TaskgroupReductionRef) {
1430     VarDecl *VD = buildVarDecl(SemaRef, SR.getBegin(),
1431                                SemaRef.Context.VoidPtrTy, ".task_red.");
1432     TaskgroupReductionRef =
1433         buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin());
1434   }
1435 }
1436 
1437 const DSAStackTy::DSAVarData DSAStackTy::getTopMostTaskgroupReductionData(
1438     const ValueDecl *D, SourceRange &SR, BinaryOperatorKind &BOK,
1439     Expr *&TaskgroupDescriptor) const {
1440   D = getCanonicalDecl(D);
1441   assert(!isStackEmpty() && "Data-sharing attributes stack is empty.");
1442   for (const_iterator I = begin() + 1, E = end(); I != E; ++I) {
1443     const DSAInfo &Data = I->SharingMap.lookup(D);
1444     if (Data.Attributes != OMPC_reduction ||
1445         Data.Modifier != OMPC_REDUCTION_task)
1446       continue;
1447     const ReductionData &ReductionData = I->ReductionMap.lookup(D);
1448     if (!ReductionData.ReductionOp ||
1449         ReductionData.ReductionOp.is<const Expr *>())
1450       return DSAVarData();
1451     SR = ReductionData.ReductionRange;
1452     BOK = ReductionData.ReductionOp.get<ReductionData::BOKPtrType>();
1453     assert(I->TaskgroupReductionRef && "taskgroup reduction reference "
1454                                        "expression for the descriptor is not "
1455                                        "set.");
1456     TaskgroupDescriptor = I->TaskgroupReductionRef;
1457     return DSAVarData(I->Directive, OMPC_reduction, Data.RefExpr.getPointer(),
1458                       Data.PrivateCopy, I->DefaultAttrLoc, OMPC_REDUCTION_task);
1459   }
1460   return DSAVarData();
1461 }
1462 
1463 const DSAStackTy::DSAVarData DSAStackTy::getTopMostTaskgroupReductionData(
1464     const ValueDecl *D, SourceRange &SR, const Expr *&ReductionRef,
1465     Expr *&TaskgroupDescriptor) const {
1466   D = getCanonicalDecl(D);
1467   assert(!isStackEmpty() && "Data-sharing attributes stack is empty.");
1468   for (const_iterator I = begin() + 1, E = end(); I != E; ++I) {
1469     const DSAInfo &Data = I->SharingMap.lookup(D);
1470     if (Data.Attributes != OMPC_reduction ||
1471         Data.Modifier != OMPC_REDUCTION_task)
1472       continue;
1473     const ReductionData &ReductionData = I->ReductionMap.lookup(D);
1474     if (!ReductionData.ReductionOp ||
1475         !ReductionData.ReductionOp.is<const Expr *>())
1476       return DSAVarData();
1477     SR = ReductionData.ReductionRange;
1478     ReductionRef = ReductionData.ReductionOp.get<const Expr *>();
1479     assert(I->TaskgroupReductionRef && "taskgroup reduction reference "
1480                                        "expression for the descriptor is not "
1481                                        "set.");
1482     TaskgroupDescriptor = I->TaskgroupReductionRef;
1483     return DSAVarData(I->Directive, OMPC_reduction, Data.RefExpr.getPointer(),
1484                       Data.PrivateCopy, I->DefaultAttrLoc, OMPC_REDUCTION_task);
1485   }
1486   return DSAVarData();
1487 }
1488 
1489 bool DSAStackTy::isOpenMPLocal(VarDecl *D, const_iterator I) const {
1490   D = D->getCanonicalDecl();
1491   for (const_iterator E = end(); I != E; ++I) {
1492     if (isImplicitOrExplicitTaskingRegion(I->Directive) ||
1493         isOpenMPTargetExecutionDirective(I->Directive)) {
1494       Scope *TopScope = I->CurScope ? I->CurScope->getParent() : nullptr;
1495       Scope *CurScope = getCurScope();
1496       while (CurScope && CurScope != TopScope && !CurScope->isDeclScope(D))
1497         CurScope = CurScope->getParent();
1498       return CurScope != TopScope;
1499     }
1500   }
1501   return false;
1502 }
1503 
1504 static bool isConstNotMutableType(Sema &SemaRef, QualType Type,
1505                                   bool AcceptIfMutable = true,
1506                                   bool *IsClassType = nullptr) {
1507   ASTContext &Context = SemaRef.getASTContext();
1508   Type = Type.getNonReferenceType().getCanonicalType();
1509   bool IsConstant = Type.isConstant(Context);
1510   Type = Context.getBaseElementType(Type);
1511   const CXXRecordDecl *RD = AcceptIfMutable && SemaRef.getLangOpts().CPlusPlus
1512                                 ? Type->getAsCXXRecordDecl()
1513                                 : nullptr;
1514   if (const auto *CTSD = dyn_cast_or_null<ClassTemplateSpecializationDecl>(RD))
1515     if (const ClassTemplateDecl *CTD = CTSD->getSpecializedTemplate())
1516       RD = CTD->getTemplatedDecl();
1517   if (IsClassType)
1518     *IsClassType = RD;
1519   return IsConstant && !(SemaRef.getLangOpts().CPlusPlus && RD &&
1520                          RD->hasDefinition() && RD->hasMutableFields());
1521 }
1522 
1523 static bool rejectConstNotMutableType(Sema &SemaRef, const ValueDecl *D,
1524                                       QualType Type, OpenMPClauseKind CKind,
1525                                       SourceLocation ELoc,
1526                                       bool AcceptIfMutable = true,
1527                                       bool ListItemNotVar = false) {
1528   ASTContext &Context = SemaRef.getASTContext();
1529   bool IsClassType;
1530   if (isConstNotMutableType(SemaRef, Type, AcceptIfMutable, &IsClassType)) {
1531     unsigned Diag = ListItemNotVar
1532                         ? diag::err_omp_const_list_item
1533                         : IsClassType ? diag::err_omp_const_not_mutable_variable
1534                                       : diag::err_omp_const_variable;
1535     SemaRef.Diag(ELoc, Diag) << getOpenMPClauseName(CKind);
1536     if (!ListItemNotVar && D) {
1537       const VarDecl *VD = dyn_cast<VarDecl>(D);
1538       bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
1539                                VarDecl::DeclarationOnly;
1540       SemaRef.Diag(D->getLocation(),
1541                    IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1542           << D;
1543     }
1544     return true;
1545   }
1546   return false;
1547 }
1548 
1549 const DSAStackTy::DSAVarData DSAStackTy::getTopDSA(ValueDecl *D,
1550                                                    bool FromParent) {
1551   D = getCanonicalDecl(D);
1552   DSAVarData DVar;
1553 
1554   auto *VD = dyn_cast<VarDecl>(D);
1555   auto TI = Threadprivates.find(D);
1556   if (TI != Threadprivates.end()) {
1557     DVar.RefExpr = TI->getSecond().RefExpr.getPointer();
1558     DVar.CKind = OMPC_threadprivate;
1559     DVar.Modifier = TI->getSecond().Modifier;
1560     return DVar;
1561   }
1562   if (VD && VD->hasAttr<OMPThreadPrivateDeclAttr>()) {
1563     DVar.RefExpr = buildDeclRefExpr(
1564         SemaRef, VD, D->getType().getNonReferenceType(),
1565         VD->getAttr<OMPThreadPrivateDeclAttr>()->getLocation());
1566     DVar.CKind = OMPC_threadprivate;
1567     addDSA(D, DVar.RefExpr, OMPC_threadprivate);
1568     return DVar;
1569   }
1570   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1571   // in a Construct, C/C++, predetermined, p.1]
1572   //  Variables appearing in threadprivate directives are threadprivate.
1573   if ((VD && VD->getTLSKind() != VarDecl::TLS_None &&
1574        !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
1575          SemaRef.getLangOpts().OpenMPUseTLS &&
1576          SemaRef.getASTContext().getTargetInfo().isTLSSupported())) ||
1577       (VD && VD->getStorageClass() == SC_Register &&
1578        VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())) {
1579     DVar.RefExpr = buildDeclRefExpr(
1580         SemaRef, VD, D->getType().getNonReferenceType(), D->getLocation());
1581     DVar.CKind = OMPC_threadprivate;
1582     addDSA(D, DVar.RefExpr, OMPC_threadprivate);
1583     return DVar;
1584   }
1585   if (SemaRef.getLangOpts().OpenMPCUDAMode && VD &&
1586       VD->isLocalVarDeclOrParm() && !isStackEmpty() &&
1587       !isLoopControlVariable(D).first) {
1588     const_iterator IterTarget =
1589         std::find_if(begin(), end(), [](const SharingMapTy &Data) {
1590           return isOpenMPTargetExecutionDirective(Data.Directive);
1591         });
1592     if (IterTarget != end()) {
1593       const_iterator ParentIterTarget = IterTarget + 1;
1594       for (const_iterator Iter = begin();
1595            Iter != ParentIterTarget; ++Iter) {
1596         if (isOpenMPLocal(VD, Iter)) {
1597           DVar.RefExpr =
1598               buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(),
1599                                D->getLocation());
1600           DVar.CKind = OMPC_threadprivate;
1601           return DVar;
1602         }
1603       }
1604       if (!isClauseParsingMode() || IterTarget != begin()) {
1605         auto DSAIter = IterTarget->SharingMap.find(D);
1606         if (DSAIter != IterTarget->SharingMap.end() &&
1607             isOpenMPPrivate(DSAIter->getSecond().Attributes)) {
1608           DVar.RefExpr = DSAIter->getSecond().RefExpr.getPointer();
1609           DVar.CKind = OMPC_threadprivate;
1610           return DVar;
1611         }
1612         const_iterator End = end();
1613         if (!SemaRef.isOpenMPCapturedByRef(
1614                 D, std::distance(ParentIterTarget, End),
1615                 /*OpenMPCaptureLevel=*/0)) {
1616           DVar.RefExpr =
1617               buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(),
1618                                IterTarget->ConstructLoc);
1619           DVar.CKind = OMPC_threadprivate;
1620           return DVar;
1621         }
1622       }
1623     }
1624   }
1625 
1626   if (isStackEmpty())
1627     // Not in OpenMP execution region and top scope was already checked.
1628     return DVar;
1629 
1630   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1631   // in a Construct, C/C++, predetermined, p.4]
1632   //  Static data members are shared.
1633   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1634   // in a Construct, C/C++, predetermined, p.7]
1635   //  Variables with static storage duration that are declared in a scope
1636   //  inside the construct are shared.
1637   if (VD && VD->isStaticDataMember()) {
1638     // Check for explicitly specified attributes.
1639     const_iterator I = begin();
1640     const_iterator EndI = end();
1641     if (FromParent && I != EndI)
1642       ++I;
1643     if (I != EndI) {
1644       auto It = I->SharingMap.find(D);
1645       if (It != I->SharingMap.end()) {
1646         const DSAInfo &Data = It->getSecond();
1647         DVar.RefExpr = Data.RefExpr.getPointer();
1648         DVar.PrivateCopy = Data.PrivateCopy;
1649         DVar.CKind = Data.Attributes;
1650         DVar.ImplicitDSALoc = I->DefaultAttrLoc;
1651         DVar.DKind = I->Directive;
1652         DVar.Modifier = Data.Modifier;
1653         return DVar;
1654       }
1655     }
1656 
1657     DVar.CKind = OMPC_shared;
1658     return DVar;
1659   }
1660 
1661   auto &&MatchesAlways = [](OpenMPDirectiveKind) { return true; };
1662   // The predetermined shared attribute for const-qualified types having no
1663   // mutable members was removed after OpenMP 3.1.
1664   if (SemaRef.LangOpts.OpenMP <= 31) {
1665     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1666     // in a Construct, C/C++, predetermined, p.6]
1667     //  Variables with const qualified type having no mutable member are
1668     //  shared.
1669     if (isConstNotMutableType(SemaRef, D->getType())) {
1670       // Variables with const-qualified type having no mutable member may be
1671       // listed in a firstprivate clause, even if they are static data members.
1672       DSAVarData DVarTemp = hasInnermostDSA(
1673           D,
1674           [](OpenMPClauseKind C) {
1675             return C == OMPC_firstprivate || C == OMPC_shared;
1676           },
1677           MatchesAlways, FromParent);
1678       if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr)
1679         return DVarTemp;
1680 
1681       DVar.CKind = OMPC_shared;
1682       return DVar;
1683     }
1684   }
1685 
1686   // Explicitly specified attributes and local variables with predetermined
1687   // attributes.
1688   const_iterator I = begin();
1689   const_iterator EndI = end();
1690   if (FromParent && I != EndI)
1691     ++I;
1692   if (I == EndI)
1693     return DVar;
1694   auto It = I->SharingMap.find(D);
1695   if (It != I->SharingMap.end()) {
1696     const DSAInfo &Data = It->getSecond();
1697     DVar.RefExpr = Data.RefExpr.getPointer();
1698     DVar.PrivateCopy = Data.PrivateCopy;
1699     DVar.CKind = Data.Attributes;
1700     DVar.ImplicitDSALoc = I->DefaultAttrLoc;
1701     DVar.DKind = I->Directive;
1702     DVar.Modifier = Data.Modifier;
1703   }
1704 
1705   return DVar;
1706 }
1707 
1708 const DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(ValueDecl *D,
1709                                                         bool FromParent) const {
1710   if (isStackEmpty()) {
1711     const_iterator I;
1712     return getDSA(I, D);
1713   }
1714   D = getCanonicalDecl(D);
1715   const_iterator StartI = begin();
1716   const_iterator EndI = end();
1717   if (FromParent && StartI != EndI)
1718     ++StartI;
1719   return getDSA(StartI, D);
1720 }
1721 
1722 const DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(ValueDecl *D,
1723                                                         unsigned Level) const {
1724   if (getStackSize() <= Level)
1725     return DSAVarData();
1726   D = getCanonicalDecl(D);
1727   const_iterator StartI = std::next(begin(), getStackSize() - 1 - Level);
1728   return getDSA(StartI, D);
1729 }
1730 
1731 const DSAStackTy::DSAVarData
1732 DSAStackTy::hasDSA(ValueDecl *D,
1733                    const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
1734                    const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
1735                    bool FromParent) const {
1736   if (isStackEmpty())
1737     return {};
1738   D = getCanonicalDecl(D);
1739   const_iterator I = begin();
1740   const_iterator EndI = end();
1741   if (FromParent && I != EndI)
1742     ++I;
1743   for (; I != EndI; ++I) {
1744     if (!DPred(I->Directive) &&
1745         !isImplicitOrExplicitTaskingRegion(I->Directive))
1746       continue;
1747     const_iterator NewI = I;
1748     DSAVarData DVar = getDSA(NewI, D);
1749     if (I == NewI && CPred(DVar.CKind))
1750       return DVar;
1751   }
1752   return {};
1753 }
1754 
1755 const DSAStackTy::DSAVarData DSAStackTy::hasInnermostDSA(
1756     ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
1757     const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
1758     bool FromParent) const {
1759   if (isStackEmpty())
1760     return {};
1761   D = getCanonicalDecl(D);
1762   const_iterator StartI = begin();
1763   const_iterator EndI = end();
1764   if (FromParent && StartI != EndI)
1765     ++StartI;
1766   if (StartI == EndI || !DPred(StartI->Directive))
1767     return {};
1768   const_iterator NewI = StartI;
1769   DSAVarData DVar = getDSA(NewI, D);
1770   return (NewI == StartI && CPred(DVar.CKind)) ? DVar : DSAVarData();
1771 }
1772 
1773 bool DSAStackTy::hasExplicitDSA(
1774     const ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
1775     unsigned Level, bool NotLastprivate) const {
1776   if (getStackSize() <= Level)
1777     return false;
1778   D = getCanonicalDecl(D);
1779   const SharingMapTy &StackElem = getStackElemAtLevel(Level);
1780   auto I = StackElem.SharingMap.find(D);
1781   if (I != StackElem.SharingMap.end() &&
1782       I->getSecond().RefExpr.getPointer() &&
1783       CPred(I->getSecond().Attributes) &&
1784       (!NotLastprivate || !I->getSecond().RefExpr.getInt()))
1785     return true;
1786   // Check predetermined rules for the loop control variables.
1787   auto LI = StackElem.LCVMap.find(D);
1788   if (LI != StackElem.LCVMap.end())
1789     return CPred(OMPC_private);
1790   return false;
1791 }
1792 
1793 bool DSAStackTy::hasExplicitDirective(
1794     const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
1795     unsigned Level) const {
1796   if (getStackSize() <= Level)
1797     return false;
1798   const SharingMapTy &StackElem = getStackElemAtLevel(Level);
1799   return DPred(StackElem.Directive);
1800 }
1801 
1802 bool DSAStackTy::hasDirective(
1803     const llvm::function_ref<bool(OpenMPDirectiveKind,
1804                                   const DeclarationNameInfo &, SourceLocation)>
1805         DPred,
1806     bool FromParent) const {
1807   // We look only in the enclosing region.
1808   size_t Skip = FromParent ? 2 : 1;
1809   for (const_iterator I = begin() + std::min(Skip, getStackSize()), E = end();
1810        I != E; ++I) {
1811     if (DPred(I->Directive, I->DirectiveName, I->ConstructLoc))
1812       return true;
1813   }
1814   return false;
1815 }
1816 
1817 void Sema::InitDataSharingAttributesStack() {
1818   VarDataSharingAttributesStack = new DSAStackTy(*this);
1819 }
1820 
1821 #define DSAStack static_cast<DSAStackTy *>(VarDataSharingAttributesStack)
1822 
1823 void Sema::pushOpenMPFunctionRegion() {
1824   DSAStack->pushFunction();
1825 }
1826 
1827 void Sema::popOpenMPFunctionRegion(const FunctionScopeInfo *OldFSI) {
1828   DSAStack->popFunction(OldFSI);
1829 }
1830 
1831 static bool isOpenMPDeviceDelayedContext(Sema &S) {
1832   assert(S.LangOpts.OpenMP && S.LangOpts.OpenMPIsDevice &&
1833          "Expected OpenMP device compilation.");
1834   return !S.isInOpenMPTargetExecutionDirective() &&
1835          !S.isInOpenMPDeclareTargetContext();
1836 }
1837 
1838 namespace {
1839 /// Status of the function emission on the host/device.
1840 enum class FunctionEmissionStatus {
1841   Emitted,
1842   Discarded,
1843   Unknown,
1844 };
1845 } // anonymous namespace
1846 
1847 Sema::DeviceDiagBuilder Sema::diagIfOpenMPDeviceCode(SourceLocation Loc,
1848                                                      unsigned DiagID) {
1849   assert(LangOpts.OpenMP && LangOpts.OpenMPIsDevice &&
1850          "Expected OpenMP device compilation.");
1851 
1852   FunctionDecl *FD = getCurFunctionDecl();
1853   DeviceDiagBuilder::Kind Kind = DeviceDiagBuilder::K_Nop;
1854   if (FD) {
1855     FunctionEmissionStatus FES = getEmissionStatus(FD);
1856     switch (FES) {
1857     case FunctionEmissionStatus::Emitted:
1858       Kind = DeviceDiagBuilder::K_Immediate;
1859       break;
1860     case FunctionEmissionStatus::Unknown:
1861       Kind = isOpenMPDeviceDelayedContext(*this)
1862                  ? DeviceDiagBuilder::K_Deferred
1863                  : DeviceDiagBuilder::K_Immediate;
1864       break;
1865     case FunctionEmissionStatus::TemplateDiscarded:
1866     case FunctionEmissionStatus::OMPDiscarded:
1867       Kind = DeviceDiagBuilder::K_Nop;
1868       break;
1869     case FunctionEmissionStatus::CUDADiscarded:
1870       llvm_unreachable("CUDADiscarded unexpected in OpenMP device compilation");
1871       break;
1872     }
1873   }
1874 
1875   return DeviceDiagBuilder(Kind, Loc, DiagID, getCurFunctionDecl(), *this);
1876 }
1877 
1878 Sema::DeviceDiagBuilder Sema::diagIfOpenMPHostCode(SourceLocation Loc,
1879                                                    unsigned DiagID) {
1880   assert(LangOpts.OpenMP && !LangOpts.OpenMPIsDevice &&
1881          "Expected OpenMP host compilation.");
1882   FunctionEmissionStatus FES = getEmissionStatus(getCurFunctionDecl());
1883   DeviceDiagBuilder::Kind Kind = DeviceDiagBuilder::K_Nop;
1884   switch (FES) {
1885   case FunctionEmissionStatus::Emitted:
1886     Kind = DeviceDiagBuilder::K_Immediate;
1887     break;
1888   case FunctionEmissionStatus::Unknown:
1889     Kind = DeviceDiagBuilder::K_Deferred;
1890     break;
1891   case FunctionEmissionStatus::TemplateDiscarded:
1892   case FunctionEmissionStatus::OMPDiscarded:
1893   case FunctionEmissionStatus::CUDADiscarded:
1894     Kind = DeviceDiagBuilder::K_Nop;
1895     break;
1896   }
1897 
1898   return DeviceDiagBuilder(Kind, Loc, DiagID, getCurFunctionDecl(), *this);
1899 }
1900 
1901 static OpenMPDefaultmapClauseKind
1902 getVariableCategoryFromDecl(const LangOptions &LO, const ValueDecl *VD) {
1903   if (LO.OpenMP <= 45) {
1904     if (VD->getType().getNonReferenceType()->isScalarType())
1905       return OMPC_DEFAULTMAP_scalar;
1906     return OMPC_DEFAULTMAP_aggregate;
1907   }
1908   if (VD->getType().getNonReferenceType()->isAnyPointerType())
1909     return OMPC_DEFAULTMAP_pointer;
1910   if (VD->getType().getNonReferenceType()->isScalarType())
1911     return OMPC_DEFAULTMAP_scalar;
1912   return OMPC_DEFAULTMAP_aggregate;
1913 }
1914 
1915 bool Sema::isOpenMPCapturedByRef(const ValueDecl *D, unsigned Level,
1916                                  unsigned OpenMPCaptureLevel) const {
1917   assert(LangOpts.OpenMP && "OpenMP is not allowed");
1918 
1919   ASTContext &Ctx = getASTContext();
1920   bool IsByRef = true;
1921 
1922   // Find the directive that is associated with the provided scope.
1923   D = cast<ValueDecl>(D->getCanonicalDecl());
1924   QualType Ty = D->getType();
1925 
1926   bool IsVariableUsedInMapClause = false;
1927   if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, Level)) {
1928     // This table summarizes how a given variable should be passed to the device
1929     // given its type and the clauses where it appears. This table is based on
1930     // the description in OpenMP 4.5 [2.10.4, target Construct] and
1931     // OpenMP 4.5 [2.15.5, Data-mapping Attribute Rules and Clauses].
1932     //
1933     // =========================================================================
1934     // | type |  defaultmap   | pvt | first | is_device_ptr |    map   | res.  |
1935     // |      |(tofrom:scalar)|     |  pvt  |               |          |       |
1936     // =========================================================================
1937     // | scl  |               |     |       |       -       |          | bycopy|
1938     // | scl  |               |  -  |   x   |       -       |     -    | bycopy|
1939     // | scl  |               |  x  |   -   |       -       |     -    | null  |
1940     // | scl  |       x       |     |       |       -       |          | byref |
1941     // | scl  |       x       |  -  |   x   |       -       |     -    | bycopy|
1942     // | scl  |       x       |  x  |   -   |       -       |     -    | null  |
1943     // | scl  |               |  -  |   -   |       -       |     x    | byref |
1944     // | scl  |       x       |  -  |   -   |       -       |     x    | byref |
1945     //
1946     // | agg  |      n.a.     |     |       |       -       |          | byref |
1947     // | agg  |      n.a.     |  -  |   x   |       -       |     -    | byref |
1948     // | agg  |      n.a.     |  x  |   -   |       -       |     -    | null  |
1949     // | agg  |      n.a.     |  -  |   -   |       -       |     x    | byref |
1950     // | agg  |      n.a.     |  -  |   -   |       -       |    x[]   | byref |
1951     //
1952     // | ptr  |      n.a.     |     |       |       -       |          | bycopy|
1953     // | ptr  |      n.a.     |  -  |   x   |       -       |     -    | bycopy|
1954     // | ptr  |      n.a.     |  x  |   -   |       -       |     -    | null  |
1955     // | ptr  |      n.a.     |  -  |   -   |       -       |     x    | byref |
1956     // | ptr  |      n.a.     |  -  |   -   |       -       |    x[]   | bycopy|
1957     // | ptr  |      n.a.     |  -  |   -   |       x       |          | bycopy|
1958     // | ptr  |      n.a.     |  -  |   -   |       x       |     x    | bycopy|
1959     // | ptr  |      n.a.     |  -  |   -   |       x       |    x[]   | bycopy|
1960     // =========================================================================
1961     // Legend:
1962     //  scl - scalar
1963     //  ptr - pointer
1964     //  agg - aggregate
1965     //  x - applies
1966     //  - - invalid in this combination
1967     //  [] - mapped with an array section
1968     //  byref - should be mapped by reference
1969     //  byval - should be mapped by value
1970     //  null - initialize a local variable to null on the device
1971     //
1972     // Observations:
1973     //  - All scalar declarations that show up in a map clause have to be passed
1974     //    by reference, because they may have been mapped in the enclosing data
1975     //    environment.
1976     //  - If the scalar value does not fit the size of uintptr, it has to be
1977     //    passed by reference, regardless the result in the table above.
1978     //  - For pointers mapped by value that have either an implicit map or an
1979     //    array section, the runtime library may pass the NULL value to the
1980     //    device instead of the value passed to it by the compiler.
1981 
1982     if (Ty->isReferenceType())
1983       Ty = Ty->castAs<ReferenceType>()->getPointeeType();
1984 
1985     // Locate map clauses and see if the variable being captured is referred to
1986     // in any of those clauses. Here we only care about variables, not fields,
1987     // because fields are part of aggregates.
1988     bool IsVariableAssociatedWithSection = false;
1989 
1990     DSAStack->checkMappableExprComponentListsForDeclAtLevel(
1991         D, Level,
1992         [&IsVariableUsedInMapClause, &IsVariableAssociatedWithSection, D](
1993             OMPClauseMappableExprCommon::MappableExprComponentListRef
1994                 MapExprComponents,
1995             OpenMPClauseKind WhereFoundClauseKind) {
1996           // Only the map clause information influences how a variable is
1997           // captured. E.g. is_device_ptr does not require changing the default
1998           // behavior.
1999           if (WhereFoundClauseKind != OMPC_map)
2000             return false;
2001 
2002           auto EI = MapExprComponents.rbegin();
2003           auto EE = MapExprComponents.rend();
2004 
2005           assert(EI != EE && "Invalid map expression!");
2006 
2007           if (isa<DeclRefExpr>(EI->getAssociatedExpression()))
2008             IsVariableUsedInMapClause |= EI->getAssociatedDeclaration() == D;
2009 
2010           ++EI;
2011           if (EI == EE)
2012             return false;
2013 
2014           if (isa<ArraySubscriptExpr>(EI->getAssociatedExpression()) ||
2015               isa<OMPArraySectionExpr>(EI->getAssociatedExpression()) ||
2016               isa<MemberExpr>(EI->getAssociatedExpression()) ||
2017               isa<OMPArrayShapingExpr>(EI->getAssociatedExpression())) {
2018             IsVariableAssociatedWithSection = true;
2019             // There is nothing more we need to know about this variable.
2020             return true;
2021           }
2022 
2023           // Keep looking for more map info.
2024           return false;
2025         });
2026 
2027     if (IsVariableUsedInMapClause) {
2028       // If variable is identified in a map clause it is always captured by
2029       // reference except if it is a pointer that is dereferenced somehow.
2030       IsByRef = !(Ty->isPointerType() && IsVariableAssociatedWithSection);
2031     } else {
2032       // By default, all the data that has a scalar type is mapped by copy
2033       // (except for reduction variables).
2034       // Defaultmap scalar is mutual exclusive to defaultmap pointer
2035       IsByRef =
2036           (DSAStack->isForceCaptureByReferenceInTargetExecutable() &&
2037            !Ty->isAnyPointerType()) ||
2038           !Ty->isScalarType() ||
2039           DSAStack->isDefaultmapCapturedByRef(
2040               Level, getVariableCategoryFromDecl(LangOpts, D)) ||
2041           DSAStack->hasExplicitDSA(
2042               D, [](OpenMPClauseKind K) { return K == OMPC_reduction; }, Level);
2043     }
2044   }
2045 
2046   if (IsByRef && Ty.getNonReferenceType()->isScalarType()) {
2047     IsByRef =
2048         ((IsVariableUsedInMapClause &&
2049           DSAStack->getCaptureRegion(Level, OpenMPCaptureLevel) ==
2050               OMPD_target) ||
2051          !(DSAStack->hasExplicitDSA(
2052                D,
2053                [](OpenMPClauseKind K) -> bool {
2054                  return K == OMPC_firstprivate;
2055                },
2056                Level, /*NotLastprivate=*/true) ||
2057            DSAStack->isUsesAllocatorsDecl(Level, D))) &&
2058         // If the variable is artificial and must be captured by value - try to
2059         // capture by value.
2060         !(isa<OMPCapturedExprDecl>(D) && !D->hasAttr<OMPCaptureNoInitAttr>() &&
2061           !cast<OMPCapturedExprDecl>(D)->getInit()->isGLValue());
2062   }
2063 
2064   // When passing data by copy, we need to make sure it fits the uintptr size
2065   // and alignment, because the runtime library only deals with uintptr types.
2066   // If it does not fit the uintptr size, we need to pass the data by reference
2067   // instead.
2068   if (!IsByRef &&
2069       (Ctx.getTypeSizeInChars(Ty) >
2070            Ctx.getTypeSizeInChars(Ctx.getUIntPtrType()) ||
2071        Ctx.getDeclAlign(D) > Ctx.getTypeAlignInChars(Ctx.getUIntPtrType()))) {
2072     IsByRef = true;
2073   }
2074 
2075   return IsByRef;
2076 }
2077 
2078 unsigned Sema::getOpenMPNestingLevel() const {
2079   assert(getLangOpts().OpenMP);
2080   return DSAStack->getNestingLevel();
2081 }
2082 
2083 bool Sema::isInOpenMPTargetExecutionDirective() const {
2084   return (isOpenMPTargetExecutionDirective(DSAStack->getCurrentDirective()) &&
2085           !DSAStack->isClauseParsingMode()) ||
2086          DSAStack->hasDirective(
2087              [](OpenMPDirectiveKind K, const DeclarationNameInfo &,
2088                 SourceLocation) -> bool {
2089                return isOpenMPTargetExecutionDirective(K);
2090              },
2091              false);
2092 }
2093 
2094 VarDecl *Sema::isOpenMPCapturedDecl(ValueDecl *D, bool CheckScopeInfo,
2095                                     unsigned StopAt) {
2096   assert(LangOpts.OpenMP && "OpenMP is not allowed");
2097   D = getCanonicalDecl(D);
2098 
2099   auto *VD = dyn_cast<VarDecl>(D);
2100   // Do not capture constexpr variables.
2101   if (VD && VD->isConstexpr())
2102     return nullptr;
2103 
2104   // If we want to determine whether the variable should be captured from the
2105   // perspective of the current capturing scope, and we've already left all the
2106   // capturing scopes of the top directive on the stack, check from the
2107   // perspective of its parent directive (if any) instead.
2108   DSAStackTy::ParentDirectiveScope InParentDirectiveRAII(
2109       *DSAStack, CheckScopeInfo && DSAStack->isBodyComplete());
2110 
2111   // If we are attempting to capture a global variable in a directive with
2112   // 'target' we return true so that this global is also mapped to the device.
2113   //
2114   if (VD && !VD->hasLocalStorage() &&
2115       (getCurCapturedRegion() || getCurBlock() || getCurLambda())) {
2116     if (isInOpenMPDeclareTargetContext()) {
2117       // Try to mark variable as declare target if it is used in capturing
2118       // regions.
2119       if (LangOpts.OpenMP <= 45 &&
2120           !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
2121         checkDeclIsAllowedInOpenMPTarget(nullptr, VD);
2122       return nullptr;
2123     } else if (isInOpenMPTargetExecutionDirective()) {
2124       // If the declaration is enclosed in a 'declare target' directive,
2125       // then it should not be captured.
2126       //
2127       if (OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
2128         return nullptr;
2129       CapturedRegionScopeInfo *CSI = nullptr;
2130       for (FunctionScopeInfo *FSI : llvm::drop_begin(
2131                llvm::reverse(FunctionScopes),
2132                CheckScopeInfo ? (FunctionScopes.size() - (StopAt + 1)) : 0)) {
2133         if (!isa<CapturingScopeInfo>(FSI))
2134           return nullptr;
2135         if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(FSI))
2136           if (RSI->CapRegionKind == CR_OpenMP) {
2137             CSI = RSI;
2138             break;
2139           }
2140       }
2141       SmallVector<OpenMPDirectiveKind, 4> Regions;
2142       getOpenMPCaptureRegions(Regions,
2143                               DSAStack->getDirective(CSI->OpenMPLevel));
2144       if (Regions[CSI->OpenMPCaptureLevel] != OMPD_task)
2145         return VD;
2146     }
2147   }
2148 
2149   if (CheckScopeInfo) {
2150     bool OpenMPFound = false;
2151     for (unsigned I = StopAt + 1; I > 0; --I) {
2152       FunctionScopeInfo *FSI = FunctionScopes[I - 1];
2153       if(!isa<CapturingScopeInfo>(FSI))
2154         return nullptr;
2155       if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(FSI))
2156         if (RSI->CapRegionKind == CR_OpenMP) {
2157           OpenMPFound = true;
2158           break;
2159         }
2160     }
2161     if (!OpenMPFound)
2162       return nullptr;
2163   }
2164 
2165   if (DSAStack->getCurrentDirective() != OMPD_unknown &&
2166       (!DSAStack->isClauseParsingMode() ||
2167        DSAStack->getParentDirective() != OMPD_unknown)) {
2168     auto &&Info = DSAStack->isLoopControlVariable(D);
2169     if (Info.first ||
2170         (VD && VD->hasLocalStorage() &&
2171          isImplicitOrExplicitTaskingRegion(DSAStack->getCurrentDirective())) ||
2172         (VD && DSAStack->isForceVarCapturing()))
2173       return VD ? VD : Info.second;
2174     DSAStackTy::DSAVarData DVarTop =
2175         DSAStack->getTopDSA(D, DSAStack->isClauseParsingMode());
2176     if (DVarTop.CKind != OMPC_unknown && isOpenMPPrivate(DVarTop.CKind))
2177       return VD ? VD : cast<VarDecl>(DVarTop.PrivateCopy->getDecl());
2178     // Threadprivate variables must not be captured.
2179     if (isOpenMPThreadPrivate(DVarTop.CKind))
2180       return nullptr;
2181     // The variable is not private or it is the variable in the directive with
2182     // default(none) clause and not used in any clause.
2183     DSAStackTy::DSAVarData DVarPrivate = DSAStack->hasDSA(
2184         D, isOpenMPPrivate, [](OpenMPDirectiveKind) { return true; },
2185         DSAStack->isClauseParsingMode());
2186     // Global shared must not be captured.
2187     if (VD && !VD->hasLocalStorage() && DVarPrivate.CKind == OMPC_unknown &&
2188         (DSAStack->getDefaultDSA() != DSA_none || DVarTop.CKind == OMPC_shared))
2189       return nullptr;
2190     if (DVarPrivate.CKind != OMPC_unknown ||
2191         (VD && DSAStack->getDefaultDSA() == DSA_none))
2192       return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
2193   }
2194   return nullptr;
2195 }
2196 
2197 void Sema::adjustOpenMPTargetScopeIndex(unsigned &FunctionScopesIndex,
2198                                         unsigned Level) const {
2199   FunctionScopesIndex -= getOpenMPCaptureLevels(DSAStack->getDirective(Level));
2200 }
2201 
2202 void Sema::startOpenMPLoop() {
2203   assert(LangOpts.OpenMP && "OpenMP must be enabled.");
2204   if (isOpenMPLoopDirective(DSAStack->getCurrentDirective()))
2205     DSAStack->loopInit();
2206 }
2207 
2208 void Sema::startOpenMPCXXRangeFor() {
2209   assert(LangOpts.OpenMP && "OpenMP must be enabled.");
2210   if (isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
2211     DSAStack->resetPossibleLoopCounter();
2212     DSAStack->loopStart();
2213   }
2214 }
2215 
2216 OpenMPClauseKind Sema::isOpenMPPrivateDecl(ValueDecl *D, unsigned Level,
2217                                            unsigned CapLevel) const {
2218   assert(LangOpts.OpenMP && "OpenMP is not allowed");
2219   if (DSAStack->hasExplicitDirective(
2220           [](OpenMPDirectiveKind K) { return isOpenMPTaskingDirective(K); },
2221           Level)) {
2222     bool IsTriviallyCopyable =
2223         D->getType().getNonReferenceType().isTriviallyCopyableType(Context);
2224     OpenMPDirectiveKind DKind = DSAStack->getDirective(Level);
2225     SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
2226     getOpenMPCaptureRegions(CaptureRegions, DKind);
2227     if (isOpenMPTaskingDirective(CaptureRegions[CapLevel]) &&
2228         (IsTriviallyCopyable ||
2229          !isOpenMPTaskLoopDirective(CaptureRegions[CapLevel]))) {
2230       if (DSAStack->hasExplicitDSA(
2231               D, [](OpenMPClauseKind K) { return K == OMPC_firstprivate; },
2232               Level, /*NotLastprivate=*/true))
2233         return OMPC_firstprivate;
2234       DSAStackTy::DSAVarData DVar = DSAStack->getImplicitDSA(D, Level);
2235       if (DVar.CKind != OMPC_shared &&
2236           !DSAStack->isLoopControlVariable(D, Level).first && !DVar.RefExpr) {
2237         DSAStack->addImplicitTaskFirstprivate(Level, D);
2238         return OMPC_firstprivate;
2239       }
2240     }
2241   }
2242   if (isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
2243     if (DSAStack->getAssociatedLoops() > 0 &&
2244         !DSAStack->isLoopStarted()) {
2245       DSAStack->resetPossibleLoopCounter(D);
2246       DSAStack->loopStart();
2247       return OMPC_private;
2248     }
2249     if ((DSAStack->getPossiblyLoopCunter() == D->getCanonicalDecl() ||
2250          DSAStack->isLoopControlVariable(D).first) &&
2251         !DSAStack->hasExplicitDSA(
2252             D, [](OpenMPClauseKind K) { return K != OMPC_private; }, Level) &&
2253         !isOpenMPSimdDirective(DSAStack->getCurrentDirective()))
2254       return OMPC_private;
2255   }
2256   if (const auto *VD = dyn_cast<VarDecl>(D)) {
2257     if (DSAStack->isThreadPrivate(const_cast<VarDecl *>(VD)) &&
2258         DSAStack->isForceVarCapturing() &&
2259         !DSAStack->hasExplicitDSA(
2260             D, [](OpenMPClauseKind K) { return K == OMPC_copyin; }, Level))
2261       return OMPC_private;
2262   }
2263   // User-defined allocators are private since they must be defined in the
2264   // context of target region.
2265   if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, Level) &&
2266       DSAStack->isUsesAllocatorsDecl(Level, D).getValueOr(
2267           DSAStackTy::UsesAllocatorsDeclKind::AllocatorTrait) ==
2268           DSAStackTy::UsesAllocatorsDeclKind::UserDefinedAllocator)
2269     return OMPC_private;
2270   return (DSAStack->hasExplicitDSA(
2271               D, [](OpenMPClauseKind K) { return K == OMPC_private; }, Level) ||
2272           (DSAStack->isClauseParsingMode() &&
2273            DSAStack->getClauseParsingMode() == OMPC_private) ||
2274           // Consider taskgroup reduction descriptor variable a private
2275           // to avoid possible capture in the region.
2276           (DSAStack->hasExplicitDirective(
2277                [](OpenMPDirectiveKind K) {
2278                  return K == OMPD_taskgroup ||
2279                         ((isOpenMPParallelDirective(K) ||
2280                           isOpenMPWorksharingDirective(K)) &&
2281                          !isOpenMPSimdDirective(K));
2282                },
2283                Level) &&
2284            DSAStack->isTaskgroupReductionRef(D, Level)))
2285              ? OMPC_private
2286              : OMPC_unknown;
2287 }
2288 
2289 void Sema::setOpenMPCaptureKind(FieldDecl *FD, const ValueDecl *D,
2290                                 unsigned Level) {
2291   assert(LangOpts.OpenMP && "OpenMP is not allowed");
2292   D = getCanonicalDecl(D);
2293   OpenMPClauseKind OMPC = OMPC_unknown;
2294   for (unsigned I = DSAStack->getNestingLevel() + 1; I > Level; --I) {
2295     const unsigned NewLevel = I - 1;
2296     if (DSAStack->hasExplicitDSA(D,
2297                                  [&OMPC](const OpenMPClauseKind K) {
2298                                    if (isOpenMPPrivate(K)) {
2299                                      OMPC = K;
2300                                      return true;
2301                                    }
2302                                    return false;
2303                                  },
2304                                  NewLevel))
2305       break;
2306     if (DSAStack->checkMappableExprComponentListsForDeclAtLevel(
2307             D, NewLevel,
2308             [](OMPClauseMappableExprCommon::MappableExprComponentListRef,
2309                OpenMPClauseKind) { return true; })) {
2310       OMPC = OMPC_map;
2311       break;
2312     }
2313     if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
2314                                        NewLevel)) {
2315       OMPC = OMPC_map;
2316       if (DSAStack->mustBeFirstprivateAtLevel(
2317               NewLevel, getVariableCategoryFromDecl(LangOpts, D)))
2318         OMPC = OMPC_firstprivate;
2319       break;
2320     }
2321   }
2322   if (OMPC != OMPC_unknown)
2323     FD->addAttr(OMPCaptureKindAttr::CreateImplicit(Context, unsigned(OMPC)));
2324 }
2325 
2326 bool Sema::isOpenMPTargetCapturedDecl(const ValueDecl *D, unsigned Level,
2327                                       unsigned CaptureLevel) const {
2328   assert(LangOpts.OpenMP && "OpenMP is not allowed");
2329   // Return true if the current level is no longer enclosed in a target region.
2330 
2331   SmallVector<OpenMPDirectiveKind, 4> Regions;
2332   getOpenMPCaptureRegions(Regions, DSAStack->getDirective(Level));
2333   const auto *VD = dyn_cast<VarDecl>(D);
2334   return VD && !VD->hasLocalStorage() &&
2335          DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
2336                                         Level) &&
2337          Regions[CaptureLevel] != OMPD_task;
2338 }
2339 
2340 bool Sema::isOpenMPGlobalCapturedDecl(ValueDecl *D, unsigned Level,
2341                                       unsigned CaptureLevel) const {
2342   assert(LangOpts.OpenMP && "OpenMP is not allowed");
2343   // Return true if the current level is no longer enclosed in a target region.
2344 
2345   if (const auto *VD = dyn_cast<VarDecl>(D)) {
2346     if (!VD->hasLocalStorage()) {
2347       DSAStackTy::DSAVarData TopDVar =
2348           DSAStack->getTopDSA(D, /*FromParent=*/false);
2349       unsigned NumLevels =
2350           getOpenMPCaptureLevels(DSAStack->getDirective(Level));
2351       if (Level == 0)
2352         return (NumLevels == CaptureLevel + 1) && TopDVar.CKind != OMPC_shared;
2353       DSAStackTy::DSAVarData DVar = DSAStack->getImplicitDSA(D, Level - 1);
2354       return DVar.CKind != OMPC_shared ||
2355              isOpenMPGlobalCapturedDecl(
2356                  D, Level - 1,
2357                  getOpenMPCaptureLevels(DSAStack->getDirective(Level - 1)) - 1);
2358     }
2359   }
2360   return true;
2361 }
2362 
2363 void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; }
2364 
2365 void Sema::ActOnOpenMPBeginDeclareVariant(SourceLocation Loc,
2366                                           OMPTraitInfo &TI) {
2367   if (!OMPDeclareVariantScopes.empty()) {
2368     Diag(Loc, diag::warn_nested_declare_variant);
2369     return;
2370   }
2371   OMPDeclareVariantScopes.push_back(OMPDeclareVariantScope(TI));
2372 }
2373 
2374 void Sema::ActOnOpenMPEndDeclareVariant() {
2375   assert(isInOpenMPDeclareVariantScope() &&
2376          "Not in OpenMP declare variant scope!");
2377 
2378   OMPDeclareVariantScopes.pop_back();
2379 }
2380 
2381 void Sema::finalizeOpenMPDelayedAnalysis(const FunctionDecl *Caller,
2382                                          const FunctionDecl *Callee,
2383                                          SourceLocation Loc) {
2384   assert(LangOpts.OpenMP && "Expected OpenMP compilation mode.");
2385   Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
2386       OMPDeclareTargetDeclAttr::getDeviceType(Caller->getMostRecentDecl());
2387   // Ignore host functions during device analyzis.
2388   if (LangOpts.OpenMPIsDevice && DevTy &&
2389       *DevTy == OMPDeclareTargetDeclAttr::DT_Host)
2390     return;
2391   // Ignore nohost functions during host analyzis.
2392   if (!LangOpts.OpenMPIsDevice && DevTy &&
2393       *DevTy == OMPDeclareTargetDeclAttr::DT_NoHost)
2394     return;
2395   const FunctionDecl *FD = Callee->getMostRecentDecl();
2396   DevTy = OMPDeclareTargetDeclAttr::getDeviceType(FD);
2397   if (LangOpts.OpenMPIsDevice && DevTy &&
2398       *DevTy == OMPDeclareTargetDeclAttr::DT_Host) {
2399     // Diagnose host function called during device codegen.
2400     StringRef HostDevTy =
2401         getOpenMPSimpleClauseTypeName(OMPC_device_type, OMPC_DEVICE_TYPE_host);
2402     Diag(Loc, diag::err_omp_wrong_device_function_call) << HostDevTy << 0;
2403     Diag(FD->getAttr<OMPDeclareTargetDeclAttr>()->getLocation(),
2404          diag::note_omp_marked_device_type_here)
2405         << HostDevTy;
2406     return;
2407   }
2408       if (!LangOpts.OpenMPIsDevice && DevTy &&
2409           *DevTy == OMPDeclareTargetDeclAttr::DT_NoHost) {
2410         // Diagnose nohost function called during host codegen.
2411         StringRef NoHostDevTy = getOpenMPSimpleClauseTypeName(
2412             OMPC_device_type, OMPC_DEVICE_TYPE_nohost);
2413         Diag(Loc, diag::err_omp_wrong_device_function_call) << NoHostDevTy << 1;
2414         Diag(FD->getAttr<OMPDeclareTargetDeclAttr>()->getLocation(),
2415              diag::note_omp_marked_device_type_here)
2416             << NoHostDevTy;
2417       }
2418 }
2419 
2420 void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind,
2421                                const DeclarationNameInfo &DirName,
2422                                Scope *CurScope, SourceLocation Loc) {
2423   DSAStack->push(DKind, DirName, CurScope, Loc);
2424   PushExpressionEvaluationContext(
2425       ExpressionEvaluationContext::PotentiallyEvaluated);
2426 }
2427 
2428 void Sema::StartOpenMPClause(OpenMPClauseKind K) {
2429   DSAStack->setClauseParsingMode(K);
2430 }
2431 
2432 void Sema::EndOpenMPClause() {
2433   DSAStack->setClauseParsingMode(/*K=*/OMPC_unknown);
2434 }
2435 
2436 static std::pair<ValueDecl *, bool>
2437 getPrivateItem(Sema &S, Expr *&RefExpr, SourceLocation &ELoc,
2438                SourceRange &ERange, bool AllowArraySection = false);
2439 
2440 /// Check consistency of the reduction clauses.
2441 static void checkReductionClauses(Sema &S, DSAStackTy *Stack,
2442                                   ArrayRef<OMPClause *> Clauses) {
2443   bool InscanFound = false;
2444   SourceLocation InscanLoc;
2445   // OpenMP 5.0, 2.19.5.4 reduction Clause, Restrictions.
2446   // A reduction clause without the inscan reduction-modifier may not appear on
2447   // a construct on which a reduction clause with the inscan reduction-modifier
2448   // appears.
2449   for (OMPClause *C : Clauses) {
2450     if (C->getClauseKind() != OMPC_reduction)
2451       continue;
2452     auto *RC = cast<OMPReductionClause>(C);
2453     if (RC->getModifier() == OMPC_REDUCTION_inscan) {
2454       InscanFound = true;
2455       InscanLoc = RC->getModifierLoc();
2456       continue;
2457     }
2458     if (RC->getModifier() == OMPC_REDUCTION_task) {
2459       // OpenMP 5.0, 2.19.5.4 reduction Clause.
2460       // A reduction clause with the task reduction-modifier may only appear on
2461       // a parallel construct, a worksharing construct or a combined or
2462       // composite construct for which any of the aforementioned constructs is a
2463       // constituent construct and simd or loop are not constituent constructs.
2464       OpenMPDirectiveKind CurDir = Stack->getCurrentDirective();
2465       if (!(isOpenMPParallelDirective(CurDir) ||
2466             isOpenMPWorksharingDirective(CurDir)) ||
2467           isOpenMPSimdDirective(CurDir))
2468         S.Diag(RC->getModifierLoc(),
2469                diag::err_omp_reduction_task_not_parallel_or_worksharing);
2470       continue;
2471     }
2472   }
2473   if (InscanFound) {
2474     for (OMPClause *C : Clauses) {
2475       if (C->getClauseKind() != OMPC_reduction)
2476         continue;
2477       auto *RC = cast<OMPReductionClause>(C);
2478       if (RC->getModifier() != OMPC_REDUCTION_inscan) {
2479         S.Diag(RC->getModifier() == OMPC_REDUCTION_unknown
2480                    ? RC->getBeginLoc()
2481                    : RC->getModifierLoc(),
2482                diag::err_omp_inscan_reduction_expected);
2483         S.Diag(InscanLoc, diag::note_omp_previous_inscan_reduction);
2484         continue;
2485       }
2486       for (Expr *Ref : RC->varlists()) {
2487         assert(Ref && "NULL expr in OpenMP nontemporal clause.");
2488         SourceLocation ELoc;
2489         SourceRange ERange;
2490         Expr *SimpleRefExpr = Ref;
2491         auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange,
2492                                   /*AllowArraySection=*/true);
2493         ValueDecl *D = Res.first;
2494         if (!D)
2495           continue;
2496         if (!Stack->isUsedInScanDirective(getCanonicalDecl(D))) {
2497           S.Diag(Ref->getExprLoc(),
2498                  diag::err_omp_reduction_not_inclusive_exclusive)
2499               << Ref->getSourceRange();
2500         }
2501       }
2502     }
2503   }
2504 }
2505 
2506 static void checkAllocateClauses(Sema &S, DSAStackTy *Stack,
2507                                  ArrayRef<OMPClause *> Clauses);
2508 static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr,
2509                                  bool WithInit);
2510 
2511 static void reportOriginalDsa(Sema &SemaRef, const DSAStackTy *Stack,
2512                               const ValueDecl *D,
2513                               const DSAStackTy::DSAVarData &DVar,
2514                               bool IsLoopIterVar = false);
2515 
2516 void Sema::EndOpenMPDSABlock(Stmt *CurDirective) {
2517   // OpenMP [2.14.3.5, Restrictions, C/C++, p.1]
2518   //  A variable of class type (or array thereof) that appears in a lastprivate
2519   //  clause requires an accessible, unambiguous default constructor for the
2520   //  class type, unless the list item is also specified in a firstprivate
2521   //  clause.
2522   if (const auto *D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) {
2523     for (OMPClause *C : D->clauses()) {
2524       if (auto *Clause = dyn_cast<OMPLastprivateClause>(C)) {
2525         SmallVector<Expr *, 8> PrivateCopies;
2526         for (Expr *DE : Clause->varlists()) {
2527           if (DE->isValueDependent() || DE->isTypeDependent()) {
2528             PrivateCopies.push_back(nullptr);
2529             continue;
2530           }
2531           auto *DRE = cast<DeclRefExpr>(DE->IgnoreParens());
2532           auto *VD = cast<VarDecl>(DRE->getDecl());
2533           QualType Type = VD->getType().getNonReferenceType();
2534           const DSAStackTy::DSAVarData DVar =
2535               DSAStack->getTopDSA(VD, /*FromParent=*/false);
2536           if (DVar.CKind == OMPC_lastprivate) {
2537             // Generate helper private variable and initialize it with the
2538             // default value. The address of the original variable is replaced
2539             // by the address of the new private variable in CodeGen. This new
2540             // variable is not added to IdResolver, so the code in the OpenMP
2541             // region uses original variable for proper diagnostics.
2542             VarDecl *VDPrivate = buildVarDecl(
2543                 *this, DE->getExprLoc(), Type.getUnqualifiedType(),
2544                 VD->getName(), VD->hasAttrs() ? &VD->getAttrs() : nullptr, DRE);
2545             ActOnUninitializedDecl(VDPrivate);
2546             if (VDPrivate->isInvalidDecl()) {
2547               PrivateCopies.push_back(nullptr);
2548               continue;
2549             }
2550             PrivateCopies.push_back(buildDeclRefExpr(
2551                 *this, VDPrivate, DE->getType(), DE->getExprLoc()));
2552           } else {
2553             // The variable is also a firstprivate, so initialization sequence
2554             // for private copy is generated already.
2555             PrivateCopies.push_back(nullptr);
2556           }
2557         }
2558         Clause->setPrivateCopies(PrivateCopies);
2559         continue;
2560       }
2561       // Finalize nontemporal clause by handling private copies, if any.
2562       if (auto *Clause = dyn_cast<OMPNontemporalClause>(C)) {
2563         SmallVector<Expr *, 8> PrivateRefs;
2564         for (Expr *RefExpr : Clause->varlists()) {
2565           assert(RefExpr && "NULL expr in OpenMP nontemporal clause.");
2566           SourceLocation ELoc;
2567           SourceRange ERange;
2568           Expr *SimpleRefExpr = RefExpr;
2569           auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
2570           if (Res.second)
2571             // It will be analyzed later.
2572             PrivateRefs.push_back(RefExpr);
2573           ValueDecl *D = Res.first;
2574           if (!D)
2575             continue;
2576 
2577           const DSAStackTy::DSAVarData DVar =
2578               DSAStack->getTopDSA(D, /*FromParent=*/false);
2579           PrivateRefs.push_back(DVar.PrivateCopy ? DVar.PrivateCopy
2580                                                  : SimpleRefExpr);
2581         }
2582         Clause->setPrivateRefs(PrivateRefs);
2583         continue;
2584       }
2585       if (auto *Clause = dyn_cast<OMPUsesAllocatorsClause>(C)) {
2586         for (unsigned I = 0, E = Clause->getNumberOfAllocators(); I < E; ++I) {
2587           OMPUsesAllocatorsClause::Data D = Clause->getAllocatorData(I);
2588           auto *DRE = dyn_cast<DeclRefExpr>(D.Allocator->IgnoreParenImpCasts());
2589           if (!DRE)
2590             continue;
2591           ValueDecl *VD = DRE->getDecl();
2592           if (!VD || !isa<VarDecl>(VD))
2593             continue;
2594           DSAStackTy::DSAVarData DVar =
2595               DSAStack->getTopDSA(VD, /*FromParent=*/false);
2596           // OpenMP [2.12.5, target Construct]
2597           // Memory allocators that appear in a uses_allocators clause cannot
2598           // appear in other data-sharing attribute clauses or data-mapping
2599           // attribute clauses in the same construct.
2600           Expr *MapExpr = nullptr;
2601           if (DVar.RefExpr ||
2602               DSAStack->checkMappableExprComponentListsForDecl(
2603                   VD, /*CurrentRegionOnly=*/true,
2604                   [VD, &MapExpr](
2605                       OMPClauseMappableExprCommon::MappableExprComponentListRef
2606                           MapExprComponents,
2607                       OpenMPClauseKind C) {
2608                     auto MI = MapExprComponents.rbegin();
2609                     auto ME = MapExprComponents.rend();
2610                     if (MI != ME &&
2611                         MI->getAssociatedDeclaration()->getCanonicalDecl() ==
2612                             VD->getCanonicalDecl()) {
2613                       MapExpr = MI->getAssociatedExpression();
2614                       return true;
2615                     }
2616                     return false;
2617                   })) {
2618             Diag(D.Allocator->getExprLoc(),
2619                  diag::err_omp_allocator_used_in_clauses)
2620                 << D.Allocator->getSourceRange();
2621             if (DVar.RefExpr)
2622               reportOriginalDsa(*this, DSAStack, VD, DVar);
2623             else
2624               Diag(MapExpr->getExprLoc(), diag::note_used_here)
2625                   << MapExpr->getSourceRange();
2626           }
2627         }
2628         continue;
2629       }
2630     }
2631     // Check allocate clauses.
2632     if (!CurContext->isDependentContext())
2633       checkAllocateClauses(*this, DSAStack, D->clauses());
2634     checkReductionClauses(*this, DSAStack, D->clauses());
2635   }
2636 
2637   DSAStack->pop();
2638   DiscardCleanupsInEvaluationContext();
2639   PopExpressionEvaluationContext();
2640 }
2641 
2642 static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
2643                                      Expr *NumIterations, Sema &SemaRef,
2644                                      Scope *S, DSAStackTy *Stack);
2645 
2646 namespace {
2647 
2648 class VarDeclFilterCCC final : public CorrectionCandidateCallback {
2649 private:
2650   Sema &SemaRef;
2651 
2652 public:
2653   explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {}
2654   bool ValidateCandidate(const TypoCorrection &Candidate) override {
2655     NamedDecl *ND = Candidate.getCorrectionDecl();
2656     if (const auto *VD = dyn_cast_or_null<VarDecl>(ND)) {
2657       return VD->hasGlobalStorage() &&
2658              SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
2659                                    SemaRef.getCurScope());
2660     }
2661     return false;
2662   }
2663 
2664   std::unique_ptr<CorrectionCandidateCallback> clone() override {
2665     return std::make_unique<VarDeclFilterCCC>(*this);
2666   }
2667 
2668 };
2669 
2670 class VarOrFuncDeclFilterCCC final : public CorrectionCandidateCallback {
2671 private:
2672   Sema &SemaRef;
2673 
2674 public:
2675   explicit VarOrFuncDeclFilterCCC(Sema &S) : SemaRef(S) {}
2676   bool ValidateCandidate(const TypoCorrection &Candidate) override {
2677     NamedDecl *ND = Candidate.getCorrectionDecl();
2678     if (ND && ((isa<VarDecl>(ND) && ND->getKind() == Decl::Var) ||
2679                isa<FunctionDecl>(ND))) {
2680       return SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
2681                                    SemaRef.getCurScope());
2682     }
2683     return false;
2684   }
2685 
2686   std::unique_ptr<CorrectionCandidateCallback> clone() override {
2687     return std::make_unique<VarOrFuncDeclFilterCCC>(*this);
2688   }
2689 };
2690 
2691 } // namespace
2692 
2693 ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope,
2694                                          CXXScopeSpec &ScopeSpec,
2695                                          const DeclarationNameInfo &Id,
2696                                          OpenMPDirectiveKind Kind) {
2697   LookupResult Lookup(*this, Id, LookupOrdinaryName);
2698   LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
2699 
2700   if (Lookup.isAmbiguous())
2701     return ExprError();
2702 
2703   VarDecl *VD;
2704   if (!Lookup.isSingleResult()) {
2705     VarDeclFilterCCC CCC(*this);
2706     if (TypoCorrection Corrected =
2707             CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr, CCC,
2708                         CTK_ErrorRecovery)) {
2709       diagnoseTypo(Corrected,
2710                    PDiag(Lookup.empty()
2711                              ? diag::err_undeclared_var_use_suggest
2712                              : diag::err_omp_expected_var_arg_suggest)
2713                        << Id.getName());
2714       VD = Corrected.getCorrectionDeclAs<VarDecl>();
2715     } else {
2716       Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use
2717                                        : diag::err_omp_expected_var_arg)
2718           << Id.getName();
2719       return ExprError();
2720     }
2721   } else if (!(VD = Lookup.getAsSingle<VarDecl>())) {
2722     Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName();
2723     Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at);
2724     return ExprError();
2725   }
2726   Lookup.suppressDiagnostics();
2727 
2728   // OpenMP [2.9.2, Syntax, C/C++]
2729   //   Variables must be file-scope, namespace-scope, or static block-scope.
2730   if (Kind == OMPD_threadprivate && !VD->hasGlobalStorage()) {
2731     Diag(Id.getLoc(), diag::err_omp_global_var_arg)
2732         << getOpenMPDirectiveName(Kind) << !VD->isStaticLocal();
2733     bool IsDecl =
2734         VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2735     Diag(VD->getLocation(),
2736          IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2737         << VD;
2738     return ExprError();
2739   }
2740 
2741   VarDecl *CanonicalVD = VD->getCanonicalDecl();
2742   NamedDecl *ND = CanonicalVD;
2743   // OpenMP [2.9.2, Restrictions, C/C++, p.2]
2744   //   A threadprivate directive for file-scope variables must appear outside
2745   //   any definition or declaration.
2746   if (CanonicalVD->getDeclContext()->isTranslationUnit() &&
2747       !getCurLexicalContext()->isTranslationUnit()) {
2748     Diag(Id.getLoc(), diag::err_omp_var_scope)
2749         << getOpenMPDirectiveName(Kind) << VD;
2750     bool IsDecl =
2751         VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2752     Diag(VD->getLocation(),
2753          IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2754         << VD;
2755     return ExprError();
2756   }
2757   // OpenMP [2.9.2, Restrictions, C/C++, p.3]
2758   //   A threadprivate directive for static class member variables must appear
2759   //   in the class definition, in the same scope in which the member
2760   //   variables are declared.
2761   if (CanonicalVD->isStaticDataMember() &&
2762       !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) {
2763     Diag(Id.getLoc(), diag::err_omp_var_scope)
2764         << getOpenMPDirectiveName(Kind) << VD;
2765     bool IsDecl =
2766         VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2767     Diag(VD->getLocation(),
2768          IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2769         << VD;
2770     return ExprError();
2771   }
2772   // OpenMP [2.9.2, Restrictions, C/C++, p.4]
2773   //   A threadprivate directive for namespace-scope variables must appear
2774   //   outside any definition or declaration other than the namespace
2775   //   definition itself.
2776   if (CanonicalVD->getDeclContext()->isNamespace() &&
2777       (!getCurLexicalContext()->isFileContext() ||
2778        !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) {
2779     Diag(Id.getLoc(), diag::err_omp_var_scope)
2780         << getOpenMPDirectiveName(Kind) << VD;
2781     bool IsDecl =
2782         VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2783     Diag(VD->getLocation(),
2784          IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2785         << VD;
2786     return ExprError();
2787   }
2788   // OpenMP [2.9.2, Restrictions, C/C++, p.6]
2789   //   A threadprivate directive for static block-scope variables must appear
2790   //   in the scope of the variable and not in a nested scope.
2791   if (CanonicalVD->isLocalVarDecl() && CurScope &&
2792       !isDeclInScope(ND, getCurLexicalContext(), CurScope)) {
2793     Diag(Id.getLoc(), diag::err_omp_var_scope)
2794         << getOpenMPDirectiveName(Kind) << VD;
2795     bool IsDecl =
2796         VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2797     Diag(VD->getLocation(),
2798          IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2799         << VD;
2800     return ExprError();
2801   }
2802 
2803   // OpenMP [2.9.2, Restrictions, C/C++, p.2-6]
2804   //   A threadprivate directive must lexically precede all references to any
2805   //   of the variables in its list.
2806   if (Kind == OMPD_threadprivate && VD->isUsed() &&
2807       !DSAStack->isThreadPrivate(VD)) {
2808     Diag(Id.getLoc(), diag::err_omp_var_used)
2809         << getOpenMPDirectiveName(Kind) << VD;
2810     return ExprError();
2811   }
2812 
2813   QualType ExprType = VD->getType().getNonReferenceType();
2814   return DeclRefExpr::Create(Context, NestedNameSpecifierLoc(),
2815                              SourceLocation(), VD,
2816                              /*RefersToEnclosingVariableOrCapture=*/false,
2817                              Id.getLoc(), ExprType, VK_LValue);
2818 }
2819 
2820 Sema::DeclGroupPtrTy
2821 Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc,
2822                                         ArrayRef<Expr *> VarList) {
2823   if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) {
2824     CurContext->addDecl(D);
2825     return DeclGroupPtrTy::make(DeclGroupRef(D));
2826   }
2827   return nullptr;
2828 }
2829 
2830 namespace {
2831 class LocalVarRefChecker final
2832     : public ConstStmtVisitor<LocalVarRefChecker, bool> {
2833   Sema &SemaRef;
2834 
2835 public:
2836   bool VisitDeclRefExpr(const DeclRefExpr *E) {
2837     if (const auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
2838       if (VD->hasLocalStorage()) {
2839         SemaRef.Diag(E->getBeginLoc(),
2840                      diag::err_omp_local_var_in_threadprivate_init)
2841             << E->getSourceRange();
2842         SemaRef.Diag(VD->getLocation(), diag::note_defined_here)
2843             << VD << VD->getSourceRange();
2844         return true;
2845       }
2846     }
2847     return false;
2848   }
2849   bool VisitStmt(const Stmt *S) {
2850     for (const Stmt *Child : S->children()) {
2851       if (Child && Visit(Child))
2852         return true;
2853     }
2854     return false;
2855   }
2856   explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {}
2857 };
2858 } // namespace
2859 
2860 OMPThreadPrivateDecl *
2861 Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) {
2862   SmallVector<Expr *, 8> Vars;
2863   for (Expr *RefExpr : VarList) {
2864     auto *DE = cast<DeclRefExpr>(RefExpr);
2865     auto *VD = cast<VarDecl>(DE->getDecl());
2866     SourceLocation ILoc = DE->getExprLoc();
2867 
2868     // Mark variable as used.
2869     VD->setReferenced();
2870     VD->markUsed(Context);
2871 
2872     QualType QType = VD->getType();
2873     if (QType->isDependentType() || QType->isInstantiationDependentType()) {
2874       // It will be analyzed later.
2875       Vars.push_back(DE);
2876       continue;
2877     }
2878 
2879     // OpenMP [2.9.2, Restrictions, C/C++, p.10]
2880     //   A threadprivate variable must not have an incomplete type.
2881     if (RequireCompleteType(ILoc, VD->getType(),
2882                             diag::err_omp_threadprivate_incomplete_type)) {
2883       continue;
2884     }
2885 
2886     // OpenMP [2.9.2, Restrictions, C/C++, p.10]
2887     //   A threadprivate variable must not have a reference type.
2888     if (VD->getType()->isReferenceType()) {
2889       Diag(ILoc, diag::err_omp_ref_type_arg)
2890           << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType();
2891       bool IsDecl =
2892           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2893       Diag(VD->getLocation(),
2894            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2895           << VD;
2896       continue;
2897     }
2898 
2899     // Check if this is a TLS variable. If TLS is not being supported, produce
2900     // the corresponding diagnostic.
2901     if ((VD->getTLSKind() != VarDecl::TLS_None &&
2902          !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
2903            getLangOpts().OpenMPUseTLS &&
2904            getASTContext().getTargetInfo().isTLSSupported())) ||
2905         (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
2906          !VD->isLocalVarDecl())) {
2907       Diag(ILoc, diag::err_omp_var_thread_local)
2908           << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1);
2909       bool IsDecl =
2910           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2911       Diag(VD->getLocation(),
2912            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2913           << VD;
2914       continue;
2915     }
2916 
2917     // Check if initial value of threadprivate variable reference variable with
2918     // local storage (it is not supported by runtime).
2919     if (const Expr *Init = VD->getAnyInitializer()) {
2920       LocalVarRefChecker Checker(*this);
2921       if (Checker.Visit(Init))
2922         continue;
2923     }
2924 
2925     Vars.push_back(RefExpr);
2926     DSAStack->addDSA(VD, DE, OMPC_threadprivate);
2927     VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit(
2928         Context, SourceRange(Loc, Loc)));
2929     if (ASTMutationListener *ML = Context.getASTMutationListener())
2930       ML->DeclarationMarkedOpenMPThreadPrivate(VD);
2931   }
2932   OMPThreadPrivateDecl *D = nullptr;
2933   if (!Vars.empty()) {
2934     D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc,
2935                                      Vars);
2936     D->setAccess(AS_public);
2937   }
2938   return D;
2939 }
2940 
2941 static OMPAllocateDeclAttr::AllocatorTypeTy
2942 getAllocatorKind(Sema &S, DSAStackTy *Stack, Expr *Allocator) {
2943   if (!Allocator)
2944     return OMPAllocateDeclAttr::OMPNullMemAlloc;
2945   if (Allocator->isTypeDependent() || Allocator->isValueDependent() ||
2946       Allocator->isInstantiationDependent() ||
2947       Allocator->containsUnexpandedParameterPack())
2948     return OMPAllocateDeclAttr::OMPUserDefinedMemAlloc;
2949   auto AllocatorKindRes = OMPAllocateDeclAttr::OMPUserDefinedMemAlloc;
2950   const Expr *AE = Allocator->IgnoreParenImpCasts();
2951   for (int I = 0; I < OMPAllocateDeclAttr::OMPUserDefinedMemAlloc; ++I) {
2952     auto AllocatorKind = static_cast<OMPAllocateDeclAttr::AllocatorTypeTy>(I);
2953     const Expr *DefAllocator = Stack->getAllocator(AllocatorKind);
2954     llvm::FoldingSetNodeID AEId, DAEId;
2955     AE->Profile(AEId, S.getASTContext(), /*Canonical=*/true);
2956     DefAllocator->Profile(DAEId, S.getASTContext(), /*Canonical=*/true);
2957     if (AEId == DAEId) {
2958       AllocatorKindRes = AllocatorKind;
2959       break;
2960     }
2961   }
2962   return AllocatorKindRes;
2963 }
2964 
2965 static bool checkPreviousOMPAllocateAttribute(
2966     Sema &S, DSAStackTy *Stack, Expr *RefExpr, VarDecl *VD,
2967     OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind, Expr *Allocator) {
2968   if (!VD->hasAttr<OMPAllocateDeclAttr>())
2969     return false;
2970   const auto *A = VD->getAttr<OMPAllocateDeclAttr>();
2971   Expr *PrevAllocator = A->getAllocator();
2972   OMPAllocateDeclAttr::AllocatorTypeTy PrevAllocatorKind =
2973       getAllocatorKind(S, Stack, PrevAllocator);
2974   bool AllocatorsMatch = AllocatorKind == PrevAllocatorKind;
2975   if (AllocatorsMatch &&
2976       AllocatorKind == OMPAllocateDeclAttr::OMPUserDefinedMemAlloc &&
2977       Allocator && PrevAllocator) {
2978     const Expr *AE = Allocator->IgnoreParenImpCasts();
2979     const Expr *PAE = PrevAllocator->IgnoreParenImpCasts();
2980     llvm::FoldingSetNodeID AEId, PAEId;
2981     AE->Profile(AEId, S.Context, /*Canonical=*/true);
2982     PAE->Profile(PAEId, S.Context, /*Canonical=*/true);
2983     AllocatorsMatch = AEId == PAEId;
2984   }
2985   if (!AllocatorsMatch) {
2986     SmallString<256> AllocatorBuffer;
2987     llvm::raw_svector_ostream AllocatorStream(AllocatorBuffer);
2988     if (Allocator)
2989       Allocator->printPretty(AllocatorStream, nullptr, S.getPrintingPolicy());
2990     SmallString<256> PrevAllocatorBuffer;
2991     llvm::raw_svector_ostream PrevAllocatorStream(PrevAllocatorBuffer);
2992     if (PrevAllocator)
2993       PrevAllocator->printPretty(PrevAllocatorStream, nullptr,
2994                                  S.getPrintingPolicy());
2995 
2996     SourceLocation AllocatorLoc =
2997         Allocator ? Allocator->getExprLoc() : RefExpr->getExprLoc();
2998     SourceRange AllocatorRange =
2999         Allocator ? Allocator->getSourceRange() : RefExpr->getSourceRange();
3000     SourceLocation PrevAllocatorLoc =
3001         PrevAllocator ? PrevAllocator->getExprLoc() : A->getLocation();
3002     SourceRange PrevAllocatorRange =
3003         PrevAllocator ? PrevAllocator->getSourceRange() : A->getRange();
3004     S.Diag(AllocatorLoc, diag::warn_omp_used_different_allocator)
3005         << (Allocator ? 1 : 0) << AllocatorStream.str()
3006         << (PrevAllocator ? 1 : 0) << PrevAllocatorStream.str()
3007         << AllocatorRange;
3008     S.Diag(PrevAllocatorLoc, diag::note_omp_previous_allocator)
3009         << PrevAllocatorRange;
3010     return true;
3011   }
3012   return false;
3013 }
3014 
3015 static void
3016 applyOMPAllocateAttribute(Sema &S, VarDecl *VD,
3017                           OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind,
3018                           Expr *Allocator, SourceRange SR) {
3019   if (VD->hasAttr<OMPAllocateDeclAttr>())
3020     return;
3021   if (Allocator &&
3022       (Allocator->isTypeDependent() || Allocator->isValueDependent() ||
3023        Allocator->isInstantiationDependent() ||
3024        Allocator->containsUnexpandedParameterPack()))
3025     return;
3026   auto *A = OMPAllocateDeclAttr::CreateImplicit(S.Context, AllocatorKind,
3027                                                 Allocator, SR);
3028   VD->addAttr(A);
3029   if (ASTMutationListener *ML = S.Context.getASTMutationListener())
3030     ML->DeclarationMarkedOpenMPAllocate(VD, A);
3031 }
3032 
3033 Sema::DeclGroupPtrTy Sema::ActOnOpenMPAllocateDirective(
3034     SourceLocation Loc, ArrayRef<Expr *> VarList,
3035     ArrayRef<OMPClause *> Clauses, DeclContext *Owner) {
3036   assert(Clauses.size() <= 1 && "Expected at most one clause.");
3037   Expr *Allocator = nullptr;
3038   if (Clauses.empty()) {
3039     // OpenMP 5.0, 2.11.3 allocate Directive, Restrictions.
3040     // allocate directives that appear in a target region must specify an
3041     // allocator clause unless a requires directive with the dynamic_allocators
3042     // clause is present in the same compilation unit.
3043     if (LangOpts.OpenMPIsDevice &&
3044         !DSAStack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>())
3045       targetDiag(Loc, diag::err_expected_allocator_clause);
3046   } else {
3047     Allocator = cast<OMPAllocatorClause>(Clauses.back())->getAllocator();
3048   }
3049   OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind =
3050       getAllocatorKind(*this, DSAStack, Allocator);
3051   SmallVector<Expr *, 8> Vars;
3052   for (Expr *RefExpr : VarList) {
3053     auto *DE = cast<DeclRefExpr>(RefExpr);
3054     auto *VD = cast<VarDecl>(DE->getDecl());
3055 
3056     // Check if this is a TLS variable or global register.
3057     if (VD->getTLSKind() != VarDecl::TLS_None ||
3058         VD->hasAttr<OMPThreadPrivateDeclAttr>() ||
3059         (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
3060          !VD->isLocalVarDecl()))
3061       continue;
3062 
3063     // If the used several times in the allocate directive, the same allocator
3064     // must be used.
3065     if (checkPreviousOMPAllocateAttribute(*this, DSAStack, RefExpr, VD,
3066                                           AllocatorKind, Allocator))
3067       continue;
3068 
3069     // OpenMP, 2.11.3 allocate Directive, Restrictions, C / C++
3070     // If a list item has a static storage type, the allocator expression in the
3071     // allocator clause must be a constant expression that evaluates to one of
3072     // the predefined memory allocator values.
3073     if (Allocator && VD->hasGlobalStorage()) {
3074       if (AllocatorKind == OMPAllocateDeclAttr::OMPUserDefinedMemAlloc) {
3075         Diag(Allocator->getExprLoc(),
3076              diag::err_omp_expected_predefined_allocator)
3077             << Allocator->getSourceRange();
3078         bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
3079                       VarDecl::DeclarationOnly;
3080         Diag(VD->getLocation(),
3081              IsDecl ? diag::note_previous_decl : diag::note_defined_here)
3082             << VD;
3083         continue;
3084       }
3085     }
3086 
3087     Vars.push_back(RefExpr);
3088     applyOMPAllocateAttribute(*this, VD, AllocatorKind, Allocator,
3089                               DE->getSourceRange());
3090   }
3091   if (Vars.empty())
3092     return nullptr;
3093   if (!Owner)
3094     Owner = getCurLexicalContext();
3095   auto *D = OMPAllocateDecl::Create(Context, Owner, Loc, Vars, Clauses);
3096   D->setAccess(AS_public);
3097   Owner->addDecl(D);
3098   return DeclGroupPtrTy::make(DeclGroupRef(D));
3099 }
3100 
3101 Sema::DeclGroupPtrTy
3102 Sema::ActOnOpenMPRequiresDirective(SourceLocation Loc,
3103                                    ArrayRef<OMPClause *> ClauseList) {
3104   OMPRequiresDecl *D = nullptr;
3105   if (!CurContext->isFileContext()) {
3106     Diag(Loc, diag::err_omp_invalid_scope) << "requires";
3107   } else {
3108     D = CheckOMPRequiresDecl(Loc, ClauseList);
3109     if (D) {
3110       CurContext->addDecl(D);
3111       DSAStack->addRequiresDecl(D);
3112     }
3113   }
3114   return DeclGroupPtrTy::make(DeclGroupRef(D));
3115 }
3116 
3117 OMPRequiresDecl *Sema::CheckOMPRequiresDecl(SourceLocation Loc,
3118                                             ArrayRef<OMPClause *> ClauseList) {
3119   /// For target specific clauses, the requires directive cannot be
3120   /// specified after the handling of any of the target regions in the
3121   /// current compilation unit.
3122   ArrayRef<SourceLocation> TargetLocations =
3123       DSAStack->getEncounteredTargetLocs();
3124   SourceLocation AtomicLoc = DSAStack->getAtomicDirectiveLoc();
3125   if (!TargetLocations.empty() || !AtomicLoc.isInvalid()) {
3126     for (const OMPClause *CNew : ClauseList) {
3127       // Check if any of the requires clauses affect target regions.
3128       if (isa<OMPUnifiedSharedMemoryClause>(CNew) ||
3129           isa<OMPUnifiedAddressClause>(CNew) ||
3130           isa<OMPReverseOffloadClause>(CNew) ||
3131           isa<OMPDynamicAllocatorsClause>(CNew)) {
3132         Diag(Loc, diag::err_omp_directive_before_requires)
3133             << "target" << getOpenMPClauseName(CNew->getClauseKind());
3134         for (SourceLocation TargetLoc : TargetLocations) {
3135           Diag(TargetLoc, diag::note_omp_requires_encountered_directive)
3136               << "target";
3137         }
3138       } else if (!AtomicLoc.isInvalid() &&
3139                  isa<OMPAtomicDefaultMemOrderClause>(CNew)) {
3140         Diag(Loc, diag::err_omp_directive_before_requires)
3141             << "atomic" << getOpenMPClauseName(CNew->getClauseKind());
3142         Diag(AtomicLoc, diag::note_omp_requires_encountered_directive)
3143             << "atomic";
3144       }
3145     }
3146   }
3147 
3148   if (!DSAStack->hasDuplicateRequiresClause(ClauseList))
3149     return OMPRequiresDecl::Create(Context, getCurLexicalContext(), Loc,
3150                                    ClauseList);
3151   return nullptr;
3152 }
3153 
3154 static void reportOriginalDsa(Sema &SemaRef, const DSAStackTy *Stack,
3155                               const ValueDecl *D,
3156                               const DSAStackTy::DSAVarData &DVar,
3157                               bool IsLoopIterVar) {
3158   if (DVar.RefExpr) {
3159     SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
3160         << getOpenMPClauseName(DVar.CKind);
3161     return;
3162   }
3163   enum {
3164     PDSA_StaticMemberShared,
3165     PDSA_StaticLocalVarShared,
3166     PDSA_LoopIterVarPrivate,
3167     PDSA_LoopIterVarLinear,
3168     PDSA_LoopIterVarLastprivate,
3169     PDSA_ConstVarShared,
3170     PDSA_GlobalVarShared,
3171     PDSA_TaskVarFirstprivate,
3172     PDSA_LocalVarPrivate,
3173     PDSA_Implicit
3174   } Reason = PDSA_Implicit;
3175   bool ReportHint = false;
3176   auto ReportLoc = D->getLocation();
3177   auto *VD = dyn_cast<VarDecl>(D);
3178   if (IsLoopIterVar) {
3179     if (DVar.CKind == OMPC_private)
3180       Reason = PDSA_LoopIterVarPrivate;
3181     else if (DVar.CKind == OMPC_lastprivate)
3182       Reason = PDSA_LoopIterVarLastprivate;
3183     else
3184       Reason = PDSA_LoopIterVarLinear;
3185   } else if (isOpenMPTaskingDirective(DVar.DKind) &&
3186              DVar.CKind == OMPC_firstprivate) {
3187     Reason = PDSA_TaskVarFirstprivate;
3188     ReportLoc = DVar.ImplicitDSALoc;
3189   } else if (VD && VD->isStaticLocal())
3190     Reason = PDSA_StaticLocalVarShared;
3191   else if (VD && VD->isStaticDataMember())
3192     Reason = PDSA_StaticMemberShared;
3193   else if (VD && VD->isFileVarDecl())
3194     Reason = PDSA_GlobalVarShared;
3195   else if (D->getType().isConstant(SemaRef.getASTContext()))
3196     Reason = PDSA_ConstVarShared;
3197   else if (VD && VD->isLocalVarDecl() && DVar.CKind == OMPC_private) {
3198     ReportHint = true;
3199     Reason = PDSA_LocalVarPrivate;
3200   }
3201   if (Reason != PDSA_Implicit) {
3202     SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa)
3203         << Reason << ReportHint
3204         << getOpenMPDirectiveName(Stack->getCurrentDirective());
3205   } else if (DVar.ImplicitDSALoc.isValid()) {
3206     SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa)
3207         << getOpenMPClauseName(DVar.CKind);
3208   }
3209 }
3210 
3211 static OpenMPMapClauseKind
3212 getMapClauseKindFromModifier(OpenMPDefaultmapClauseModifier M,
3213                              bool IsAggregateOrDeclareTarget) {
3214   OpenMPMapClauseKind Kind = OMPC_MAP_unknown;
3215   switch (M) {
3216   case OMPC_DEFAULTMAP_MODIFIER_alloc:
3217     Kind = OMPC_MAP_alloc;
3218     break;
3219   case OMPC_DEFAULTMAP_MODIFIER_to:
3220     Kind = OMPC_MAP_to;
3221     break;
3222   case OMPC_DEFAULTMAP_MODIFIER_from:
3223     Kind = OMPC_MAP_from;
3224     break;
3225   case OMPC_DEFAULTMAP_MODIFIER_tofrom:
3226     Kind = OMPC_MAP_tofrom;
3227     break;
3228   case OMPC_DEFAULTMAP_MODIFIER_firstprivate:
3229   case OMPC_DEFAULTMAP_MODIFIER_last:
3230     llvm_unreachable("Unexpected defaultmap implicit behavior");
3231   case OMPC_DEFAULTMAP_MODIFIER_none:
3232   case OMPC_DEFAULTMAP_MODIFIER_default:
3233   case OMPC_DEFAULTMAP_MODIFIER_unknown:
3234     // IsAggregateOrDeclareTarget could be true if:
3235     // 1. the implicit behavior for aggregate is tofrom
3236     // 2. it's a declare target link
3237     if (IsAggregateOrDeclareTarget) {
3238       Kind = OMPC_MAP_tofrom;
3239       break;
3240     }
3241     llvm_unreachable("Unexpected defaultmap implicit behavior");
3242   }
3243   assert(Kind != OMPC_MAP_unknown && "Expect map kind to be known");
3244   return Kind;
3245 }
3246 
3247 namespace {
3248 class DSAAttrChecker final : public StmtVisitor<DSAAttrChecker, void> {
3249   DSAStackTy *Stack;
3250   Sema &SemaRef;
3251   bool ErrorFound = false;
3252   bool TryCaptureCXXThisMembers = false;
3253   CapturedStmt *CS = nullptr;
3254   llvm::SmallVector<Expr *, 4> ImplicitFirstprivate;
3255   llvm::SmallVector<Expr *, 4> ImplicitMap[OMPC_MAP_delete];
3256   Sema::VarsWithInheritedDSAType VarsWithInheritedDSA;
3257   llvm::SmallDenseSet<const ValueDecl *, 4> ImplicitDeclarations;
3258 
3259   void VisitSubCaptures(OMPExecutableDirective *S) {
3260     // Check implicitly captured variables.
3261     if (!S->hasAssociatedStmt() || !S->getAssociatedStmt())
3262       return;
3263     visitSubCaptures(S->getInnermostCapturedStmt());
3264     // Try to capture inner this->member references to generate correct mappings
3265     // and diagnostics.
3266     if (TryCaptureCXXThisMembers ||
3267         (isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()) &&
3268          llvm::any_of(S->getInnermostCapturedStmt()->captures(),
3269                       [](const CapturedStmt::Capture &C) {
3270                         return C.capturesThis();
3271                       }))) {
3272       bool SavedTryCaptureCXXThisMembers = TryCaptureCXXThisMembers;
3273       TryCaptureCXXThisMembers = true;
3274       Visit(S->getInnermostCapturedStmt()->getCapturedStmt());
3275       TryCaptureCXXThisMembers = SavedTryCaptureCXXThisMembers;
3276     }
3277     // In tasks firstprivates are not captured anymore, need to analyze them
3278     // explicitly.
3279     if (isOpenMPTaskingDirective(S->getDirectiveKind()) &&
3280         !isOpenMPTaskLoopDirective(S->getDirectiveKind())) {
3281       for (OMPClause *C : S->clauses())
3282         if (auto *FC = dyn_cast<OMPFirstprivateClause>(C)) {
3283           for (Expr *Ref : FC->varlists())
3284             Visit(Ref);
3285         }
3286     }
3287   }
3288 
3289 public:
3290   void VisitDeclRefExpr(DeclRefExpr *E) {
3291     if (TryCaptureCXXThisMembers || E->isTypeDependent() ||
3292         E->isValueDependent() || E->containsUnexpandedParameterPack() ||
3293         E->isInstantiationDependent())
3294       return;
3295     if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
3296       // Check the datasharing rules for the expressions in the clauses.
3297       if (!CS) {
3298         if (auto *CED = dyn_cast<OMPCapturedExprDecl>(VD))
3299           if (!CED->hasAttr<OMPCaptureNoInitAttr>()) {
3300             Visit(CED->getInit());
3301             return;
3302           }
3303       } else if (VD->isImplicit() || isa<OMPCapturedExprDecl>(VD))
3304         // Do not analyze internal variables and do not enclose them into
3305         // implicit clauses.
3306         return;
3307       VD = VD->getCanonicalDecl();
3308       // Skip internally declared variables.
3309       if (VD->hasLocalStorage() && CS && !CS->capturesVariable(VD) &&
3310           !Stack->isImplicitTaskFirstprivate(VD))
3311         return;
3312       // Skip allocators in uses_allocators clauses.
3313       if (Stack->isUsesAllocatorsDecl(VD).hasValue())
3314         return;
3315 
3316       DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, /*FromParent=*/false);
3317       // Check if the variable has explicit DSA set and stop analysis if it so.
3318       if (DVar.RefExpr || !ImplicitDeclarations.insert(VD).second)
3319         return;
3320 
3321       // Skip internally declared static variables.
3322       llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
3323           OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
3324       if (VD->hasGlobalStorage() && CS && !CS->capturesVariable(VD) &&
3325           (Stack->hasRequiresDeclWithClause<OMPUnifiedSharedMemoryClause>() ||
3326            !Res || *Res != OMPDeclareTargetDeclAttr::MT_Link) &&
3327           !Stack->isImplicitTaskFirstprivate(VD))
3328         return;
3329 
3330       SourceLocation ELoc = E->getExprLoc();
3331       OpenMPDirectiveKind DKind = Stack->getCurrentDirective();
3332       // The default(none) clause requires that each variable that is referenced
3333       // in the construct, and does not have a predetermined data-sharing
3334       // attribute, must have its data-sharing attribute explicitly determined
3335       // by being listed in a data-sharing attribute clause.
3336       if (DVar.CKind == OMPC_unknown && Stack->getDefaultDSA() == DSA_none &&
3337           isImplicitOrExplicitTaskingRegion(DKind) &&
3338           VarsWithInheritedDSA.count(VD) == 0) {
3339         VarsWithInheritedDSA[VD] = E;
3340         return;
3341       }
3342 
3343       // OpenMP 5.0 [2.19.7.2, defaultmap clause, Description]
3344       // If implicit-behavior is none, each variable referenced in the
3345       // construct that does not have a predetermined data-sharing attribute
3346       // and does not appear in a to or link clause on a declare target
3347       // directive must be listed in a data-mapping attribute clause, a
3348       // data-haring attribute clause (including a data-sharing attribute
3349       // clause on a combined construct where target. is one of the
3350       // constituent constructs), or an is_device_ptr clause.
3351       OpenMPDefaultmapClauseKind ClauseKind =
3352           getVariableCategoryFromDecl(SemaRef.getLangOpts(), VD);
3353       if (SemaRef.getLangOpts().OpenMP >= 50) {
3354         bool IsModifierNone = Stack->getDefaultmapModifier(ClauseKind) ==
3355                               OMPC_DEFAULTMAP_MODIFIER_none;
3356         if (DVar.CKind == OMPC_unknown && IsModifierNone &&
3357             VarsWithInheritedDSA.count(VD) == 0 && !Res) {
3358           // Only check for data-mapping attribute and is_device_ptr here
3359           // since we have already make sure that the declaration does not
3360           // have a data-sharing attribute above
3361           if (!Stack->checkMappableExprComponentListsForDecl(
3362                   VD, /*CurrentRegionOnly=*/true,
3363                   [VD](OMPClauseMappableExprCommon::MappableExprComponentListRef
3364                            MapExprComponents,
3365                        OpenMPClauseKind) {
3366                     auto MI = MapExprComponents.rbegin();
3367                     auto ME = MapExprComponents.rend();
3368                     return MI != ME && MI->getAssociatedDeclaration() == VD;
3369                   })) {
3370             VarsWithInheritedDSA[VD] = E;
3371             return;
3372           }
3373         }
3374       }
3375 
3376       if (isOpenMPTargetExecutionDirective(DKind) &&
3377           !Stack->isLoopControlVariable(VD).first) {
3378         if (!Stack->checkMappableExprComponentListsForDecl(
3379                 VD, /*CurrentRegionOnly=*/true,
3380                 [](OMPClauseMappableExprCommon::MappableExprComponentListRef
3381                        StackComponents,
3382                    OpenMPClauseKind) {
3383                   // Variable is used if it has been marked as an array, array
3384                   // section, array shaping or the variable iself.
3385                   return StackComponents.size() == 1 ||
3386                          std::all_of(
3387                              std::next(StackComponents.rbegin()),
3388                              StackComponents.rend(),
3389                              [](const OMPClauseMappableExprCommon::
3390                                     MappableComponent &MC) {
3391                                return MC.getAssociatedDeclaration() ==
3392                                           nullptr &&
3393                                       (isa<OMPArraySectionExpr>(
3394                                            MC.getAssociatedExpression()) ||
3395                                        isa<OMPArrayShapingExpr>(
3396                                            MC.getAssociatedExpression()) ||
3397                                        isa<ArraySubscriptExpr>(
3398                                            MC.getAssociatedExpression()));
3399                              });
3400                 })) {
3401           bool IsFirstprivate = false;
3402           // By default lambdas are captured as firstprivates.
3403           if (const auto *RD =
3404                   VD->getType().getNonReferenceType()->getAsCXXRecordDecl())
3405             IsFirstprivate = RD->isLambda();
3406           IsFirstprivate =
3407               IsFirstprivate || (Stack->mustBeFirstprivate(ClauseKind) && !Res);
3408           if (IsFirstprivate) {
3409             ImplicitFirstprivate.emplace_back(E);
3410           } else {
3411             OpenMPDefaultmapClauseModifier M =
3412                 Stack->getDefaultmapModifier(ClauseKind);
3413             OpenMPMapClauseKind Kind = getMapClauseKindFromModifier(
3414                 M, ClauseKind == OMPC_DEFAULTMAP_aggregate || Res);
3415             ImplicitMap[Kind].emplace_back(E);
3416           }
3417           return;
3418         }
3419       }
3420 
3421       // OpenMP [2.9.3.6, Restrictions, p.2]
3422       //  A list item that appears in a reduction clause of the innermost
3423       //  enclosing worksharing or parallel construct may not be accessed in an
3424       //  explicit task.
3425       DVar = Stack->hasInnermostDSA(
3426           VD, [](OpenMPClauseKind C) { return C == OMPC_reduction; },
3427           [](OpenMPDirectiveKind K) {
3428             return isOpenMPParallelDirective(K) ||
3429                    isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
3430           },
3431           /*FromParent=*/true);
3432       if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
3433         ErrorFound = true;
3434         SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
3435         reportOriginalDsa(SemaRef, Stack, VD, DVar);
3436         return;
3437       }
3438 
3439       // Define implicit data-sharing attributes for task.
3440       DVar = Stack->getImplicitDSA(VD, /*FromParent=*/false);
3441       if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
3442           !Stack->isLoopControlVariable(VD).first) {
3443         ImplicitFirstprivate.push_back(E);
3444         return;
3445       }
3446 
3447       // Store implicitly used globals with declare target link for parent
3448       // target.
3449       if (!isOpenMPTargetExecutionDirective(DKind) && Res &&
3450           *Res == OMPDeclareTargetDeclAttr::MT_Link) {
3451         Stack->addToParentTargetRegionLinkGlobals(E);
3452         return;
3453       }
3454     }
3455   }
3456   void VisitMemberExpr(MemberExpr *E) {
3457     if (E->isTypeDependent() || E->isValueDependent() ||
3458         E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
3459       return;
3460     auto *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
3461     OpenMPDirectiveKind DKind = Stack->getCurrentDirective();
3462     if (auto *TE = dyn_cast<CXXThisExpr>(E->getBase()->IgnoreParenCasts())) {
3463       if (!FD)
3464         return;
3465       DSAStackTy::DSAVarData DVar = Stack->getTopDSA(FD, /*FromParent=*/false);
3466       // Check if the variable has explicit DSA set and stop analysis if it
3467       // so.
3468       if (DVar.RefExpr || !ImplicitDeclarations.insert(FD).second)
3469         return;
3470 
3471       if (isOpenMPTargetExecutionDirective(DKind) &&
3472           !Stack->isLoopControlVariable(FD).first &&
3473           !Stack->checkMappableExprComponentListsForDecl(
3474               FD, /*CurrentRegionOnly=*/true,
3475               [](OMPClauseMappableExprCommon::MappableExprComponentListRef
3476                      StackComponents,
3477                  OpenMPClauseKind) {
3478                 return isa<CXXThisExpr>(
3479                     cast<MemberExpr>(
3480                         StackComponents.back().getAssociatedExpression())
3481                         ->getBase()
3482                         ->IgnoreParens());
3483               })) {
3484         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
3485         //  A bit-field cannot appear in a map clause.
3486         //
3487         if (FD->isBitField())
3488           return;
3489 
3490         // Check to see if the member expression is referencing a class that
3491         // has already been explicitly mapped
3492         if (Stack->isClassPreviouslyMapped(TE->getType()))
3493           return;
3494 
3495         OpenMPDefaultmapClauseModifier Modifier =
3496             Stack->getDefaultmapModifier(OMPC_DEFAULTMAP_aggregate);
3497         OpenMPMapClauseKind Kind = getMapClauseKindFromModifier(
3498             Modifier, /*IsAggregateOrDeclareTarget*/ true);
3499         ImplicitMap[Kind].emplace_back(E);
3500         return;
3501       }
3502 
3503       SourceLocation ELoc = E->getExprLoc();
3504       // OpenMP [2.9.3.6, Restrictions, p.2]
3505       //  A list item that appears in a reduction clause of the innermost
3506       //  enclosing worksharing or parallel construct may not be accessed in
3507       //  an  explicit task.
3508       DVar = Stack->hasInnermostDSA(
3509           FD, [](OpenMPClauseKind C) { return C == OMPC_reduction; },
3510           [](OpenMPDirectiveKind K) {
3511             return isOpenMPParallelDirective(K) ||
3512                    isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
3513           },
3514           /*FromParent=*/true);
3515       if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
3516         ErrorFound = true;
3517         SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
3518         reportOriginalDsa(SemaRef, Stack, FD, DVar);
3519         return;
3520       }
3521 
3522       // Define implicit data-sharing attributes for task.
3523       DVar = Stack->getImplicitDSA(FD, /*FromParent=*/false);
3524       if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
3525           !Stack->isLoopControlVariable(FD).first) {
3526         // Check if there is a captured expression for the current field in the
3527         // region. Do not mark it as firstprivate unless there is no captured
3528         // expression.
3529         // TODO: try to make it firstprivate.
3530         if (DVar.CKind != OMPC_unknown)
3531           ImplicitFirstprivate.push_back(E);
3532       }
3533       return;
3534     }
3535     if (isOpenMPTargetExecutionDirective(DKind)) {
3536       OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
3537       if (!checkMapClauseExpressionBase(SemaRef, E, CurComponents, OMPC_map,
3538                                         /*NoDiagnose=*/true))
3539         return;
3540       const auto *VD = cast<ValueDecl>(
3541           CurComponents.back().getAssociatedDeclaration()->getCanonicalDecl());
3542       if (!Stack->checkMappableExprComponentListsForDecl(
3543               VD, /*CurrentRegionOnly=*/true,
3544               [&CurComponents](
3545                   OMPClauseMappableExprCommon::MappableExprComponentListRef
3546                       StackComponents,
3547                   OpenMPClauseKind) {
3548                 auto CCI = CurComponents.rbegin();
3549                 auto CCE = CurComponents.rend();
3550                 for (const auto &SC : llvm::reverse(StackComponents)) {
3551                   // Do both expressions have the same kind?
3552                   if (CCI->getAssociatedExpression()->getStmtClass() !=
3553                       SC.getAssociatedExpression()->getStmtClass())
3554                     if (!((isa<OMPArraySectionExpr>(
3555                                SC.getAssociatedExpression()) ||
3556                            isa<OMPArrayShapingExpr>(
3557                                SC.getAssociatedExpression())) &&
3558                           isa<ArraySubscriptExpr>(
3559                               CCI->getAssociatedExpression())))
3560                       return false;
3561 
3562                   const Decl *CCD = CCI->getAssociatedDeclaration();
3563                   const Decl *SCD = SC.getAssociatedDeclaration();
3564                   CCD = CCD ? CCD->getCanonicalDecl() : nullptr;
3565                   SCD = SCD ? SCD->getCanonicalDecl() : nullptr;
3566                   if (SCD != CCD)
3567                     return false;
3568                   std::advance(CCI, 1);
3569                   if (CCI == CCE)
3570                     break;
3571                 }
3572                 return true;
3573               })) {
3574         Visit(E->getBase());
3575       }
3576     } else if (!TryCaptureCXXThisMembers) {
3577       Visit(E->getBase());
3578     }
3579   }
3580   void VisitOMPExecutableDirective(OMPExecutableDirective *S) {
3581     for (OMPClause *C : S->clauses()) {
3582       // Skip analysis of arguments of implicitly defined firstprivate clause
3583       // for task|target directives.
3584       // Skip analysis of arguments of implicitly defined map clause for target
3585       // directives.
3586       if (C && !((isa<OMPFirstprivateClause>(C) || isa<OMPMapClause>(C)) &&
3587                  C->isImplicit())) {
3588         for (Stmt *CC : C->children()) {
3589           if (CC)
3590             Visit(CC);
3591         }
3592       }
3593     }
3594     // Check implicitly captured variables.
3595     VisitSubCaptures(S);
3596   }
3597   void VisitStmt(Stmt *S) {
3598     for (Stmt *C : S->children()) {
3599       if (C) {
3600         // Check implicitly captured variables in the task-based directives to
3601         // check if they must be firstprivatized.
3602         Visit(C);
3603       }
3604     }
3605   }
3606 
3607   void visitSubCaptures(CapturedStmt *S) {
3608     for (const CapturedStmt::Capture &Cap : S->captures()) {
3609       if (!Cap.capturesVariable() && !Cap.capturesVariableByCopy())
3610         continue;
3611       VarDecl *VD = Cap.getCapturedVar();
3612       // Do not try to map the variable if it or its sub-component was mapped
3613       // already.
3614       if (isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()) &&
3615           Stack->checkMappableExprComponentListsForDecl(
3616               VD, /*CurrentRegionOnly=*/true,
3617               [](OMPClauseMappableExprCommon::MappableExprComponentListRef,
3618                  OpenMPClauseKind) { return true; }))
3619         continue;
3620       DeclRefExpr *DRE = buildDeclRefExpr(
3621           SemaRef, VD, VD->getType().getNonLValueExprType(SemaRef.Context),
3622           Cap.getLocation(), /*RefersToCapture=*/true);
3623       Visit(DRE);
3624     }
3625   }
3626   bool isErrorFound() const { return ErrorFound; }
3627   ArrayRef<Expr *> getImplicitFirstprivate() const {
3628     return ImplicitFirstprivate;
3629   }
3630   ArrayRef<Expr *> getImplicitMap(OpenMPDefaultmapClauseKind Kind) const {
3631     return ImplicitMap[Kind];
3632   }
3633   const Sema::VarsWithInheritedDSAType &getVarsWithInheritedDSA() const {
3634     return VarsWithInheritedDSA;
3635   }
3636 
3637   DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS)
3638       : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {
3639     // Process declare target link variables for the target directives.
3640     if (isOpenMPTargetExecutionDirective(S->getCurrentDirective())) {
3641       for (DeclRefExpr *E : Stack->getLinkGlobals())
3642         Visit(E);
3643     }
3644   }
3645 };
3646 } // namespace
3647 
3648 void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) {
3649   switch (DKind) {
3650   case OMPD_parallel:
3651   case OMPD_parallel_for:
3652   case OMPD_parallel_for_simd:
3653   case OMPD_parallel_sections:
3654   case OMPD_parallel_master:
3655   case OMPD_teams:
3656   case OMPD_teams_distribute:
3657   case OMPD_teams_distribute_simd: {
3658     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
3659     QualType KmpInt32PtrTy =
3660         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3661     Sema::CapturedParamNameType Params[] = {
3662         std::make_pair(".global_tid.", KmpInt32PtrTy),
3663         std::make_pair(".bound_tid.", KmpInt32PtrTy),
3664         std::make_pair(StringRef(), QualType()) // __context with shared vars
3665     };
3666     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3667                              Params);
3668     break;
3669   }
3670   case OMPD_target_teams:
3671   case OMPD_target_parallel:
3672   case OMPD_target_parallel_for:
3673   case OMPD_target_parallel_for_simd:
3674   case OMPD_target_teams_distribute:
3675   case OMPD_target_teams_distribute_simd: {
3676     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
3677     QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
3678     QualType KmpInt32PtrTy =
3679         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3680     QualType Args[] = {VoidPtrTy};
3681     FunctionProtoType::ExtProtoInfo EPI;
3682     EPI.Variadic = true;
3683     QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
3684     Sema::CapturedParamNameType Params[] = {
3685         std::make_pair(".global_tid.", KmpInt32Ty),
3686         std::make_pair(".part_id.", KmpInt32PtrTy),
3687         std::make_pair(".privates.", VoidPtrTy),
3688         std::make_pair(
3689             ".copy_fn.",
3690             Context.getPointerType(CopyFnType).withConst().withRestrict()),
3691         std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
3692         std::make_pair(StringRef(), QualType()) // __context with shared vars
3693     };
3694     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3695                              Params, /*OpenMPCaptureLevel=*/0);
3696     // Mark this captured region as inlined, because we don't use outlined
3697     // function directly.
3698     getCurCapturedRegion()->TheCapturedDecl->addAttr(
3699         AlwaysInlineAttr::CreateImplicit(
3700             Context, {}, AttributeCommonInfo::AS_Keyword,
3701             AlwaysInlineAttr::Keyword_forceinline));
3702     Sema::CapturedParamNameType ParamsTarget[] = {
3703         std::make_pair(StringRef(), QualType()) // __context with shared vars
3704     };
3705     // Start a captured region for 'target' with no implicit parameters.
3706     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3707                              ParamsTarget, /*OpenMPCaptureLevel=*/1);
3708     Sema::CapturedParamNameType ParamsTeamsOrParallel[] = {
3709         std::make_pair(".global_tid.", KmpInt32PtrTy),
3710         std::make_pair(".bound_tid.", KmpInt32PtrTy),
3711         std::make_pair(StringRef(), QualType()) // __context with shared vars
3712     };
3713     // Start a captured region for 'teams' or 'parallel'.  Both regions have
3714     // the same implicit parameters.
3715     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3716                              ParamsTeamsOrParallel, /*OpenMPCaptureLevel=*/2);
3717     break;
3718   }
3719   case OMPD_target:
3720   case OMPD_target_simd: {
3721     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
3722     QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
3723     QualType KmpInt32PtrTy =
3724         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3725     QualType Args[] = {VoidPtrTy};
3726     FunctionProtoType::ExtProtoInfo EPI;
3727     EPI.Variadic = true;
3728     QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
3729     Sema::CapturedParamNameType Params[] = {
3730         std::make_pair(".global_tid.", KmpInt32Ty),
3731         std::make_pair(".part_id.", KmpInt32PtrTy),
3732         std::make_pair(".privates.", VoidPtrTy),
3733         std::make_pair(
3734             ".copy_fn.",
3735             Context.getPointerType(CopyFnType).withConst().withRestrict()),
3736         std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
3737         std::make_pair(StringRef(), QualType()) // __context with shared vars
3738     };
3739     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3740                              Params, /*OpenMPCaptureLevel=*/0);
3741     // Mark this captured region as inlined, because we don't use outlined
3742     // function directly.
3743     getCurCapturedRegion()->TheCapturedDecl->addAttr(
3744         AlwaysInlineAttr::CreateImplicit(
3745             Context, {}, AttributeCommonInfo::AS_Keyword,
3746             AlwaysInlineAttr::Keyword_forceinline));
3747     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3748                              std::make_pair(StringRef(), QualType()),
3749                              /*OpenMPCaptureLevel=*/1);
3750     break;
3751   }
3752   case OMPD_simd:
3753   case OMPD_for:
3754   case OMPD_for_simd:
3755   case OMPD_sections:
3756   case OMPD_section:
3757   case OMPD_single:
3758   case OMPD_master:
3759   case OMPD_critical:
3760   case OMPD_taskgroup:
3761   case OMPD_distribute:
3762   case OMPD_distribute_simd:
3763   case OMPD_ordered:
3764   case OMPD_atomic:
3765   case OMPD_target_data: {
3766     Sema::CapturedParamNameType Params[] = {
3767         std::make_pair(StringRef(), QualType()) // __context with shared vars
3768     };
3769     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3770                              Params);
3771     break;
3772   }
3773   case OMPD_task: {
3774     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
3775     QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
3776     QualType KmpInt32PtrTy =
3777         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3778     QualType Args[] = {VoidPtrTy};
3779     FunctionProtoType::ExtProtoInfo EPI;
3780     EPI.Variadic = true;
3781     QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
3782     Sema::CapturedParamNameType Params[] = {
3783         std::make_pair(".global_tid.", KmpInt32Ty),
3784         std::make_pair(".part_id.", KmpInt32PtrTy),
3785         std::make_pair(".privates.", VoidPtrTy),
3786         std::make_pair(
3787             ".copy_fn.",
3788             Context.getPointerType(CopyFnType).withConst().withRestrict()),
3789         std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
3790         std::make_pair(StringRef(), QualType()) // __context with shared vars
3791     };
3792     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3793                              Params);
3794     // Mark this captured region as inlined, because we don't use outlined
3795     // function directly.
3796     getCurCapturedRegion()->TheCapturedDecl->addAttr(
3797         AlwaysInlineAttr::CreateImplicit(
3798             Context, {}, AttributeCommonInfo::AS_Keyword,
3799             AlwaysInlineAttr::Keyword_forceinline));
3800     break;
3801   }
3802   case OMPD_taskloop:
3803   case OMPD_taskloop_simd:
3804   case OMPD_master_taskloop:
3805   case OMPD_master_taskloop_simd: {
3806     QualType KmpInt32Ty =
3807         Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1)
3808             .withConst();
3809     QualType KmpUInt64Ty =
3810         Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0)
3811             .withConst();
3812     QualType KmpInt64Ty =
3813         Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1)
3814             .withConst();
3815     QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
3816     QualType KmpInt32PtrTy =
3817         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3818     QualType Args[] = {VoidPtrTy};
3819     FunctionProtoType::ExtProtoInfo EPI;
3820     EPI.Variadic = true;
3821     QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
3822     Sema::CapturedParamNameType Params[] = {
3823         std::make_pair(".global_tid.", KmpInt32Ty),
3824         std::make_pair(".part_id.", KmpInt32PtrTy),
3825         std::make_pair(".privates.", VoidPtrTy),
3826         std::make_pair(
3827             ".copy_fn.",
3828             Context.getPointerType(CopyFnType).withConst().withRestrict()),
3829         std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
3830         std::make_pair(".lb.", KmpUInt64Ty),
3831         std::make_pair(".ub.", KmpUInt64Ty),
3832         std::make_pair(".st.", KmpInt64Ty),
3833         std::make_pair(".liter.", KmpInt32Ty),
3834         std::make_pair(".reductions.", VoidPtrTy),
3835         std::make_pair(StringRef(), QualType()) // __context with shared vars
3836     };
3837     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3838                              Params);
3839     // Mark this captured region as inlined, because we don't use outlined
3840     // function directly.
3841     getCurCapturedRegion()->TheCapturedDecl->addAttr(
3842         AlwaysInlineAttr::CreateImplicit(
3843             Context, {}, AttributeCommonInfo::AS_Keyword,
3844             AlwaysInlineAttr::Keyword_forceinline));
3845     break;
3846   }
3847   case OMPD_parallel_master_taskloop:
3848   case OMPD_parallel_master_taskloop_simd: {
3849     QualType KmpInt32Ty =
3850         Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1)
3851             .withConst();
3852     QualType KmpUInt64Ty =
3853         Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0)
3854             .withConst();
3855     QualType KmpInt64Ty =
3856         Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1)
3857             .withConst();
3858     QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
3859     QualType KmpInt32PtrTy =
3860         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3861     Sema::CapturedParamNameType ParamsParallel[] = {
3862         std::make_pair(".global_tid.", KmpInt32PtrTy),
3863         std::make_pair(".bound_tid.", KmpInt32PtrTy),
3864         std::make_pair(StringRef(), QualType()) // __context with shared vars
3865     };
3866     // Start a captured region for 'parallel'.
3867     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3868                              ParamsParallel, /*OpenMPCaptureLevel=*/0);
3869     QualType Args[] = {VoidPtrTy};
3870     FunctionProtoType::ExtProtoInfo EPI;
3871     EPI.Variadic = true;
3872     QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
3873     Sema::CapturedParamNameType Params[] = {
3874         std::make_pair(".global_tid.", KmpInt32Ty),
3875         std::make_pair(".part_id.", KmpInt32PtrTy),
3876         std::make_pair(".privates.", VoidPtrTy),
3877         std::make_pair(
3878             ".copy_fn.",
3879             Context.getPointerType(CopyFnType).withConst().withRestrict()),
3880         std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
3881         std::make_pair(".lb.", KmpUInt64Ty),
3882         std::make_pair(".ub.", KmpUInt64Ty),
3883         std::make_pair(".st.", KmpInt64Ty),
3884         std::make_pair(".liter.", KmpInt32Ty),
3885         std::make_pair(".reductions.", VoidPtrTy),
3886         std::make_pair(StringRef(), QualType()) // __context with shared vars
3887     };
3888     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3889                              Params, /*OpenMPCaptureLevel=*/1);
3890     // Mark this captured region as inlined, because we don't use outlined
3891     // function directly.
3892     getCurCapturedRegion()->TheCapturedDecl->addAttr(
3893         AlwaysInlineAttr::CreateImplicit(
3894             Context, {}, AttributeCommonInfo::AS_Keyword,
3895             AlwaysInlineAttr::Keyword_forceinline));
3896     break;
3897   }
3898   case OMPD_distribute_parallel_for_simd:
3899   case OMPD_distribute_parallel_for: {
3900     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
3901     QualType KmpInt32PtrTy =
3902         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3903     Sema::CapturedParamNameType Params[] = {
3904         std::make_pair(".global_tid.", KmpInt32PtrTy),
3905         std::make_pair(".bound_tid.", KmpInt32PtrTy),
3906         std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
3907         std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
3908         std::make_pair(StringRef(), QualType()) // __context with shared vars
3909     };
3910     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3911                              Params);
3912     break;
3913   }
3914   case OMPD_target_teams_distribute_parallel_for:
3915   case OMPD_target_teams_distribute_parallel_for_simd: {
3916     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
3917     QualType KmpInt32PtrTy =
3918         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3919     QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
3920 
3921     QualType Args[] = {VoidPtrTy};
3922     FunctionProtoType::ExtProtoInfo EPI;
3923     EPI.Variadic = true;
3924     QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
3925     Sema::CapturedParamNameType Params[] = {
3926         std::make_pair(".global_tid.", KmpInt32Ty),
3927         std::make_pair(".part_id.", KmpInt32PtrTy),
3928         std::make_pair(".privates.", VoidPtrTy),
3929         std::make_pair(
3930             ".copy_fn.",
3931             Context.getPointerType(CopyFnType).withConst().withRestrict()),
3932         std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
3933         std::make_pair(StringRef(), QualType()) // __context with shared vars
3934     };
3935     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3936                              Params, /*OpenMPCaptureLevel=*/0);
3937     // Mark this captured region as inlined, because we don't use outlined
3938     // function directly.
3939     getCurCapturedRegion()->TheCapturedDecl->addAttr(
3940         AlwaysInlineAttr::CreateImplicit(
3941             Context, {}, AttributeCommonInfo::AS_Keyword,
3942             AlwaysInlineAttr::Keyword_forceinline));
3943     Sema::CapturedParamNameType ParamsTarget[] = {
3944         std::make_pair(StringRef(), QualType()) // __context with shared vars
3945     };
3946     // Start a captured region for 'target' with no implicit parameters.
3947     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3948                              ParamsTarget, /*OpenMPCaptureLevel=*/1);
3949 
3950     Sema::CapturedParamNameType ParamsTeams[] = {
3951         std::make_pair(".global_tid.", KmpInt32PtrTy),
3952         std::make_pair(".bound_tid.", KmpInt32PtrTy),
3953         std::make_pair(StringRef(), QualType()) // __context with shared vars
3954     };
3955     // Start a captured region for 'target' with no implicit parameters.
3956     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3957                              ParamsTeams, /*OpenMPCaptureLevel=*/2);
3958 
3959     Sema::CapturedParamNameType ParamsParallel[] = {
3960         std::make_pair(".global_tid.", KmpInt32PtrTy),
3961         std::make_pair(".bound_tid.", KmpInt32PtrTy),
3962         std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
3963         std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
3964         std::make_pair(StringRef(), QualType()) // __context with shared vars
3965     };
3966     // Start a captured region for 'teams' or 'parallel'.  Both regions have
3967     // the same implicit parameters.
3968     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3969                              ParamsParallel, /*OpenMPCaptureLevel=*/3);
3970     break;
3971   }
3972 
3973   case OMPD_teams_distribute_parallel_for:
3974   case OMPD_teams_distribute_parallel_for_simd: {
3975     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
3976     QualType KmpInt32PtrTy =
3977         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3978 
3979     Sema::CapturedParamNameType ParamsTeams[] = {
3980         std::make_pair(".global_tid.", KmpInt32PtrTy),
3981         std::make_pair(".bound_tid.", KmpInt32PtrTy),
3982         std::make_pair(StringRef(), QualType()) // __context with shared vars
3983     };
3984     // Start a captured region for 'target' with no implicit parameters.
3985     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3986                              ParamsTeams, /*OpenMPCaptureLevel=*/0);
3987 
3988     Sema::CapturedParamNameType ParamsParallel[] = {
3989         std::make_pair(".global_tid.", KmpInt32PtrTy),
3990         std::make_pair(".bound_tid.", KmpInt32PtrTy),
3991         std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
3992         std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
3993         std::make_pair(StringRef(), QualType()) // __context with shared vars
3994     };
3995     // Start a captured region for 'teams' or 'parallel'.  Both regions have
3996     // the same implicit parameters.
3997     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3998                              ParamsParallel, /*OpenMPCaptureLevel=*/1);
3999     break;
4000   }
4001   case OMPD_target_update:
4002   case OMPD_target_enter_data:
4003   case OMPD_target_exit_data: {
4004     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
4005     QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
4006     QualType KmpInt32PtrTy =
4007         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
4008     QualType Args[] = {VoidPtrTy};
4009     FunctionProtoType::ExtProtoInfo EPI;
4010     EPI.Variadic = true;
4011     QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
4012     Sema::CapturedParamNameType Params[] = {
4013         std::make_pair(".global_tid.", KmpInt32Ty),
4014         std::make_pair(".part_id.", KmpInt32PtrTy),
4015         std::make_pair(".privates.", VoidPtrTy),
4016         std::make_pair(
4017             ".copy_fn.",
4018             Context.getPointerType(CopyFnType).withConst().withRestrict()),
4019         std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
4020         std::make_pair(StringRef(), QualType()) // __context with shared vars
4021     };
4022     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
4023                              Params);
4024     // Mark this captured region as inlined, because we don't use outlined
4025     // function directly.
4026     getCurCapturedRegion()->TheCapturedDecl->addAttr(
4027         AlwaysInlineAttr::CreateImplicit(
4028             Context, {}, AttributeCommonInfo::AS_Keyword,
4029             AlwaysInlineAttr::Keyword_forceinline));
4030     break;
4031   }
4032   case OMPD_threadprivate:
4033   case OMPD_allocate:
4034   case OMPD_taskyield:
4035   case OMPD_barrier:
4036   case OMPD_taskwait:
4037   case OMPD_cancellation_point:
4038   case OMPD_cancel:
4039   case OMPD_flush:
4040   case OMPD_depobj:
4041   case OMPD_scan:
4042   case OMPD_declare_reduction:
4043   case OMPD_declare_mapper:
4044   case OMPD_declare_simd:
4045   case OMPD_declare_target:
4046   case OMPD_end_declare_target:
4047   case OMPD_requires:
4048   case OMPD_declare_variant:
4049   case OMPD_begin_declare_variant:
4050   case OMPD_end_declare_variant:
4051     llvm_unreachable("OpenMP Directive is not allowed");
4052   case OMPD_unknown:
4053   default:
4054     llvm_unreachable("Unknown OpenMP directive");
4055   }
4056 }
4057 
4058 int Sema::getNumberOfConstructScopes(unsigned Level) const {
4059   return getOpenMPCaptureLevels(DSAStack->getDirective(Level));
4060 }
4061 
4062 int Sema::getOpenMPCaptureLevels(OpenMPDirectiveKind DKind) {
4063   SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
4064   getOpenMPCaptureRegions(CaptureRegions, DKind);
4065   return CaptureRegions.size();
4066 }
4067 
4068 static OMPCapturedExprDecl *buildCaptureDecl(Sema &S, IdentifierInfo *Id,
4069                                              Expr *CaptureExpr, bool WithInit,
4070                                              bool AsExpression) {
4071   assert(CaptureExpr);
4072   ASTContext &C = S.getASTContext();
4073   Expr *Init = AsExpression ? CaptureExpr : CaptureExpr->IgnoreImpCasts();
4074   QualType Ty = Init->getType();
4075   if (CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue()) {
4076     if (S.getLangOpts().CPlusPlus) {
4077       Ty = C.getLValueReferenceType(Ty);
4078     } else {
4079       Ty = C.getPointerType(Ty);
4080       ExprResult Res =
4081           S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_AddrOf, Init);
4082       if (!Res.isUsable())
4083         return nullptr;
4084       Init = Res.get();
4085     }
4086     WithInit = true;
4087   }
4088   auto *CED = OMPCapturedExprDecl::Create(C, S.CurContext, Id, Ty,
4089                                           CaptureExpr->getBeginLoc());
4090   if (!WithInit)
4091     CED->addAttr(OMPCaptureNoInitAttr::CreateImplicit(C));
4092   S.CurContext->addHiddenDecl(CED);
4093   S.AddInitializerToDecl(CED, Init, /*DirectInit=*/false);
4094   return CED;
4095 }
4096 
4097 static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr,
4098                                  bool WithInit) {
4099   OMPCapturedExprDecl *CD;
4100   if (VarDecl *VD = S.isOpenMPCapturedDecl(D))
4101     CD = cast<OMPCapturedExprDecl>(VD);
4102   else
4103     CD = buildCaptureDecl(S, D->getIdentifier(), CaptureExpr, WithInit,
4104                           /*AsExpression=*/false);
4105   return buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
4106                           CaptureExpr->getExprLoc());
4107 }
4108 
4109 static ExprResult buildCapture(Sema &S, Expr *CaptureExpr, DeclRefExpr *&Ref) {
4110   CaptureExpr = S.DefaultLvalueConversion(CaptureExpr).get();
4111   if (!Ref) {
4112     OMPCapturedExprDecl *CD = buildCaptureDecl(
4113         S, &S.getASTContext().Idents.get(".capture_expr."), CaptureExpr,
4114         /*WithInit=*/true, /*AsExpression=*/true);
4115     Ref = buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
4116                            CaptureExpr->getExprLoc());
4117   }
4118   ExprResult Res = Ref;
4119   if (!S.getLangOpts().CPlusPlus &&
4120       CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue() &&
4121       Ref->getType()->isPointerType()) {
4122     Res = S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_Deref, Ref);
4123     if (!Res.isUsable())
4124       return ExprError();
4125   }
4126   return S.DefaultLvalueConversion(Res.get());
4127 }
4128 
4129 namespace {
4130 // OpenMP directives parsed in this section are represented as a
4131 // CapturedStatement with an associated statement.  If a syntax error
4132 // is detected during the parsing of the associated statement, the
4133 // compiler must abort processing and close the CapturedStatement.
4134 //
4135 // Combined directives such as 'target parallel' have more than one
4136 // nested CapturedStatements.  This RAII ensures that we unwind out
4137 // of all the nested CapturedStatements when an error is found.
4138 class CaptureRegionUnwinderRAII {
4139 private:
4140   Sema &S;
4141   bool &ErrorFound;
4142   OpenMPDirectiveKind DKind = OMPD_unknown;
4143 
4144 public:
4145   CaptureRegionUnwinderRAII(Sema &S, bool &ErrorFound,
4146                             OpenMPDirectiveKind DKind)
4147       : S(S), ErrorFound(ErrorFound), DKind(DKind) {}
4148   ~CaptureRegionUnwinderRAII() {
4149     if (ErrorFound) {
4150       int ThisCaptureLevel = S.getOpenMPCaptureLevels(DKind);
4151       while (--ThisCaptureLevel >= 0)
4152         S.ActOnCapturedRegionError();
4153     }
4154   }
4155 };
4156 } // namespace
4157 
4158 void Sema::tryCaptureOpenMPLambdas(ValueDecl *V) {
4159   // Capture variables captured by reference in lambdas for target-based
4160   // directives.
4161   if (!CurContext->isDependentContext() &&
4162       (isOpenMPTargetExecutionDirective(DSAStack->getCurrentDirective()) ||
4163        isOpenMPTargetDataManagementDirective(
4164            DSAStack->getCurrentDirective()))) {
4165     QualType Type = V->getType();
4166     if (const auto *RD = Type.getCanonicalType()
4167                              .getNonReferenceType()
4168                              ->getAsCXXRecordDecl()) {
4169       bool SavedForceCaptureByReferenceInTargetExecutable =
4170           DSAStack->isForceCaptureByReferenceInTargetExecutable();
4171       DSAStack->setForceCaptureByReferenceInTargetExecutable(
4172           /*V=*/true);
4173       if (RD->isLambda()) {
4174         llvm::DenseMap<const VarDecl *, FieldDecl *> Captures;
4175         FieldDecl *ThisCapture;
4176         RD->getCaptureFields(Captures, ThisCapture);
4177         for (const LambdaCapture &LC : RD->captures()) {
4178           if (LC.getCaptureKind() == LCK_ByRef) {
4179             VarDecl *VD = LC.getCapturedVar();
4180             DeclContext *VDC = VD->getDeclContext();
4181             if (!VDC->Encloses(CurContext))
4182               continue;
4183             MarkVariableReferenced(LC.getLocation(), VD);
4184           } else if (LC.getCaptureKind() == LCK_This) {
4185             QualType ThisTy = getCurrentThisType();
4186             if (!ThisTy.isNull() &&
4187                 Context.typesAreCompatible(ThisTy, ThisCapture->getType()))
4188               CheckCXXThisCapture(LC.getLocation());
4189           }
4190         }
4191       }
4192       DSAStack->setForceCaptureByReferenceInTargetExecutable(
4193           SavedForceCaptureByReferenceInTargetExecutable);
4194     }
4195   }
4196 }
4197 
4198 static bool checkOrderedOrderSpecified(Sema &S,
4199                                        const ArrayRef<OMPClause *> Clauses) {
4200   const OMPOrderedClause *Ordered = nullptr;
4201   const OMPOrderClause *Order = nullptr;
4202 
4203   for (const OMPClause *Clause : Clauses) {
4204     if (Clause->getClauseKind() == OMPC_ordered)
4205       Ordered = cast<OMPOrderedClause>(Clause);
4206     else if (Clause->getClauseKind() == OMPC_order) {
4207       Order = cast<OMPOrderClause>(Clause);
4208       if (Order->getKind() != OMPC_ORDER_concurrent)
4209         Order = nullptr;
4210     }
4211     if (Ordered && Order)
4212       break;
4213   }
4214 
4215   if (Ordered && Order) {
4216     S.Diag(Order->getKindKwLoc(),
4217            diag::err_omp_simple_clause_incompatible_with_ordered)
4218         << getOpenMPClauseName(OMPC_order)
4219         << getOpenMPSimpleClauseTypeName(OMPC_order, OMPC_ORDER_concurrent)
4220         << SourceRange(Order->getBeginLoc(), Order->getEndLoc());
4221     S.Diag(Ordered->getBeginLoc(), diag::note_omp_ordered_param)
4222         << 0 << SourceRange(Ordered->getBeginLoc(), Ordered->getEndLoc());
4223     return true;
4224   }
4225   return false;
4226 }
4227 
4228 StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S,
4229                                       ArrayRef<OMPClause *> Clauses) {
4230   bool ErrorFound = false;
4231   CaptureRegionUnwinderRAII CaptureRegionUnwinder(
4232       *this, ErrorFound, DSAStack->getCurrentDirective());
4233   if (!S.isUsable()) {
4234     ErrorFound = true;
4235     return StmtError();
4236   }
4237 
4238   SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
4239   getOpenMPCaptureRegions(CaptureRegions, DSAStack->getCurrentDirective());
4240   OMPOrderedClause *OC = nullptr;
4241   OMPScheduleClause *SC = nullptr;
4242   SmallVector<const OMPLinearClause *, 4> LCs;
4243   SmallVector<const OMPClauseWithPreInit *, 4> PICs;
4244   // This is required for proper codegen.
4245   for (OMPClause *Clause : Clauses) {
4246     if (!LangOpts.OpenMPSimd &&
4247         isOpenMPTaskingDirective(DSAStack->getCurrentDirective()) &&
4248         Clause->getClauseKind() == OMPC_in_reduction) {
4249       // Capture taskgroup task_reduction descriptors inside the tasking regions
4250       // with the corresponding in_reduction items.
4251       auto *IRC = cast<OMPInReductionClause>(Clause);
4252       for (Expr *E : IRC->taskgroup_descriptors())
4253         if (E)
4254           MarkDeclarationsReferencedInExpr(E);
4255     }
4256     if (isOpenMPPrivate(Clause->getClauseKind()) ||
4257         Clause->getClauseKind() == OMPC_copyprivate ||
4258         (getLangOpts().OpenMPUseTLS &&
4259          getASTContext().getTargetInfo().isTLSSupported() &&
4260          Clause->getClauseKind() == OMPC_copyin)) {
4261       DSAStack->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin);
4262       // Mark all variables in private list clauses as used in inner region.
4263       for (Stmt *VarRef : Clause->children()) {
4264         if (auto *E = cast_or_null<Expr>(VarRef)) {
4265           MarkDeclarationsReferencedInExpr(E);
4266         }
4267       }
4268       DSAStack->setForceVarCapturing(/*V=*/false);
4269     } else if (CaptureRegions.size() > 1 ||
4270                CaptureRegions.back() != OMPD_unknown) {
4271       if (auto *C = OMPClauseWithPreInit::get(Clause))
4272         PICs.push_back(C);
4273       if (auto *C = OMPClauseWithPostUpdate::get(Clause)) {
4274         if (Expr *E = C->getPostUpdateExpr())
4275           MarkDeclarationsReferencedInExpr(E);
4276       }
4277     }
4278     if (Clause->getClauseKind() == OMPC_schedule)
4279       SC = cast<OMPScheduleClause>(Clause);
4280     else if (Clause->getClauseKind() == OMPC_ordered)
4281       OC = cast<OMPOrderedClause>(Clause);
4282     else if (Clause->getClauseKind() == OMPC_linear)
4283       LCs.push_back(cast<OMPLinearClause>(Clause));
4284   }
4285   // Capture allocator expressions if used.
4286   for (Expr *E : DSAStack->getInnerAllocators())
4287     MarkDeclarationsReferencedInExpr(E);
4288   // OpenMP, 2.7.1 Loop Construct, Restrictions
4289   // The nonmonotonic modifier cannot be specified if an ordered clause is
4290   // specified.
4291   if (SC &&
4292       (SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
4293        SC->getSecondScheduleModifier() ==
4294            OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
4295       OC) {
4296     Diag(SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic
4297              ? SC->getFirstScheduleModifierLoc()
4298              : SC->getSecondScheduleModifierLoc(),
4299          diag::err_omp_simple_clause_incompatible_with_ordered)
4300         << getOpenMPClauseName(OMPC_schedule)
4301         << getOpenMPSimpleClauseTypeName(OMPC_schedule,
4302                                          OMPC_SCHEDULE_MODIFIER_nonmonotonic)
4303         << SourceRange(OC->getBeginLoc(), OC->getEndLoc());
4304     ErrorFound = true;
4305   }
4306   // OpenMP 5.0, 2.9.2 Worksharing-Loop Construct, Restrictions.
4307   // If an order(concurrent) clause is present, an ordered clause may not appear
4308   // on the same directive.
4309   if (checkOrderedOrderSpecified(*this, Clauses))
4310     ErrorFound = true;
4311   if (!LCs.empty() && OC && OC->getNumForLoops()) {
4312     for (const OMPLinearClause *C : LCs) {
4313       Diag(C->getBeginLoc(), diag::err_omp_linear_ordered)
4314           << SourceRange(OC->getBeginLoc(), OC->getEndLoc());
4315     }
4316     ErrorFound = true;
4317   }
4318   if (isOpenMPWorksharingDirective(DSAStack->getCurrentDirective()) &&
4319       isOpenMPSimdDirective(DSAStack->getCurrentDirective()) && OC &&
4320       OC->getNumForLoops()) {
4321     Diag(OC->getBeginLoc(), diag::err_omp_ordered_simd)
4322         << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
4323     ErrorFound = true;
4324   }
4325   if (ErrorFound) {
4326     return StmtError();
4327   }
4328   StmtResult SR = S;
4329   unsigned CompletedRegions = 0;
4330   for (OpenMPDirectiveKind ThisCaptureRegion : llvm::reverse(CaptureRegions)) {
4331     // Mark all variables in private list clauses as used in inner region.
4332     // Required for proper codegen of combined directives.
4333     // TODO: add processing for other clauses.
4334     if (ThisCaptureRegion != OMPD_unknown) {
4335       for (const clang::OMPClauseWithPreInit *C : PICs) {
4336         OpenMPDirectiveKind CaptureRegion = C->getCaptureRegion();
4337         // Find the particular capture region for the clause if the
4338         // directive is a combined one with multiple capture regions.
4339         // If the directive is not a combined one, the capture region
4340         // associated with the clause is OMPD_unknown and is generated
4341         // only once.
4342         if (CaptureRegion == ThisCaptureRegion ||
4343             CaptureRegion == OMPD_unknown) {
4344           if (auto *DS = cast_or_null<DeclStmt>(C->getPreInitStmt())) {
4345             for (Decl *D : DS->decls())
4346               MarkVariableReferenced(D->getLocation(), cast<VarDecl>(D));
4347           }
4348         }
4349       }
4350     }
4351     if (ThisCaptureRegion == OMPD_target) {
4352       // Capture allocator traits in the target region. They are used implicitly
4353       // and, thus, are not captured by default.
4354       for (OMPClause *C : Clauses) {
4355         if (const auto *UAC = dyn_cast<OMPUsesAllocatorsClause>(C)) {
4356           for (unsigned I = 0, End = UAC->getNumberOfAllocators(); I < End;
4357                ++I) {
4358             OMPUsesAllocatorsClause::Data D = UAC->getAllocatorData(I);
4359             if (Expr *E = D.AllocatorTraits)
4360               MarkDeclarationsReferencedInExpr(E);
4361           }
4362           continue;
4363         }
4364       }
4365     }
4366     if (++CompletedRegions == CaptureRegions.size())
4367       DSAStack->setBodyComplete();
4368     SR = ActOnCapturedRegionEnd(SR.get());
4369   }
4370   return SR;
4371 }
4372 
4373 static bool checkCancelRegion(Sema &SemaRef, OpenMPDirectiveKind CurrentRegion,
4374                               OpenMPDirectiveKind CancelRegion,
4375                               SourceLocation StartLoc) {
4376   // CancelRegion is only needed for cancel and cancellation_point.
4377   if (CurrentRegion != OMPD_cancel && CurrentRegion != OMPD_cancellation_point)
4378     return false;
4379 
4380   if (CancelRegion == OMPD_parallel || CancelRegion == OMPD_for ||
4381       CancelRegion == OMPD_sections || CancelRegion == OMPD_taskgroup)
4382     return false;
4383 
4384   SemaRef.Diag(StartLoc, diag::err_omp_wrong_cancel_region)
4385       << getOpenMPDirectiveName(CancelRegion);
4386   return true;
4387 }
4388 
4389 static bool checkNestingOfRegions(Sema &SemaRef, const DSAStackTy *Stack,
4390                                   OpenMPDirectiveKind CurrentRegion,
4391                                   const DeclarationNameInfo &CurrentName,
4392                                   OpenMPDirectiveKind CancelRegion,
4393                                   SourceLocation StartLoc) {
4394   if (Stack->getCurScope()) {
4395     OpenMPDirectiveKind ParentRegion = Stack->getParentDirective();
4396     OpenMPDirectiveKind OffendingRegion = ParentRegion;
4397     bool NestingProhibited = false;
4398     bool CloseNesting = true;
4399     bool OrphanSeen = false;
4400     enum {
4401       NoRecommend,
4402       ShouldBeInParallelRegion,
4403       ShouldBeInOrderedRegion,
4404       ShouldBeInTargetRegion,
4405       ShouldBeInTeamsRegion,
4406       ShouldBeInLoopSimdRegion,
4407     } Recommend = NoRecommend;
4408     if (isOpenMPSimdDirective(ParentRegion) &&
4409         ((SemaRef.LangOpts.OpenMP <= 45 && CurrentRegion != OMPD_ordered) ||
4410          (SemaRef.LangOpts.OpenMP >= 50 && CurrentRegion != OMPD_ordered &&
4411           CurrentRegion != OMPD_simd && CurrentRegion != OMPD_atomic &&
4412           CurrentRegion != OMPD_scan))) {
4413       // OpenMP [2.16, Nesting of Regions]
4414       // OpenMP constructs may not be nested inside a simd region.
4415       // OpenMP [2.8.1,simd Construct, Restrictions]
4416       // An ordered construct with the simd clause is the only OpenMP
4417       // construct that can appear in the simd region.
4418       // Allowing a SIMD construct nested in another SIMD construct is an
4419       // extension. The OpenMP 4.5 spec does not allow it. Issue a warning
4420       // message.
4421       // OpenMP 5.0 [2.9.3.1, simd Construct, Restrictions]
4422       // The only OpenMP constructs that can be encountered during execution of
4423       // a simd region are the atomic construct, the loop construct, the simd
4424       // construct and the ordered construct with the simd clause.
4425       SemaRef.Diag(StartLoc, (CurrentRegion != OMPD_simd)
4426                                  ? diag::err_omp_prohibited_region_simd
4427                                  : diag::warn_omp_nesting_simd)
4428           << (SemaRef.LangOpts.OpenMP >= 50 ? 1 : 0);
4429       return CurrentRegion != OMPD_simd;
4430     }
4431     if (ParentRegion == OMPD_atomic) {
4432       // OpenMP [2.16, Nesting of Regions]
4433       // OpenMP constructs may not be nested inside an atomic region.
4434       SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic);
4435       return true;
4436     }
4437     if (CurrentRegion == OMPD_section) {
4438       // OpenMP [2.7.2, sections Construct, Restrictions]
4439       // Orphaned section directives are prohibited. That is, the section
4440       // directives must appear within the sections construct and must not be
4441       // encountered elsewhere in the sections region.
4442       if (ParentRegion != OMPD_sections &&
4443           ParentRegion != OMPD_parallel_sections) {
4444         SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive)
4445             << (ParentRegion != OMPD_unknown)
4446             << getOpenMPDirectiveName(ParentRegion);
4447         return true;
4448       }
4449       return false;
4450     }
4451     // Allow some constructs (except teams and cancellation constructs) to be
4452     // orphaned (they could be used in functions, called from OpenMP regions
4453     // with the required preconditions).
4454     if (ParentRegion == OMPD_unknown &&
4455         !isOpenMPNestingTeamsDirective(CurrentRegion) &&
4456         CurrentRegion != OMPD_cancellation_point &&
4457         CurrentRegion != OMPD_cancel && CurrentRegion != OMPD_scan)
4458       return false;
4459     if (CurrentRegion == OMPD_cancellation_point ||
4460         CurrentRegion == OMPD_cancel) {
4461       // OpenMP [2.16, Nesting of Regions]
4462       // A cancellation point construct for which construct-type-clause is
4463       // taskgroup must be nested inside a task construct. A cancellation
4464       // point construct for which construct-type-clause is not taskgroup must
4465       // be closely nested inside an OpenMP construct that matches the type
4466       // specified in construct-type-clause.
4467       // A cancel construct for which construct-type-clause is taskgroup must be
4468       // nested inside a task construct. A cancel construct for which
4469       // construct-type-clause is not taskgroup must be closely nested inside an
4470       // OpenMP construct that matches the type specified in
4471       // construct-type-clause.
4472       NestingProhibited =
4473           !((CancelRegion == OMPD_parallel &&
4474              (ParentRegion == OMPD_parallel ||
4475               ParentRegion == OMPD_target_parallel)) ||
4476             (CancelRegion == OMPD_for &&
4477              (ParentRegion == OMPD_for || ParentRegion == OMPD_parallel_for ||
4478               ParentRegion == OMPD_target_parallel_for ||
4479               ParentRegion == OMPD_distribute_parallel_for ||
4480               ParentRegion == OMPD_teams_distribute_parallel_for ||
4481               ParentRegion == OMPD_target_teams_distribute_parallel_for)) ||
4482             (CancelRegion == OMPD_taskgroup &&
4483              (ParentRegion == OMPD_task ||
4484               (SemaRef.getLangOpts().OpenMP >= 50 &&
4485                (ParentRegion == OMPD_taskloop ||
4486                 ParentRegion == OMPD_master_taskloop ||
4487                 ParentRegion == OMPD_parallel_master_taskloop)))) ||
4488             (CancelRegion == OMPD_sections &&
4489              (ParentRegion == OMPD_section || ParentRegion == OMPD_sections ||
4490               ParentRegion == OMPD_parallel_sections)));
4491       OrphanSeen = ParentRegion == OMPD_unknown;
4492     } else if (CurrentRegion == OMPD_master) {
4493       // OpenMP [2.16, Nesting of Regions]
4494       // A master region may not be closely nested inside a worksharing,
4495       // atomic, or explicit task region.
4496       NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
4497                           isOpenMPTaskingDirective(ParentRegion);
4498     } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) {
4499       // OpenMP [2.16, Nesting of Regions]
4500       // A critical region may not be nested (closely or otherwise) inside a
4501       // critical region with the same name. Note that this restriction is not
4502       // sufficient to prevent deadlock.
4503       SourceLocation PreviousCriticalLoc;
4504       bool DeadLock = Stack->hasDirective(
4505           [CurrentName, &PreviousCriticalLoc](OpenMPDirectiveKind K,
4506                                               const DeclarationNameInfo &DNI,
4507                                               SourceLocation Loc) {
4508             if (K == OMPD_critical && DNI.getName() == CurrentName.getName()) {
4509               PreviousCriticalLoc = Loc;
4510               return true;
4511             }
4512             return false;
4513           },
4514           false /* skip top directive */);
4515       if (DeadLock) {
4516         SemaRef.Diag(StartLoc,
4517                      diag::err_omp_prohibited_region_critical_same_name)
4518             << CurrentName.getName();
4519         if (PreviousCriticalLoc.isValid())
4520           SemaRef.Diag(PreviousCriticalLoc,
4521                        diag::note_omp_previous_critical_region);
4522         return true;
4523       }
4524     } else if (CurrentRegion == OMPD_barrier) {
4525       // OpenMP [2.16, Nesting of Regions]
4526       // A barrier region may not be closely nested inside a worksharing,
4527       // explicit task, critical, ordered, atomic, or master region.
4528       NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
4529                           isOpenMPTaskingDirective(ParentRegion) ||
4530                           ParentRegion == OMPD_master ||
4531                           ParentRegion == OMPD_parallel_master ||
4532                           ParentRegion == OMPD_critical ||
4533                           ParentRegion == OMPD_ordered;
4534     } else if (isOpenMPWorksharingDirective(CurrentRegion) &&
4535                !isOpenMPParallelDirective(CurrentRegion) &&
4536                !isOpenMPTeamsDirective(CurrentRegion)) {
4537       // OpenMP [2.16, Nesting of Regions]
4538       // A worksharing region may not be closely nested inside a worksharing,
4539       // explicit task, critical, ordered, atomic, or master region.
4540       NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
4541                           isOpenMPTaskingDirective(ParentRegion) ||
4542                           ParentRegion == OMPD_master ||
4543                           ParentRegion == OMPD_parallel_master ||
4544                           ParentRegion == OMPD_critical ||
4545                           ParentRegion == OMPD_ordered;
4546       Recommend = ShouldBeInParallelRegion;
4547     } else if (CurrentRegion == OMPD_ordered) {
4548       // OpenMP [2.16, Nesting of Regions]
4549       // An ordered region may not be closely nested inside a critical,
4550       // atomic, or explicit task region.
4551       // An ordered region must be closely nested inside a loop region (or
4552       // parallel loop region) with an ordered clause.
4553       // OpenMP [2.8.1,simd Construct, Restrictions]
4554       // An ordered construct with the simd clause is the only OpenMP construct
4555       // that can appear in the simd region.
4556       NestingProhibited = ParentRegion == OMPD_critical ||
4557                           isOpenMPTaskingDirective(ParentRegion) ||
4558                           !(isOpenMPSimdDirective(ParentRegion) ||
4559                             Stack->isParentOrderedRegion());
4560       Recommend = ShouldBeInOrderedRegion;
4561     } else if (isOpenMPNestingTeamsDirective(CurrentRegion)) {
4562       // OpenMP [2.16, Nesting of Regions]
4563       // If specified, a teams construct must be contained within a target
4564       // construct.
4565       NestingProhibited =
4566           (SemaRef.LangOpts.OpenMP <= 45 && ParentRegion != OMPD_target) ||
4567           (SemaRef.LangOpts.OpenMP >= 50 && ParentRegion != OMPD_unknown &&
4568            ParentRegion != OMPD_target);
4569       OrphanSeen = ParentRegion == OMPD_unknown;
4570       Recommend = ShouldBeInTargetRegion;
4571     } else if (CurrentRegion == OMPD_scan) {
4572       // OpenMP [2.16, Nesting of Regions]
4573       // If specified, a teams construct must be contained within a target
4574       // construct.
4575       NestingProhibited =
4576           SemaRef.LangOpts.OpenMP < 50 ||
4577           (ParentRegion != OMPD_simd && ParentRegion != OMPD_for &&
4578            ParentRegion != OMPD_for_simd && ParentRegion != OMPD_parallel_for &&
4579            ParentRegion != OMPD_parallel_for_simd);
4580       OrphanSeen = ParentRegion == OMPD_unknown;
4581       Recommend = ShouldBeInLoopSimdRegion;
4582     }
4583     if (!NestingProhibited &&
4584         !isOpenMPTargetExecutionDirective(CurrentRegion) &&
4585         !isOpenMPTargetDataManagementDirective(CurrentRegion) &&
4586         (ParentRegion == OMPD_teams || ParentRegion == OMPD_target_teams)) {
4587       // OpenMP [2.16, Nesting of Regions]
4588       // distribute, parallel, parallel sections, parallel workshare, and the
4589       // parallel loop and parallel loop SIMD constructs are the only OpenMP
4590       // constructs that can be closely nested in the teams region.
4591       NestingProhibited = !isOpenMPParallelDirective(CurrentRegion) &&
4592                           !isOpenMPDistributeDirective(CurrentRegion);
4593       Recommend = ShouldBeInParallelRegion;
4594     }
4595     if (!NestingProhibited &&
4596         isOpenMPNestingDistributeDirective(CurrentRegion)) {
4597       // OpenMP 4.5 [2.17 Nesting of Regions]
4598       // The region associated with the distribute construct must be strictly
4599       // nested inside a teams region
4600       NestingProhibited =
4601           (ParentRegion != OMPD_teams && ParentRegion != OMPD_target_teams);
4602       Recommend = ShouldBeInTeamsRegion;
4603     }
4604     if (!NestingProhibited &&
4605         (isOpenMPTargetExecutionDirective(CurrentRegion) ||
4606          isOpenMPTargetDataManagementDirective(CurrentRegion))) {
4607       // OpenMP 4.5 [2.17 Nesting of Regions]
4608       // If a target, target update, target data, target enter data, or
4609       // target exit data construct is encountered during execution of a
4610       // target region, the behavior is unspecified.
4611       NestingProhibited = Stack->hasDirective(
4612           [&OffendingRegion](OpenMPDirectiveKind K, const DeclarationNameInfo &,
4613                              SourceLocation) {
4614             if (isOpenMPTargetExecutionDirective(K)) {
4615               OffendingRegion = K;
4616               return true;
4617             }
4618             return false;
4619           },
4620           false /* don't skip top directive */);
4621       CloseNesting = false;
4622     }
4623     if (NestingProhibited) {
4624       if (OrphanSeen) {
4625         SemaRef.Diag(StartLoc, diag::err_omp_orphaned_device_directive)
4626             << getOpenMPDirectiveName(CurrentRegion) << Recommend;
4627       } else {
4628         SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region)
4629             << CloseNesting << getOpenMPDirectiveName(OffendingRegion)
4630             << Recommend << getOpenMPDirectiveName(CurrentRegion);
4631       }
4632       return true;
4633     }
4634   }
4635   return false;
4636 }
4637 
4638 struct Kind2Unsigned {
4639   using argument_type = OpenMPDirectiveKind;
4640   unsigned operator()(argument_type DK) { return unsigned(DK); }
4641 };
4642 static bool checkIfClauses(Sema &S, OpenMPDirectiveKind Kind,
4643                            ArrayRef<OMPClause *> Clauses,
4644                            ArrayRef<OpenMPDirectiveKind> AllowedNameModifiers) {
4645   bool ErrorFound = false;
4646   unsigned NamedModifiersNumber = 0;
4647   llvm::IndexedMap<const OMPIfClause *, Kind2Unsigned> FoundNameModifiers;
4648   FoundNameModifiers.resize(llvm::omp::Directive_enumSize + 1);
4649   SmallVector<SourceLocation, 4> NameModifierLoc;
4650   for (const OMPClause *C : Clauses) {
4651     if (const auto *IC = dyn_cast_or_null<OMPIfClause>(C)) {
4652       // At most one if clause without a directive-name-modifier can appear on
4653       // the directive.
4654       OpenMPDirectiveKind CurNM = IC->getNameModifier();
4655       if (FoundNameModifiers[CurNM]) {
4656         S.Diag(C->getBeginLoc(), diag::err_omp_more_one_clause)
4657             << getOpenMPDirectiveName(Kind) << getOpenMPClauseName(OMPC_if)
4658             << (CurNM != OMPD_unknown) << getOpenMPDirectiveName(CurNM);
4659         ErrorFound = true;
4660       } else if (CurNM != OMPD_unknown) {
4661         NameModifierLoc.push_back(IC->getNameModifierLoc());
4662         ++NamedModifiersNumber;
4663       }
4664       FoundNameModifiers[CurNM] = IC;
4665       if (CurNM == OMPD_unknown)
4666         continue;
4667       // Check if the specified name modifier is allowed for the current
4668       // directive.
4669       // At most one if clause with the particular directive-name-modifier can
4670       // appear on the directive.
4671       bool MatchFound = false;
4672       for (auto NM : AllowedNameModifiers) {
4673         if (CurNM == NM) {
4674           MatchFound = true;
4675           break;
4676         }
4677       }
4678       if (!MatchFound) {
4679         S.Diag(IC->getNameModifierLoc(),
4680                diag::err_omp_wrong_if_directive_name_modifier)
4681             << getOpenMPDirectiveName(CurNM) << getOpenMPDirectiveName(Kind);
4682         ErrorFound = true;
4683       }
4684     }
4685   }
4686   // If any if clause on the directive includes a directive-name-modifier then
4687   // all if clauses on the directive must include a directive-name-modifier.
4688   if (FoundNameModifiers[OMPD_unknown] && NamedModifiersNumber > 0) {
4689     if (NamedModifiersNumber == AllowedNameModifiers.size()) {
4690       S.Diag(FoundNameModifiers[OMPD_unknown]->getBeginLoc(),
4691              diag::err_omp_no_more_if_clause);
4692     } else {
4693       std::string Values;
4694       std::string Sep(", ");
4695       unsigned AllowedCnt = 0;
4696       unsigned TotalAllowedNum =
4697           AllowedNameModifiers.size() - NamedModifiersNumber;
4698       for (unsigned Cnt = 0, End = AllowedNameModifiers.size(); Cnt < End;
4699            ++Cnt) {
4700         OpenMPDirectiveKind NM = AllowedNameModifiers[Cnt];
4701         if (!FoundNameModifiers[NM]) {
4702           Values += "'";
4703           Values += getOpenMPDirectiveName(NM);
4704           Values += "'";
4705           if (AllowedCnt + 2 == TotalAllowedNum)
4706             Values += " or ";
4707           else if (AllowedCnt + 1 != TotalAllowedNum)
4708             Values += Sep;
4709           ++AllowedCnt;
4710         }
4711       }
4712       S.Diag(FoundNameModifiers[OMPD_unknown]->getCondition()->getBeginLoc(),
4713              diag::err_omp_unnamed_if_clause)
4714           << (TotalAllowedNum > 1) << Values;
4715     }
4716     for (SourceLocation Loc : NameModifierLoc) {
4717       S.Diag(Loc, diag::note_omp_previous_named_if_clause);
4718     }
4719     ErrorFound = true;
4720   }
4721   return ErrorFound;
4722 }
4723 
4724 static std::pair<ValueDecl *, bool> getPrivateItem(Sema &S, Expr *&RefExpr,
4725                                                    SourceLocation &ELoc,
4726                                                    SourceRange &ERange,
4727                                                    bool AllowArraySection) {
4728   if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() ||
4729       RefExpr->containsUnexpandedParameterPack())
4730     return std::make_pair(nullptr, true);
4731 
4732   // OpenMP [3.1, C/C++]
4733   //  A list item is a variable name.
4734   // OpenMP  [2.9.3.3, Restrictions, p.1]
4735   //  A variable that is part of another variable (as an array or
4736   //  structure element) cannot appear in a private clause.
4737   RefExpr = RefExpr->IgnoreParens();
4738   enum {
4739     NoArrayExpr = -1,
4740     ArraySubscript = 0,
4741     OMPArraySection = 1
4742   } IsArrayExpr = NoArrayExpr;
4743   if (AllowArraySection) {
4744     if (auto *ASE = dyn_cast_or_null<ArraySubscriptExpr>(RefExpr)) {
4745       Expr *Base = ASE->getBase()->IgnoreParenImpCasts();
4746       while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
4747         Base = TempASE->getBase()->IgnoreParenImpCasts();
4748       RefExpr = Base;
4749       IsArrayExpr = ArraySubscript;
4750     } else if (auto *OASE = dyn_cast_or_null<OMPArraySectionExpr>(RefExpr)) {
4751       Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
4752       while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
4753         Base = TempOASE->getBase()->IgnoreParenImpCasts();
4754       while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
4755         Base = TempASE->getBase()->IgnoreParenImpCasts();
4756       RefExpr = Base;
4757       IsArrayExpr = OMPArraySection;
4758     }
4759   }
4760   ELoc = RefExpr->getExprLoc();
4761   ERange = RefExpr->getSourceRange();
4762   RefExpr = RefExpr->IgnoreParenImpCasts();
4763   auto *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
4764   auto *ME = dyn_cast_or_null<MemberExpr>(RefExpr);
4765   if ((!DE || !isa<VarDecl>(DE->getDecl())) &&
4766       (S.getCurrentThisType().isNull() || !ME ||
4767        !isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()) ||
4768        !isa<FieldDecl>(ME->getMemberDecl()))) {
4769     if (IsArrayExpr != NoArrayExpr) {
4770       S.Diag(ELoc, diag::err_omp_expected_base_var_name) << IsArrayExpr
4771                                                          << ERange;
4772     } else {
4773       S.Diag(ELoc,
4774              AllowArraySection
4775                  ? diag::err_omp_expected_var_name_member_expr_or_array_item
4776                  : diag::err_omp_expected_var_name_member_expr)
4777           << (S.getCurrentThisType().isNull() ? 0 : 1) << ERange;
4778     }
4779     return std::make_pair(nullptr, false);
4780   }
4781   return std::make_pair(
4782       getCanonicalDecl(DE ? DE->getDecl() : ME->getMemberDecl()), false);
4783 }
4784 
4785 namespace {
4786 /// Checks if the allocator is used in uses_allocators clause to be allowed in
4787 /// target regions.
4788 class AllocatorChecker final : public ConstStmtVisitor<AllocatorChecker, bool> {
4789   DSAStackTy *S = nullptr;
4790 
4791 public:
4792   bool VisitDeclRefExpr(const DeclRefExpr *E) {
4793     return S->isUsesAllocatorsDecl(E->getDecl())
4794                .getValueOr(
4795                    DSAStackTy::UsesAllocatorsDeclKind::AllocatorTrait) ==
4796            DSAStackTy::UsesAllocatorsDeclKind::AllocatorTrait;
4797   }
4798   bool VisitStmt(const Stmt *S) {
4799     for (const Stmt *Child : S->children()) {
4800       if (Child && Visit(Child))
4801         return true;
4802     }
4803     return false;
4804   }
4805   explicit AllocatorChecker(DSAStackTy *S) : S(S) {}
4806 };
4807 } // namespace
4808 
4809 static void checkAllocateClauses(Sema &S, DSAStackTy *Stack,
4810                                  ArrayRef<OMPClause *> Clauses) {
4811   assert(!S.CurContext->isDependentContext() &&
4812          "Expected non-dependent context.");
4813   auto AllocateRange =
4814       llvm::make_filter_range(Clauses, OMPAllocateClause::classof);
4815   llvm::DenseMap<CanonicalDeclPtr<Decl>, CanonicalDeclPtr<VarDecl>>
4816       DeclToCopy;
4817   auto PrivateRange = llvm::make_filter_range(Clauses, [](const OMPClause *C) {
4818     return isOpenMPPrivate(C->getClauseKind());
4819   });
4820   for (OMPClause *Cl : PrivateRange) {
4821     MutableArrayRef<Expr *>::iterator I, It, Et;
4822     if (Cl->getClauseKind() == OMPC_private) {
4823       auto *PC = cast<OMPPrivateClause>(Cl);
4824       I = PC->private_copies().begin();
4825       It = PC->varlist_begin();
4826       Et = PC->varlist_end();
4827     } else if (Cl->getClauseKind() == OMPC_firstprivate) {
4828       auto *PC = cast<OMPFirstprivateClause>(Cl);
4829       I = PC->private_copies().begin();
4830       It = PC->varlist_begin();
4831       Et = PC->varlist_end();
4832     } else if (Cl->getClauseKind() == OMPC_lastprivate) {
4833       auto *PC = cast<OMPLastprivateClause>(Cl);
4834       I = PC->private_copies().begin();
4835       It = PC->varlist_begin();
4836       Et = PC->varlist_end();
4837     } else if (Cl->getClauseKind() == OMPC_linear) {
4838       auto *PC = cast<OMPLinearClause>(Cl);
4839       I = PC->privates().begin();
4840       It = PC->varlist_begin();
4841       Et = PC->varlist_end();
4842     } else if (Cl->getClauseKind() == OMPC_reduction) {
4843       auto *PC = cast<OMPReductionClause>(Cl);
4844       I = PC->privates().begin();
4845       It = PC->varlist_begin();
4846       Et = PC->varlist_end();
4847     } else if (Cl->getClauseKind() == OMPC_task_reduction) {
4848       auto *PC = cast<OMPTaskReductionClause>(Cl);
4849       I = PC->privates().begin();
4850       It = PC->varlist_begin();
4851       Et = PC->varlist_end();
4852     } else if (Cl->getClauseKind() == OMPC_in_reduction) {
4853       auto *PC = cast<OMPInReductionClause>(Cl);
4854       I = PC->privates().begin();
4855       It = PC->varlist_begin();
4856       Et = PC->varlist_end();
4857     } else {
4858       llvm_unreachable("Expected private clause.");
4859     }
4860     for (Expr *E : llvm::make_range(It, Et)) {
4861       if (!*I) {
4862         ++I;
4863         continue;
4864       }
4865       SourceLocation ELoc;
4866       SourceRange ERange;
4867       Expr *SimpleRefExpr = E;
4868       auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange,
4869                                 /*AllowArraySection=*/true);
4870       DeclToCopy.try_emplace(Res.first,
4871                              cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()));
4872       ++I;
4873     }
4874   }
4875   for (OMPClause *C : AllocateRange) {
4876     auto *AC = cast<OMPAllocateClause>(C);
4877     if (S.getLangOpts().OpenMP >= 50 &&
4878         !Stack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>() &&
4879         isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()) &&
4880         AC->getAllocator()) {
4881       Expr *Allocator = AC->getAllocator();
4882       // OpenMP, 2.12.5 target Construct
4883       // Memory allocators that do not appear in a uses_allocators clause cannot
4884       // appear as an allocator in an allocate clause or be used in the target
4885       // region unless a requires directive with the dynamic_allocators clause
4886       // is present in the same compilation unit.
4887       AllocatorChecker Checker(Stack);
4888       if (Checker.Visit(Allocator))
4889         S.Diag(Allocator->getExprLoc(),
4890                diag::err_omp_allocator_not_in_uses_allocators)
4891             << Allocator->getSourceRange();
4892     }
4893     OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind =
4894         getAllocatorKind(S, Stack, AC->getAllocator());
4895     // OpenMP, 2.11.4 allocate Clause, Restrictions.
4896     // For task, taskloop or target directives, allocation requests to memory
4897     // allocators with the trait access set to thread result in unspecified
4898     // behavior.
4899     if (AllocatorKind == OMPAllocateDeclAttr::OMPThreadMemAlloc &&
4900         (isOpenMPTaskingDirective(Stack->getCurrentDirective()) ||
4901          isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()))) {
4902       S.Diag(AC->getAllocator()->getExprLoc(),
4903              diag::warn_omp_allocate_thread_on_task_target_directive)
4904           << getOpenMPDirectiveName(Stack->getCurrentDirective());
4905     }
4906     for (Expr *E : AC->varlists()) {
4907       SourceLocation ELoc;
4908       SourceRange ERange;
4909       Expr *SimpleRefExpr = E;
4910       auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange);
4911       ValueDecl *VD = Res.first;
4912       DSAStackTy::DSAVarData Data = Stack->getTopDSA(VD, /*FromParent=*/false);
4913       if (!isOpenMPPrivate(Data.CKind)) {
4914         S.Diag(E->getExprLoc(),
4915                diag::err_omp_expected_private_copy_for_allocate);
4916         continue;
4917       }
4918       VarDecl *PrivateVD = DeclToCopy[VD];
4919       if (checkPreviousOMPAllocateAttribute(S, Stack, E, PrivateVD,
4920                                             AllocatorKind, AC->getAllocator()))
4921         continue;
4922       applyOMPAllocateAttribute(S, PrivateVD, AllocatorKind, AC->getAllocator(),
4923                                 E->getSourceRange());
4924     }
4925   }
4926 }
4927 
4928 StmtResult Sema::ActOnOpenMPExecutableDirective(
4929     OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
4930     OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
4931     Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
4932   StmtResult Res = StmtError();
4933   // First check CancelRegion which is then used in checkNestingOfRegions.
4934   if (checkCancelRegion(*this, Kind, CancelRegion, StartLoc) ||
4935       checkNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion,
4936                             StartLoc))
4937     return StmtError();
4938 
4939   llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit;
4940   VarsWithInheritedDSAType VarsWithInheritedDSA;
4941   bool ErrorFound = false;
4942   ClausesWithImplicit.append(Clauses.begin(), Clauses.end());
4943   if (AStmt && !CurContext->isDependentContext()) {
4944     assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
4945 
4946     // Check default data sharing attributes for referenced variables.
4947     DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt));
4948     int ThisCaptureLevel = getOpenMPCaptureLevels(Kind);
4949     Stmt *S = AStmt;
4950     while (--ThisCaptureLevel >= 0)
4951       S = cast<CapturedStmt>(S)->getCapturedStmt();
4952     DSAChecker.Visit(S);
4953     if (!isOpenMPTargetDataManagementDirective(Kind) &&
4954         !isOpenMPTaskingDirective(Kind)) {
4955       // Visit subcaptures to generate implicit clauses for captured vars.
4956       auto *CS = cast<CapturedStmt>(AStmt);
4957       SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
4958       getOpenMPCaptureRegions(CaptureRegions, Kind);
4959       // Ignore outer tasking regions for target directives.
4960       if (CaptureRegions.size() > 1 && CaptureRegions.front() == OMPD_task)
4961         CS = cast<CapturedStmt>(CS->getCapturedStmt());
4962       DSAChecker.visitSubCaptures(CS);
4963     }
4964     if (DSAChecker.isErrorFound())
4965       return StmtError();
4966     // Generate list of implicitly defined firstprivate variables.
4967     VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA();
4968 
4969     SmallVector<Expr *, 4> ImplicitFirstprivates(
4970         DSAChecker.getImplicitFirstprivate().begin(),
4971         DSAChecker.getImplicitFirstprivate().end());
4972     SmallVector<Expr *, 4> ImplicitMaps[OMPC_MAP_delete];
4973     for (unsigned I = 0; I < OMPC_MAP_delete; ++I) {
4974       ArrayRef<Expr *> ImplicitMap =
4975           DSAChecker.getImplicitMap(static_cast<OpenMPDefaultmapClauseKind>(I));
4976       ImplicitMaps[I].append(ImplicitMap.begin(), ImplicitMap.end());
4977     }
4978     // Mark taskgroup task_reduction descriptors as implicitly firstprivate.
4979     for (OMPClause *C : Clauses) {
4980       if (auto *IRC = dyn_cast<OMPInReductionClause>(C)) {
4981         for (Expr *E : IRC->taskgroup_descriptors())
4982           if (E)
4983             ImplicitFirstprivates.emplace_back(E);
4984       }
4985       // OpenMP 5.0, 2.10.1 task Construct
4986       // [detach clause]... The event-handle will be considered as if it was
4987       // specified on a firstprivate clause.
4988       if (auto *DC = dyn_cast<OMPDetachClause>(C))
4989         ImplicitFirstprivates.push_back(DC->getEventHandler());
4990     }
4991     if (!ImplicitFirstprivates.empty()) {
4992       if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause(
4993               ImplicitFirstprivates, SourceLocation(), SourceLocation(),
4994               SourceLocation())) {
4995         ClausesWithImplicit.push_back(Implicit);
4996         ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() !=
4997                      ImplicitFirstprivates.size();
4998       } else {
4999         ErrorFound = true;
5000       }
5001     }
5002     int ClauseKindCnt = -1;
5003     for (ArrayRef<Expr *> ImplicitMap : ImplicitMaps) {
5004       ++ClauseKindCnt;
5005       if (ImplicitMap.empty())
5006         continue;
5007       CXXScopeSpec MapperIdScopeSpec;
5008       DeclarationNameInfo MapperId;
5009       auto Kind = static_cast<OpenMPMapClauseKind>(ClauseKindCnt);
5010       if (OMPClause *Implicit = ActOnOpenMPMapClause(
5011               llvm::None, llvm::None, MapperIdScopeSpec, MapperId, Kind,
5012               /*IsMapTypeImplicit=*/true, SourceLocation(), SourceLocation(),
5013               ImplicitMap, OMPVarListLocTy())) {
5014         ClausesWithImplicit.emplace_back(Implicit);
5015         ErrorFound |=
5016             cast<OMPMapClause>(Implicit)->varlist_size() != ImplicitMap.size();
5017       } else {
5018         ErrorFound = true;
5019       }
5020     }
5021   }
5022 
5023   llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers;
5024   switch (Kind) {
5025   case OMPD_parallel:
5026     Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc,
5027                                        EndLoc);
5028     AllowedNameModifiers.push_back(OMPD_parallel);
5029     break;
5030   case OMPD_simd:
5031     Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
5032                                    VarsWithInheritedDSA);
5033     if (LangOpts.OpenMP >= 50)
5034       AllowedNameModifiers.push_back(OMPD_simd);
5035     break;
5036   case OMPD_for:
5037     Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
5038                                   VarsWithInheritedDSA);
5039     break;
5040   case OMPD_for_simd:
5041     Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
5042                                       EndLoc, VarsWithInheritedDSA);
5043     if (LangOpts.OpenMP >= 50)
5044       AllowedNameModifiers.push_back(OMPD_simd);
5045     break;
5046   case OMPD_sections:
5047     Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc,
5048                                        EndLoc);
5049     break;
5050   case OMPD_section:
5051     assert(ClausesWithImplicit.empty() &&
5052            "No clauses are allowed for 'omp section' directive");
5053     Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc);
5054     break;
5055   case OMPD_single:
5056     Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc,
5057                                      EndLoc);
5058     break;
5059   case OMPD_master:
5060     assert(ClausesWithImplicit.empty() &&
5061            "No clauses are allowed for 'omp master' directive");
5062     Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc);
5063     break;
5064   case OMPD_critical:
5065     Res = ActOnOpenMPCriticalDirective(DirName, ClausesWithImplicit, AStmt,
5066                                        StartLoc, EndLoc);
5067     break;
5068   case OMPD_parallel_for:
5069     Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc,
5070                                           EndLoc, VarsWithInheritedDSA);
5071     AllowedNameModifiers.push_back(OMPD_parallel);
5072     break;
5073   case OMPD_parallel_for_simd:
5074     Res = ActOnOpenMPParallelForSimdDirective(
5075         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
5076     AllowedNameModifiers.push_back(OMPD_parallel);
5077     if (LangOpts.OpenMP >= 50)
5078       AllowedNameModifiers.push_back(OMPD_simd);
5079     break;
5080   case OMPD_parallel_master:
5081     Res = ActOnOpenMPParallelMasterDirective(ClausesWithImplicit, AStmt,
5082                                                StartLoc, EndLoc);
5083     AllowedNameModifiers.push_back(OMPD_parallel);
5084     break;
5085   case OMPD_parallel_sections:
5086     Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt,
5087                                                StartLoc, EndLoc);
5088     AllowedNameModifiers.push_back(OMPD_parallel);
5089     break;
5090   case OMPD_task:
5091     Res =
5092         ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
5093     AllowedNameModifiers.push_back(OMPD_task);
5094     break;
5095   case OMPD_taskyield:
5096     assert(ClausesWithImplicit.empty() &&
5097            "No clauses are allowed for 'omp taskyield' directive");
5098     assert(AStmt == nullptr &&
5099            "No associated statement allowed for 'omp taskyield' directive");
5100     Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc);
5101     break;
5102   case OMPD_barrier:
5103     assert(ClausesWithImplicit.empty() &&
5104            "No clauses are allowed for 'omp barrier' directive");
5105     assert(AStmt == nullptr &&
5106            "No associated statement allowed for 'omp barrier' directive");
5107     Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc);
5108     break;
5109   case OMPD_taskwait:
5110     assert(ClausesWithImplicit.empty() &&
5111            "No clauses are allowed for 'omp taskwait' directive");
5112     assert(AStmt == nullptr &&
5113            "No associated statement allowed for 'omp taskwait' directive");
5114     Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc);
5115     break;
5116   case OMPD_taskgroup:
5117     Res = ActOnOpenMPTaskgroupDirective(ClausesWithImplicit, AStmt, StartLoc,
5118                                         EndLoc);
5119     break;
5120   case OMPD_flush:
5121     assert(AStmt == nullptr &&
5122            "No associated statement allowed for 'omp flush' directive");
5123     Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc);
5124     break;
5125   case OMPD_depobj:
5126     assert(AStmt == nullptr &&
5127            "No associated statement allowed for 'omp depobj' directive");
5128     Res = ActOnOpenMPDepobjDirective(ClausesWithImplicit, StartLoc, EndLoc);
5129     break;
5130   case OMPD_scan:
5131     assert(AStmt == nullptr &&
5132            "No associated statement allowed for 'omp scan' directive");
5133     Res = ActOnOpenMPScanDirective(ClausesWithImplicit, StartLoc, EndLoc);
5134     break;
5135   case OMPD_ordered:
5136     Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc,
5137                                       EndLoc);
5138     break;
5139   case OMPD_atomic:
5140     Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc,
5141                                      EndLoc);
5142     break;
5143   case OMPD_teams:
5144     Res =
5145         ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
5146     break;
5147   case OMPD_target:
5148     Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc,
5149                                      EndLoc);
5150     AllowedNameModifiers.push_back(OMPD_target);
5151     break;
5152   case OMPD_target_parallel:
5153     Res = ActOnOpenMPTargetParallelDirective(ClausesWithImplicit, AStmt,
5154                                              StartLoc, EndLoc);
5155     AllowedNameModifiers.push_back(OMPD_target);
5156     AllowedNameModifiers.push_back(OMPD_parallel);
5157     break;
5158   case OMPD_target_parallel_for:
5159     Res = ActOnOpenMPTargetParallelForDirective(
5160         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
5161     AllowedNameModifiers.push_back(OMPD_target);
5162     AllowedNameModifiers.push_back(OMPD_parallel);
5163     break;
5164   case OMPD_cancellation_point:
5165     assert(ClausesWithImplicit.empty() &&
5166            "No clauses are allowed for 'omp cancellation point' directive");
5167     assert(AStmt == nullptr && "No associated statement allowed for 'omp "
5168                                "cancellation point' directive");
5169     Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion);
5170     break;
5171   case OMPD_cancel:
5172     assert(AStmt == nullptr &&
5173            "No associated statement allowed for 'omp cancel' directive");
5174     Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc,
5175                                      CancelRegion);
5176     AllowedNameModifiers.push_back(OMPD_cancel);
5177     break;
5178   case OMPD_target_data:
5179     Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc,
5180                                          EndLoc);
5181     AllowedNameModifiers.push_back(OMPD_target_data);
5182     break;
5183   case OMPD_target_enter_data:
5184     Res = ActOnOpenMPTargetEnterDataDirective(ClausesWithImplicit, StartLoc,
5185                                               EndLoc, AStmt);
5186     AllowedNameModifiers.push_back(OMPD_target_enter_data);
5187     break;
5188   case OMPD_target_exit_data:
5189     Res = ActOnOpenMPTargetExitDataDirective(ClausesWithImplicit, StartLoc,
5190                                              EndLoc, AStmt);
5191     AllowedNameModifiers.push_back(OMPD_target_exit_data);
5192     break;
5193   case OMPD_taskloop:
5194     Res = ActOnOpenMPTaskLoopDirective(ClausesWithImplicit, AStmt, StartLoc,
5195                                        EndLoc, VarsWithInheritedDSA);
5196     AllowedNameModifiers.push_back(OMPD_taskloop);
5197     break;
5198   case OMPD_taskloop_simd:
5199     Res = ActOnOpenMPTaskLoopSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
5200                                            EndLoc, VarsWithInheritedDSA);
5201     AllowedNameModifiers.push_back(OMPD_taskloop);
5202     if (LangOpts.OpenMP >= 50)
5203       AllowedNameModifiers.push_back(OMPD_simd);
5204     break;
5205   case OMPD_master_taskloop:
5206     Res = ActOnOpenMPMasterTaskLoopDirective(
5207         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
5208     AllowedNameModifiers.push_back(OMPD_taskloop);
5209     break;
5210   case OMPD_master_taskloop_simd:
5211     Res = ActOnOpenMPMasterTaskLoopSimdDirective(
5212         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
5213     AllowedNameModifiers.push_back(OMPD_taskloop);
5214     if (LangOpts.OpenMP >= 50)
5215       AllowedNameModifiers.push_back(OMPD_simd);
5216     break;
5217   case OMPD_parallel_master_taskloop:
5218     Res = ActOnOpenMPParallelMasterTaskLoopDirective(
5219         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
5220     AllowedNameModifiers.push_back(OMPD_taskloop);
5221     AllowedNameModifiers.push_back(OMPD_parallel);
5222     break;
5223   case OMPD_parallel_master_taskloop_simd:
5224     Res = ActOnOpenMPParallelMasterTaskLoopSimdDirective(
5225         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
5226     AllowedNameModifiers.push_back(OMPD_taskloop);
5227     AllowedNameModifiers.push_back(OMPD_parallel);
5228     if (LangOpts.OpenMP >= 50)
5229       AllowedNameModifiers.push_back(OMPD_simd);
5230     break;
5231   case OMPD_distribute:
5232     Res = ActOnOpenMPDistributeDirective(ClausesWithImplicit, AStmt, StartLoc,
5233                                          EndLoc, VarsWithInheritedDSA);
5234     break;
5235   case OMPD_target_update:
5236     Res = ActOnOpenMPTargetUpdateDirective(ClausesWithImplicit, StartLoc,
5237                                            EndLoc, AStmt);
5238     AllowedNameModifiers.push_back(OMPD_target_update);
5239     break;
5240   case OMPD_distribute_parallel_for:
5241     Res = ActOnOpenMPDistributeParallelForDirective(
5242         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
5243     AllowedNameModifiers.push_back(OMPD_parallel);
5244     break;
5245   case OMPD_distribute_parallel_for_simd:
5246     Res = ActOnOpenMPDistributeParallelForSimdDirective(
5247         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
5248     AllowedNameModifiers.push_back(OMPD_parallel);
5249     if (LangOpts.OpenMP >= 50)
5250       AllowedNameModifiers.push_back(OMPD_simd);
5251     break;
5252   case OMPD_distribute_simd:
5253     Res = ActOnOpenMPDistributeSimdDirective(
5254         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
5255     if (LangOpts.OpenMP >= 50)
5256       AllowedNameModifiers.push_back(OMPD_simd);
5257     break;
5258   case OMPD_target_parallel_for_simd:
5259     Res = ActOnOpenMPTargetParallelForSimdDirective(
5260         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
5261     AllowedNameModifiers.push_back(OMPD_target);
5262     AllowedNameModifiers.push_back(OMPD_parallel);
5263     if (LangOpts.OpenMP >= 50)
5264       AllowedNameModifiers.push_back(OMPD_simd);
5265     break;
5266   case OMPD_target_simd:
5267     Res = ActOnOpenMPTargetSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
5268                                          EndLoc, VarsWithInheritedDSA);
5269     AllowedNameModifiers.push_back(OMPD_target);
5270     if (LangOpts.OpenMP >= 50)
5271       AllowedNameModifiers.push_back(OMPD_simd);
5272     break;
5273   case OMPD_teams_distribute:
5274     Res = ActOnOpenMPTeamsDistributeDirective(
5275         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
5276     break;
5277   case OMPD_teams_distribute_simd:
5278     Res = ActOnOpenMPTeamsDistributeSimdDirective(
5279         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
5280     if (LangOpts.OpenMP >= 50)
5281       AllowedNameModifiers.push_back(OMPD_simd);
5282     break;
5283   case OMPD_teams_distribute_parallel_for_simd:
5284     Res = ActOnOpenMPTeamsDistributeParallelForSimdDirective(
5285         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
5286     AllowedNameModifiers.push_back(OMPD_parallel);
5287     if (LangOpts.OpenMP >= 50)
5288       AllowedNameModifiers.push_back(OMPD_simd);
5289     break;
5290   case OMPD_teams_distribute_parallel_for:
5291     Res = ActOnOpenMPTeamsDistributeParallelForDirective(
5292         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
5293     AllowedNameModifiers.push_back(OMPD_parallel);
5294     break;
5295   case OMPD_target_teams:
5296     Res = ActOnOpenMPTargetTeamsDirective(ClausesWithImplicit, AStmt, StartLoc,
5297                                           EndLoc);
5298     AllowedNameModifiers.push_back(OMPD_target);
5299     break;
5300   case OMPD_target_teams_distribute:
5301     Res = ActOnOpenMPTargetTeamsDistributeDirective(
5302         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
5303     AllowedNameModifiers.push_back(OMPD_target);
5304     break;
5305   case OMPD_target_teams_distribute_parallel_for:
5306     Res = ActOnOpenMPTargetTeamsDistributeParallelForDirective(
5307         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
5308     AllowedNameModifiers.push_back(OMPD_target);
5309     AllowedNameModifiers.push_back(OMPD_parallel);
5310     break;
5311   case OMPD_target_teams_distribute_parallel_for_simd:
5312     Res = ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
5313         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
5314     AllowedNameModifiers.push_back(OMPD_target);
5315     AllowedNameModifiers.push_back(OMPD_parallel);
5316     if (LangOpts.OpenMP >= 50)
5317       AllowedNameModifiers.push_back(OMPD_simd);
5318     break;
5319   case OMPD_target_teams_distribute_simd:
5320     Res = ActOnOpenMPTargetTeamsDistributeSimdDirective(
5321         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
5322     AllowedNameModifiers.push_back(OMPD_target);
5323     if (LangOpts.OpenMP >= 50)
5324       AllowedNameModifiers.push_back(OMPD_simd);
5325     break;
5326   case OMPD_declare_target:
5327   case OMPD_end_declare_target:
5328   case OMPD_threadprivate:
5329   case OMPD_allocate:
5330   case OMPD_declare_reduction:
5331   case OMPD_declare_mapper:
5332   case OMPD_declare_simd:
5333   case OMPD_requires:
5334   case OMPD_declare_variant:
5335   case OMPD_begin_declare_variant:
5336   case OMPD_end_declare_variant:
5337     llvm_unreachable("OpenMP Directive is not allowed");
5338   case OMPD_unknown:
5339   default:
5340     llvm_unreachable("Unknown OpenMP directive");
5341   }
5342 
5343   ErrorFound = Res.isInvalid() || ErrorFound;
5344 
5345   // Check variables in the clauses if default(none) was specified.
5346   if (DSAStack->getDefaultDSA() == DSA_none) {
5347     DSAAttrChecker DSAChecker(DSAStack, *this, nullptr);
5348     for (OMPClause *C : Clauses) {
5349       switch (C->getClauseKind()) {
5350       case OMPC_num_threads:
5351       case OMPC_dist_schedule:
5352         // Do not analyse if no parent teams directive.
5353         if (isOpenMPTeamsDirective(Kind))
5354           break;
5355         continue;
5356       case OMPC_if:
5357         if (isOpenMPTeamsDirective(Kind) &&
5358             cast<OMPIfClause>(C)->getNameModifier() != OMPD_target)
5359           break;
5360         if (isOpenMPParallelDirective(Kind) &&
5361             isOpenMPTaskLoopDirective(Kind) &&
5362             cast<OMPIfClause>(C)->getNameModifier() != OMPD_parallel)
5363           break;
5364         continue;
5365       case OMPC_schedule:
5366       case OMPC_detach:
5367         break;
5368       case OMPC_grainsize:
5369       case OMPC_num_tasks:
5370       case OMPC_final:
5371       case OMPC_priority:
5372         // Do not analyze if no parent parallel directive.
5373         if (isOpenMPParallelDirective(Kind))
5374           break;
5375         continue;
5376       case OMPC_ordered:
5377       case OMPC_device:
5378       case OMPC_num_teams:
5379       case OMPC_thread_limit:
5380       case OMPC_hint:
5381       case OMPC_collapse:
5382       case OMPC_safelen:
5383       case OMPC_simdlen:
5384       case OMPC_default:
5385       case OMPC_proc_bind:
5386       case OMPC_private:
5387       case OMPC_firstprivate:
5388       case OMPC_lastprivate:
5389       case OMPC_shared:
5390       case OMPC_reduction:
5391       case OMPC_task_reduction:
5392       case OMPC_in_reduction:
5393       case OMPC_linear:
5394       case OMPC_aligned:
5395       case OMPC_copyin:
5396       case OMPC_copyprivate:
5397       case OMPC_nowait:
5398       case OMPC_untied:
5399       case OMPC_mergeable:
5400       case OMPC_allocate:
5401       case OMPC_read:
5402       case OMPC_write:
5403       case OMPC_update:
5404       case OMPC_capture:
5405       case OMPC_seq_cst:
5406       case OMPC_acq_rel:
5407       case OMPC_acquire:
5408       case OMPC_release:
5409       case OMPC_relaxed:
5410       case OMPC_depend:
5411       case OMPC_threads:
5412       case OMPC_simd:
5413       case OMPC_map:
5414       case OMPC_nogroup:
5415       case OMPC_defaultmap:
5416       case OMPC_to:
5417       case OMPC_from:
5418       case OMPC_use_device_ptr:
5419       case OMPC_use_device_addr:
5420       case OMPC_is_device_ptr:
5421       case OMPC_nontemporal:
5422       case OMPC_order:
5423       case OMPC_destroy:
5424       case OMPC_inclusive:
5425       case OMPC_exclusive:
5426       case OMPC_uses_allocators:
5427       case OMPC_affinity:
5428         continue;
5429       case OMPC_allocator:
5430       case OMPC_flush:
5431       case OMPC_depobj:
5432       case OMPC_threadprivate:
5433       case OMPC_uniform:
5434       case OMPC_unknown:
5435       case OMPC_unified_address:
5436       case OMPC_unified_shared_memory:
5437       case OMPC_reverse_offload:
5438       case OMPC_dynamic_allocators:
5439       case OMPC_atomic_default_mem_order:
5440       case OMPC_device_type:
5441       case OMPC_match:
5442       default:
5443         llvm_unreachable("Unexpected clause");
5444       }
5445       for (Stmt *CC : C->children()) {
5446         if (CC)
5447           DSAChecker.Visit(CC);
5448       }
5449     }
5450     for (const auto &P : DSAChecker.getVarsWithInheritedDSA())
5451       VarsWithInheritedDSA[P.getFirst()] = P.getSecond();
5452   }
5453   for (const auto &P : VarsWithInheritedDSA) {
5454     if (P.getFirst()->isImplicit() || isa<OMPCapturedExprDecl>(P.getFirst()))
5455       continue;
5456     ErrorFound = true;
5457     if (DSAStack->getDefaultDSA() == DSA_none) {
5458       Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable)
5459           << P.first << P.second->getSourceRange();
5460       Diag(DSAStack->getDefaultDSALocation(), diag::note_omp_default_dsa_none);
5461     } else if (getLangOpts().OpenMP >= 50) {
5462       Diag(P.second->getExprLoc(),
5463            diag::err_omp_defaultmap_no_attr_for_variable)
5464           << P.first << P.second->getSourceRange();
5465       Diag(DSAStack->getDefaultDSALocation(),
5466            diag::note_omp_defaultmap_attr_none);
5467     }
5468   }
5469 
5470   if (!AllowedNameModifiers.empty())
5471     ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) ||
5472                  ErrorFound;
5473 
5474   if (ErrorFound)
5475     return StmtError();
5476 
5477   if (!CurContext->isDependentContext() &&
5478       isOpenMPTargetExecutionDirective(Kind) &&
5479       !(DSAStack->hasRequiresDeclWithClause<OMPUnifiedSharedMemoryClause>() ||
5480         DSAStack->hasRequiresDeclWithClause<OMPUnifiedAddressClause>() ||
5481         DSAStack->hasRequiresDeclWithClause<OMPReverseOffloadClause>() ||
5482         DSAStack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>())) {
5483     // Register target to DSA Stack.
5484     DSAStack->addTargetDirLocation(StartLoc);
5485   }
5486 
5487   return Res;
5488 }
5489 
5490 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareSimdDirective(
5491     DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen,
5492     ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
5493     ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
5494     ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR) {
5495   assert(Aligneds.size() == Alignments.size());
5496   assert(Linears.size() == LinModifiers.size());
5497   assert(Linears.size() == Steps.size());
5498   if (!DG || DG.get().isNull())
5499     return DeclGroupPtrTy();
5500 
5501   const int SimdId = 0;
5502   if (!DG.get().isSingleDecl()) {
5503     Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd_variant)
5504         << SimdId;
5505     return DG;
5506   }
5507   Decl *ADecl = DG.get().getSingleDecl();
5508   if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
5509     ADecl = FTD->getTemplatedDecl();
5510 
5511   auto *FD = dyn_cast<FunctionDecl>(ADecl);
5512   if (!FD) {
5513     Diag(ADecl->getLocation(), diag::err_omp_function_expected) << SimdId;
5514     return DeclGroupPtrTy();
5515   }
5516 
5517   // OpenMP [2.8.2, declare simd construct, Description]
5518   // The parameter of the simdlen clause must be a constant positive integer
5519   // expression.
5520   ExprResult SL;
5521   if (Simdlen)
5522     SL = VerifyPositiveIntegerConstantInClause(Simdlen, OMPC_simdlen);
5523   // OpenMP [2.8.2, declare simd construct, Description]
5524   // The special this pointer can be used as if was one of the arguments to the
5525   // function in any of the linear, aligned, or uniform clauses.
5526   // The uniform clause declares one or more arguments to have an invariant
5527   // value for all concurrent invocations of the function in the execution of a
5528   // single SIMD loop.
5529   llvm::DenseMap<const Decl *, const Expr *> UniformedArgs;
5530   const Expr *UniformedLinearThis = nullptr;
5531   for (const Expr *E : Uniforms) {
5532     E = E->IgnoreParenImpCasts();
5533     if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
5534       if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
5535         if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
5536             FD->getParamDecl(PVD->getFunctionScopeIndex())
5537                     ->getCanonicalDecl() == PVD->getCanonicalDecl()) {
5538           UniformedArgs.try_emplace(PVD->getCanonicalDecl(), E);
5539           continue;
5540         }
5541     if (isa<CXXThisExpr>(E)) {
5542       UniformedLinearThis = E;
5543       continue;
5544     }
5545     Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
5546         << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
5547   }
5548   // OpenMP [2.8.2, declare simd construct, Description]
5549   // The aligned clause declares that the object to which each list item points
5550   // is aligned to the number of bytes expressed in the optional parameter of
5551   // the aligned clause.
5552   // The special this pointer can be used as if was one of the arguments to the
5553   // function in any of the linear, aligned, or uniform clauses.
5554   // The type of list items appearing in the aligned clause must be array,
5555   // pointer, reference to array, or reference to pointer.
5556   llvm::DenseMap<const Decl *, const Expr *> AlignedArgs;
5557   const Expr *AlignedThis = nullptr;
5558   for (const Expr *E : Aligneds) {
5559     E = E->IgnoreParenImpCasts();
5560     if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
5561       if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
5562         const VarDecl *CanonPVD = PVD->getCanonicalDecl();
5563         if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
5564             FD->getParamDecl(PVD->getFunctionScopeIndex())
5565                     ->getCanonicalDecl() == CanonPVD) {
5566           // OpenMP  [2.8.1, simd construct, Restrictions]
5567           // A list-item cannot appear in more than one aligned clause.
5568           if (AlignedArgs.count(CanonPVD) > 0) {
5569             Diag(E->getExprLoc(), diag::err_omp_used_in_clause_twice)
5570                 << 1 << getOpenMPClauseName(OMPC_aligned)
5571                 << E->getSourceRange();
5572             Diag(AlignedArgs[CanonPVD]->getExprLoc(),
5573                  diag::note_omp_explicit_dsa)
5574                 << getOpenMPClauseName(OMPC_aligned);
5575             continue;
5576           }
5577           AlignedArgs[CanonPVD] = E;
5578           QualType QTy = PVD->getType()
5579                              .getNonReferenceType()
5580                              .getUnqualifiedType()
5581                              .getCanonicalType();
5582           const Type *Ty = QTy.getTypePtrOrNull();
5583           if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
5584             Diag(E->getExprLoc(), diag::err_omp_aligned_expected_array_or_ptr)
5585                 << QTy << getLangOpts().CPlusPlus << E->getSourceRange();
5586             Diag(PVD->getLocation(), diag::note_previous_decl) << PVD;
5587           }
5588           continue;
5589         }
5590       }
5591     if (isa<CXXThisExpr>(E)) {
5592       if (AlignedThis) {
5593         Diag(E->getExprLoc(), diag::err_omp_used_in_clause_twice)
5594             << 2 << getOpenMPClauseName(OMPC_aligned) << E->getSourceRange();
5595         Diag(AlignedThis->getExprLoc(), diag::note_omp_explicit_dsa)
5596             << getOpenMPClauseName(OMPC_aligned);
5597       }
5598       AlignedThis = E;
5599       continue;
5600     }
5601     Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
5602         << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
5603   }
5604   // The optional parameter of the aligned clause, alignment, must be a constant
5605   // positive integer expression. If no optional parameter is specified,
5606   // implementation-defined default alignments for SIMD instructions on the
5607   // target platforms are assumed.
5608   SmallVector<const Expr *, 4> NewAligns;
5609   for (Expr *E : Alignments) {
5610     ExprResult Align;
5611     if (E)
5612       Align = VerifyPositiveIntegerConstantInClause(E, OMPC_aligned);
5613     NewAligns.push_back(Align.get());
5614   }
5615   // OpenMP [2.8.2, declare simd construct, Description]
5616   // The linear clause declares one or more list items to be private to a SIMD
5617   // lane and to have a linear relationship with respect to the iteration space
5618   // of a loop.
5619   // The special this pointer can be used as if was one of the arguments to the
5620   // function in any of the linear, aligned, or uniform clauses.
5621   // When a linear-step expression is specified in a linear clause it must be
5622   // either a constant integer expression or an integer-typed parameter that is
5623   // specified in a uniform clause on the directive.
5624   llvm::DenseMap<const Decl *, const Expr *> LinearArgs;
5625   const bool IsUniformedThis = UniformedLinearThis != nullptr;
5626   auto MI = LinModifiers.begin();
5627   for (const Expr *E : Linears) {
5628     auto LinKind = static_cast<OpenMPLinearClauseKind>(*MI);
5629     ++MI;
5630     E = E->IgnoreParenImpCasts();
5631     if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
5632       if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
5633         const VarDecl *CanonPVD = PVD->getCanonicalDecl();
5634         if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
5635             FD->getParamDecl(PVD->getFunctionScopeIndex())
5636                     ->getCanonicalDecl() == CanonPVD) {
5637           // OpenMP  [2.15.3.7, linear Clause, Restrictions]
5638           // A list-item cannot appear in more than one linear clause.
5639           if (LinearArgs.count(CanonPVD) > 0) {
5640             Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
5641                 << getOpenMPClauseName(OMPC_linear)
5642                 << getOpenMPClauseName(OMPC_linear) << E->getSourceRange();
5643             Diag(LinearArgs[CanonPVD]->getExprLoc(),
5644                  diag::note_omp_explicit_dsa)
5645                 << getOpenMPClauseName(OMPC_linear);
5646             continue;
5647           }
5648           // Each argument can appear in at most one uniform or linear clause.
5649           if (UniformedArgs.count(CanonPVD) > 0) {
5650             Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
5651                 << getOpenMPClauseName(OMPC_linear)
5652                 << getOpenMPClauseName(OMPC_uniform) << E->getSourceRange();
5653             Diag(UniformedArgs[CanonPVD]->getExprLoc(),
5654                  diag::note_omp_explicit_dsa)
5655                 << getOpenMPClauseName(OMPC_uniform);
5656             continue;
5657           }
5658           LinearArgs[CanonPVD] = E;
5659           if (E->isValueDependent() || E->isTypeDependent() ||
5660               E->isInstantiationDependent() ||
5661               E->containsUnexpandedParameterPack())
5662             continue;
5663           (void)CheckOpenMPLinearDecl(CanonPVD, E->getExprLoc(), LinKind,
5664                                       PVD->getOriginalType(),
5665                                       /*IsDeclareSimd=*/true);
5666           continue;
5667         }
5668       }
5669     if (isa<CXXThisExpr>(E)) {
5670       if (UniformedLinearThis) {
5671         Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
5672             << getOpenMPClauseName(OMPC_linear)
5673             << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform : OMPC_linear)
5674             << E->getSourceRange();
5675         Diag(UniformedLinearThis->getExprLoc(), diag::note_omp_explicit_dsa)
5676             << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform
5677                                                    : OMPC_linear);
5678         continue;
5679       }
5680       UniformedLinearThis = E;
5681       if (E->isValueDependent() || E->isTypeDependent() ||
5682           E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
5683         continue;
5684       (void)CheckOpenMPLinearDecl(/*D=*/nullptr, E->getExprLoc(), LinKind,
5685                                   E->getType(), /*IsDeclareSimd=*/true);
5686       continue;
5687     }
5688     Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
5689         << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
5690   }
5691   Expr *Step = nullptr;
5692   Expr *NewStep = nullptr;
5693   SmallVector<Expr *, 4> NewSteps;
5694   for (Expr *E : Steps) {
5695     // Skip the same step expression, it was checked already.
5696     if (Step == E || !E) {
5697       NewSteps.push_back(E ? NewStep : nullptr);
5698       continue;
5699     }
5700     Step = E;
5701     if (const auto *DRE = dyn_cast<DeclRefExpr>(Step))
5702       if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
5703         const VarDecl *CanonPVD = PVD->getCanonicalDecl();
5704         if (UniformedArgs.count(CanonPVD) == 0) {
5705           Diag(Step->getExprLoc(), diag::err_omp_expected_uniform_param)
5706               << Step->getSourceRange();
5707         } else if (E->isValueDependent() || E->isTypeDependent() ||
5708                    E->isInstantiationDependent() ||
5709                    E->containsUnexpandedParameterPack() ||
5710                    CanonPVD->getType()->hasIntegerRepresentation()) {
5711           NewSteps.push_back(Step);
5712         } else {
5713           Diag(Step->getExprLoc(), diag::err_omp_expected_int_param)
5714               << Step->getSourceRange();
5715         }
5716         continue;
5717       }
5718     NewStep = Step;
5719     if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
5720         !Step->isInstantiationDependent() &&
5721         !Step->containsUnexpandedParameterPack()) {
5722       NewStep = PerformOpenMPImplicitIntegerConversion(Step->getExprLoc(), Step)
5723                     .get();
5724       if (NewStep)
5725         NewStep = VerifyIntegerConstantExpression(NewStep).get();
5726     }
5727     NewSteps.push_back(NewStep);
5728   }
5729   auto *NewAttr = OMPDeclareSimdDeclAttr::CreateImplicit(
5730       Context, BS, SL.get(), const_cast<Expr **>(Uniforms.data()),
5731       Uniforms.size(), const_cast<Expr **>(Aligneds.data()), Aligneds.size(),
5732       const_cast<Expr **>(NewAligns.data()), NewAligns.size(),
5733       const_cast<Expr **>(Linears.data()), Linears.size(),
5734       const_cast<unsigned *>(LinModifiers.data()), LinModifiers.size(),
5735       NewSteps.data(), NewSteps.size(), SR);
5736   ADecl->addAttr(NewAttr);
5737   return DG;
5738 }
5739 
5740 static void setPrototype(Sema &S, FunctionDecl *FD, FunctionDecl *FDWithProto,
5741                          QualType NewType) {
5742   assert(NewType->isFunctionProtoType() &&
5743          "Expected function type with prototype.");
5744   assert(FD->getType()->isFunctionNoProtoType() &&
5745          "Expected function with type with no prototype.");
5746   assert(FDWithProto->getType()->isFunctionProtoType() &&
5747          "Expected function with prototype.");
5748   // Synthesize parameters with the same types.
5749   FD->setType(NewType);
5750   SmallVector<ParmVarDecl *, 16> Params;
5751   for (const ParmVarDecl *P : FDWithProto->parameters()) {
5752     auto *Param = ParmVarDecl::Create(S.getASTContext(), FD, SourceLocation(),
5753                                       SourceLocation(), nullptr, P->getType(),
5754                                       /*TInfo=*/nullptr, SC_None, nullptr);
5755     Param->setScopeInfo(0, Params.size());
5756     Param->setImplicit();
5757     Params.push_back(Param);
5758   }
5759 
5760   FD->setParams(Params);
5761 }
5762 
5763 Sema::OMPDeclareVariantScope::OMPDeclareVariantScope(OMPTraitInfo &TI)
5764     : TI(&TI), NameSuffix(TI.getMangledName()) {}
5765 
5766 FunctionDecl *
5767 Sema::ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(Scope *S,
5768                                                                 Declarator &D) {
5769   IdentifierInfo *BaseII = D.getIdentifier();
5770   LookupResult Lookup(*this, DeclarationName(BaseII), D.getIdentifierLoc(),
5771                       LookupOrdinaryName);
5772   LookupParsedName(Lookup, S, &D.getCXXScopeSpec());
5773 
5774   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
5775   QualType FType = TInfo->getType();
5776 
5777   bool IsConstexpr = D.getDeclSpec().getConstexprSpecifier() == CSK_constexpr;
5778   bool IsConsteval = D.getDeclSpec().getConstexprSpecifier() == CSK_consteval;
5779 
5780   FunctionDecl *BaseFD = nullptr;
5781   for (auto *Candidate : Lookup) {
5782     auto *UDecl = dyn_cast<FunctionDecl>(Candidate->getUnderlyingDecl());
5783     if (!UDecl)
5784       continue;
5785 
5786     // Don't specialize constexpr/consteval functions with
5787     // non-constexpr/consteval functions.
5788     if (UDecl->isConstexpr() && !IsConstexpr)
5789       continue;
5790     if (UDecl->isConsteval() && !IsConsteval)
5791       continue;
5792 
5793     QualType NewType = Context.mergeFunctionTypes(
5794         FType, UDecl->getType(), /* OfBlockPointer */ false,
5795         /* Unqualified */ false, /* AllowCXX */ true);
5796     if (NewType.isNull())
5797       continue;
5798 
5799     // Found a base!
5800     BaseFD = UDecl;
5801     break;
5802   }
5803   if (!BaseFD) {
5804     BaseFD = cast<FunctionDecl>(ActOnDeclarator(S, D));
5805     BaseFD->setImplicit(true);
5806   }
5807 
5808   OMPDeclareVariantScope &DVScope = OMPDeclareVariantScopes.back();
5809   std::string MangledName;
5810   MangledName += D.getIdentifier()->getName();
5811   MangledName += getOpenMPVariantManglingSeparatorStr();
5812   MangledName += DVScope.NameSuffix;
5813   IdentifierInfo &VariantII = Context.Idents.get(MangledName);
5814 
5815   VariantII.setMangledOpenMPVariantName(true);
5816   D.SetIdentifier(&VariantII, D.getBeginLoc());
5817   return BaseFD;
5818 }
5819 
5820 void Sema::ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(
5821     FunctionDecl *FD, FunctionDecl *BaseFD) {
5822   // Do not mark function as is used to prevent its emission if this is the
5823   // only place where it is used.
5824   EnterExpressionEvaluationContext Unevaluated(
5825       *this, Sema::ExpressionEvaluationContext::Unevaluated);
5826 
5827   Expr *VariantFuncRef = DeclRefExpr::Create(
5828       Context, NestedNameSpecifierLoc(), SourceLocation(), FD,
5829       /* RefersToEnclosingVariableOrCapture */ false,
5830       /* NameLoc */ FD->getLocation(), FD->getType(), ExprValueKind::VK_RValue);
5831 
5832   OMPDeclareVariantScope &DVScope = OMPDeclareVariantScopes.back();
5833   auto *OMPDeclareVariantA = OMPDeclareVariantAttr::CreateImplicit(
5834       Context, VariantFuncRef, DVScope.TI);
5835   BaseFD->addAttr(OMPDeclareVariantA);
5836 }
5837 
5838 ExprResult Sema::ActOnOpenMPCall(ExprResult Call, Scope *Scope,
5839                                  SourceLocation LParenLoc,
5840                                  MultiExprArg ArgExprs,
5841                                  SourceLocation RParenLoc, Expr *ExecConfig) {
5842   // The common case is a regular call we do not want to specialize at all. Try
5843   // to make that case fast by bailing early.
5844   CallExpr *CE = dyn_cast<CallExpr>(Call.get());
5845   if (!CE)
5846     return Call;
5847 
5848   FunctionDecl *CalleeFnDecl = CE->getDirectCallee();
5849   if (!CalleeFnDecl)
5850     return Call;
5851 
5852   if (!CalleeFnDecl->hasAttr<OMPDeclareVariantAttr>())
5853     return Call;
5854 
5855   ASTContext &Context = getASTContext();
5856   OMPContext OMPCtx(getLangOpts().OpenMPIsDevice,
5857                     Context.getTargetInfo().getTriple());
5858 
5859   SmallVector<Expr *, 4> Exprs;
5860   SmallVector<VariantMatchInfo, 4> VMIs;
5861   while (CalleeFnDecl) {
5862     for (OMPDeclareVariantAttr *A :
5863          CalleeFnDecl->specific_attrs<OMPDeclareVariantAttr>()) {
5864       Expr *VariantRef = A->getVariantFuncRef();
5865 
5866       VariantMatchInfo VMI;
5867       OMPTraitInfo &TI = A->getTraitInfo();
5868       TI.getAsVariantMatchInfo(Context, VMI);
5869       if (!isVariantApplicableInContext(VMI, OMPCtx, /* DeviceSetOnly */ false))
5870         continue;
5871 
5872       VMIs.push_back(VMI);
5873       Exprs.push_back(VariantRef);
5874     }
5875 
5876     CalleeFnDecl = CalleeFnDecl->getPreviousDecl();
5877   }
5878 
5879   ExprResult NewCall;
5880   do {
5881     int BestIdx = getBestVariantMatchForContext(VMIs, OMPCtx);
5882     if (BestIdx < 0)
5883       return Call;
5884     Expr *BestExpr = cast<DeclRefExpr>(Exprs[BestIdx]);
5885     Decl *BestDecl = cast<DeclRefExpr>(BestExpr)->getDecl();
5886 
5887     {
5888       // Try to build a (member) call expression for the current best applicable
5889       // variant expression. We allow this to fail in which case we continue
5890       // with the next best variant expression. The fail case is part of the
5891       // implementation defined behavior in the OpenMP standard when it talks
5892       // about what differences in the function prototypes: "Any differences
5893       // that the specific OpenMP context requires in the prototype of the
5894       // variant from the base function prototype are implementation defined."
5895       // This wording is there to allow the specialized variant to have a
5896       // different type than the base function. This is intended and OK but if
5897       // we cannot create a call the difference is not in the "implementation
5898       // defined range" we allow.
5899       Sema::TentativeAnalysisScope Trap(*this);
5900 
5901       if (auto *SpecializedMethod = dyn_cast<CXXMethodDecl>(BestDecl)) {
5902         auto *MemberCall = dyn_cast<CXXMemberCallExpr>(CE);
5903         BestExpr = MemberExpr::CreateImplicit(
5904             Context, MemberCall->getImplicitObjectArgument(),
5905             /* IsArrow */ false, SpecializedMethod, Context.BoundMemberTy,
5906             MemberCall->getValueKind(), MemberCall->getObjectKind());
5907       }
5908       NewCall = BuildCallExpr(Scope, BestExpr, LParenLoc, ArgExprs, RParenLoc,
5909                               ExecConfig);
5910       if (NewCall.isUsable())
5911         break;
5912     }
5913 
5914     VMIs.erase(VMIs.begin() + BestIdx);
5915     Exprs.erase(Exprs.begin() + BestIdx);
5916   } while (!VMIs.empty());
5917 
5918   if (!NewCall.isUsable())
5919     return Call;
5920   return PseudoObjectExpr::Create(Context, CE, {NewCall.get()}, 0);
5921 }
5922 
5923 Optional<std::pair<FunctionDecl *, Expr *>>
5924 Sema::checkOpenMPDeclareVariantFunction(Sema::DeclGroupPtrTy DG,
5925                                         Expr *VariantRef, OMPTraitInfo &TI,
5926                                         SourceRange SR) {
5927   if (!DG || DG.get().isNull())
5928     return None;
5929 
5930   const int VariantId = 1;
5931   // Must be applied only to single decl.
5932   if (!DG.get().isSingleDecl()) {
5933     Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd_variant)
5934         << VariantId << SR;
5935     return None;
5936   }
5937   Decl *ADecl = DG.get().getSingleDecl();
5938   if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
5939     ADecl = FTD->getTemplatedDecl();
5940 
5941   // Decl must be a function.
5942   auto *FD = dyn_cast<FunctionDecl>(ADecl);
5943   if (!FD) {
5944     Diag(ADecl->getLocation(), diag::err_omp_function_expected)
5945         << VariantId << SR;
5946     return None;
5947   }
5948 
5949   auto &&HasMultiVersionAttributes = [](const FunctionDecl *FD) {
5950     return FD->hasAttrs() &&
5951            (FD->hasAttr<CPUDispatchAttr>() || FD->hasAttr<CPUSpecificAttr>() ||
5952             FD->hasAttr<TargetAttr>());
5953   };
5954   // OpenMP is not compatible with CPU-specific attributes.
5955   if (HasMultiVersionAttributes(FD)) {
5956     Diag(FD->getLocation(), diag::err_omp_declare_variant_incompat_attributes)
5957         << SR;
5958     return None;
5959   }
5960 
5961   // Allow #pragma omp declare variant only if the function is not used.
5962   if (FD->isUsed(false))
5963     Diag(SR.getBegin(), diag::warn_omp_declare_variant_after_used)
5964         << FD->getLocation();
5965 
5966   // Check if the function was emitted already.
5967   const FunctionDecl *Definition;
5968   if (!FD->isThisDeclarationADefinition() && FD->isDefined(Definition) &&
5969       (LangOpts.EmitAllDecls || Context.DeclMustBeEmitted(Definition)))
5970     Diag(SR.getBegin(), diag::warn_omp_declare_variant_after_emitted)
5971         << FD->getLocation();
5972 
5973   // The VariantRef must point to function.
5974   if (!VariantRef) {
5975     Diag(SR.getBegin(), diag::err_omp_function_expected) << VariantId;
5976     return None;
5977   }
5978 
5979   auto ShouldDelayChecks = [](Expr *&E, bool) {
5980     return E && (E->isTypeDependent() || E->isValueDependent() ||
5981                  E->containsUnexpandedParameterPack() ||
5982                  E->isInstantiationDependent());
5983   };
5984   // Do not check templates, wait until instantiation.
5985   if (FD->isDependentContext() || ShouldDelayChecks(VariantRef, false) ||
5986       TI.anyScoreOrCondition(ShouldDelayChecks))
5987     return std::make_pair(FD, VariantRef);
5988 
5989   // Deal with non-constant score and user condition expressions.
5990   auto HandleNonConstantScoresAndConditions = [this](Expr *&E,
5991                                                      bool IsScore) -> bool {
5992     llvm::APSInt Result;
5993     if (!E || E->isIntegerConstantExpr(Result, Context))
5994       return false;
5995 
5996     if (IsScore) {
5997       // We warn on non-constant scores and pretend they were not present.
5998       Diag(E->getExprLoc(), diag::warn_omp_declare_variant_score_not_constant)
5999           << E;
6000       E = nullptr;
6001     } else {
6002       // We could replace a non-constant user condition with "false" but we
6003       // will soon need to handle these anyway for the dynamic version of
6004       // OpenMP context selectors.
6005       Diag(E->getExprLoc(),
6006            diag::err_omp_declare_variant_user_condition_not_constant)
6007           << E;
6008     }
6009     return true;
6010   };
6011   if (TI.anyScoreOrCondition(HandleNonConstantScoresAndConditions))
6012     return None;
6013 
6014   // Convert VariantRef expression to the type of the original function to
6015   // resolve possible conflicts.
6016   ExprResult VariantRefCast;
6017   if (LangOpts.CPlusPlus) {
6018     QualType FnPtrType;
6019     auto *Method = dyn_cast<CXXMethodDecl>(FD);
6020     if (Method && !Method->isStatic()) {
6021       const Type *ClassType =
6022           Context.getTypeDeclType(Method->getParent()).getTypePtr();
6023       FnPtrType = Context.getMemberPointerType(FD->getType(), ClassType);
6024       ExprResult ER;
6025       {
6026         // Build adrr_of unary op to correctly handle type checks for member
6027         // functions.
6028         Sema::TentativeAnalysisScope Trap(*this);
6029         ER = CreateBuiltinUnaryOp(VariantRef->getBeginLoc(), UO_AddrOf,
6030                                   VariantRef);
6031       }
6032       if (!ER.isUsable()) {
6033         Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected)
6034             << VariantId << VariantRef->getSourceRange();
6035         return None;
6036       }
6037       VariantRef = ER.get();
6038     } else {
6039       FnPtrType = Context.getPointerType(FD->getType());
6040     }
6041     ImplicitConversionSequence ICS =
6042         TryImplicitConversion(VariantRef, FnPtrType.getUnqualifiedType(),
6043                               /*SuppressUserConversions=*/false,
6044                               AllowedExplicit::None,
6045                               /*InOverloadResolution=*/false,
6046                               /*CStyle=*/false,
6047                               /*AllowObjCWritebackConversion=*/false);
6048     if (ICS.isFailure()) {
6049       Diag(VariantRef->getExprLoc(),
6050            diag::err_omp_declare_variant_incompat_types)
6051           << VariantRef->getType()
6052           << ((Method && !Method->isStatic()) ? FnPtrType : FD->getType())
6053           << VariantRef->getSourceRange();
6054       return None;
6055     }
6056     VariantRefCast = PerformImplicitConversion(
6057         VariantRef, FnPtrType.getUnqualifiedType(), AA_Converting);
6058     if (!VariantRefCast.isUsable())
6059       return None;
6060     // Drop previously built artificial addr_of unary op for member functions.
6061     if (Method && !Method->isStatic()) {
6062       Expr *PossibleAddrOfVariantRef = VariantRefCast.get();
6063       if (auto *UO = dyn_cast<UnaryOperator>(
6064               PossibleAddrOfVariantRef->IgnoreImplicit()))
6065         VariantRefCast = UO->getSubExpr();
6066     }
6067   } else {
6068     VariantRefCast = VariantRef;
6069   }
6070 
6071   ExprResult ER = CheckPlaceholderExpr(VariantRefCast.get());
6072   if (!ER.isUsable() ||
6073       !ER.get()->IgnoreParenImpCasts()->getType()->isFunctionType()) {
6074     Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected)
6075         << VariantId << VariantRef->getSourceRange();
6076     return None;
6077   }
6078 
6079   // The VariantRef must point to function.
6080   auto *DRE = dyn_cast<DeclRefExpr>(ER.get()->IgnoreParenImpCasts());
6081   if (!DRE) {
6082     Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected)
6083         << VariantId << VariantRef->getSourceRange();
6084     return None;
6085   }
6086   auto *NewFD = dyn_cast_or_null<FunctionDecl>(DRE->getDecl());
6087   if (!NewFD) {
6088     Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected)
6089         << VariantId << VariantRef->getSourceRange();
6090     return None;
6091   }
6092 
6093   // Check if function types are compatible in C.
6094   if (!LangOpts.CPlusPlus) {
6095     QualType NewType =
6096         Context.mergeFunctionTypes(FD->getType(), NewFD->getType());
6097     if (NewType.isNull()) {
6098       Diag(VariantRef->getExprLoc(),
6099            diag::err_omp_declare_variant_incompat_types)
6100           << NewFD->getType() << FD->getType() << VariantRef->getSourceRange();
6101       return None;
6102     }
6103     if (NewType->isFunctionProtoType()) {
6104       if (FD->getType()->isFunctionNoProtoType())
6105         setPrototype(*this, FD, NewFD, NewType);
6106       else if (NewFD->getType()->isFunctionNoProtoType())
6107         setPrototype(*this, NewFD, FD, NewType);
6108     }
6109   }
6110 
6111   // Check if variant function is not marked with declare variant directive.
6112   if (NewFD->hasAttrs() && NewFD->hasAttr<OMPDeclareVariantAttr>()) {
6113     Diag(VariantRef->getExprLoc(),
6114          diag::warn_omp_declare_variant_marked_as_declare_variant)
6115         << VariantRef->getSourceRange();
6116     SourceRange SR =
6117         NewFD->specific_attr_begin<OMPDeclareVariantAttr>()->getRange();
6118     Diag(SR.getBegin(), diag::note_omp_marked_declare_variant_here) << SR;
6119     return None;
6120   }
6121 
6122   enum DoesntSupport {
6123     VirtFuncs = 1,
6124     Constructors = 3,
6125     Destructors = 4,
6126     DeletedFuncs = 5,
6127     DefaultedFuncs = 6,
6128     ConstexprFuncs = 7,
6129     ConstevalFuncs = 8,
6130   };
6131   if (const auto *CXXFD = dyn_cast<CXXMethodDecl>(FD)) {
6132     if (CXXFD->isVirtual()) {
6133       Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
6134           << VirtFuncs;
6135       return None;
6136     }
6137 
6138     if (isa<CXXConstructorDecl>(FD)) {
6139       Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
6140           << Constructors;
6141       return None;
6142     }
6143 
6144     if (isa<CXXDestructorDecl>(FD)) {
6145       Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
6146           << Destructors;
6147       return None;
6148     }
6149   }
6150 
6151   if (FD->isDeleted()) {
6152     Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
6153         << DeletedFuncs;
6154     return None;
6155   }
6156 
6157   if (FD->isDefaulted()) {
6158     Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
6159         << DefaultedFuncs;
6160     return None;
6161   }
6162 
6163   if (FD->isConstexpr()) {
6164     Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
6165         << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
6166     return None;
6167   }
6168 
6169   // Check general compatibility.
6170   if (areMultiversionVariantFunctionsCompatible(
6171           FD, NewFD, PartialDiagnostic::NullDiagnostic(),
6172           PartialDiagnosticAt(SourceLocation(),
6173                               PartialDiagnostic::NullDiagnostic()),
6174           PartialDiagnosticAt(
6175               VariantRef->getExprLoc(),
6176               PDiag(diag::err_omp_declare_variant_doesnt_support)),
6177           PartialDiagnosticAt(VariantRef->getExprLoc(),
6178                               PDiag(diag::err_omp_declare_variant_diff)
6179                                   << FD->getLocation()),
6180           /*TemplatesSupported=*/true, /*ConstexprSupported=*/false,
6181           /*CLinkageMayDiffer=*/true))
6182     return None;
6183   return std::make_pair(FD, cast<Expr>(DRE));
6184 }
6185 
6186 void Sema::ActOnOpenMPDeclareVariantDirective(FunctionDecl *FD,
6187                                               Expr *VariantRef,
6188                                               OMPTraitInfo &TI,
6189                                               SourceRange SR) {
6190   auto *NewAttr =
6191       OMPDeclareVariantAttr::CreateImplicit(Context, VariantRef, &TI, SR);
6192   FD->addAttr(NewAttr);
6193 }
6194 
6195 StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
6196                                               Stmt *AStmt,
6197                                               SourceLocation StartLoc,
6198                                               SourceLocation EndLoc) {
6199   if (!AStmt)
6200     return StmtError();
6201 
6202   auto *CS = cast<CapturedStmt>(AStmt);
6203   // 1.2.2 OpenMP Language Terminology
6204   // Structured block - An executable statement with a single entry at the
6205   // top and a single exit at the bottom.
6206   // The point of exit cannot be a branch out of the structured block.
6207   // longjmp() and throw() must not violate the entry/exit criteria.
6208   CS->getCapturedDecl()->setNothrow();
6209 
6210   setFunctionHasBranchProtectedScope();
6211 
6212   return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
6213                                       DSAStack->getTaskgroupReductionRef(),
6214                                       DSAStack->isCancelRegion());
6215 }
6216 
6217 namespace {
6218 /// Iteration space of a single for loop.
6219 struct LoopIterationSpace final {
6220   /// True if the condition operator is the strict compare operator (<, > or
6221   /// !=).
6222   bool IsStrictCompare = false;
6223   /// Condition of the loop.
6224   Expr *PreCond = nullptr;
6225   /// This expression calculates the number of iterations in the loop.
6226   /// It is always possible to calculate it before starting the loop.
6227   Expr *NumIterations = nullptr;
6228   /// The loop counter variable.
6229   Expr *CounterVar = nullptr;
6230   /// Private loop counter variable.
6231   Expr *PrivateCounterVar = nullptr;
6232   /// This is initializer for the initial value of #CounterVar.
6233   Expr *CounterInit = nullptr;
6234   /// This is step for the #CounterVar used to generate its update:
6235   /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration.
6236   Expr *CounterStep = nullptr;
6237   /// Should step be subtracted?
6238   bool Subtract = false;
6239   /// Source range of the loop init.
6240   SourceRange InitSrcRange;
6241   /// Source range of the loop condition.
6242   SourceRange CondSrcRange;
6243   /// Source range of the loop increment.
6244   SourceRange IncSrcRange;
6245   /// Minimum value that can have the loop control variable. Used to support
6246   /// non-rectangular loops. Applied only for LCV with the non-iterator types,
6247   /// since only such variables can be used in non-loop invariant expressions.
6248   Expr *MinValue = nullptr;
6249   /// Maximum value that can have the loop control variable. Used to support
6250   /// non-rectangular loops. Applied only for LCV with the non-iterator type,
6251   /// since only such variables can be used in non-loop invariant expressions.
6252   Expr *MaxValue = nullptr;
6253   /// true, if the lower bound depends on the outer loop control var.
6254   bool IsNonRectangularLB = false;
6255   /// true, if the upper bound depends on the outer loop control var.
6256   bool IsNonRectangularUB = false;
6257   /// Index of the loop this loop depends on and forms non-rectangular loop
6258   /// nest.
6259   unsigned LoopDependentIdx = 0;
6260   /// Final condition for the non-rectangular loop nest support. It is used to
6261   /// check that the number of iterations for this particular counter must be
6262   /// finished.
6263   Expr *FinalCondition = nullptr;
6264 };
6265 
6266 /// Helper class for checking canonical form of the OpenMP loops and
6267 /// extracting iteration space of each loop in the loop nest, that will be used
6268 /// for IR generation.
6269 class OpenMPIterationSpaceChecker {
6270   /// Reference to Sema.
6271   Sema &SemaRef;
6272   /// Data-sharing stack.
6273   DSAStackTy &Stack;
6274   /// A location for diagnostics (when there is no some better location).
6275   SourceLocation DefaultLoc;
6276   /// A location for diagnostics (when increment is not compatible).
6277   SourceLocation ConditionLoc;
6278   /// A source location for referring to loop init later.
6279   SourceRange InitSrcRange;
6280   /// A source location for referring to condition later.
6281   SourceRange ConditionSrcRange;
6282   /// A source location for referring to increment later.
6283   SourceRange IncrementSrcRange;
6284   /// Loop variable.
6285   ValueDecl *LCDecl = nullptr;
6286   /// Reference to loop variable.
6287   Expr *LCRef = nullptr;
6288   /// Lower bound (initializer for the var).
6289   Expr *LB = nullptr;
6290   /// Upper bound.
6291   Expr *UB = nullptr;
6292   /// Loop step (increment).
6293   Expr *Step = nullptr;
6294   /// This flag is true when condition is one of:
6295   ///   Var <  UB
6296   ///   Var <= UB
6297   ///   UB  >  Var
6298   ///   UB  >= Var
6299   /// This will have no value when the condition is !=
6300   llvm::Optional<bool> TestIsLessOp;
6301   /// This flag is true when condition is strict ( < or > ).
6302   bool TestIsStrictOp = false;
6303   /// This flag is true when step is subtracted on each iteration.
6304   bool SubtractStep = false;
6305   /// The outer loop counter this loop depends on (if any).
6306   const ValueDecl *DepDecl = nullptr;
6307   /// Contains number of loop (starts from 1) on which loop counter init
6308   /// expression of this loop depends on.
6309   Optional<unsigned> InitDependOnLC;
6310   /// Contains number of loop (starts from 1) on which loop counter condition
6311   /// expression of this loop depends on.
6312   Optional<unsigned> CondDependOnLC;
6313   /// Checks if the provide statement depends on the loop counter.
6314   Optional<unsigned> doesDependOnLoopCounter(const Stmt *S, bool IsInitializer);
6315   /// Original condition required for checking of the exit condition for
6316   /// non-rectangular loop.
6317   Expr *Condition = nullptr;
6318 
6319 public:
6320   OpenMPIterationSpaceChecker(Sema &SemaRef, DSAStackTy &Stack,
6321                               SourceLocation DefaultLoc)
6322       : SemaRef(SemaRef), Stack(Stack), DefaultLoc(DefaultLoc),
6323         ConditionLoc(DefaultLoc) {}
6324   /// Check init-expr for canonical loop form and save loop counter
6325   /// variable - #Var and its initialization value - #LB.
6326   bool checkAndSetInit(Stmt *S, bool EmitDiags = true);
6327   /// Check test-expr for canonical form, save upper-bound (#UB), flags
6328   /// for less/greater and for strict/non-strict comparison.
6329   bool checkAndSetCond(Expr *S);
6330   /// Check incr-expr for canonical loop form and return true if it
6331   /// does not conform, otherwise save loop step (#Step).
6332   bool checkAndSetInc(Expr *S);
6333   /// Return the loop counter variable.
6334   ValueDecl *getLoopDecl() const { return LCDecl; }
6335   /// Return the reference expression to loop counter variable.
6336   Expr *getLoopDeclRefExpr() const { return LCRef; }
6337   /// Source range of the loop init.
6338   SourceRange getInitSrcRange() const { return InitSrcRange; }
6339   /// Source range of the loop condition.
6340   SourceRange getConditionSrcRange() const { return ConditionSrcRange; }
6341   /// Source range of the loop increment.
6342   SourceRange getIncrementSrcRange() const { return IncrementSrcRange; }
6343   /// True if the step should be subtracted.
6344   bool shouldSubtractStep() const { return SubtractStep; }
6345   /// True, if the compare operator is strict (<, > or !=).
6346   bool isStrictTestOp() const { return TestIsStrictOp; }
6347   /// Build the expression to calculate the number of iterations.
6348   Expr *buildNumIterations(
6349       Scope *S, ArrayRef<LoopIterationSpace> ResultIterSpaces, bool LimitedType,
6350       llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
6351   /// Build the precondition expression for the loops.
6352   Expr *
6353   buildPreCond(Scope *S, Expr *Cond,
6354                llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
6355   /// Build reference expression to the counter be used for codegen.
6356   DeclRefExpr *
6357   buildCounterVar(llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
6358                   DSAStackTy &DSA) const;
6359   /// Build reference expression to the private counter be used for
6360   /// codegen.
6361   Expr *buildPrivateCounterVar() const;
6362   /// Build initialization of the counter be used for codegen.
6363   Expr *buildCounterInit() const;
6364   /// Build step of the counter be used for codegen.
6365   Expr *buildCounterStep() const;
6366   /// Build loop data with counter value for depend clauses in ordered
6367   /// directives.
6368   Expr *
6369   buildOrderedLoopData(Scope *S, Expr *Counter,
6370                        llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
6371                        SourceLocation Loc, Expr *Inc = nullptr,
6372                        OverloadedOperatorKind OOK = OO_Amp);
6373   /// Builds the minimum value for the loop counter.
6374   std::pair<Expr *, Expr *> buildMinMaxValues(
6375       Scope *S, llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
6376   /// Builds final condition for the non-rectangular loops.
6377   Expr *buildFinalCondition(Scope *S) const;
6378   /// Return true if any expression is dependent.
6379   bool dependent() const;
6380   /// Returns true if the initializer forms non-rectangular loop.
6381   bool doesInitDependOnLC() const { return InitDependOnLC.hasValue(); }
6382   /// Returns true if the condition forms non-rectangular loop.
6383   bool doesCondDependOnLC() const { return CondDependOnLC.hasValue(); }
6384   /// Returns index of the loop we depend on (starting from 1), or 0 otherwise.
6385   unsigned getLoopDependentIdx() const {
6386     return InitDependOnLC.getValueOr(CondDependOnLC.getValueOr(0));
6387   }
6388 
6389 private:
6390   /// Check the right-hand side of an assignment in the increment
6391   /// expression.
6392   bool checkAndSetIncRHS(Expr *RHS);
6393   /// Helper to set loop counter variable and its initializer.
6394   bool setLCDeclAndLB(ValueDecl *NewLCDecl, Expr *NewDeclRefExpr, Expr *NewLB,
6395                       bool EmitDiags);
6396   /// Helper to set upper bound.
6397   bool setUB(Expr *NewUB, llvm::Optional<bool> LessOp, bool StrictOp,
6398              SourceRange SR, SourceLocation SL);
6399   /// Helper to set loop increment.
6400   bool setStep(Expr *NewStep, bool Subtract);
6401 };
6402 
6403 bool OpenMPIterationSpaceChecker::dependent() const {
6404   if (!LCDecl) {
6405     assert(!LB && !UB && !Step);
6406     return false;
6407   }
6408   return LCDecl->getType()->isDependentType() ||
6409          (LB && LB->isValueDependent()) || (UB && UB->isValueDependent()) ||
6410          (Step && Step->isValueDependent());
6411 }
6412 
6413 bool OpenMPIterationSpaceChecker::setLCDeclAndLB(ValueDecl *NewLCDecl,
6414                                                  Expr *NewLCRefExpr,
6415                                                  Expr *NewLB, bool EmitDiags) {
6416   // State consistency checking to ensure correct usage.
6417   assert(LCDecl == nullptr && LB == nullptr && LCRef == nullptr &&
6418          UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
6419   if (!NewLCDecl || !NewLB)
6420     return true;
6421   LCDecl = getCanonicalDecl(NewLCDecl);
6422   LCRef = NewLCRefExpr;
6423   if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB))
6424     if (const CXXConstructorDecl *Ctor = CE->getConstructor())
6425       if ((Ctor->isCopyOrMoveConstructor() ||
6426            Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
6427           CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
6428         NewLB = CE->getArg(0)->IgnoreParenImpCasts();
6429   LB = NewLB;
6430   if (EmitDiags)
6431     InitDependOnLC = doesDependOnLoopCounter(LB, /*IsInitializer=*/true);
6432   return false;
6433 }
6434 
6435 bool OpenMPIterationSpaceChecker::setUB(Expr *NewUB,
6436                                         llvm::Optional<bool> LessOp,
6437                                         bool StrictOp, SourceRange SR,
6438                                         SourceLocation SL) {
6439   // State consistency checking to ensure correct usage.
6440   assert(LCDecl != nullptr && LB != nullptr && UB == nullptr &&
6441          Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
6442   if (!NewUB)
6443     return true;
6444   UB = NewUB;
6445   if (LessOp)
6446     TestIsLessOp = LessOp;
6447   TestIsStrictOp = StrictOp;
6448   ConditionSrcRange = SR;
6449   ConditionLoc = SL;
6450   CondDependOnLC = doesDependOnLoopCounter(UB, /*IsInitializer=*/false);
6451   return false;
6452 }
6453 
6454 bool OpenMPIterationSpaceChecker::setStep(Expr *NewStep, bool Subtract) {
6455   // State consistency checking to ensure correct usage.
6456   assert(LCDecl != nullptr && LB != nullptr && Step == nullptr);
6457   if (!NewStep)
6458     return true;
6459   if (!NewStep->isValueDependent()) {
6460     // Check that the step is integer expression.
6461     SourceLocation StepLoc = NewStep->getBeginLoc();
6462     ExprResult Val = SemaRef.PerformOpenMPImplicitIntegerConversion(
6463         StepLoc, getExprAsWritten(NewStep));
6464     if (Val.isInvalid())
6465       return true;
6466     NewStep = Val.get();
6467 
6468     // OpenMP [2.6, Canonical Loop Form, Restrictions]
6469     //  If test-expr is of form var relational-op b and relational-op is < or
6470     //  <= then incr-expr must cause var to increase on each iteration of the
6471     //  loop. If test-expr is of form var relational-op b and relational-op is
6472     //  > or >= then incr-expr must cause var to decrease on each iteration of
6473     //  the loop.
6474     //  If test-expr is of form b relational-op var and relational-op is < or
6475     //  <= then incr-expr must cause var to decrease on each iteration of the
6476     //  loop. If test-expr is of form b relational-op var and relational-op is
6477     //  > or >= then incr-expr must cause var to increase on each iteration of
6478     //  the loop.
6479     llvm::APSInt Result;
6480     bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context);
6481     bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation();
6482     bool IsConstNeg =
6483         IsConstant && Result.isSigned() && (Subtract != Result.isNegative());
6484     bool IsConstPos =
6485         IsConstant && Result.isSigned() && (Subtract == Result.isNegative());
6486     bool IsConstZero = IsConstant && !Result.getBoolValue();
6487 
6488     // != with increment is treated as <; != with decrement is treated as >
6489     if (!TestIsLessOp.hasValue())
6490       TestIsLessOp = IsConstPos || (IsUnsigned && !Subtract);
6491     if (UB && (IsConstZero ||
6492                (TestIsLessOp.getValue() ?
6493                   (IsConstNeg || (IsUnsigned && Subtract)) :
6494                   (IsConstPos || (IsUnsigned && !Subtract))))) {
6495       SemaRef.Diag(NewStep->getExprLoc(),
6496                    diag::err_omp_loop_incr_not_compatible)
6497           << LCDecl << TestIsLessOp.getValue() << NewStep->getSourceRange();
6498       SemaRef.Diag(ConditionLoc,
6499                    diag::note_omp_loop_cond_requres_compatible_incr)
6500           << TestIsLessOp.getValue() << ConditionSrcRange;
6501       return true;
6502     }
6503     if (TestIsLessOp.getValue() == Subtract) {
6504       NewStep =
6505           SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus, NewStep)
6506               .get();
6507       Subtract = !Subtract;
6508     }
6509   }
6510 
6511   Step = NewStep;
6512   SubtractStep = Subtract;
6513   return false;
6514 }
6515 
6516 namespace {
6517 /// Checker for the non-rectangular loops. Checks if the initializer or
6518 /// condition expression references loop counter variable.
6519 class LoopCounterRefChecker final
6520     : public ConstStmtVisitor<LoopCounterRefChecker, bool> {
6521   Sema &SemaRef;
6522   DSAStackTy &Stack;
6523   const ValueDecl *CurLCDecl = nullptr;
6524   const ValueDecl *DepDecl = nullptr;
6525   const ValueDecl *PrevDepDecl = nullptr;
6526   bool IsInitializer = true;
6527   unsigned BaseLoopId = 0;
6528   bool checkDecl(const Expr *E, const ValueDecl *VD) {
6529     if (getCanonicalDecl(VD) == getCanonicalDecl(CurLCDecl)) {
6530       SemaRef.Diag(E->getExprLoc(), diag::err_omp_stmt_depends_on_loop_counter)
6531           << (IsInitializer ? 0 : 1);
6532       return false;
6533     }
6534     const auto &&Data = Stack.isLoopControlVariable(VD);
6535     // OpenMP, 2.9.1 Canonical Loop Form, Restrictions.
6536     // The type of the loop iterator on which we depend may not have a random
6537     // access iterator type.
6538     if (Data.first && VD->getType()->isRecordType()) {
6539       SmallString<128> Name;
6540       llvm::raw_svector_ostream OS(Name);
6541       VD->getNameForDiagnostic(OS, SemaRef.getPrintingPolicy(),
6542                                /*Qualified=*/true);
6543       SemaRef.Diag(E->getExprLoc(),
6544                    diag::err_omp_wrong_dependency_iterator_type)
6545           << OS.str();
6546       SemaRef.Diag(VD->getLocation(), diag::note_previous_decl) << VD;
6547       return false;
6548     }
6549     if (Data.first &&
6550         (DepDecl || (PrevDepDecl &&
6551                      getCanonicalDecl(VD) != getCanonicalDecl(PrevDepDecl)))) {
6552       if (!DepDecl && PrevDepDecl)
6553         DepDecl = PrevDepDecl;
6554       SmallString<128> Name;
6555       llvm::raw_svector_ostream OS(Name);
6556       DepDecl->getNameForDiagnostic(OS, SemaRef.getPrintingPolicy(),
6557                                     /*Qualified=*/true);
6558       SemaRef.Diag(E->getExprLoc(),
6559                    diag::err_omp_invariant_or_linear_dependency)
6560           << OS.str();
6561       return false;
6562     }
6563     if (Data.first) {
6564       DepDecl = VD;
6565       BaseLoopId = Data.first;
6566     }
6567     return Data.first;
6568   }
6569 
6570 public:
6571   bool VisitDeclRefExpr(const DeclRefExpr *E) {
6572     const ValueDecl *VD = E->getDecl();
6573     if (isa<VarDecl>(VD))
6574       return checkDecl(E, VD);
6575     return false;
6576   }
6577   bool VisitMemberExpr(const MemberExpr *E) {
6578     if (isa<CXXThisExpr>(E->getBase()->IgnoreParens())) {
6579       const ValueDecl *VD = E->getMemberDecl();
6580       if (isa<VarDecl>(VD) || isa<FieldDecl>(VD))
6581         return checkDecl(E, VD);
6582     }
6583     return false;
6584   }
6585   bool VisitStmt(const Stmt *S) {
6586     bool Res = false;
6587     for (const Stmt *Child : S->children())
6588       Res = (Child && Visit(Child)) || Res;
6589     return Res;
6590   }
6591   explicit LoopCounterRefChecker(Sema &SemaRef, DSAStackTy &Stack,
6592                                  const ValueDecl *CurLCDecl, bool IsInitializer,
6593                                  const ValueDecl *PrevDepDecl = nullptr)
6594       : SemaRef(SemaRef), Stack(Stack), CurLCDecl(CurLCDecl),
6595         PrevDepDecl(PrevDepDecl), IsInitializer(IsInitializer) {}
6596   unsigned getBaseLoopId() const {
6597     assert(CurLCDecl && "Expected loop dependency.");
6598     return BaseLoopId;
6599   }
6600   const ValueDecl *getDepDecl() const {
6601     assert(CurLCDecl && "Expected loop dependency.");
6602     return DepDecl;
6603   }
6604 };
6605 } // namespace
6606 
6607 Optional<unsigned>
6608 OpenMPIterationSpaceChecker::doesDependOnLoopCounter(const Stmt *S,
6609                                                      bool IsInitializer) {
6610   // Check for the non-rectangular loops.
6611   LoopCounterRefChecker LoopStmtChecker(SemaRef, Stack, LCDecl, IsInitializer,
6612                                         DepDecl);
6613   if (LoopStmtChecker.Visit(S)) {
6614     DepDecl = LoopStmtChecker.getDepDecl();
6615     return LoopStmtChecker.getBaseLoopId();
6616   }
6617   return llvm::None;
6618 }
6619 
6620 bool OpenMPIterationSpaceChecker::checkAndSetInit(Stmt *S, bool EmitDiags) {
6621   // Check init-expr for canonical loop form and save loop counter
6622   // variable - #Var and its initialization value - #LB.
6623   // OpenMP [2.6] Canonical loop form. init-expr may be one of the following:
6624   //   var = lb
6625   //   integer-type var = lb
6626   //   random-access-iterator-type var = lb
6627   //   pointer-type var = lb
6628   //
6629   if (!S) {
6630     if (EmitDiags) {
6631       SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init);
6632     }
6633     return true;
6634   }
6635   if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
6636     if (!ExprTemp->cleanupsHaveSideEffects())
6637       S = ExprTemp->getSubExpr();
6638 
6639   InitSrcRange = S->getSourceRange();
6640   if (Expr *E = dyn_cast<Expr>(S))
6641     S = E->IgnoreParens();
6642   if (auto *BO = dyn_cast<BinaryOperator>(S)) {
6643     if (BO->getOpcode() == BO_Assign) {
6644       Expr *LHS = BO->getLHS()->IgnoreParens();
6645       if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
6646         if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
6647           if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
6648             return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
6649                                   EmitDiags);
6650         return setLCDeclAndLB(DRE->getDecl(), DRE, BO->getRHS(), EmitDiags);
6651       }
6652       if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
6653         if (ME->isArrow() &&
6654             isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
6655           return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
6656                                 EmitDiags);
6657       }
6658     }
6659   } else if (auto *DS = dyn_cast<DeclStmt>(S)) {
6660     if (DS->isSingleDecl()) {
6661       if (auto *Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) {
6662         if (Var->hasInit() && !Var->getType()->isReferenceType()) {
6663           // Accept non-canonical init form here but emit ext. warning.
6664           if (Var->getInitStyle() != VarDecl::CInit && EmitDiags)
6665             SemaRef.Diag(S->getBeginLoc(),
6666                          diag::ext_omp_loop_not_canonical_init)
6667                 << S->getSourceRange();
6668           return setLCDeclAndLB(
6669               Var,
6670               buildDeclRefExpr(SemaRef, Var,
6671                                Var->getType().getNonReferenceType(),
6672                                DS->getBeginLoc()),
6673               Var->getInit(), EmitDiags);
6674         }
6675       }
6676     }
6677   } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
6678     if (CE->getOperator() == OO_Equal) {
6679       Expr *LHS = CE->getArg(0);
6680       if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
6681         if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
6682           if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
6683             return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
6684                                   EmitDiags);
6685         return setLCDeclAndLB(DRE->getDecl(), DRE, CE->getArg(1), EmitDiags);
6686       }
6687       if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
6688         if (ME->isArrow() &&
6689             isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
6690           return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
6691                                 EmitDiags);
6692       }
6693     }
6694   }
6695 
6696   if (dependent() || SemaRef.CurContext->isDependentContext())
6697     return false;
6698   if (EmitDiags) {
6699     SemaRef.Diag(S->getBeginLoc(), diag::err_omp_loop_not_canonical_init)
6700         << S->getSourceRange();
6701   }
6702   return true;
6703 }
6704 
6705 /// Ignore parenthesizes, implicit casts, copy constructor and return the
6706 /// variable (which may be the loop variable) if possible.
6707 static const ValueDecl *getInitLCDecl(const Expr *E) {
6708   if (!E)
6709     return nullptr;
6710   E = getExprAsWritten(E);
6711   if (const auto *CE = dyn_cast_or_null<CXXConstructExpr>(E))
6712     if (const CXXConstructorDecl *Ctor = CE->getConstructor())
6713       if ((Ctor->isCopyOrMoveConstructor() ||
6714            Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
6715           CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
6716         E = CE->getArg(0)->IgnoreParenImpCasts();
6717   if (const auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) {
6718     if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
6719       return getCanonicalDecl(VD);
6720   }
6721   if (const auto *ME = dyn_cast_or_null<MemberExpr>(E))
6722     if (ME->isArrow() && isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
6723       return getCanonicalDecl(ME->getMemberDecl());
6724   return nullptr;
6725 }
6726 
6727 bool OpenMPIterationSpaceChecker::checkAndSetCond(Expr *S) {
6728   // Check test-expr for canonical form, save upper-bound UB, flags for
6729   // less/greater and for strict/non-strict comparison.
6730   // OpenMP [2.9] Canonical loop form. Test-expr may be one of the following:
6731   //   var relational-op b
6732   //   b relational-op var
6733   //
6734   bool IneqCondIsCanonical = SemaRef.getLangOpts().OpenMP >= 50;
6735   if (!S) {
6736     SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond)
6737         << (IneqCondIsCanonical ? 1 : 0) << LCDecl;
6738     return true;
6739   }
6740   Condition = S;
6741   S = getExprAsWritten(S);
6742   SourceLocation CondLoc = S->getBeginLoc();
6743   if (auto *BO = dyn_cast<BinaryOperator>(S)) {
6744     if (BO->isRelationalOp()) {
6745       if (getInitLCDecl(BO->getLHS()) == LCDecl)
6746         return setUB(BO->getRHS(),
6747                      (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE),
6748                      (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
6749                      BO->getSourceRange(), BO->getOperatorLoc());
6750       if (getInitLCDecl(BO->getRHS()) == LCDecl)
6751         return setUB(BO->getLHS(),
6752                      (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE),
6753                      (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
6754                      BO->getSourceRange(), BO->getOperatorLoc());
6755     } else if (IneqCondIsCanonical && BO->getOpcode() == BO_NE)
6756       return setUB(
6757           getInitLCDecl(BO->getLHS()) == LCDecl ? BO->getRHS() : BO->getLHS(),
6758           /*LessOp=*/llvm::None,
6759           /*StrictOp=*/true, BO->getSourceRange(), BO->getOperatorLoc());
6760   } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
6761     if (CE->getNumArgs() == 2) {
6762       auto Op = CE->getOperator();
6763       switch (Op) {
6764       case OO_Greater:
6765       case OO_GreaterEqual:
6766       case OO_Less:
6767       case OO_LessEqual:
6768         if (getInitLCDecl(CE->getArg(0)) == LCDecl)
6769           return setUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual,
6770                        Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
6771                        CE->getOperatorLoc());
6772         if (getInitLCDecl(CE->getArg(1)) == LCDecl)
6773           return setUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual,
6774                        Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
6775                        CE->getOperatorLoc());
6776         break;
6777       case OO_ExclaimEqual:
6778         if (IneqCondIsCanonical)
6779           return setUB(getInitLCDecl(CE->getArg(0)) == LCDecl ? CE->getArg(1)
6780                                                               : CE->getArg(0),
6781                        /*LessOp=*/llvm::None,
6782                        /*StrictOp=*/true, CE->getSourceRange(),
6783                        CE->getOperatorLoc());
6784         break;
6785       default:
6786         break;
6787       }
6788     }
6789   }
6790   if (dependent() || SemaRef.CurContext->isDependentContext())
6791     return false;
6792   SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond)
6793       << (IneqCondIsCanonical ? 1 : 0) << S->getSourceRange() << LCDecl;
6794   return true;
6795 }
6796 
6797 bool OpenMPIterationSpaceChecker::checkAndSetIncRHS(Expr *RHS) {
6798   // RHS of canonical loop form increment can be:
6799   //   var + incr
6800   //   incr + var
6801   //   var - incr
6802   //
6803   RHS = RHS->IgnoreParenImpCasts();
6804   if (auto *BO = dyn_cast<BinaryOperator>(RHS)) {
6805     if (BO->isAdditiveOp()) {
6806       bool IsAdd = BO->getOpcode() == BO_Add;
6807       if (getInitLCDecl(BO->getLHS()) == LCDecl)
6808         return setStep(BO->getRHS(), !IsAdd);
6809       if (IsAdd && getInitLCDecl(BO->getRHS()) == LCDecl)
6810         return setStep(BO->getLHS(), /*Subtract=*/false);
6811     }
6812   } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(RHS)) {
6813     bool IsAdd = CE->getOperator() == OO_Plus;
6814     if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) {
6815       if (getInitLCDecl(CE->getArg(0)) == LCDecl)
6816         return setStep(CE->getArg(1), !IsAdd);
6817       if (IsAdd && getInitLCDecl(CE->getArg(1)) == LCDecl)
6818         return setStep(CE->getArg(0), /*Subtract=*/false);
6819     }
6820   }
6821   if (dependent() || SemaRef.CurContext->isDependentContext())
6822     return false;
6823   SemaRef.Diag(RHS->getBeginLoc(), diag::err_omp_loop_not_canonical_incr)
6824       << RHS->getSourceRange() << LCDecl;
6825   return true;
6826 }
6827 
6828 bool OpenMPIterationSpaceChecker::checkAndSetInc(Expr *S) {
6829   // Check incr-expr for canonical loop form and return true if it
6830   // does not conform.
6831   // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
6832   //   ++var
6833   //   var++
6834   //   --var
6835   //   var--
6836   //   var += incr
6837   //   var -= incr
6838   //   var = var + incr
6839   //   var = incr + var
6840   //   var = var - incr
6841   //
6842   if (!S) {
6843     SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << LCDecl;
6844     return true;
6845   }
6846   if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
6847     if (!ExprTemp->cleanupsHaveSideEffects())
6848       S = ExprTemp->getSubExpr();
6849 
6850   IncrementSrcRange = S->getSourceRange();
6851   S = S->IgnoreParens();
6852   if (auto *UO = dyn_cast<UnaryOperator>(S)) {
6853     if (UO->isIncrementDecrementOp() &&
6854         getInitLCDecl(UO->getSubExpr()) == LCDecl)
6855       return setStep(SemaRef
6856                          .ActOnIntegerConstant(UO->getBeginLoc(),
6857                                                (UO->isDecrementOp() ? -1 : 1))
6858                          .get(),
6859                      /*Subtract=*/false);
6860   } else if (auto *BO = dyn_cast<BinaryOperator>(S)) {
6861     switch (BO->getOpcode()) {
6862     case BO_AddAssign:
6863     case BO_SubAssign:
6864       if (getInitLCDecl(BO->getLHS()) == LCDecl)
6865         return setStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign);
6866       break;
6867     case BO_Assign:
6868       if (getInitLCDecl(BO->getLHS()) == LCDecl)
6869         return checkAndSetIncRHS(BO->getRHS());
6870       break;
6871     default:
6872       break;
6873     }
6874   } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
6875     switch (CE->getOperator()) {
6876     case OO_PlusPlus:
6877     case OO_MinusMinus:
6878       if (getInitLCDecl(CE->getArg(0)) == LCDecl)
6879         return setStep(SemaRef
6880                            .ActOnIntegerConstant(
6881                                CE->getBeginLoc(),
6882                                ((CE->getOperator() == OO_MinusMinus) ? -1 : 1))
6883                            .get(),
6884                        /*Subtract=*/false);
6885       break;
6886     case OO_PlusEqual:
6887     case OO_MinusEqual:
6888       if (getInitLCDecl(CE->getArg(0)) == LCDecl)
6889         return setStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual);
6890       break;
6891     case OO_Equal:
6892       if (getInitLCDecl(CE->getArg(0)) == LCDecl)
6893         return checkAndSetIncRHS(CE->getArg(1));
6894       break;
6895     default:
6896       break;
6897     }
6898   }
6899   if (dependent() || SemaRef.CurContext->isDependentContext())
6900     return false;
6901   SemaRef.Diag(S->getBeginLoc(), diag::err_omp_loop_not_canonical_incr)
6902       << S->getSourceRange() << LCDecl;
6903   return true;
6904 }
6905 
6906 static ExprResult
6907 tryBuildCapture(Sema &SemaRef, Expr *Capture,
6908                 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
6909   if (SemaRef.CurContext->isDependentContext() || Capture->containsErrors())
6910     return Capture;
6911   if (Capture->isEvaluatable(SemaRef.Context, Expr::SE_AllowSideEffects))
6912     return SemaRef.PerformImplicitConversion(
6913         Capture->IgnoreImpCasts(), Capture->getType(), Sema::AA_Converting,
6914         /*AllowExplicit=*/true);
6915   auto I = Captures.find(Capture);
6916   if (I != Captures.end())
6917     return buildCapture(SemaRef, Capture, I->second);
6918   DeclRefExpr *Ref = nullptr;
6919   ExprResult Res = buildCapture(SemaRef, Capture, Ref);
6920   Captures[Capture] = Ref;
6921   return Res;
6922 }
6923 
6924 /// Calculate number of iterations, transforming to unsigned, if number of
6925 /// iterations may be larger than the original type.
6926 static Expr *
6927 calculateNumIters(Sema &SemaRef, Scope *S, SourceLocation DefaultLoc,
6928                   Expr *Lower, Expr *Upper, Expr *Step, QualType LCTy,
6929                   bool TestIsStrictOp, bool RoundToStep,
6930                   llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
6931   ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures);
6932   if (!NewStep.isUsable())
6933     return nullptr;
6934   llvm::APSInt LRes, URes, SRes;
6935   bool IsLowerConst = Lower->isIntegerConstantExpr(LRes, SemaRef.Context);
6936   bool IsStepConst = Step->isIntegerConstantExpr(SRes, SemaRef.Context);
6937   bool NoNeedToConvert = IsLowerConst && !RoundToStep &&
6938                          ((!TestIsStrictOp && LRes.isNonNegative()) ||
6939                           (TestIsStrictOp && LRes.isStrictlyPositive()));
6940   bool NeedToReorganize = false;
6941   // Check if any subexpressions in Lower -Step [+ 1] lead to overflow.
6942   if (!NoNeedToConvert && IsLowerConst &&
6943       (TestIsStrictOp || (RoundToStep && IsStepConst))) {
6944     NoNeedToConvert = true;
6945     if (RoundToStep) {
6946       unsigned BW = LRes.getBitWidth() > SRes.getBitWidth()
6947                         ? LRes.getBitWidth()
6948                         : SRes.getBitWidth();
6949       LRes = LRes.extend(BW + 1);
6950       LRes.setIsSigned(true);
6951       SRes = SRes.extend(BW + 1);
6952       SRes.setIsSigned(true);
6953       LRes -= SRes;
6954       NoNeedToConvert = LRes.trunc(BW).extend(BW + 1) == LRes;
6955       LRes = LRes.trunc(BW);
6956     }
6957     if (TestIsStrictOp) {
6958       unsigned BW = LRes.getBitWidth();
6959       LRes = LRes.extend(BW + 1);
6960       LRes.setIsSigned(true);
6961       ++LRes;
6962       NoNeedToConvert =
6963           NoNeedToConvert && LRes.trunc(BW).extend(BW + 1) == LRes;
6964       // truncate to the original bitwidth.
6965       LRes = LRes.trunc(BW);
6966     }
6967     NeedToReorganize = NoNeedToConvert;
6968   }
6969   bool IsUpperConst = Upper->isIntegerConstantExpr(URes, SemaRef.Context);
6970   if (NoNeedToConvert && IsLowerConst && IsUpperConst &&
6971       (!RoundToStep || IsStepConst)) {
6972     unsigned BW = LRes.getBitWidth() > URes.getBitWidth() ? LRes.getBitWidth()
6973                                                           : URes.getBitWidth();
6974     LRes = LRes.extend(BW + 1);
6975     LRes.setIsSigned(true);
6976     URes = URes.extend(BW + 1);
6977     URes.setIsSigned(true);
6978     URes -= LRes;
6979     NoNeedToConvert = URes.trunc(BW).extend(BW + 1) == URes;
6980     NeedToReorganize = NoNeedToConvert;
6981   }
6982   // If the boundaries are not constant or (Lower - Step [+ 1]) is not constant
6983   // or less than zero (Upper - (Lower - Step [+ 1]) may overflow) - promote to
6984   // unsigned.
6985   if ((!NoNeedToConvert || (LRes.isNegative() && !IsUpperConst)) &&
6986       !LCTy->isDependentType() && LCTy->isIntegerType()) {
6987     QualType LowerTy = Lower->getType();
6988     QualType UpperTy = Upper->getType();
6989     uint64_t LowerSize = SemaRef.Context.getTypeSize(LowerTy);
6990     uint64_t UpperSize = SemaRef.Context.getTypeSize(UpperTy);
6991     if ((LowerSize <= UpperSize && UpperTy->hasSignedIntegerRepresentation()) ||
6992         (LowerSize > UpperSize && LowerTy->hasSignedIntegerRepresentation())) {
6993       QualType CastType = SemaRef.Context.getIntTypeForBitwidth(
6994           LowerSize > UpperSize ? LowerSize : UpperSize, /*Signed=*/0);
6995       Upper =
6996           SemaRef
6997               .PerformImplicitConversion(
6998                   SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Upper).get(),
6999                   CastType, Sema::AA_Converting)
7000               .get();
7001       Lower = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Lower).get();
7002       NewStep = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, NewStep.get());
7003     }
7004   }
7005   if (!Lower || !Upper || NewStep.isInvalid())
7006     return nullptr;
7007 
7008   ExprResult Diff;
7009   // If need to reorganize, then calculate the form as Upper - (Lower - Step [+
7010   // 1]).
7011   if (NeedToReorganize) {
7012     Diff = Lower;
7013 
7014     if (RoundToStep) {
7015       // Lower - Step
7016       Diff =
7017           SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Diff.get(), NewStep.get());
7018       if (!Diff.isUsable())
7019         return nullptr;
7020     }
7021 
7022     // Lower - Step [+ 1]
7023     if (TestIsStrictOp)
7024       Diff = SemaRef.BuildBinOp(
7025           S, DefaultLoc, BO_Add, Diff.get(),
7026           SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
7027     if (!Diff.isUsable())
7028       return nullptr;
7029 
7030     Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
7031     if (!Diff.isUsable())
7032       return nullptr;
7033 
7034     // Upper - (Lower - Step [+ 1]).
7035     Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Diff.get());
7036     if (!Diff.isUsable())
7037       return nullptr;
7038   } else {
7039     Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
7040 
7041     if (!Diff.isUsable() && LCTy->getAsCXXRecordDecl()) {
7042       // BuildBinOp already emitted error, this one is to point user to upper
7043       // and lower bound, and to tell what is passed to 'operator-'.
7044       SemaRef.Diag(Upper->getBeginLoc(), diag::err_omp_loop_diff_cxx)
7045           << Upper->getSourceRange() << Lower->getSourceRange();
7046       return nullptr;
7047     }
7048 
7049     if (!Diff.isUsable())
7050       return nullptr;
7051 
7052     // Upper - Lower [- 1]
7053     if (TestIsStrictOp)
7054       Diff = SemaRef.BuildBinOp(
7055           S, DefaultLoc, BO_Sub, Diff.get(),
7056           SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
7057     if (!Diff.isUsable())
7058       return nullptr;
7059 
7060     if (RoundToStep) {
7061       // Upper - Lower [- 1] + Step
7062       Diff =
7063           SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get());
7064       if (!Diff.isUsable())
7065         return nullptr;
7066     }
7067   }
7068 
7069   // Parentheses (for dumping/debugging purposes only).
7070   Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
7071   if (!Diff.isUsable())
7072     return nullptr;
7073 
7074   // (Upper - Lower [- 1] + Step) / Step or (Upper - Lower) / Step
7075   Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
7076   if (!Diff.isUsable())
7077     return nullptr;
7078 
7079   return Diff.get();
7080 }
7081 
7082 /// Build the expression to calculate the number of iterations.
7083 Expr *OpenMPIterationSpaceChecker::buildNumIterations(
7084     Scope *S, ArrayRef<LoopIterationSpace> ResultIterSpaces, bool LimitedType,
7085     llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
7086   QualType VarType = LCDecl->getType().getNonReferenceType();
7087   if (!VarType->isIntegerType() && !VarType->isPointerType() &&
7088       !SemaRef.getLangOpts().CPlusPlus)
7089     return nullptr;
7090   Expr *LBVal = LB;
7091   Expr *UBVal = UB;
7092   // LB = TestIsLessOp.getValue() ? min(LB(MinVal), LB(MaxVal)) :
7093   // max(LB(MinVal), LB(MaxVal))
7094   if (InitDependOnLC) {
7095     const LoopIterationSpace &IS =
7096         ResultIterSpaces[ResultIterSpaces.size() - 1 -
7097                          InitDependOnLC.getValueOr(
7098                              CondDependOnLC.getValueOr(0))];
7099     if (!IS.MinValue || !IS.MaxValue)
7100       return nullptr;
7101     // OuterVar = Min
7102     ExprResult MinValue =
7103         SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MinValue);
7104     if (!MinValue.isUsable())
7105       return nullptr;
7106 
7107     ExprResult LBMinVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign,
7108                                              IS.CounterVar, MinValue.get());
7109     if (!LBMinVal.isUsable())
7110       return nullptr;
7111     // OuterVar = Min, LBVal
7112     LBMinVal =
7113         SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, LBMinVal.get(), LBVal);
7114     if (!LBMinVal.isUsable())
7115       return nullptr;
7116     // (OuterVar = Min, LBVal)
7117     LBMinVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, LBMinVal.get());
7118     if (!LBMinVal.isUsable())
7119       return nullptr;
7120 
7121     // OuterVar = Max
7122     ExprResult MaxValue =
7123         SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MaxValue);
7124     if (!MaxValue.isUsable())
7125       return nullptr;
7126 
7127     ExprResult LBMaxVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign,
7128                                              IS.CounterVar, MaxValue.get());
7129     if (!LBMaxVal.isUsable())
7130       return nullptr;
7131     // OuterVar = Max, LBVal
7132     LBMaxVal =
7133         SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, LBMaxVal.get(), LBVal);
7134     if (!LBMaxVal.isUsable())
7135       return nullptr;
7136     // (OuterVar = Max, LBVal)
7137     LBMaxVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, LBMaxVal.get());
7138     if (!LBMaxVal.isUsable())
7139       return nullptr;
7140 
7141     Expr *LBMin = tryBuildCapture(SemaRef, LBMinVal.get(), Captures).get();
7142     Expr *LBMax = tryBuildCapture(SemaRef, LBMaxVal.get(), Captures).get();
7143     if (!LBMin || !LBMax)
7144       return nullptr;
7145     // LB(MinVal) < LB(MaxVal)
7146     ExprResult MinLessMaxRes =
7147         SemaRef.BuildBinOp(S, DefaultLoc, BO_LT, LBMin, LBMax);
7148     if (!MinLessMaxRes.isUsable())
7149       return nullptr;
7150     Expr *MinLessMax =
7151         tryBuildCapture(SemaRef, MinLessMaxRes.get(), Captures).get();
7152     if (!MinLessMax)
7153       return nullptr;
7154     if (TestIsLessOp.getValue()) {
7155       // LB(MinVal) < LB(MaxVal) ? LB(MinVal) : LB(MaxVal) - min(LB(MinVal),
7156       // LB(MaxVal))
7157       ExprResult MinLB = SemaRef.ActOnConditionalOp(DefaultLoc, DefaultLoc,
7158                                                     MinLessMax, LBMin, LBMax);
7159       if (!MinLB.isUsable())
7160         return nullptr;
7161       LBVal = MinLB.get();
7162     } else {
7163       // LB(MinVal) < LB(MaxVal) ? LB(MaxVal) : LB(MinVal) - max(LB(MinVal),
7164       // LB(MaxVal))
7165       ExprResult MaxLB = SemaRef.ActOnConditionalOp(DefaultLoc, DefaultLoc,
7166                                                     MinLessMax, LBMax, LBMin);
7167       if (!MaxLB.isUsable())
7168         return nullptr;
7169       LBVal = MaxLB.get();
7170     }
7171   }
7172   // UB = TestIsLessOp.getValue() ? max(UB(MinVal), UB(MaxVal)) :
7173   // min(UB(MinVal), UB(MaxVal))
7174   if (CondDependOnLC) {
7175     const LoopIterationSpace &IS =
7176         ResultIterSpaces[ResultIterSpaces.size() - 1 -
7177                          InitDependOnLC.getValueOr(
7178                              CondDependOnLC.getValueOr(0))];
7179     if (!IS.MinValue || !IS.MaxValue)
7180       return nullptr;
7181     // OuterVar = Min
7182     ExprResult MinValue =
7183         SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MinValue);
7184     if (!MinValue.isUsable())
7185       return nullptr;
7186 
7187     ExprResult UBMinVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign,
7188                                              IS.CounterVar, MinValue.get());
7189     if (!UBMinVal.isUsable())
7190       return nullptr;
7191     // OuterVar = Min, UBVal
7192     UBMinVal =
7193         SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, UBMinVal.get(), UBVal);
7194     if (!UBMinVal.isUsable())
7195       return nullptr;
7196     // (OuterVar = Min, UBVal)
7197     UBMinVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, UBMinVal.get());
7198     if (!UBMinVal.isUsable())
7199       return nullptr;
7200 
7201     // OuterVar = Max
7202     ExprResult MaxValue =
7203         SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MaxValue);
7204     if (!MaxValue.isUsable())
7205       return nullptr;
7206 
7207     ExprResult UBMaxVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign,
7208                                              IS.CounterVar, MaxValue.get());
7209     if (!UBMaxVal.isUsable())
7210       return nullptr;
7211     // OuterVar = Max, UBVal
7212     UBMaxVal =
7213         SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, UBMaxVal.get(), UBVal);
7214     if (!UBMaxVal.isUsable())
7215       return nullptr;
7216     // (OuterVar = Max, UBVal)
7217     UBMaxVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, UBMaxVal.get());
7218     if (!UBMaxVal.isUsable())
7219       return nullptr;
7220 
7221     Expr *UBMin = tryBuildCapture(SemaRef, UBMinVal.get(), Captures).get();
7222     Expr *UBMax = tryBuildCapture(SemaRef, UBMaxVal.get(), Captures).get();
7223     if (!UBMin || !UBMax)
7224       return nullptr;
7225     // UB(MinVal) > UB(MaxVal)
7226     ExprResult MinGreaterMaxRes =
7227         SemaRef.BuildBinOp(S, DefaultLoc, BO_GT, UBMin, UBMax);
7228     if (!MinGreaterMaxRes.isUsable())
7229       return nullptr;
7230     Expr *MinGreaterMax =
7231         tryBuildCapture(SemaRef, MinGreaterMaxRes.get(), Captures).get();
7232     if (!MinGreaterMax)
7233       return nullptr;
7234     if (TestIsLessOp.getValue()) {
7235       // UB(MinVal) > UB(MaxVal) ? UB(MinVal) : UB(MaxVal) - max(UB(MinVal),
7236       // UB(MaxVal))
7237       ExprResult MaxUB = SemaRef.ActOnConditionalOp(
7238           DefaultLoc, DefaultLoc, MinGreaterMax, UBMin, UBMax);
7239       if (!MaxUB.isUsable())
7240         return nullptr;
7241       UBVal = MaxUB.get();
7242     } else {
7243       // UB(MinVal) > UB(MaxVal) ? UB(MaxVal) : UB(MinVal) - min(UB(MinVal),
7244       // UB(MaxVal))
7245       ExprResult MinUB = SemaRef.ActOnConditionalOp(
7246           DefaultLoc, DefaultLoc, MinGreaterMax, UBMax, UBMin);
7247       if (!MinUB.isUsable())
7248         return nullptr;
7249       UBVal = MinUB.get();
7250     }
7251   }
7252   Expr *UBExpr = TestIsLessOp.getValue() ? UBVal : LBVal;
7253   Expr *LBExpr = TestIsLessOp.getValue() ? LBVal : UBVal;
7254   Expr *Upper = tryBuildCapture(SemaRef, UBExpr, Captures).get();
7255   Expr *Lower = tryBuildCapture(SemaRef, LBExpr, Captures).get();
7256   if (!Upper || !Lower)
7257     return nullptr;
7258 
7259   ExprResult Diff =
7260       calculateNumIters(SemaRef, S, DefaultLoc, Lower, Upper, Step, VarType,
7261                         TestIsStrictOp, /*RoundToStep=*/true, Captures);
7262   if (!Diff.isUsable())
7263     return nullptr;
7264 
7265   // OpenMP runtime requires 32-bit or 64-bit loop variables.
7266   QualType Type = Diff.get()->getType();
7267   ASTContext &C = SemaRef.Context;
7268   bool UseVarType = VarType->hasIntegerRepresentation() &&
7269                     C.getTypeSize(Type) > C.getTypeSize(VarType);
7270   if (!Type->isIntegerType() || UseVarType) {
7271     unsigned NewSize =
7272         UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type);
7273     bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation()
7274                                : Type->hasSignedIntegerRepresentation();
7275     Type = C.getIntTypeForBitwidth(NewSize, IsSigned);
7276     if (!SemaRef.Context.hasSameType(Diff.get()->getType(), Type)) {
7277       Diff = SemaRef.PerformImplicitConversion(
7278           Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true);
7279       if (!Diff.isUsable())
7280         return nullptr;
7281     }
7282   }
7283   if (LimitedType) {
7284     unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32;
7285     if (NewSize != C.getTypeSize(Type)) {
7286       if (NewSize < C.getTypeSize(Type)) {
7287         assert(NewSize == 64 && "incorrect loop var size");
7288         SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var)
7289             << InitSrcRange << ConditionSrcRange;
7290       }
7291       QualType NewType = C.getIntTypeForBitwidth(
7292           NewSize, Type->hasSignedIntegerRepresentation() ||
7293                        C.getTypeSize(Type) < NewSize);
7294       if (!SemaRef.Context.hasSameType(Diff.get()->getType(), NewType)) {
7295         Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType,
7296                                                  Sema::AA_Converting, true);
7297         if (!Diff.isUsable())
7298           return nullptr;
7299       }
7300     }
7301   }
7302 
7303   return Diff.get();
7304 }
7305 
7306 std::pair<Expr *, Expr *> OpenMPIterationSpaceChecker::buildMinMaxValues(
7307     Scope *S, llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
7308   // Do not build for iterators, they cannot be used in non-rectangular loop
7309   // nests.
7310   if (LCDecl->getType()->isRecordType())
7311     return std::make_pair(nullptr, nullptr);
7312   // If we subtract, the min is in the condition, otherwise the min is in the
7313   // init value.
7314   Expr *MinExpr = nullptr;
7315   Expr *MaxExpr = nullptr;
7316   Expr *LBExpr = TestIsLessOp.getValue() ? LB : UB;
7317   Expr *UBExpr = TestIsLessOp.getValue() ? UB : LB;
7318   bool LBNonRect = TestIsLessOp.getValue() ? InitDependOnLC.hasValue()
7319                                            : CondDependOnLC.hasValue();
7320   bool UBNonRect = TestIsLessOp.getValue() ? CondDependOnLC.hasValue()
7321                                            : InitDependOnLC.hasValue();
7322   Expr *Lower =
7323       LBNonRect ? LBExpr : tryBuildCapture(SemaRef, LBExpr, Captures).get();
7324   Expr *Upper =
7325       UBNonRect ? UBExpr : tryBuildCapture(SemaRef, UBExpr, Captures).get();
7326   if (!Upper || !Lower)
7327     return std::make_pair(nullptr, nullptr);
7328 
7329   if (TestIsLessOp.getValue())
7330     MinExpr = Lower;
7331   else
7332     MaxExpr = Upper;
7333 
7334   // Build minimum/maximum value based on number of iterations.
7335   QualType VarType = LCDecl->getType().getNonReferenceType();
7336 
7337   ExprResult Diff =
7338       calculateNumIters(SemaRef, S, DefaultLoc, Lower, Upper, Step, VarType,
7339                         TestIsStrictOp, /*RoundToStep=*/false, Captures);
7340   if (!Diff.isUsable())
7341     return std::make_pair(nullptr, nullptr);
7342 
7343   // ((Upper - Lower [- 1]) / Step) * Step
7344   // Parentheses (for dumping/debugging purposes only).
7345   Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
7346   if (!Diff.isUsable())
7347     return std::make_pair(nullptr, nullptr);
7348 
7349   ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures);
7350   if (!NewStep.isUsable())
7351     return std::make_pair(nullptr, nullptr);
7352   Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Mul, Diff.get(), NewStep.get());
7353   if (!Diff.isUsable())
7354     return std::make_pair(nullptr, nullptr);
7355 
7356   // Parentheses (for dumping/debugging purposes only).
7357   Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
7358   if (!Diff.isUsable())
7359     return std::make_pair(nullptr, nullptr);
7360 
7361   // Convert to the ptrdiff_t, if original type is pointer.
7362   if (VarType->isAnyPointerType() &&
7363       !SemaRef.Context.hasSameType(
7364           Diff.get()->getType(),
7365           SemaRef.Context.getUnsignedPointerDiffType())) {
7366     Diff = SemaRef.PerformImplicitConversion(
7367         Diff.get(), SemaRef.Context.getUnsignedPointerDiffType(),
7368         Sema::AA_Converting, /*AllowExplicit=*/true);
7369   }
7370   if (!Diff.isUsable())
7371     return std::make_pair(nullptr, nullptr);
7372 
7373   if (TestIsLessOp.getValue()) {
7374     // MinExpr = Lower;
7375     // MaxExpr = Lower + (((Upper - Lower [- 1]) / Step) * Step)
7376     Diff = SemaRef.BuildBinOp(
7377         S, DefaultLoc, BO_Add,
7378         SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Lower).get(),
7379         Diff.get());
7380     if (!Diff.isUsable())
7381       return std::make_pair(nullptr, nullptr);
7382   } else {
7383     // MaxExpr = Upper;
7384     // MinExpr = Upper - (((Upper - Lower [- 1]) / Step) * Step)
7385     Diff = SemaRef.BuildBinOp(
7386         S, DefaultLoc, BO_Sub,
7387         SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Upper).get(),
7388         Diff.get());
7389     if (!Diff.isUsable())
7390       return std::make_pair(nullptr, nullptr);
7391   }
7392 
7393   // Convert to the original type.
7394   if (SemaRef.Context.hasSameType(Diff.get()->getType(), VarType))
7395     Diff = SemaRef.PerformImplicitConversion(Diff.get(), VarType,
7396                                              Sema::AA_Converting,
7397                                              /*AllowExplicit=*/true);
7398   if (!Diff.isUsable())
7399     return std::make_pair(nullptr, nullptr);
7400 
7401   Diff = SemaRef.ActOnFinishFullExpr(Diff.get(), /*DiscardedValue=*/false);
7402   if (!Diff.isUsable())
7403     return std::make_pair(nullptr, nullptr);
7404 
7405   if (TestIsLessOp.getValue())
7406     MaxExpr = Diff.get();
7407   else
7408     MinExpr = Diff.get();
7409 
7410   return std::make_pair(MinExpr, MaxExpr);
7411 }
7412 
7413 Expr *OpenMPIterationSpaceChecker::buildFinalCondition(Scope *S) const {
7414   if (InitDependOnLC || CondDependOnLC)
7415     return Condition;
7416   return nullptr;
7417 }
7418 
7419 Expr *OpenMPIterationSpaceChecker::buildPreCond(
7420     Scope *S, Expr *Cond,
7421     llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
7422   // Do not build a precondition when the condition/initialization is dependent
7423   // to prevent pessimistic early loop exit.
7424   // TODO: this can be improved by calculating min/max values but not sure that
7425   // it will be very effective.
7426   if (CondDependOnLC || InitDependOnLC)
7427     return SemaRef.PerformImplicitConversion(
7428         SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get(),
7429         SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
7430         /*AllowExplicit=*/true).get();
7431 
7432   // Try to build LB <op> UB, where <op> is <, >, <=, or >=.
7433   Sema::TentativeAnalysisScope Trap(SemaRef);
7434 
7435   ExprResult NewLB = tryBuildCapture(SemaRef, LB, Captures);
7436   ExprResult NewUB = tryBuildCapture(SemaRef, UB, Captures);
7437   if (!NewLB.isUsable() || !NewUB.isUsable())
7438     return nullptr;
7439 
7440   ExprResult CondExpr =
7441       SemaRef.BuildBinOp(S, DefaultLoc,
7442                          TestIsLessOp.getValue() ?
7443                            (TestIsStrictOp ? BO_LT : BO_LE) :
7444                            (TestIsStrictOp ? BO_GT : BO_GE),
7445                          NewLB.get(), NewUB.get());
7446   if (CondExpr.isUsable()) {
7447     if (!SemaRef.Context.hasSameUnqualifiedType(CondExpr.get()->getType(),
7448                                                 SemaRef.Context.BoolTy))
7449       CondExpr = SemaRef.PerformImplicitConversion(
7450           CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
7451           /*AllowExplicit=*/true);
7452   }
7453 
7454   // Otherwise use original loop condition and evaluate it in runtime.
7455   return CondExpr.isUsable() ? CondExpr.get() : Cond;
7456 }
7457 
7458 /// Build reference expression to the counter be used for codegen.
7459 DeclRefExpr *OpenMPIterationSpaceChecker::buildCounterVar(
7460     llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
7461     DSAStackTy &DSA) const {
7462   auto *VD = dyn_cast<VarDecl>(LCDecl);
7463   if (!VD) {
7464     VD = SemaRef.isOpenMPCapturedDecl(LCDecl);
7465     DeclRefExpr *Ref = buildDeclRefExpr(
7466         SemaRef, VD, VD->getType().getNonReferenceType(), DefaultLoc);
7467     const DSAStackTy::DSAVarData Data =
7468         DSA.getTopDSA(LCDecl, /*FromParent=*/false);
7469     // If the loop control decl is explicitly marked as private, do not mark it
7470     // as captured again.
7471     if (!isOpenMPPrivate(Data.CKind) || !Data.RefExpr)
7472       Captures.insert(std::make_pair(LCRef, Ref));
7473     return Ref;
7474   }
7475   return cast<DeclRefExpr>(LCRef);
7476 }
7477 
7478 Expr *OpenMPIterationSpaceChecker::buildPrivateCounterVar() const {
7479   if (LCDecl && !LCDecl->isInvalidDecl()) {
7480     QualType Type = LCDecl->getType().getNonReferenceType();
7481     VarDecl *PrivateVar = buildVarDecl(
7482         SemaRef, DefaultLoc, Type, LCDecl->getName(),
7483         LCDecl->hasAttrs() ? &LCDecl->getAttrs() : nullptr,
7484         isa<VarDecl>(LCDecl)
7485             ? buildDeclRefExpr(SemaRef, cast<VarDecl>(LCDecl), Type, DefaultLoc)
7486             : nullptr);
7487     if (PrivateVar->isInvalidDecl())
7488       return nullptr;
7489     return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc);
7490   }
7491   return nullptr;
7492 }
7493 
7494 /// Build initialization of the counter to be used for codegen.
7495 Expr *OpenMPIterationSpaceChecker::buildCounterInit() const { return LB; }
7496 
7497 /// Build step of the counter be used for codegen.
7498 Expr *OpenMPIterationSpaceChecker::buildCounterStep() const { return Step; }
7499 
7500 Expr *OpenMPIterationSpaceChecker::buildOrderedLoopData(
7501     Scope *S, Expr *Counter,
7502     llvm::MapVector<const Expr *, DeclRefExpr *> &Captures, SourceLocation Loc,
7503     Expr *Inc, OverloadedOperatorKind OOK) {
7504   Expr *Cnt = SemaRef.DefaultLvalueConversion(Counter).get();
7505   if (!Cnt)
7506     return nullptr;
7507   if (Inc) {
7508     assert((OOK == OO_Plus || OOK == OO_Minus) &&
7509            "Expected only + or - operations for depend clauses.");
7510     BinaryOperatorKind BOK = (OOK == OO_Plus) ? BO_Add : BO_Sub;
7511     Cnt = SemaRef.BuildBinOp(S, Loc, BOK, Cnt, Inc).get();
7512     if (!Cnt)
7513       return nullptr;
7514   }
7515   QualType VarType = LCDecl->getType().getNonReferenceType();
7516   if (!VarType->isIntegerType() && !VarType->isPointerType() &&
7517       !SemaRef.getLangOpts().CPlusPlus)
7518     return nullptr;
7519   // Upper - Lower
7520   Expr *Upper = TestIsLessOp.getValue()
7521                     ? Cnt
7522                     : tryBuildCapture(SemaRef, LB, Captures).get();
7523   Expr *Lower = TestIsLessOp.getValue()
7524                     ? tryBuildCapture(SemaRef, LB, Captures).get()
7525                     : Cnt;
7526   if (!Upper || !Lower)
7527     return nullptr;
7528 
7529   ExprResult Diff = calculateNumIters(SemaRef, S, DefaultLoc, Lower, Upper,
7530                                       Step, VarType, /*TestIsStrictOp=*/false,
7531                                       /*RoundToStep=*/false, Captures);
7532   if (!Diff.isUsable())
7533     return nullptr;
7534 
7535   return Diff.get();
7536 }
7537 } // namespace
7538 
7539 void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) {
7540   assert(getLangOpts().OpenMP && "OpenMP is not active.");
7541   assert(Init && "Expected loop in canonical form.");
7542   unsigned AssociatedLoops = DSAStack->getAssociatedLoops();
7543   if (AssociatedLoops > 0 &&
7544       isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
7545     DSAStack->loopStart();
7546     OpenMPIterationSpaceChecker ISC(*this, *DSAStack, ForLoc);
7547     if (!ISC.checkAndSetInit(Init, /*EmitDiags=*/false)) {
7548       if (ValueDecl *D = ISC.getLoopDecl()) {
7549         auto *VD = dyn_cast<VarDecl>(D);
7550         DeclRefExpr *PrivateRef = nullptr;
7551         if (!VD) {
7552           if (VarDecl *Private = isOpenMPCapturedDecl(D)) {
7553             VD = Private;
7554           } else {
7555             PrivateRef = buildCapture(*this, D, ISC.getLoopDeclRefExpr(),
7556                                       /*WithInit=*/false);
7557             VD = cast<VarDecl>(PrivateRef->getDecl());
7558           }
7559         }
7560         DSAStack->addLoopControlVariable(D, VD);
7561         const Decl *LD = DSAStack->getPossiblyLoopCunter();
7562         if (LD != D->getCanonicalDecl()) {
7563           DSAStack->resetPossibleLoopCounter();
7564           if (auto *Var = dyn_cast_or_null<VarDecl>(LD))
7565             MarkDeclarationsReferencedInExpr(
7566                 buildDeclRefExpr(*this, const_cast<VarDecl *>(Var),
7567                                  Var->getType().getNonLValueExprType(Context),
7568                                  ForLoc, /*RefersToCapture=*/true));
7569         }
7570         OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
7571         // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables
7572         // Referenced in a Construct, C/C++]. The loop iteration variable in the
7573         // associated for-loop of a simd construct with just one associated
7574         // for-loop may be listed in a linear clause with a constant-linear-step
7575         // that is the increment of the associated for-loop. The loop iteration
7576         // variable(s) in the associated for-loop(s) of a for or parallel for
7577         // construct may be listed in a private or lastprivate clause.
7578         DSAStackTy::DSAVarData DVar =
7579             DSAStack->getTopDSA(D, /*FromParent=*/false);
7580         // If LoopVarRefExpr is nullptr it means the corresponding loop variable
7581         // is declared in the loop and it is predetermined as a private.
7582         Expr *LoopDeclRefExpr = ISC.getLoopDeclRefExpr();
7583         OpenMPClauseKind PredeterminedCKind =
7584             isOpenMPSimdDirective(DKind)
7585                 ? (DSAStack->hasMutipleLoops() ? OMPC_lastprivate : OMPC_linear)
7586                 : OMPC_private;
7587         if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
7588               DVar.CKind != PredeterminedCKind && DVar.RefExpr &&
7589               (LangOpts.OpenMP <= 45 || (DVar.CKind != OMPC_lastprivate &&
7590                                          DVar.CKind != OMPC_private))) ||
7591              ((isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop ||
7592                DKind == OMPD_master_taskloop ||
7593                DKind == OMPD_parallel_master_taskloop ||
7594                isOpenMPDistributeDirective(DKind)) &&
7595               !isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
7596               DVar.CKind != OMPC_private && DVar.CKind != OMPC_lastprivate)) &&
7597             (DVar.CKind != OMPC_private || DVar.RefExpr)) {
7598           Diag(Init->getBeginLoc(), diag::err_omp_loop_var_dsa)
7599               << getOpenMPClauseName(DVar.CKind)
7600               << getOpenMPDirectiveName(DKind)
7601               << getOpenMPClauseName(PredeterminedCKind);
7602           if (DVar.RefExpr == nullptr)
7603             DVar.CKind = PredeterminedCKind;
7604           reportOriginalDsa(*this, DSAStack, D, DVar,
7605                             /*IsLoopIterVar=*/true);
7606         } else if (LoopDeclRefExpr) {
7607           // Make the loop iteration variable private (for worksharing
7608           // constructs), linear (for simd directives with the only one
7609           // associated loop) or lastprivate (for simd directives with several
7610           // collapsed or ordered loops).
7611           if (DVar.CKind == OMPC_unknown)
7612             DSAStack->addDSA(D, LoopDeclRefExpr, PredeterminedCKind,
7613                              PrivateRef);
7614         }
7615       }
7616     }
7617     DSAStack->setAssociatedLoops(AssociatedLoops - 1);
7618   }
7619 }
7620 
7621 /// Called on a for stmt to check and extract its iteration space
7622 /// for further processing (such as collapsing).
7623 static bool checkOpenMPIterationSpace(
7624     OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA,
7625     unsigned CurrentNestedLoopCount, unsigned NestedLoopCount,
7626     unsigned TotalNestedLoopCount, Expr *CollapseLoopCountExpr,
7627     Expr *OrderedLoopCountExpr,
7628     Sema::VarsWithInheritedDSAType &VarsWithImplicitDSA,
7629     llvm::MutableArrayRef<LoopIterationSpace> ResultIterSpaces,
7630     llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
7631   // OpenMP [2.9.1, Canonical Loop Form]
7632   //   for (init-expr; test-expr; incr-expr) structured-block
7633   //   for (range-decl: range-expr) structured-block
7634   auto *For = dyn_cast_or_null<ForStmt>(S);
7635   auto *CXXFor = dyn_cast_or_null<CXXForRangeStmt>(S);
7636   // Ranged for is supported only in OpenMP 5.0.
7637   if (!For && (SemaRef.LangOpts.OpenMP <= 45 || !CXXFor)) {
7638     SemaRef.Diag(S->getBeginLoc(), diag::err_omp_not_for)
7639         << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr)
7640         << getOpenMPDirectiveName(DKind) << TotalNestedLoopCount
7641         << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount;
7642     if (TotalNestedLoopCount > 1) {
7643       if (CollapseLoopCountExpr && OrderedLoopCountExpr)
7644         SemaRef.Diag(DSA.getConstructLoc(),
7645                      diag::note_omp_collapse_ordered_expr)
7646             << 2 << CollapseLoopCountExpr->getSourceRange()
7647             << OrderedLoopCountExpr->getSourceRange();
7648       else if (CollapseLoopCountExpr)
7649         SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
7650                      diag::note_omp_collapse_ordered_expr)
7651             << 0 << CollapseLoopCountExpr->getSourceRange();
7652       else
7653         SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
7654                      diag::note_omp_collapse_ordered_expr)
7655             << 1 << OrderedLoopCountExpr->getSourceRange();
7656     }
7657     return true;
7658   }
7659   assert(((For && For->getBody()) || (CXXFor && CXXFor->getBody())) &&
7660          "No loop body.");
7661 
7662   OpenMPIterationSpaceChecker ISC(SemaRef, DSA,
7663                                   For ? For->getForLoc() : CXXFor->getForLoc());
7664 
7665   // Check init.
7666   Stmt *Init = For ? For->getInit() : CXXFor->getBeginStmt();
7667   if (ISC.checkAndSetInit(Init))
7668     return true;
7669 
7670   bool HasErrors = false;
7671 
7672   // Check loop variable's type.
7673   if (ValueDecl *LCDecl = ISC.getLoopDecl()) {
7674     // OpenMP [2.6, Canonical Loop Form]
7675     // Var is one of the following:
7676     //   A variable of signed or unsigned integer type.
7677     //   For C++, a variable of a random access iterator type.
7678     //   For C, a variable of a pointer type.
7679     QualType VarType = LCDecl->getType().getNonReferenceType();
7680     if (!VarType->isDependentType() && !VarType->isIntegerType() &&
7681         !VarType->isPointerType() &&
7682         !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) {
7683       SemaRef.Diag(Init->getBeginLoc(), diag::err_omp_loop_variable_type)
7684           << SemaRef.getLangOpts().CPlusPlus;
7685       HasErrors = true;
7686     }
7687 
7688     // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in
7689     // a Construct
7690     // The loop iteration variable(s) in the associated for-loop(s) of a for or
7691     // parallel for construct is (are) private.
7692     // The loop iteration variable in the associated for-loop of a simd
7693     // construct with just one associated for-loop is linear with a
7694     // constant-linear-step that is the increment of the associated for-loop.
7695     // Exclude loop var from the list of variables with implicitly defined data
7696     // sharing attributes.
7697     VarsWithImplicitDSA.erase(LCDecl);
7698 
7699     assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars");
7700 
7701     // Check test-expr.
7702     HasErrors |= ISC.checkAndSetCond(For ? For->getCond() : CXXFor->getCond());
7703 
7704     // Check incr-expr.
7705     HasErrors |= ISC.checkAndSetInc(For ? For->getInc() : CXXFor->getInc());
7706   }
7707 
7708   if (ISC.dependent() || SemaRef.CurContext->isDependentContext() || HasErrors)
7709     return HasErrors;
7710 
7711   // Build the loop's iteration space representation.
7712   ResultIterSpaces[CurrentNestedLoopCount].PreCond = ISC.buildPreCond(
7713       DSA.getCurScope(), For ? For->getCond() : CXXFor->getCond(), Captures);
7714   ResultIterSpaces[CurrentNestedLoopCount].NumIterations =
7715       ISC.buildNumIterations(DSA.getCurScope(), ResultIterSpaces,
7716                              (isOpenMPWorksharingDirective(DKind) ||
7717                               isOpenMPTaskLoopDirective(DKind) ||
7718                               isOpenMPDistributeDirective(DKind)),
7719                              Captures);
7720   ResultIterSpaces[CurrentNestedLoopCount].CounterVar =
7721       ISC.buildCounterVar(Captures, DSA);
7722   ResultIterSpaces[CurrentNestedLoopCount].PrivateCounterVar =
7723       ISC.buildPrivateCounterVar();
7724   ResultIterSpaces[CurrentNestedLoopCount].CounterInit = ISC.buildCounterInit();
7725   ResultIterSpaces[CurrentNestedLoopCount].CounterStep = ISC.buildCounterStep();
7726   ResultIterSpaces[CurrentNestedLoopCount].InitSrcRange = ISC.getInitSrcRange();
7727   ResultIterSpaces[CurrentNestedLoopCount].CondSrcRange =
7728       ISC.getConditionSrcRange();
7729   ResultIterSpaces[CurrentNestedLoopCount].IncSrcRange =
7730       ISC.getIncrementSrcRange();
7731   ResultIterSpaces[CurrentNestedLoopCount].Subtract = ISC.shouldSubtractStep();
7732   ResultIterSpaces[CurrentNestedLoopCount].IsStrictCompare =
7733       ISC.isStrictTestOp();
7734   std::tie(ResultIterSpaces[CurrentNestedLoopCount].MinValue,
7735            ResultIterSpaces[CurrentNestedLoopCount].MaxValue) =
7736       ISC.buildMinMaxValues(DSA.getCurScope(), Captures);
7737   ResultIterSpaces[CurrentNestedLoopCount].FinalCondition =
7738       ISC.buildFinalCondition(DSA.getCurScope());
7739   ResultIterSpaces[CurrentNestedLoopCount].IsNonRectangularLB =
7740       ISC.doesInitDependOnLC();
7741   ResultIterSpaces[CurrentNestedLoopCount].IsNonRectangularUB =
7742       ISC.doesCondDependOnLC();
7743   ResultIterSpaces[CurrentNestedLoopCount].LoopDependentIdx =
7744       ISC.getLoopDependentIdx();
7745 
7746   HasErrors |=
7747       (ResultIterSpaces[CurrentNestedLoopCount].PreCond == nullptr ||
7748        ResultIterSpaces[CurrentNestedLoopCount].NumIterations == nullptr ||
7749        ResultIterSpaces[CurrentNestedLoopCount].CounterVar == nullptr ||
7750        ResultIterSpaces[CurrentNestedLoopCount].PrivateCounterVar == nullptr ||
7751        ResultIterSpaces[CurrentNestedLoopCount].CounterInit == nullptr ||
7752        ResultIterSpaces[CurrentNestedLoopCount].CounterStep == nullptr);
7753   if (!HasErrors && DSA.isOrderedRegion()) {
7754     if (DSA.getOrderedRegionParam().second->getNumForLoops()) {
7755       if (CurrentNestedLoopCount <
7756           DSA.getOrderedRegionParam().second->getLoopNumIterations().size()) {
7757         DSA.getOrderedRegionParam().second->setLoopNumIterations(
7758             CurrentNestedLoopCount,
7759             ResultIterSpaces[CurrentNestedLoopCount].NumIterations);
7760         DSA.getOrderedRegionParam().second->setLoopCounter(
7761             CurrentNestedLoopCount,
7762             ResultIterSpaces[CurrentNestedLoopCount].CounterVar);
7763       }
7764     }
7765     for (auto &Pair : DSA.getDoacrossDependClauses()) {
7766       if (CurrentNestedLoopCount >= Pair.first->getNumLoops()) {
7767         // Erroneous case - clause has some problems.
7768         continue;
7769       }
7770       if (Pair.first->getDependencyKind() == OMPC_DEPEND_sink &&
7771           Pair.second.size() <= CurrentNestedLoopCount) {
7772         // Erroneous case - clause has some problems.
7773         Pair.first->setLoopData(CurrentNestedLoopCount, nullptr);
7774         continue;
7775       }
7776       Expr *CntValue;
7777       if (Pair.first->getDependencyKind() == OMPC_DEPEND_source)
7778         CntValue = ISC.buildOrderedLoopData(
7779             DSA.getCurScope(),
7780             ResultIterSpaces[CurrentNestedLoopCount].CounterVar, Captures,
7781             Pair.first->getDependencyLoc());
7782       else
7783         CntValue = ISC.buildOrderedLoopData(
7784             DSA.getCurScope(),
7785             ResultIterSpaces[CurrentNestedLoopCount].CounterVar, Captures,
7786             Pair.first->getDependencyLoc(),
7787             Pair.second[CurrentNestedLoopCount].first,
7788             Pair.second[CurrentNestedLoopCount].second);
7789       Pair.first->setLoopData(CurrentNestedLoopCount, CntValue);
7790     }
7791   }
7792 
7793   return HasErrors;
7794 }
7795 
7796 /// Build 'VarRef = Start.
7797 static ExprResult
7798 buildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
7799                  ExprResult Start, bool IsNonRectangularLB,
7800                  llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
7801   // Build 'VarRef = Start.
7802   ExprResult NewStart = IsNonRectangularLB
7803                             ? Start.get()
7804                             : tryBuildCapture(SemaRef, Start.get(), Captures);
7805   if (!NewStart.isUsable())
7806     return ExprError();
7807   if (!SemaRef.Context.hasSameType(NewStart.get()->getType(),
7808                                    VarRef.get()->getType())) {
7809     NewStart = SemaRef.PerformImplicitConversion(
7810         NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting,
7811         /*AllowExplicit=*/true);
7812     if (!NewStart.isUsable())
7813       return ExprError();
7814   }
7815 
7816   ExprResult Init =
7817       SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
7818   return Init;
7819 }
7820 
7821 /// Build 'VarRef = Start + Iter * Step'.
7822 static ExprResult buildCounterUpdate(
7823     Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
7824     ExprResult Start, ExprResult Iter, ExprResult Step, bool Subtract,
7825     bool IsNonRectangularLB,
7826     llvm::MapVector<const Expr *, DeclRefExpr *> *Captures = nullptr) {
7827   // Add parentheses (for debugging purposes only).
7828   Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get());
7829   if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() ||
7830       !Step.isUsable())
7831     return ExprError();
7832 
7833   ExprResult NewStep = Step;
7834   if (Captures)
7835     NewStep = tryBuildCapture(SemaRef, Step.get(), *Captures);
7836   if (NewStep.isInvalid())
7837     return ExprError();
7838   ExprResult Update =
7839       SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get());
7840   if (!Update.isUsable())
7841     return ExprError();
7842 
7843   // Try to build 'VarRef = Start, VarRef (+|-)= Iter * Step' or
7844   // 'VarRef = Start (+|-) Iter * Step'.
7845   if (!Start.isUsable())
7846     return ExprError();
7847   ExprResult NewStart = SemaRef.ActOnParenExpr(Loc, Loc, Start.get());
7848   if (!NewStart.isUsable())
7849     return ExprError();
7850   if (Captures && !IsNonRectangularLB)
7851     NewStart = tryBuildCapture(SemaRef, Start.get(), *Captures);
7852   if (NewStart.isInvalid())
7853     return ExprError();
7854 
7855   // First attempt: try to build 'VarRef = Start, VarRef += Iter * Step'.
7856   ExprResult SavedUpdate = Update;
7857   ExprResult UpdateVal;
7858   if (VarRef.get()->getType()->isOverloadableType() ||
7859       NewStart.get()->getType()->isOverloadableType() ||
7860       Update.get()->getType()->isOverloadableType()) {
7861     Sema::TentativeAnalysisScope Trap(SemaRef);
7862 
7863     Update =
7864         SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
7865     if (Update.isUsable()) {
7866       UpdateVal =
7867           SemaRef.BuildBinOp(S, Loc, Subtract ? BO_SubAssign : BO_AddAssign,
7868                              VarRef.get(), SavedUpdate.get());
7869       if (UpdateVal.isUsable()) {
7870         Update = SemaRef.CreateBuiltinBinOp(Loc, BO_Comma, Update.get(),
7871                                             UpdateVal.get());
7872       }
7873     }
7874   }
7875 
7876   // Second attempt: try to build 'VarRef = Start (+|-) Iter * Step'.
7877   if (!Update.isUsable() || !UpdateVal.isUsable()) {
7878     Update = SemaRef.BuildBinOp(S, Loc, Subtract ? BO_Sub : BO_Add,
7879                                 NewStart.get(), SavedUpdate.get());
7880     if (!Update.isUsable())
7881       return ExprError();
7882 
7883     if (!SemaRef.Context.hasSameType(Update.get()->getType(),
7884                                      VarRef.get()->getType())) {
7885       Update = SemaRef.PerformImplicitConversion(
7886           Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true);
7887       if (!Update.isUsable())
7888         return ExprError();
7889     }
7890 
7891     Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get());
7892   }
7893   return Update;
7894 }
7895 
7896 /// Convert integer expression \a E to make it have at least \a Bits
7897 /// bits.
7898 static ExprResult widenIterationCount(unsigned Bits, Expr *E, Sema &SemaRef) {
7899   if (E == nullptr)
7900     return ExprError();
7901   ASTContext &C = SemaRef.Context;
7902   QualType OldType = E->getType();
7903   unsigned HasBits = C.getTypeSize(OldType);
7904   if (HasBits >= Bits)
7905     return ExprResult(E);
7906   // OK to convert to signed, because new type has more bits than old.
7907   QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true);
7908   return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting,
7909                                            true);
7910 }
7911 
7912 /// Check if the given expression \a E is a constant integer that fits
7913 /// into \a Bits bits.
7914 static bool fitsInto(unsigned Bits, bool Signed, const Expr *E, Sema &SemaRef) {
7915   if (E == nullptr)
7916     return false;
7917   llvm::APSInt Result;
7918   if (E->isIntegerConstantExpr(Result, SemaRef.Context))
7919     return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits);
7920   return false;
7921 }
7922 
7923 /// Build preinits statement for the given declarations.
7924 static Stmt *buildPreInits(ASTContext &Context,
7925                            MutableArrayRef<Decl *> PreInits) {
7926   if (!PreInits.empty()) {
7927     return new (Context) DeclStmt(
7928         DeclGroupRef::Create(Context, PreInits.begin(), PreInits.size()),
7929         SourceLocation(), SourceLocation());
7930   }
7931   return nullptr;
7932 }
7933 
7934 /// Build preinits statement for the given declarations.
7935 static Stmt *
7936 buildPreInits(ASTContext &Context,
7937               const llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
7938   if (!Captures.empty()) {
7939     SmallVector<Decl *, 16> PreInits;
7940     for (const auto &Pair : Captures)
7941       PreInits.push_back(Pair.second->getDecl());
7942     return buildPreInits(Context, PreInits);
7943   }
7944   return nullptr;
7945 }
7946 
7947 /// Build postupdate expression for the given list of postupdates expressions.
7948 static Expr *buildPostUpdate(Sema &S, ArrayRef<Expr *> PostUpdates) {
7949   Expr *PostUpdate = nullptr;
7950   if (!PostUpdates.empty()) {
7951     for (Expr *E : PostUpdates) {
7952       Expr *ConvE = S.BuildCStyleCastExpr(
7953                          E->getExprLoc(),
7954                          S.Context.getTrivialTypeSourceInfo(S.Context.VoidTy),
7955                          E->getExprLoc(), E)
7956                         .get();
7957       PostUpdate = PostUpdate
7958                        ? S.CreateBuiltinBinOp(ConvE->getExprLoc(), BO_Comma,
7959                                               PostUpdate, ConvE)
7960                              .get()
7961                        : ConvE;
7962     }
7963   }
7964   return PostUpdate;
7965 }
7966 
7967 /// Called on a for stmt to check itself and nested loops (if any).
7968 /// \return Returns 0 if one of the collapsed stmts is not canonical for loop,
7969 /// number of collapsed loops otherwise.
7970 static unsigned
7971 checkOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr,
7972                 Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef,
7973                 DSAStackTy &DSA,
7974                 Sema::VarsWithInheritedDSAType &VarsWithImplicitDSA,
7975                 OMPLoopDirective::HelperExprs &Built) {
7976   unsigned NestedLoopCount = 1;
7977   if (CollapseLoopCountExpr) {
7978     // Found 'collapse' clause - calculate collapse number.
7979     Expr::EvalResult Result;
7980     if (!CollapseLoopCountExpr->isValueDependent() &&
7981         CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext())) {
7982       NestedLoopCount = Result.Val.getInt().getLimitedValue();
7983     } else {
7984       Built.clear(/*Size=*/1);
7985       return 1;
7986     }
7987   }
7988   unsigned OrderedLoopCount = 1;
7989   if (OrderedLoopCountExpr) {
7990     // Found 'ordered' clause - calculate collapse number.
7991     Expr::EvalResult EVResult;
7992     if (!OrderedLoopCountExpr->isValueDependent() &&
7993         OrderedLoopCountExpr->EvaluateAsInt(EVResult,
7994                                             SemaRef.getASTContext())) {
7995       llvm::APSInt Result = EVResult.Val.getInt();
7996       if (Result.getLimitedValue() < NestedLoopCount) {
7997         SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
7998                      diag::err_omp_wrong_ordered_loop_count)
7999             << OrderedLoopCountExpr->getSourceRange();
8000         SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
8001                      diag::note_collapse_loop_count)
8002             << CollapseLoopCountExpr->getSourceRange();
8003       }
8004       OrderedLoopCount = Result.getLimitedValue();
8005     } else {
8006       Built.clear(/*Size=*/1);
8007       return 1;
8008     }
8009   }
8010   // This is helper routine for loop directives (e.g., 'for', 'simd',
8011   // 'for simd', etc.).
8012   llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
8013   SmallVector<LoopIterationSpace, 4> IterSpaces(
8014       std::max(OrderedLoopCount, NestedLoopCount));
8015   Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true);
8016   for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
8017     if (checkOpenMPIterationSpace(
8018             DKind, CurStmt, SemaRef, DSA, Cnt, NestedLoopCount,
8019             std::max(OrderedLoopCount, NestedLoopCount), CollapseLoopCountExpr,
8020             OrderedLoopCountExpr, VarsWithImplicitDSA, IterSpaces, Captures))
8021       return 0;
8022     // Move on to the next nested for loop, or to the loop body.
8023     // OpenMP [2.8.1, simd construct, Restrictions]
8024     // All loops associated with the construct must be perfectly nested; that
8025     // is, there must be no intervening code nor any OpenMP directive between
8026     // any two loops.
8027     if (auto *For = dyn_cast<ForStmt>(CurStmt)) {
8028       CurStmt = For->getBody();
8029     } else {
8030       assert(isa<CXXForRangeStmt>(CurStmt) &&
8031              "Expected canonical for or range-based for loops.");
8032       CurStmt = cast<CXXForRangeStmt>(CurStmt)->getBody();
8033     }
8034     CurStmt = OMPLoopDirective::tryToFindNextInnerLoop(
8035         CurStmt, SemaRef.LangOpts.OpenMP >= 50);
8036   }
8037   for (unsigned Cnt = NestedLoopCount; Cnt < OrderedLoopCount; ++Cnt) {
8038     if (checkOpenMPIterationSpace(
8039             DKind, CurStmt, SemaRef, DSA, Cnt, NestedLoopCount,
8040             std::max(OrderedLoopCount, NestedLoopCount), CollapseLoopCountExpr,
8041             OrderedLoopCountExpr, VarsWithImplicitDSA, IterSpaces, Captures))
8042       return 0;
8043     if (Cnt > 0 && IterSpaces[Cnt].CounterVar) {
8044       // Handle initialization of captured loop iterator variables.
8045       auto *DRE = cast<DeclRefExpr>(IterSpaces[Cnt].CounterVar);
8046       if (isa<OMPCapturedExprDecl>(DRE->getDecl())) {
8047         Captures[DRE] = DRE;
8048       }
8049     }
8050     // Move on to the next nested for loop, or to the loop body.
8051     // OpenMP [2.8.1, simd construct, Restrictions]
8052     // All loops associated with the construct must be perfectly nested; that
8053     // is, there must be no intervening code nor any OpenMP directive between
8054     // any two loops.
8055     if (auto *For = dyn_cast<ForStmt>(CurStmt)) {
8056       CurStmt = For->getBody();
8057     } else {
8058       assert(isa<CXXForRangeStmt>(CurStmt) &&
8059              "Expected canonical for or range-based for loops.");
8060       CurStmt = cast<CXXForRangeStmt>(CurStmt)->getBody();
8061     }
8062     CurStmt = OMPLoopDirective::tryToFindNextInnerLoop(
8063         CurStmt, SemaRef.LangOpts.OpenMP >= 50);
8064   }
8065 
8066   Built.clear(/* size */ NestedLoopCount);
8067 
8068   if (SemaRef.CurContext->isDependentContext())
8069     return NestedLoopCount;
8070 
8071   // An example of what is generated for the following code:
8072   //
8073   //   #pragma omp simd collapse(2) ordered(2)
8074   //   for (i = 0; i < NI; ++i)
8075   //     for (k = 0; k < NK; ++k)
8076   //       for (j = J0; j < NJ; j+=2) {
8077   //         <loop body>
8078   //       }
8079   //
8080   // We generate the code below.
8081   // Note: the loop body may be outlined in CodeGen.
8082   // Note: some counters may be C++ classes, operator- is used to find number of
8083   // iterations and operator+= to calculate counter value.
8084   // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32
8085   // or i64 is currently supported).
8086   //
8087   //   #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2))
8088   //   for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) {
8089   //     .local.i = IV / ((NJ - J0 - 1 + 2) / 2);
8090   //     .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2;
8091   //     // similar updates for vars in clauses (e.g. 'linear')
8092   //     <loop body (using local i and j)>
8093   //   }
8094   //   i = NI; // assign final values of counters
8095   //   j = NJ;
8096   //
8097 
8098   // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are
8099   // the iteration counts of the collapsed for loops.
8100   // Precondition tests if there is at least one iteration (all conditions are
8101   // true).
8102   auto PreCond = ExprResult(IterSpaces[0].PreCond);
8103   Expr *N0 = IterSpaces[0].NumIterations;
8104   ExprResult LastIteration32 =
8105       widenIterationCount(/*Bits=*/32,
8106                           SemaRef
8107                               .PerformImplicitConversion(
8108                                   N0->IgnoreImpCasts(), N0->getType(),
8109                                   Sema::AA_Converting, /*AllowExplicit=*/true)
8110                               .get(),
8111                           SemaRef);
8112   ExprResult LastIteration64 = widenIterationCount(
8113       /*Bits=*/64,
8114       SemaRef
8115           .PerformImplicitConversion(N0->IgnoreImpCasts(), N0->getType(),
8116                                      Sema::AA_Converting,
8117                                      /*AllowExplicit=*/true)
8118           .get(),
8119       SemaRef);
8120 
8121   if (!LastIteration32.isUsable() || !LastIteration64.isUsable())
8122     return NestedLoopCount;
8123 
8124   ASTContext &C = SemaRef.Context;
8125   bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32;
8126 
8127   Scope *CurScope = DSA.getCurScope();
8128   for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) {
8129     if (PreCond.isUsable()) {
8130       PreCond =
8131           SemaRef.BuildBinOp(CurScope, PreCond.get()->getExprLoc(), BO_LAnd,
8132                              PreCond.get(), IterSpaces[Cnt].PreCond);
8133     }
8134     Expr *N = IterSpaces[Cnt].NumIterations;
8135     SourceLocation Loc = N->getExprLoc();
8136     AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32;
8137     if (LastIteration32.isUsable())
8138       LastIteration32 = SemaRef.BuildBinOp(
8139           CurScope, Loc, BO_Mul, LastIteration32.get(),
8140           SemaRef
8141               .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
8142                                          Sema::AA_Converting,
8143                                          /*AllowExplicit=*/true)
8144               .get());
8145     if (LastIteration64.isUsable())
8146       LastIteration64 = SemaRef.BuildBinOp(
8147           CurScope, Loc, BO_Mul, LastIteration64.get(),
8148           SemaRef
8149               .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
8150                                          Sema::AA_Converting,
8151                                          /*AllowExplicit=*/true)
8152               .get());
8153   }
8154 
8155   // Choose either the 32-bit or 64-bit version.
8156   ExprResult LastIteration = LastIteration64;
8157   if (SemaRef.getLangOpts().OpenMPOptimisticCollapse ||
8158       (LastIteration32.isUsable() &&
8159        C.getTypeSize(LastIteration32.get()->getType()) == 32 &&
8160        (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 ||
8161         fitsInto(
8162             /*Bits=*/32,
8163             LastIteration32.get()->getType()->hasSignedIntegerRepresentation(),
8164             LastIteration64.get(), SemaRef))))
8165     LastIteration = LastIteration32;
8166   QualType VType = LastIteration.get()->getType();
8167   QualType RealVType = VType;
8168   QualType StrideVType = VType;
8169   if (isOpenMPTaskLoopDirective(DKind)) {
8170     VType =
8171         SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
8172     StrideVType =
8173         SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
8174   }
8175 
8176   if (!LastIteration.isUsable())
8177     return 0;
8178 
8179   // Save the number of iterations.
8180   ExprResult NumIterations = LastIteration;
8181   {
8182     LastIteration = SemaRef.BuildBinOp(
8183         CurScope, LastIteration.get()->getExprLoc(), BO_Sub,
8184         LastIteration.get(),
8185         SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
8186     if (!LastIteration.isUsable())
8187       return 0;
8188   }
8189 
8190   // Calculate the last iteration number beforehand instead of doing this on
8191   // each iteration. Do not do this if the number of iterations may be kfold-ed.
8192   llvm::APSInt Result;
8193   bool IsConstant =
8194       LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context);
8195   ExprResult CalcLastIteration;
8196   if (!IsConstant) {
8197     ExprResult SaveRef =
8198         tryBuildCapture(SemaRef, LastIteration.get(), Captures);
8199     LastIteration = SaveRef;
8200 
8201     // Prepare SaveRef + 1.
8202     NumIterations = SemaRef.BuildBinOp(
8203         CurScope, SaveRef.get()->getExprLoc(), BO_Add, SaveRef.get(),
8204         SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
8205     if (!NumIterations.isUsable())
8206       return 0;
8207   }
8208 
8209   SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin();
8210 
8211   // Build variables passed into runtime, necessary for worksharing directives.
8212   ExprResult LB, UB, IL, ST, EUB, CombLB, CombUB, PrevLB, PrevUB, CombEUB;
8213   if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
8214       isOpenMPDistributeDirective(DKind)) {
8215     // Lower bound variable, initialized with zero.
8216     VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb");
8217     LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc);
8218     SemaRef.AddInitializerToDecl(LBDecl,
8219                                  SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
8220                                  /*DirectInit*/ false);
8221 
8222     // Upper bound variable, initialized with last iteration number.
8223     VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub");
8224     UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc);
8225     SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(),
8226                                  /*DirectInit*/ false);
8227 
8228     // A 32-bit variable-flag where runtime returns 1 for the last iteration.
8229     // This will be used to implement clause 'lastprivate'.
8230     QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true);
8231     VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last");
8232     IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc);
8233     SemaRef.AddInitializerToDecl(ILDecl,
8234                                  SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
8235                                  /*DirectInit*/ false);
8236 
8237     // Stride variable returned by runtime (we initialize it to 1 by default).
8238     VarDecl *STDecl =
8239         buildVarDecl(SemaRef, InitLoc, StrideVType, ".omp.stride");
8240     ST = buildDeclRefExpr(SemaRef, STDecl, StrideVType, InitLoc);
8241     SemaRef.AddInitializerToDecl(STDecl,
8242                                  SemaRef.ActOnIntegerConstant(InitLoc, 1).get(),
8243                                  /*DirectInit*/ false);
8244 
8245     // Build expression: UB = min(UB, LastIteration)
8246     // It is necessary for CodeGen of directives with static scheduling.
8247     ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT,
8248                                                 UB.get(), LastIteration.get());
8249     ExprResult CondOp = SemaRef.ActOnConditionalOp(
8250         LastIteration.get()->getExprLoc(), InitLoc, IsUBGreater.get(),
8251         LastIteration.get(), UB.get());
8252     EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(),
8253                              CondOp.get());
8254     EUB = SemaRef.ActOnFinishFullExpr(EUB.get(), /*DiscardedValue*/ false);
8255 
8256     // If we have a combined directive that combines 'distribute', 'for' or
8257     // 'simd' we need to be able to access the bounds of the schedule of the
8258     // enclosing region. E.g. in 'distribute parallel for' the bounds obtained
8259     // by scheduling 'distribute' have to be passed to the schedule of 'for'.
8260     if (isOpenMPLoopBoundSharingDirective(DKind)) {
8261       // Lower bound variable, initialized with zero.
8262       VarDecl *CombLBDecl =
8263           buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.lb");
8264       CombLB = buildDeclRefExpr(SemaRef, CombLBDecl, VType, InitLoc);
8265       SemaRef.AddInitializerToDecl(
8266           CombLBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
8267           /*DirectInit*/ false);
8268 
8269       // Upper bound variable, initialized with last iteration number.
8270       VarDecl *CombUBDecl =
8271           buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.ub");
8272       CombUB = buildDeclRefExpr(SemaRef, CombUBDecl, VType, InitLoc);
8273       SemaRef.AddInitializerToDecl(CombUBDecl, LastIteration.get(),
8274                                    /*DirectInit*/ false);
8275 
8276       ExprResult CombIsUBGreater = SemaRef.BuildBinOp(
8277           CurScope, InitLoc, BO_GT, CombUB.get(), LastIteration.get());
8278       ExprResult CombCondOp =
8279           SemaRef.ActOnConditionalOp(InitLoc, InitLoc, CombIsUBGreater.get(),
8280                                      LastIteration.get(), CombUB.get());
8281       CombEUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, CombUB.get(),
8282                                    CombCondOp.get());
8283       CombEUB =
8284           SemaRef.ActOnFinishFullExpr(CombEUB.get(), /*DiscardedValue*/ false);
8285 
8286       const CapturedDecl *CD = cast<CapturedStmt>(AStmt)->getCapturedDecl();
8287       // We expect to have at least 2 more parameters than the 'parallel'
8288       // directive does - the lower and upper bounds of the previous schedule.
8289       assert(CD->getNumParams() >= 4 &&
8290              "Unexpected number of parameters in loop combined directive");
8291 
8292       // Set the proper type for the bounds given what we learned from the
8293       // enclosed loops.
8294       ImplicitParamDecl *PrevLBDecl = CD->getParam(/*PrevLB=*/2);
8295       ImplicitParamDecl *PrevUBDecl = CD->getParam(/*PrevUB=*/3);
8296 
8297       // Previous lower and upper bounds are obtained from the region
8298       // parameters.
8299       PrevLB =
8300           buildDeclRefExpr(SemaRef, PrevLBDecl, PrevLBDecl->getType(), InitLoc);
8301       PrevUB =
8302           buildDeclRefExpr(SemaRef, PrevUBDecl, PrevUBDecl->getType(), InitLoc);
8303     }
8304   }
8305 
8306   // Build the iteration variable and its initialization before loop.
8307   ExprResult IV;
8308   ExprResult Init, CombInit;
8309   {
8310     VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, RealVType, ".omp.iv");
8311     IV = buildDeclRefExpr(SemaRef, IVDecl, RealVType, InitLoc);
8312     Expr *RHS =
8313         (isOpenMPWorksharingDirective(DKind) ||
8314          isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
8315             ? LB.get()
8316             : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
8317     Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS);
8318     Init = SemaRef.ActOnFinishFullExpr(Init.get(), /*DiscardedValue*/ false);
8319 
8320     if (isOpenMPLoopBoundSharingDirective(DKind)) {
8321       Expr *CombRHS =
8322           (isOpenMPWorksharingDirective(DKind) ||
8323            isOpenMPTaskLoopDirective(DKind) ||
8324            isOpenMPDistributeDirective(DKind))
8325               ? CombLB.get()
8326               : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
8327       CombInit =
8328           SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), CombRHS);
8329       CombInit =
8330           SemaRef.ActOnFinishFullExpr(CombInit.get(), /*DiscardedValue*/ false);
8331     }
8332   }
8333 
8334   bool UseStrictCompare =
8335       RealVType->hasUnsignedIntegerRepresentation() &&
8336       llvm::all_of(IterSpaces, [](const LoopIterationSpace &LIS) {
8337         return LIS.IsStrictCompare;
8338       });
8339   // Loop condition (IV < NumIterations) or (IV <= UB or IV < UB + 1 (for
8340   // unsigned IV)) for worksharing loops.
8341   SourceLocation CondLoc = AStmt->getBeginLoc();
8342   Expr *BoundUB = UB.get();
8343   if (UseStrictCompare) {
8344     BoundUB =
8345         SemaRef
8346             .BuildBinOp(CurScope, CondLoc, BO_Add, BoundUB,
8347                         SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
8348             .get();
8349     BoundUB =
8350         SemaRef.ActOnFinishFullExpr(BoundUB, /*DiscardedValue*/ false).get();
8351   }
8352   ExprResult Cond =
8353       (isOpenMPWorksharingDirective(DKind) ||
8354        isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
8355           ? SemaRef.BuildBinOp(CurScope, CondLoc,
8356                                UseStrictCompare ? BO_LT : BO_LE, IV.get(),
8357                                BoundUB)
8358           : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
8359                                NumIterations.get());
8360   ExprResult CombDistCond;
8361   if (isOpenMPLoopBoundSharingDirective(DKind)) {
8362     CombDistCond = SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
8363                                       NumIterations.get());
8364   }
8365 
8366   ExprResult CombCond;
8367   if (isOpenMPLoopBoundSharingDirective(DKind)) {
8368     Expr *BoundCombUB = CombUB.get();
8369     if (UseStrictCompare) {
8370       BoundCombUB =
8371           SemaRef
8372               .BuildBinOp(
8373                   CurScope, CondLoc, BO_Add, BoundCombUB,
8374                   SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
8375               .get();
8376       BoundCombUB =
8377           SemaRef.ActOnFinishFullExpr(BoundCombUB, /*DiscardedValue*/ false)
8378               .get();
8379     }
8380     CombCond =
8381         SemaRef.BuildBinOp(CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE,
8382                            IV.get(), BoundCombUB);
8383   }
8384   // Loop increment (IV = IV + 1)
8385   SourceLocation IncLoc = AStmt->getBeginLoc();
8386   ExprResult Inc =
8387       SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(),
8388                          SemaRef.ActOnIntegerConstant(IncLoc, 1).get());
8389   if (!Inc.isUsable())
8390     return 0;
8391   Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get());
8392   Inc = SemaRef.ActOnFinishFullExpr(Inc.get(), /*DiscardedValue*/ false);
8393   if (!Inc.isUsable())
8394     return 0;
8395 
8396   // Increments for worksharing loops (LB = LB + ST; UB = UB + ST).
8397   // Used for directives with static scheduling.
8398   // In combined construct, add combined version that use CombLB and CombUB
8399   // base variables for the update
8400   ExprResult NextLB, NextUB, CombNextLB, CombNextUB;
8401   if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
8402       isOpenMPDistributeDirective(DKind)) {
8403     // LB + ST
8404     NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get());
8405     if (!NextLB.isUsable())
8406       return 0;
8407     // LB = LB + ST
8408     NextLB =
8409         SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get());
8410     NextLB =
8411         SemaRef.ActOnFinishFullExpr(NextLB.get(), /*DiscardedValue*/ false);
8412     if (!NextLB.isUsable())
8413       return 0;
8414     // UB + ST
8415     NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get());
8416     if (!NextUB.isUsable())
8417       return 0;
8418     // UB = UB + ST
8419     NextUB =
8420         SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get());
8421     NextUB =
8422         SemaRef.ActOnFinishFullExpr(NextUB.get(), /*DiscardedValue*/ false);
8423     if (!NextUB.isUsable())
8424       return 0;
8425     if (isOpenMPLoopBoundSharingDirective(DKind)) {
8426       CombNextLB =
8427           SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombLB.get(), ST.get());
8428       if (!NextLB.isUsable())
8429         return 0;
8430       // LB = LB + ST
8431       CombNextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombLB.get(),
8432                                       CombNextLB.get());
8433       CombNextLB = SemaRef.ActOnFinishFullExpr(CombNextLB.get(),
8434                                                /*DiscardedValue*/ false);
8435       if (!CombNextLB.isUsable())
8436         return 0;
8437       // UB + ST
8438       CombNextUB =
8439           SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombUB.get(), ST.get());
8440       if (!CombNextUB.isUsable())
8441         return 0;
8442       // UB = UB + ST
8443       CombNextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombUB.get(),
8444                                       CombNextUB.get());
8445       CombNextUB = SemaRef.ActOnFinishFullExpr(CombNextUB.get(),
8446                                                /*DiscardedValue*/ false);
8447       if (!CombNextUB.isUsable())
8448         return 0;
8449     }
8450   }
8451 
8452   // Create increment expression for distribute loop when combined in a same
8453   // directive with for as IV = IV + ST; ensure upper bound expression based
8454   // on PrevUB instead of NumIterations - used to implement 'for' when found
8455   // in combination with 'distribute', like in 'distribute parallel for'
8456   SourceLocation DistIncLoc = AStmt->getBeginLoc();
8457   ExprResult DistCond, DistInc, PrevEUB, ParForInDistCond;
8458   if (isOpenMPLoopBoundSharingDirective(DKind)) {
8459     DistCond = SemaRef.BuildBinOp(
8460         CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE, IV.get(), BoundUB);
8461     assert(DistCond.isUsable() && "distribute cond expr was not built");
8462 
8463     DistInc =
8464         SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Add, IV.get(), ST.get());
8465     assert(DistInc.isUsable() && "distribute inc expr was not built");
8466     DistInc = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, IV.get(),
8467                                  DistInc.get());
8468     DistInc =
8469         SemaRef.ActOnFinishFullExpr(DistInc.get(), /*DiscardedValue*/ false);
8470     assert(DistInc.isUsable() && "distribute inc expr was not built");
8471 
8472     // Build expression: UB = min(UB, prevUB) for #for in composite or combined
8473     // construct
8474     SourceLocation DistEUBLoc = AStmt->getBeginLoc();
8475     ExprResult IsUBGreater =
8476         SemaRef.BuildBinOp(CurScope, DistEUBLoc, BO_GT, UB.get(), PrevUB.get());
8477     ExprResult CondOp = SemaRef.ActOnConditionalOp(
8478         DistEUBLoc, DistEUBLoc, IsUBGreater.get(), PrevUB.get(), UB.get());
8479     PrevEUB = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, UB.get(),
8480                                  CondOp.get());
8481     PrevEUB =
8482         SemaRef.ActOnFinishFullExpr(PrevEUB.get(), /*DiscardedValue*/ false);
8483 
8484     // Build IV <= PrevUB or IV < PrevUB + 1 for unsigned IV to be used in
8485     // parallel for is in combination with a distribute directive with
8486     // schedule(static, 1)
8487     Expr *BoundPrevUB = PrevUB.get();
8488     if (UseStrictCompare) {
8489       BoundPrevUB =
8490           SemaRef
8491               .BuildBinOp(
8492                   CurScope, CondLoc, BO_Add, BoundPrevUB,
8493                   SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
8494               .get();
8495       BoundPrevUB =
8496           SemaRef.ActOnFinishFullExpr(BoundPrevUB, /*DiscardedValue*/ false)
8497               .get();
8498     }
8499     ParForInDistCond =
8500         SemaRef.BuildBinOp(CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE,
8501                            IV.get(), BoundPrevUB);
8502   }
8503 
8504   // Build updates and final values of the loop counters.
8505   bool HasErrors = false;
8506   Built.Counters.resize(NestedLoopCount);
8507   Built.Inits.resize(NestedLoopCount);
8508   Built.Updates.resize(NestedLoopCount);
8509   Built.Finals.resize(NestedLoopCount);
8510   Built.DependentCounters.resize(NestedLoopCount);
8511   Built.DependentInits.resize(NestedLoopCount);
8512   Built.FinalsConditions.resize(NestedLoopCount);
8513   {
8514     // We implement the following algorithm for obtaining the
8515     // original loop iteration variable values based on the
8516     // value of the collapsed loop iteration variable IV.
8517     //
8518     // Let n+1 be the number of collapsed loops in the nest.
8519     // Iteration variables (I0, I1, .... In)
8520     // Iteration counts (N0, N1, ... Nn)
8521     //
8522     // Acc = IV;
8523     //
8524     // To compute Ik for loop k, 0 <= k <= n, generate:
8525     //    Prod = N(k+1) * N(k+2) * ... * Nn;
8526     //    Ik = Acc / Prod;
8527     //    Acc -= Ik * Prod;
8528     //
8529     ExprResult Acc = IV;
8530     for (unsigned int Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
8531       LoopIterationSpace &IS = IterSpaces[Cnt];
8532       SourceLocation UpdLoc = IS.IncSrcRange.getBegin();
8533       ExprResult Iter;
8534 
8535       // Compute prod
8536       ExprResult Prod =
8537           SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
8538       for (unsigned int K = Cnt+1; K < NestedLoopCount; ++K)
8539         Prod = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Prod.get(),
8540                                   IterSpaces[K].NumIterations);
8541 
8542       // Iter = Acc / Prod
8543       // If there is at least one more inner loop to avoid
8544       // multiplication by 1.
8545       if (Cnt + 1 < NestedLoopCount)
8546         Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div,
8547                                   Acc.get(), Prod.get());
8548       else
8549         Iter = Acc;
8550       if (!Iter.isUsable()) {
8551         HasErrors = true;
8552         break;
8553       }
8554 
8555       // Update Acc:
8556       // Acc -= Iter * Prod
8557       // Check if there is at least one more inner loop to avoid
8558       // multiplication by 1.
8559       if (Cnt + 1 < NestedLoopCount)
8560         Prod = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul,
8561                                   Iter.get(), Prod.get());
8562       else
8563         Prod = Iter;
8564       Acc = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Sub,
8565                                Acc.get(), Prod.get());
8566 
8567       // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step
8568       auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl());
8569       DeclRefExpr *CounterVar = buildDeclRefExpr(
8570           SemaRef, VD, IS.CounterVar->getType(), IS.CounterVar->getExprLoc(),
8571           /*RefersToCapture=*/true);
8572       ExprResult Init =
8573           buildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar,
8574                            IS.CounterInit, IS.IsNonRectangularLB, Captures);
8575       if (!Init.isUsable()) {
8576         HasErrors = true;
8577         break;
8578       }
8579       ExprResult Update = buildCounterUpdate(
8580           SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, Iter,
8581           IS.CounterStep, IS.Subtract, IS.IsNonRectangularLB, &Captures);
8582       if (!Update.isUsable()) {
8583         HasErrors = true;
8584         break;
8585       }
8586 
8587       // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step
8588       ExprResult Final =
8589           buildCounterUpdate(SemaRef, CurScope, UpdLoc, CounterVar,
8590                              IS.CounterInit, IS.NumIterations, IS.CounterStep,
8591                              IS.Subtract, IS.IsNonRectangularLB, &Captures);
8592       if (!Final.isUsable()) {
8593         HasErrors = true;
8594         break;
8595       }
8596 
8597       if (!Update.isUsable() || !Final.isUsable()) {
8598         HasErrors = true;
8599         break;
8600       }
8601       // Save results
8602       Built.Counters[Cnt] = IS.CounterVar;
8603       Built.PrivateCounters[Cnt] = IS.PrivateCounterVar;
8604       Built.Inits[Cnt] = Init.get();
8605       Built.Updates[Cnt] = Update.get();
8606       Built.Finals[Cnt] = Final.get();
8607       Built.DependentCounters[Cnt] = nullptr;
8608       Built.DependentInits[Cnt] = nullptr;
8609       Built.FinalsConditions[Cnt] = nullptr;
8610       if (IS.IsNonRectangularLB || IS.IsNonRectangularUB) {
8611         Built.DependentCounters[Cnt] =
8612             Built.Counters[NestedLoopCount - 1 - IS.LoopDependentIdx];
8613         Built.DependentInits[Cnt] =
8614             Built.Inits[NestedLoopCount - 1 - IS.LoopDependentIdx];
8615         Built.FinalsConditions[Cnt] = IS.FinalCondition;
8616       }
8617     }
8618   }
8619 
8620   if (HasErrors)
8621     return 0;
8622 
8623   // Save results
8624   Built.IterationVarRef = IV.get();
8625   Built.LastIteration = LastIteration.get();
8626   Built.NumIterations = NumIterations.get();
8627   Built.CalcLastIteration = SemaRef
8628                                 .ActOnFinishFullExpr(CalcLastIteration.get(),
8629                                                      /*DiscardedValue=*/false)
8630                                 .get();
8631   Built.PreCond = PreCond.get();
8632   Built.PreInits = buildPreInits(C, Captures);
8633   Built.Cond = Cond.get();
8634   Built.Init = Init.get();
8635   Built.Inc = Inc.get();
8636   Built.LB = LB.get();
8637   Built.UB = UB.get();
8638   Built.IL = IL.get();
8639   Built.ST = ST.get();
8640   Built.EUB = EUB.get();
8641   Built.NLB = NextLB.get();
8642   Built.NUB = NextUB.get();
8643   Built.PrevLB = PrevLB.get();
8644   Built.PrevUB = PrevUB.get();
8645   Built.DistInc = DistInc.get();
8646   Built.PrevEUB = PrevEUB.get();
8647   Built.DistCombinedFields.LB = CombLB.get();
8648   Built.DistCombinedFields.UB = CombUB.get();
8649   Built.DistCombinedFields.EUB = CombEUB.get();
8650   Built.DistCombinedFields.Init = CombInit.get();
8651   Built.DistCombinedFields.Cond = CombCond.get();
8652   Built.DistCombinedFields.NLB = CombNextLB.get();
8653   Built.DistCombinedFields.NUB = CombNextUB.get();
8654   Built.DistCombinedFields.DistCond = CombDistCond.get();
8655   Built.DistCombinedFields.ParForInDistCond = ParForInDistCond.get();
8656 
8657   return NestedLoopCount;
8658 }
8659 
8660 static Expr *getCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) {
8661   auto CollapseClauses =
8662       OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses);
8663   if (CollapseClauses.begin() != CollapseClauses.end())
8664     return (*CollapseClauses.begin())->getNumForLoops();
8665   return nullptr;
8666 }
8667 
8668 static Expr *getOrderedNumberExpr(ArrayRef<OMPClause *> Clauses) {
8669   auto OrderedClauses =
8670       OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses);
8671   if (OrderedClauses.begin() != OrderedClauses.end())
8672     return (*OrderedClauses.begin())->getNumForLoops();
8673   return nullptr;
8674 }
8675 
8676 static bool checkSimdlenSafelenSpecified(Sema &S,
8677                                          const ArrayRef<OMPClause *> Clauses) {
8678   const OMPSafelenClause *Safelen = nullptr;
8679   const OMPSimdlenClause *Simdlen = nullptr;
8680 
8681   for (const OMPClause *Clause : Clauses) {
8682     if (Clause->getClauseKind() == OMPC_safelen)
8683       Safelen = cast<OMPSafelenClause>(Clause);
8684     else if (Clause->getClauseKind() == OMPC_simdlen)
8685       Simdlen = cast<OMPSimdlenClause>(Clause);
8686     if (Safelen && Simdlen)
8687       break;
8688   }
8689 
8690   if (Simdlen && Safelen) {
8691     const Expr *SimdlenLength = Simdlen->getSimdlen();
8692     const Expr *SafelenLength = Safelen->getSafelen();
8693     if (SimdlenLength->isValueDependent() || SimdlenLength->isTypeDependent() ||
8694         SimdlenLength->isInstantiationDependent() ||
8695         SimdlenLength->containsUnexpandedParameterPack())
8696       return false;
8697     if (SafelenLength->isValueDependent() || SafelenLength->isTypeDependent() ||
8698         SafelenLength->isInstantiationDependent() ||
8699         SafelenLength->containsUnexpandedParameterPack())
8700       return false;
8701     Expr::EvalResult SimdlenResult, SafelenResult;
8702     SimdlenLength->EvaluateAsInt(SimdlenResult, S.Context);
8703     SafelenLength->EvaluateAsInt(SafelenResult, S.Context);
8704     llvm::APSInt SimdlenRes = SimdlenResult.Val.getInt();
8705     llvm::APSInt SafelenRes = SafelenResult.Val.getInt();
8706     // OpenMP 4.5 [2.8.1, simd Construct, Restrictions]
8707     // If both simdlen and safelen clauses are specified, the value of the
8708     // simdlen parameter must be less than or equal to the value of the safelen
8709     // parameter.
8710     if (SimdlenRes > SafelenRes) {
8711       S.Diag(SimdlenLength->getExprLoc(),
8712              diag::err_omp_wrong_simdlen_safelen_values)
8713           << SimdlenLength->getSourceRange() << SafelenLength->getSourceRange();
8714       return true;
8715     }
8716   }
8717   return false;
8718 }
8719 
8720 StmtResult
8721 Sema::ActOnOpenMPSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
8722                                SourceLocation StartLoc, SourceLocation EndLoc,
8723                                VarsWithInheritedDSAType &VarsWithImplicitDSA) {
8724   if (!AStmt)
8725     return StmtError();
8726 
8727   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
8728   OMPLoopDirective::HelperExprs B;
8729   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
8730   // define the nested loops number.
8731   unsigned NestedLoopCount = checkOpenMPLoop(
8732       OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
8733       AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
8734   if (NestedLoopCount == 0)
8735     return StmtError();
8736 
8737   assert((CurContext->isDependentContext() || B.builtAll()) &&
8738          "omp simd loop exprs were not built");
8739 
8740   if (!CurContext->isDependentContext()) {
8741     // Finalize the clauses that need pre-built expressions for CodeGen.
8742     for (OMPClause *C : Clauses) {
8743       if (auto *LC = dyn_cast<OMPLinearClause>(C))
8744         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
8745                                      B.NumIterations, *this, CurScope,
8746                                      DSAStack))
8747           return StmtError();
8748     }
8749   }
8750 
8751   if (checkSimdlenSafelenSpecified(*this, Clauses))
8752     return StmtError();
8753 
8754   setFunctionHasBranchProtectedScope();
8755   return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
8756                                   Clauses, AStmt, B);
8757 }
8758 
8759 StmtResult
8760 Sema::ActOnOpenMPForDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
8761                               SourceLocation StartLoc, SourceLocation EndLoc,
8762                               VarsWithInheritedDSAType &VarsWithImplicitDSA) {
8763   if (!AStmt)
8764     return StmtError();
8765 
8766   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
8767   OMPLoopDirective::HelperExprs B;
8768   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
8769   // define the nested loops number.
8770   unsigned NestedLoopCount = checkOpenMPLoop(
8771       OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
8772       AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
8773   if (NestedLoopCount == 0)
8774     return StmtError();
8775 
8776   assert((CurContext->isDependentContext() || B.builtAll()) &&
8777          "omp for loop exprs were not built");
8778 
8779   if (!CurContext->isDependentContext()) {
8780     // Finalize the clauses that need pre-built expressions for CodeGen.
8781     for (OMPClause *C : Clauses) {
8782       if (auto *LC = dyn_cast<OMPLinearClause>(C))
8783         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
8784                                      B.NumIterations, *this, CurScope,
8785                                      DSAStack))
8786           return StmtError();
8787     }
8788   }
8789 
8790   setFunctionHasBranchProtectedScope();
8791   return OMPForDirective::Create(
8792       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
8793       DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion());
8794 }
8795 
8796 StmtResult Sema::ActOnOpenMPForSimdDirective(
8797     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8798     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
8799   if (!AStmt)
8800     return StmtError();
8801 
8802   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
8803   OMPLoopDirective::HelperExprs B;
8804   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
8805   // define the nested loops number.
8806   unsigned NestedLoopCount =
8807       checkOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses),
8808                       getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
8809                       VarsWithImplicitDSA, B);
8810   if (NestedLoopCount == 0)
8811     return StmtError();
8812 
8813   assert((CurContext->isDependentContext() || B.builtAll()) &&
8814          "omp for simd loop exprs were not built");
8815 
8816   if (!CurContext->isDependentContext()) {
8817     // Finalize the clauses that need pre-built expressions for CodeGen.
8818     for (OMPClause *C : Clauses) {
8819       if (auto *LC = dyn_cast<OMPLinearClause>(C))
8820         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
8821                                      B.NumIterations, *this, CurScope,
8822                                      DSAStack))
8823           return StmtError();
8824     }
8825   }
8826 
8827   if (checkSimdlenSafelenSpecified(*this, Clauses))
8828     return StmtError();
8829 
8830   setFunctionHasBranchProtectedScope();
8831   return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
8832                                      Clauses, AStmt, B);
8833 }
8834 
8835 StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
8836                                               Stmt *AStmt,
8837                                               SourceLocation StartLoc,
8838                                               SourceLocation EndLoc) {
8839   if (!AStmt)
8840     return StmtError();
8841 
8842   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
8843   auto BaseStmt = AStmt;
8844   while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
8845     BaseStmt = CS->getCapturedStmt();
8846   if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
8847     auto S = C->children();
8848     if (S.begin() == S.end())
8849       return StmtError();
8850     // All associated statements must be '#pragma omp section' except for
8851     // the first one.
8852     for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
8853       if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
8854         if (SectionStmt)
8855           Diag(SectionStmt->getBeginLoc(),
8856                diag::err_omp_sections_substmt_not_section);
8857         return StmtError();
8858       }
8859       cast<OMPSectionDirective>(SectionStmt)
8860           ->setHasCancel(DSAStack->isCancelRegion());
8861     }
8862   } else {
8863     Diag(AStmt->getBeginLoc(), diag::err_omp_sections_not_compound_stmt);
8864     return StmtError();
8865   }
8866 
8867   setFunctionHasBranchProtectedScope();
8868 
8869   return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
8870                                       DSAStack->getTaskgroupReductionRef(),
8871                                       DSAStack->isCancelRegion());
8872 }
8873 
8874 StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt,
8875                                              SourceLocation StartLoc,
8876                                              SourceLocation EndLoc) {
8877   if (!AStmt)
8878     return StmtError();
8879 
8880   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
8881 
8882   setFunctionHasBranchProtectedScope();
8883   DSAStack->setParentCancelRegion(DSAStack->isCancelRegion());
8884 
8885   return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt,
8886                                      DSAStack->isCancelRegion());
8887 }
8888 
8889 StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
8890                                             Stmt *AStmt,
8891                                             SourceLocation StartLoc,
8892                                             SourceLocation EndLoc) {
8893   if (!AStmt)
8894     return StmtError();
8895 
8896   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
8897 
8898   setFunctionHasBranchProtectedScope();
8899 
8900   // OpenMP [2.7.3, single Construct, Restrictions]
8901   // The copyprivate clause must not be used with the nowait clause.
8902   const OMPClause *Nowait = nullptr;
8903   const OMPClause *Copyprivate = nullptr;
8904   for (const OMPClause *Clause : Clauses) {
8905     if (Clause->getClauseKind() == OMPC_nowait)
8906       Nowait = Clause;
8907     else if (Clause->getClauseKind() == OMPC_copyprivate)
8908       Copyprivate = Clause;
8909     if (Copyprivate && Nowait) {
8910       Diag(Copyprivate->getBeginLoc(),
8911            diag::err_omp_single_copyprivate_with_nowait);
8912       Diag(Nowait->getBeginLoc(), diag::note_omp_nowait_clause_here);
8913       return StmtError();
8914     }
8915   }
8916 
8917   return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
8918 }
8919 
8920 StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt,
8921                                             SourceLocation StartLoc,
8922                                             SourceLocation EndLoc) {
8923   if (!AStmt)
8924     return StmtError();
8925 
8926   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
8927 
8928   setFunctionHasBranchProtectedScope();
8929 
8930   return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt);
8931 }
8932 
8933 StmtResult Sema::ActOnOpenMPCriticalDirective(
8934     const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses,
8935     Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
8936   if (!AStmt)
8937     return StmtError();
8938 
8939   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
8940 
8941   bool ErrorFound = false;
8942   llvm::APSInt Hint;
8943   SourceLocation HintLoc;
8944   bool DependentHint = false;
8945   for (const OMPClause *C : Clauses) {
8946     if (C->getClauseKind() == OMPC_hint) {
8947       if (!DirName.getName()) {
8948         Diag(C->getBeginLoc(), diag::err_omp_hint_clause_no_name);
8949         ErrorFound = true;
8950       }
8951       Expr *E = cast<OMPHintClause>(C)->getHint();
8952       if (E->isTypeDependent() || E->isValueDependent() ||
8953           E->isInstantiationDependent()) {
8954         DependentHint = true;
8955       } else {
8956         Hint = E->EvaluateKnownConstInt(Context);
8957         HintLoc = C->getBeginLoc();
8958       }
8959     }
8960   }
8961   if (ErrorFound)
8962     return StmtError();
8963   const auto Pair = DSAStack->getCriticalWithHint(DirName);
8964   if (Pair.first && DirName.getName() && !DependentHint) {
8965     if (llvm::APSInt::compareValues(Hint, Pair.second) != 0) {
8966       Diag(StartLoc, diag::err_omp_critical_with_hint);
8967       if (HintLoc.isValid())
8968         Diag(HintLoc, diag::note_omp_critical_hint_here)
8969             << 0 << Hint.toString(/*Radix=*/10, /*Signed=*/false);
8970       else
8971         Diag(StartLoc, diag::note_omp_critical_no_hint) << 0;
8972       if (const auto *C = Pair.first->getSingleClause<OMPHintClause>()) {
8973         Diag(C->getBeginLoc(), diag::note_omp_critical_hint_here)
8974             << 1
8975             << C->getHint()->EvaluateKnownConstInt(Context).toString(
8976                    /*Radix=*/10, /*Signed=*/false);
8977       } else {
8978         Diag(Pair.first->getBeginLoc(), diag::note_omp_critical_no_hint) << 1;
8979       }
8980     }
8981   }
8982 
8983   setFunctionHasBranchProtectedScope();
8984 
8985   auto *Dir = OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc,
8986                                            Clauses, AStmt);
8987   if (!Pair.first && DirName.getName() && !DependentHint)
8988     DSAStack->addCriticalWithHint(Dir, Hint);
8989   return Dir;
8990 }
8991 
8992 StmtResult Sema::ActOnOpenMPParallelForDirective(
8993     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8994     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
8995   if (!AStmt)
8996     return StmtError();
8997 
8998   auto *CS = cast<CapturedStmt>(AStmt);
8999   // 1.2.2 OpenMP Language Terminology
9000   // Structured block - An executable statement with a single entry at the
9001   // top and a single exit at the bottom.
9002   // The point of exit cannot be a branch out of the structured block.
9003   // longjmp() and throw() must not violate the entry/exit criteria.
9004   CS->getCapturedDecl()->setNothrow();
9005 
9006   OMPLoopDirective::HelperExprs B;
9007   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
9008   // define the nested loops number.
9009   unsigned NestedLoopCount =
9010       checkOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses),
9011                       getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
9012                       VarsWithImplicitDSA, B);
9013   if (NestedLoopCount == 0)
9014     return StmtError();
9015 
9016   assert((CurContext->isDependentContext() || B.builtAll()) &&
9017          "omp parallel for loop exprs were not built");
9018 
9019   if (!CurContext->isDependentContext()) {
9020     // Finalize the clauses that need pre-built expressions for CodeGen.
9021     for (OMPClause *C : Clauses) {
9022       if (auto *LC = dyn_cast<OMPLinearClause>(C))
9023         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
9024                                      B.NumIterations, *this, CurScope,
9025                                      DSAStack))
9026           return StmtError();
9027     }
9028   }
9029 
9030   setFunctionHasBranchProtectedScope();
9031   return OMPParallelForDirective::Create(
9032       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
9033       DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion());
9034 }
9035 
9036 StmtResult Sema::ActOnOpenMPParallelForSimdDirective(
9037     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
9038     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
9039   if (!AStmt)
9040     return StmtError();
9041 
9042   auto *CS = cast<CapturedStmt>(AStmt);
9043   // 1.2.2 OpenMP Language Terminology
9044   // Structured block - An executable statement with a single entry at the
9045   // top and a single exit at the bottom.
9046   // The point of exit cannot be a branch out of the structured block.
9047   // longjmp() and throw() must not violate the entry/exit criteria.
9048   CS->getCapturedDecl()->setNothrow();
9049 
9050   OMPLoopDirective::HelperExprs B;
9051   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
9052   // define the nested loops number.
9053   unsigned NestedLoopCount =
9054       checkOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses),
9055                       getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
9056                       VarsWithImplicitDSA, B);
9057   if (NestedLoopCount == 0)
9058     return StmtError();
9059 
9060   if (!CurContext->isDependentContext()) {
9061     // Finalize the clauses that need pre-built expressions for CodeGen.
9062     for (OMPClause *C : Clauses) {
9063       if (auto *LC = dyn_cast<OMPLinearClause>(C))
9064         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
9065                                      B.NumIterations, *this, CurScope,
9066                                      DSAStack))
9067           return StmtError();
9068     }
9069   }
9070 
9071   if (checkSimdlenSafelenSpecified(*this, Clauses))
9072     return StmtError();
9073 
9074   setFunctionHasBranchProtectedScope();
9075   return OMPParallelForSimdDirective::Create(
9076       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
9077 }
9078 
9079 StmtResult
9080 Sema::ActOnOpenMPParallelMasterDirective(ArrayRef<OMPClause *> Clauses,
9081                                          Stmt *AStmt, SourceLocation StartLoc,
9082                                          SourceLocation EndLoc) {
9083   if (!AStmt)
9084     return StmtError();
9085 
9086   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
9087   auto *CS = cast<CapturedStmt>(AStmt);
9088   // 1.2.2 OpenMP Language Terminology
9089   // Structured block - An executable statement with a single entry at the
9090   // top and a single exit at the bottom.
9091   // The point of exit cannot be a branch out of the structured block.
9092   // longjmp() and throw() must not violate the entry/exit criteria.
9093   CS->getCapturedDecl()->setNothrow();
9094 
9095   setFunctionHasBranchProtectedScope();
9096 
9097   return OMPParallelMasterDirective::Create(
9098       Context, StartLoc, EndLoc, Clauses, AStmt,
9099       DSAStack->getTaskgroupReductionRef());
9100 }
9101 
9102 StmtResult
9103 Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
9104                                            Stmt *AStmt, SourceLocation StartLoc,
9105                                            SourceLocation EndLoc) {
9106   if (!AStmt)
9107     return StmtError();
9108 
9109   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
9110   auto BaseStmt = AStmt;
9111   while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
9112     BaseStmt = CS->getCapturedStmt();
9113   if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
9114     auto S = C->children();
9115     if (S.begin() == S.end())
9116       return StmtError();
9117     // All associated statements must be '#pragma omp section' except for
9118     // the first one.
9119     for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
9120       if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
9121         if (SectionStmt)
9122           Diag(SectionStmt->getBeginLoc(),
9123                diag::err_omp_parallel_sections_substmt_not_section);
9124         return StmtError();
9125       }
9126       cast<OMPSectionDirective>(SectionStmt)
9127           ->setHasCancel(DSAStack->isCancelRegion());
9128     }
9129   } else {
9130     Diag(AStmt->getBeginLoc(),
9131          diag::err_omp_parallel_sections_not_compound_stmt);
9132     return StmtError();
9133   }
9134 
9135   setFunctionHasBranchProtectedScope();
9136 
9137   return OMPParallelSectionsDirective::Create(
9138       Context, StartLoc, EndLoc, Clauses, AStmt,
9139       DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion());
9140 }
9141 
9142 /// detach and mergeable clauses are mutially exclusive, check for it.
9143 static bool checkDetachMergeableClauses(Sema &S,
9144                                         ArrayRef<OMPClause *> Clauses) {
9145   const OMPClause *PrevClause = nullptr;
9146   bool ErrorFound = false;
9147   for (const OMPClause *C : Clauses) {
9148     if (C->getClauseKind() == OMPC_detach ||
9149         C->getClauseKind() == OMPC_mergeable) {
9150       if (!PrevClause) {
9151         PrevClause = C;
9152       } else if (PrevClause->getClauseKind() != C->getClauseKind()) {
9153         S.Diag(C->getBeginLoc(), diag::err_omp_clauses_mutually_exclusive)
9154             << getOpenMPClauseName(C->getClauseKind())
9155             << getOpenMPClauseName(PrevClause->getClauseKind());
9156         S.Diag(PrevClause->getBeginLoc(), diag::note_omp_previous_clause)
9157             << getOpenMPClauseName(PrevClause->getClauseKind());
9158         ErrorFound = true;
9159       }
9160     }
9161   }
9162   return ErrorFound;
9163 }
9164 
9165 StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
9166                                           Stmt *AStmt, SourceLocation StartLoc,
9167                                           SourceLocation EndLoc) {
9168   if (!AStmt)
9169     return StmtError();
9170 
9171   // OpenMP 5.0, 2.10.1 task Construct
9172   // If a detach clause appears on the directive, then a mergeable clause cannot
9173   // appear on the same directive.
9174   if (checkDetachMergeableClauses(*this, Clauses))
9175     return StmtError();
9176 
9177   auto *CS = cast<CapturedStmt>(AStmt);
9178   // 1.2.2 OpenMP Language Terminology
9179   // Structured block - An executable statement with a single entry at the
9180   // top and a single exit at the bottom.
9181   // The point of exit cannot be a branch out of the structured block.
9182   // longjmp() and throw() must not violate the entry/exit criteria.
9183   CS->getCapturedDecl()->setNothrow();
9184 
9185   setFunctionHasBranchProtectedScope();
9186 
9187   return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
9188                                   DSAStack->isCancelRegion());
9189 }
9190 
9191 StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
9192                                                SourceLocation EndLoc) {
9193   return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc);
9194 }
9195 
9196 StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
9197                                              SourceLocation EndLoc) {
9198   return OMPBarrierDirective::Create(Context, StartLoc, EndLoc);
9199 }
9200 
9201 StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
9202                                               SourceLocation EndLoc) {
9203   return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc);
9204 }
9205 
9206 StmtResult Sema::ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses,
9207                                                Stmt *AStmt,
9208                                                SourceLocation StartLoc,
9209                                                SourceLocation EndLoc) {
9210   if (!AStmt)
9211     return StmtError();
9212 
9213   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
9214 
9215   setFunctionHasBranchProtectedScope();
9216 
9217   return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, Clauses,
9218                                        AStmt,
9219                                        DSAStack->getTaskgroupReductionRef());
9220 }
9221 
9222 StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
9223                                            SourceLocation StartLoc,
9224                                            SourceLocation EndLoc) {
9225   OMPFlushClause *FC = nullptr;
9226   OMPClause *OrderClause = nullptr;
9227   for (OMPClause *C : Clauses) {
9228     if (C->getClauseKind() == OMPC_flush)
9229       FC = cast<OMPFlushClause>(C);
9230     else
9231       OrderClause = C;
9232   }
9233   OpenMPClauseKind MemOrderKind = OMPC_unknown;
9234   SourceLocation MemOrderLoc;
9235   for (const OMPClause *C : Clauses) {
9236     if (C->getClauseKind() == OMPC_acq_rel ||
9237         C->getClauseKind() == OMPC_acquire ||
9238         C->getClauseKind() == OMPC_release) {
9239       if (MemOrderKind != OMPC_unknown) {
9240         Diag(C->getBeginLoc(), diag::err_omp_several_mem_order_clauses)
9241             << getOpenMPDirectiveName(OMPD_flush) << 1
9242             << SourceRange(C->getBeginLoc(), C->getEndLoc());
9243         Diag(MemOrderLoc, diag::note_omp_previous_mem_order_clause)
9244             << getOpenMPClauseName(MemOrderKind);
9245       } else {
9246         MemOrderKind = C->getClauseKind();
9247         MemOrderLoc = C->getBeginLoc();
9248       }
9249     }
9250   }
9251   if (FC && OrderClause) {
9252     Diag(FC->getLParenLoc(), diag::err_omp_flush_order_clause_and_list)
9253         << getOpenMPClauseName(OrderClause->getClauseKind());
9254     Diag(OrderClause->getBeginLoc(), diag::note_omp_flush_order_clause_here)
9255         << getOpenMPClauseName(OrderClause->getClauseKind());
9256     return StmtError();
9257   }
9258   return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses);
9259 }
9260 
9261 StmtResult Sema::ActOnOpenMPDepobjDirective(ArrayRef<OMPClause *> Clauses,
9262                                             SourceLocation StartLoc,
9263                                             SourceLocation EndLoc) {
9264   if (Clauses.empty()) {
9265     Diag(StartLoc, diag::err_omp_depobj_expected);
9266     return StmtError();
9267   } else if (Clauses[0]->getClauseKind() != OMPC_depobj) {
9268     Diag(Clauses[0]->getBeginLoc(), diag::err_omp_depobj_expected);
9269     return StmtError();
9270   }
9271   // Only depobj expression and another single clause is allowed.
9272   if (Clauses.size() > 2) {
9273     Diag(Clauses[2]->getBeginLoc(),
9274          diag::err_omp_depobj_single_clause_expected);
9275     return StmtError();
9276   } else if (Clauses.size() < 1) {
9277     Diag(Clauses[0]->getEndLoc(), diag::err_omp_depobj_single_clause_expected);
9278     return StmtError();
9279   }
9280   return OMPDepobjDirective::Create(Context, StartLoc, EndLoc, Clauses);
9281 }
9282 
9283 StmtResult Sema::ActOnOpenMPScanDirective(ArrayRef<OMPClause *> Clauses,
9284                                           SourceLocation StartLoc,
9285                                           SourceLocation EndLoc) {
9286   // Check that exactly one clause is specified.
9287   if (Clauses.size() != 1) {
9288     Diag(Clauses.empty() ? EndLoc : Clauses[1]->getBeginLoc(),
9289          diag::err_omp_scan_single_clause_expected);
9290     return StmtError();
9291   }
9292   // Check that scan directive is used in the scopeof the OpenMP loop body.
9293   if (Scope *S = DSAStack->getCurScope()) {
9294     Scope *ParentS = S->getParent();
9295     if (!ParentS || ParentS->getParent() != ParentS->getBreakParent() ||
9296         !ParentS->getBreakParent()->isOpenMPLoopScope())
9297       return StmtError(Diag(StartLoc, diag::err_omp_orphaned_device_directive)
9298                        << getOpenMPDirectiveName(OMPD_scan) << 5);
9299   }
9300   // Check that only one instance of scan directives is used in the same outer
9301   // region.
9302   if (DSAStack->doesParentHasScanDirective()) {
9303     Diag(StartLoc, diag::err_omp_several_directives_in_region) << "scan";
9304     Diag(DSAStack->getParentScanDirectiveLoc(),
9305          diag::note_omp_previous_directive)
9306         << "scan";
9307     return StmtError();
9308   }
9309   DSAStack->setParentHasScanDirective(StartLoc);
9310   return OMPScanDirective::Create(Context, StartLoc, EndLoc, Clauses);
9311 }
9312 
9313 StmtResult Sema::ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
9314                                              Stmt *AStmt,
9315                                              SourceLocation StartLoc,
9316                                              SourceLocation EndLoc) {
9317   const OMPClause *DependFound = nullptr;
9318   const OMPClause *DependSourceClause = nullptr;
9319   const OMPClause *DependSinkClause = nullptr;
9320   bool ErrorFound = false;
9321   const OMPThreadsClause *TC = nullptr;
9322   const OMPSIMDClause *SC = nullptr;
9323   for (const OMPClause *C : Clauses) {
9324     if (auto *DC = dyn_cast<OMPDependClause>(C)) {
9325       DependFound = C;
9326       if (DC->getDependencyKind() == OMPC_DEPEND_source) {
9327         if (DependSourceClause) {
9328           Diag(C->getBeginLoc(), diag::err_omp_more_one_clause)
9329               << getOpenMPDirectiveName(OMPD_ordered)
9330               << getOpenMPClauseName(OMPC_depend) << 2;
9331           ErrorFound = true;
9332         } else {
9333           DependSourceClause = C;
9334         }
9335         if (DependSinkClause) {
9336           Diag(C->getBeginLoc(), diag::err_omp_depend_sink_source_not_allowed)
9337               << 0;
9338           ErrorFound = true;
9339         }
9340       } else if (DC->getDependencyKind() == OMPC_DEPEND_sink) {
9341         if (DependSourceClause) {
9342           Diag(C->getBeginLoc(), diag::err_omp_depend_sink_source_not_allowed)
9343               << 1;
9344           ErrorFound = true;
9345         }
9346         DependSinkClause = C;
9347       }
9348     } else if (C->getClauseKind() == OMPC_threads) {
9349       TC = cast<OMPThreadsClause>(C);
9350     } else if (C->getClauseKind() == OMPC_simd) {
9351       SC = cast<OMPSIMDClause>(C);
9352     }
9353   }
9354   if (!ErrorFound && !SC &&
9355       isOpenMPSimdDirective(DSAStack->getParentDirective())) {
9356     // OpenMP [2.8.1,simd Construct, Restrictions]
9357     // An ordered construct with the simd clause is the only OpenMP construct
9358     // that can appear in the simd region.
9359     Diag(StartLoc, diag::err_omp_prohibited_region_simd)
9360         << (LangOpts.OpenMP >= 50 ? 1 : 0);
9361     ErrorFound = true;
9362   } else if (DependFound && (TC || SC)) {
9363     Diag(DependFound->getBeginLoc(), diag::err_omp_depend_clause_thread_simd)
9364         << getOpenMPClauseName(TC ? TC->getClauseKind() : SC->getClauseKind());
9365     ErrorFound = true;
9366   } else if (DependFound && !DSAStack->getParentOrderedRegionParam().first) {
9367     Diag(DependFound->getBeginLoc(),
9368          diag::err_omp_ordered_directive_without_param);
9369     ErrorFound = true;
9370   } else if (TC || Clauses.empty()) {
9371     if (const Expr *Param = DSAStack->getParentOrderedRegionParam().first) {
9372       SourceLocation ErrLoc = TC ? TC->getBeginLoc() : StartLoc;
9373       Diag(ErrLoc, diag::err_omp_ordered_directive_with_param)
9374           << (TC != nullptr);
9375       Diag(Param->getBeginLoc(), diag::note_omp_ordered_param) << 1;
9376       ErrorFound = true;
9377     }
9378   }
9379   if ((!AStmt && !DependFound) || ErrorFound)
9380     return StmtError();
9381 
9382   // OpenMP 5.0, 2.17.9, ordered Construct, Restrictions.
9383   // During execution of an iteration of a worksharing-loop or a loop nest
9384   // within a worksharing-loop, simd, or worksharing-loop SIMD region, a thread
9385   // must not execute more than one ordered region corresponding to an ordered
9386   // construct without a depend clause.
9387   if (!DependFound) {
9388     if (DSAStack->doesParentHasOrderedDirective()) {
9389       Diag(StartLoc, diag::err_omp_several_directives_in_region) << "ordered";
9390       Diag(DSAStack->getParentOrderedDirectiveLoc(),
9391            diag::note_omp_previous_directive)
9392           << "ordered";
9393       return StmtError();
9394     }
9395     DSAStack->setParentHasOrderedDirective(StartLoc);
9396   }
9397 
9398   if (AStmt) {
9399     assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
9400 
9401     setFunctionHasBranchProtectedScope();
9402   }
9403 
9404   return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
9405 }
9406 
9407 namespace {
9408 /// Helper class for checking expression in 'omp atomic [update]'
9409 /// construct.
9410 class OpenMPAtomicUpdateChecker {
9411   /// Error results for atomic update expressions.
9412   enum ExprAnalysisErrorCode {
9413     /// A statement is not an expression statement.
9414     NotAnExpression,
9415     /// Expression is not builtin binary or unary operation.
9416     NotABinaryOrUnaryExpression,
9417     /// Unary operation is not post-/pre- increment/decrement operation.
9418     NotAnUnaryIncDecExpression,
9419     /// An expression is not of scalar type.
9420     NotAScalarType,
9421     /// A binary operation is not an assignment operation.
9422     NotAnAssignmentOp,
9423     /// RHS part of the binary operation is not a binary expression.
9424     NotABinaryExpression,
9425     /// RHS part is not additive/multiplicative/shift/biwise binary
9426     /// expression.
9427     NotABinaryOperator,
9428     /// RHS binary operation does not have reference to the updated LHS
9429     /// part.
9430     NotAnUpdateExpression,
9431     /// No errors is found.
9432     NoError
9433   };
9434   /// Reference to Sema.
9435   Sema &SemaRef;
9436   /// A location for note diagnostics (when error is found).
9437   SourceLocation NoteLoc;
9438   /// 'x' lvalue part of the source atomic expression.
9439   Expr *X;
9440   /// 'expr' rvalue part of the source atomic expression.
9441   Expr *E;
9442   /// Helper expression of the form
9443   /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
9444   /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
9445   Expr *UpdateExpr;
9446   /// Is 'x' a LHS in a RHS part of full update expression. It is
9447   /// important for non-associative operations.
9448   bool IsXLHSInRHSPart;
9449   BinaryOperatorKind Op;
9450   SourceLocation OpLoc;
9451   /// true if the source expression is a postfix unary operation, false
9452   /// if it is a prefix unary operation.
9453   bool IsPostfixUpdate;
9454 
9455 public:
9456   OpenMPAtomicUpdateChecker(Sema &SemaRef)
9457       : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr),
9458         IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {}
9459   /// Check specified statement that it is suitable for 'atomic update'
9460   /// constructs and extract 'x', 'expr' and Operation from the original
9461   /// expression. If DiagId and NoteId == 0, then only check is performed
9462   /// without error notification.
9463   /// \param DiagId Diagnostic which should be emitted if error is found.
9464   /// \param NoteId Diagnostic note for the main error message.
9465   /// \return true if statement is not an update expression, false otherwise.
9466   bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0);
9467   /// Return the 'x' lvalue part of the source atomic expression.
9468   Expr *getX() const { return X; }
9469   /// Return the 'expr' rvalue part of the source atomic expression.
9470   Expr *getExpr() const { return E; }
9471   /// Return the update expression used in calculation of the updated
9472   /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
9473   /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
9474   Expr *getUpdateExpr() const { return UpdateExpr; }
9475   /// Return true if 'x' is LHS in RHS part of full update expression,
9476   /// false otherwise.
9477   bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; }
9478 
9479   /// true if the source expression is a postfix unary operation, false
9480   /// if it is a prefix unary operation.
9481   bool isPostfixUpdate() const { return IsPostfixUpdate; }
9482 
9483 private:
9484   bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0,
9485                             unsigned NoteId = 0);
9486 };
9487 } // namespace
9488 
9489 bool OpenMPAtomicUpdateChecker::checkBinaryOperation(
9490     BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) {
9491   ExprAnalysisErrorCode ErrorFound = NoError;
9492   SourceLocation ErrorLoc, NoteLoc;
9493   SourceRange ErrorRange, NoteRange;
9494   // Allowed constructs are:
9495   //  x = x binop expr;
9496   //  x = expr binop x;
9497   if (AtomicBinOp->getOpcode() == BO_Assign) {
9498     X = AtomicBinOp->getLHS();
9499     if (const auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>(
9500             AtomicBinOp->getRHS()->IgnoreParenImpCasts())) {
9501       if (AtomicInnerBinOp->isMultiplicativeOp() ||
9502           AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() ||
9503           AtomicInnerBinOp->isBitwiseOp()) {
9504         Op = AtomicInnerBinOp->getOpcode();
9505         OpLoc = AtomicInnerBinOp->getOperatorLoc();
9506         Expr *LHS = AtomicInnerBinOp->getLHS();
9507         Expr *RHS = AtomicInnerBinOp->getRHS();
9508         llvm::FoldingSetNodeID XId, LHSId, RHSId;
9509         X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(),
9510                                           /*Canonical=*/true);
9511         LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(),
9512                                             /*Canonical=*/true);
9513         RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(),
9514                                             /*Canonical=*/true);
9515         if (XId == LHSId) {
9516           E = RHS;
9517           IsXLHSInRHSPart = true;
9518         } else if (XId == RHSId) {
9519           E = LHS;
9520           IsXLHSInRHSPart = false;
9521         } else {
9522           ErrorLoc = AtomicInnerBinOp->getExprLoc();
9523           ErrorRange = AtomicInnerBinOp->getSourceRange();
9524           NoteLoc = X->getExprLoc();
9525           NoteRange = X->getSourceRange();
9526           ErrorFound = NotAnUpdateExpression;
9527         }
9528       } else {
9529         ErrorLoc = AtomicInnerBinOp->getExprLoc();
9530         ErrorRange = AtomicInnerBinOp->getSourceRange();
9531         NoteLoc = AtomicInnerBinOp->getOperatorLoc();
9532         NoteRange = SourceRange(NoteLoc, NoteLoc);
9533         ErrorFound = NotABinaryOperator;
9534       }
9535     } else {
9536       NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc();
9537       NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange();
9538       ErrorFound = NotABinaryExpression;
9539     }
9540   } else {
9541     ErrorLoc = AtomicBinOp->getExprLoc();
9542     ErrorRange = AtomicBinOp->getSourceRange();
9543     NoteLoc = AtomicBinOp->getOperatorLoc();
9544     NoteRange = SourceRange(NoteLoc, NoteLoc);
9545     ErrorFound = NotAnAssignmentOp;
9546   }
9547   if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
9548     SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
9549     SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
9550     return true;
9551   }
9552   if (SemaRef.CurContext->isDependentContext())
9553     E = X = UpdateExpr = nullptr;
9554   return ErrorFound != NoError;
9555 }
9556 
9557 bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId,
9558                                                unsigned NoteId) {
9559   ExprAnalysisErrorCode ErrorFound = NoError;
9560   SourceLocation ErrorLoc, NoteLoc;
9561   SourceRange ErrorRange, NoteRange;
9562   // Allowed constructs are:
9563   //  x++;
9564   //  x--;
9565   //  ++x;
9566   //  --x;
9567   //  x binop= expr;
9568   //  x = x binop expr;
9569   //  x = expr binop x;
9570   if (auto *AtomicBody = dyn_cast<Expr>(S)) {
9571     AtomicBody = AtomicBody->IgnoreParenImpCasts();
9572     if (AtomicBody->getType()->isScalarType() ||
9573         AtomicBody->isInstantiationDependent()) {
9574       if (const auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>(
9575               AtomicBody->IgnoreParenImpCasts())) {
9576         // Check for Compound Assignment Operation
9577         Op = BinaryOperator::getOpForCompoundAssignment(
9578             AtomicCompAssignOp->getOpcode());
9579         OpLoc = AtomicCompAssignOp->getOperatorLoc();
9580         E = AtomicCompAssignOp->getRHS();
9581         X = AtomicCompAssignOp->getLHS()->IgnoreParens();
9582         IsXLHSInRHSPart = true;
9583       } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>(
9584                      AtomicBody->IgnoreParenImpCasts())) {
9585         // Check for Binary Operation
9586         if (checkBinaryOperation(AtomicBinOp, DiagId, NoteId))
9587           return true;
9588       } else if (const auto *AtomicUnaryOp = dyn_cast<UnaryOperator>(
9589                      AtomicBody->IgnoreParenImpCasts())) {
9590         // Check for Unary Operation
9591         if (AtomicUnaryOp->isIncrementDecrementOp()) {
9592           IsPostfixUpdate = AtomicUnaryOp->isPostfix();
9593           Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub;
9594           OpLoc = AtomicUnaryOp->getOperatorLoc();
9595           X = AtomicUnaryOp->getSubExpr()->IgnoreParens();
9596           E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get();
9597           IsXLHSInRHSPart = true;
9598         } else {
9599           ErrorFound = NotAnUnaryIncDecExpression;
9600           ErrorLoc = AtomicUnaryOp->getExprLoc();
9601           ErrorRange = AtomicUnaryOp->getSourceRange();
9602           NoteLoc = AtomicUnaryOp->getOperatorLoc();
9603           NoteRange = SourceRange(NoteLoc, NoteLoc);
9604         }
9605       } else if (!AtomicBody->isInstantiationDependent()) {
9606         ErrorFound = NotABinaryOrUnaryExpression;
9607         NoteLoc = ErrorLoc = AtomicBody->getExprLoc();
9608         NoteRange = ErrorRange = AtomicBody->getSourceRange();
9609       }
9610     } else {
9611       ErrorFound = NotAScalarType;
9612       NoteLoc = ErrorLoc = AtomicBody->getBeginLoc();
9613       NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
9614     }
9615   } else {
9616     ErrorFound = NotAnExpression;
9617     NoteLoc = ErrorLoc = S->getBeginLoc();
9618     NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
9619   }
9620   if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
9621     SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
9622     SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
9623     return true;
9624   }
9625   if (SemaRef.CurContext->isDependentContext())
9626     E = X = UpdateExpr = nullptr;
9627   if (ErrorFound == NoError && E && X) {
9628     // Build an update expression of form 'OpaqueValueExpr(x) binop
9629     // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop
9630     // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression.
9631     auto *OVEX = new (SemaRef.getASTContext())
9632         OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue);
9633     auto *OVEExpr = new (SemaRef.getASTContext())
9634         OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue);
9635     ExprResult Update =
9636         SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr,
9637                                    IsXLHSInRHSPart ? OVEExpr : OVEX);
9638     if (Update.isInvalid())
9639       return true;
9640     Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(),
9641                                                Sema::AA_Casting);
9642     if (Update.isInvalid())
9643       return true;
9644     UpdateExpr = Update.get();
9645   }
9646   return ErrorFound != NoError;
9647 }
9648 
9649 StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
9650                                             Stmt *AStmt,
9651                                             SourceLocation StartLoc,
9652                                             SourceLocation EndLoc) {
9653   // Register location of the first atomic directive.
9654   DSAStack->addAtomicDirectiveLoc(StartLoc);
9655   if (!AStmt)
9656     return StmtError();
9657 
9658   auto *CS = cast<CapturedStmt>(AStmt);
9659   // 1.2.2 OpenMP Language Terminology
9660   // Structured block - An executable statement with a single entry at the
9661   // top and a single exit at the bottom.
9662   // The point of exit cannot be a branch out of the structured block.
9663   // longjmp() and throw() must not violate the entry/exit criteria.
9664   OpenMPClauseKind AtomicKind = OMPC_unknown;
9665   SourceLocation AtomicKindLoc;
9666   OpenMPClauseKind MemOrderKind = OMPC_unknown;
9667   SourceLocation MemOrderLoc;
9668   for (const OMPClause *C : Clauses) {
9669     if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write ||
9670         C->getClauseKind() == OMPC_update ||
9671         C->getClauseKind() == OMPC_capture) {
9672       if (AtomicKind != OMPC_unknown) {
9673         Diag(C->getBeginLoc(), diag::err_omp_atomic_several_clauses)
9674             << SourceRange(C->getBeginLoc(), C->getEndLoc());
9675         Diag(AtomicKindLoc, diag::note_omp_previous_mem_order_clause)
9676             << getOpenMPClauseName(AtomicKind);
9677       } else {
9678         AtomicKind = C->getClauseKind();
9679         AtomicKindLoc = C->getBeginLoc();
9680       }
9681     }
9682     if (C->getClauseKind() == OMPC_seq_cst ||
9683         C->getClauseKind() == OMPC_acq_rel ||
9684         C->getClauseKind() == OMPC_acquire ||
9685         C->getClauseKind() == OMPC_release ||
9686         C->getClauseKind() == OMPC_relaxed) {
9687       if (MemOrderKind != OMPC_unknown) {
9688         Diag(C->getBeginLoc(), diag::err_omp_several_mem_order_clauses)
9689             << getOpenMPDirectiveName(OMPD_atomic) << 0
9690             << SourceRange(C->getBeginLoc(), C->getEndLoc());
9691         Diag(MemOrderLoc, diag::note_omp_previous_mem_order_clause)
9692             << getOpenMPClauseName(MemOrderKind);
9693       } else {
9694         MemOrderKind = C->getClauseKind();
9695         MemOrderLoc = C->getBeginLoc();
9696       }
9697     }
9698   }
9699   // OpenMP 5.0, 2.17.7 atomic Construct, Restrictions
9700   // If atomic-clause is read then memory-order-clause must not be acq_rel or
9701   // release.
9702   // If atomic-clause is write then memory-order-clause must not be acq_rel or
9703   // acquire.
9704   // If atomic-clause is update or not present then memory-order-clause must not
9705   // be acq_rel or acquire.
9706   if ((AtomicKind == OMPC_read &&
9707        (MemOrderKind == OMPC_acq_rel || MemOrderKind == OMPC_release)) ||
9708       ((AtomicKind == OMPC_write || AtomicKind == OMPC_update ||
9709         AtomicKind == OMPC_unknown) &&
9710        (MemOrderKind == OMPC_acq_rel || MemOrderKind == OMPC_acquire))) {
9711     SourceLocation Loc = AtomicKindLoc;
9712     if (AtomicKind == OMPC_unknown)
9713       Loc = StartLoc;
9714     Diag(Loc, diag::err_omp_atomic_incompatible_mem_order_clause)
9715         << getOpenMPClauseName(AtomicKind)
9716         << (AtomicKind == OMPC_unknown ? 1 : 0)
9717         << getOpenMPClauseName(MemOrderKind);
9718     Diag(MemOrderLoc, diag::note_omp_previous_mem_order_clause)
9719         << getOpenMPClauseName(MemOrderKind);
9720   }
9721 
9722   Stmt *Body = CS->getCapturedStmt();
9723   if (auto *EWC = dyn_cast<ExprWithCleanups>(Body))
9724     Body = EWC->getSubExpr();
9725 
9726   Expr *X = nullptr;
9727   Expr *V = nullptr;
9728   Expr *E = nullptr;
9729   Expr *UE = nullptr;
9730   bool IsXLHSInRHSPart = false;
9731   bool IsPostfixUpdate = false;
9732   // OpenMP [2.12.6, atomic Construct]
9733   // In the next expressions:
9734   // * x and v (as applicable) are both l-value expressions with scalar type.
9735   // * During the execution of an atomic region, multiple syntactic
9736   // occurrences of x must designate the same storage location.
9737   // * Neither of v and expr (as applicable) may access the storage location
9738   // designated by x.
9739   // * Neither of x and expr (as applicable) may access the storage location
9740   // designated by v.
9741   // * expr is an expression with scalar type.
9742   // * binop is one of +, *, -, /, &, ^, |, <<, or >>.
9743   // * binop, binop=, ++, and -- are not overloaded operators.
9744   // * The expression x binop expr must be numerically equivalent to x binop
9745   // (expr). This requirement is satisfied if the operators in expr have
9746   // precedence greater than binop, or by using parentheses around expr or
9747   // subexpressions of expr.
9748   // * The expression expr binop x must be numerically equivalent to (expr)
9749   // binop x. This requirement is satisfied if the operators in expr have
9750   // precedence equal to or greater than binop, or by using parentheses around
9751   // expr or subexpressions of expr.
9752   // * For forms that allow multiple occurrences of x, the number of times
9753   // that x is evaluated is unspecified.
9754   if (AtomicKind == OMPC_read) {
9755     enum {
9756       NotAnExpression,
9757       NotAnAssignmentOp,
9758       NotAScalarType,
9759       NotAnLValue,
9760       NoError
9761     } ErrorFound = NoError;
9762     SourceLocation ErrorLoc, NoteLoc;
9763     SourceRange ErrorRange, NoteRange;
9764     // If clause is read:
9765     //  v = x;
9766     if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
9767       const auto *AtomicBinOp =
9768           dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
9769       if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
9770         X = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
9771         V = AtomicBinOp->getLHS()->IgnoreParenImpCasts();
9772         if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
9773             (V->isInstantiationDependent() || V->getType()->isScalarType())) {
9774           if (!X->isLValue() || !V->isLValue()) {
9775             const Expr *NotLValueExpr = X->isLValue() ? V : X;
9776             ErrorFound = NotAnLValue;
9777             ErrorLoc = AtomicBinOp->getExprLoc();
9778             ErrorRange = AtomicBinOp->getSourceRange();
9779             NoteLoc = NotLValueExpr->getExprLoc();
9780             NoteRange = NotLValueExpr->getSourceRange();
9781           }
9782         } else if (!X->isInstantiationDependent() ||
9783                    !V->isInstantiationDependent()) {
9784           const Expr *NotScalarExpr =
9785               (X->isInstantiationDependent() || X->getType()->isScalarType())
9786                   ? V
9787                   : X;
9788           ErrorFound = NotAScalarType;
9789           ErrorLoc = AtomicBinOp->getExprLoc();
9790           ErrorRange = AtomicBinOp->getSourceRange();
9791           NoteLoc = NotScalarExpr->getExprLoc();
9792           NoteRange = NotScalarExpr->getSourceRange();
9793         }
9794       } else if (!AtomicBody->isInstantiationDependent()) {
9795         ErrorFound = NotAnAssignmentOp;
9796         ErrorLoc = AtomicBody->getExprLoc();
9797         ErrorRange = AtomicBody->getSourceRange();
9798         NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
9799                               : AtomicBody->getExprLoc();
9800         NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
9801                                 : AtomicBody->getSourceRange();
9802       }
9803     } else {
9804       ErrorFound = NotAnExpression;
9805       NoteLoc = ErrorLoc = Body->getBeginLoc();
9806       NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
9807     }
9808     if (ErrorFound != NoError) {
9809       Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement)
9810           << ErrorRange;
9811       Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
9812                                                       << NoteRange;
9813       return StmtError();
9814     }
9815     if (CurContext->isDependentContext())
9816       V = X = nullptr;
9817   } else if (AtomicKind == OMPC_write) {
9818     enum {
9819       NotAnExpression,
9820       NotAnAssignmentOp,
9821       NotAScalarType,
9822       NotAnLValue,
9823       NoError
9824     } ErrorFound = NoError;
9825     SourceLocation ErrorLoc, NoteLoc;
9826     SourceRange ErrorRange, NoteRange;
9827     // If clause is write:
9828     //  x = expr;
9829     if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
9830       const auto *AtomicBinOp =
9831           dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
9832       if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
9833         X = AtomicBinOp->getLHS();
9834         E = AtomicBinOp->getRHS();
9835         if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
9836             (E->isInstantiationDependent() || E->getType()->isScalarType())) {
9837           if (!X->isLValue()) {
9838             ErrorFound = NotAnLValue;
9839             ErrorLoc = AtomicBinOp->getExprLoc();
9840             ErrorRange = AtomicBinOp->getSourceRange();
9841             NoteLoc = X->getExprLoc();
9842             NoteRange = X->getSourceRange();
9843           }
9844         } else if (!X->isInstantiationDependent() ||
9845                    !E->isInstantiationDependent()) {
9846           const Expr *NotScalarExpr =
9847               (X->isInstantiationDependent() || X->getType()->isScalarType())
9848                   ? E
9849                   : X;
9850           ErrorFound = NotAScalarType;
9851           ErrorLoc = AtomicBinOp->getExprLoc();
9852           ErrorRange = AtomicBinOp->getSourceRange();
9853           NoteLoc = NotScalarExpr->getExprLoc();
9854           NoteRange = NotScalarExpr->getSourceRange();
9855         }
9856       } else if (!AtomicBody->isInstantiationDependent()) {
9857         ErrorFound = NotAnAssignmentOp;
9858         ErrorLoc = AtomicBody->getExprLoc();
9859         ErrorRange = AtomicBody->getSourceRange();
9860         NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
9861                               : AtomicBody->getExprLoc();
9862         NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
9863                                 : AtomicBody->getSourceRange();
9864       }
9865     } else {
9866       ErrorFound = NotAnExpression;
9867       NoteLoc = ErrorLoc = Body->getBeginLoc();
9868       NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
9869     }
9870     if (ErrorFound != NoError) {
9871       Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement)
9872           << ErrorRange;
9873       Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
9874                                                       << NoteRange;
9875       return StmtError();
9876     }
9877     if (CurContext->isDependentContext())
9878       E = X = nullptr;
9879   } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) {
9880     // If clause is update:
9881     //  x++;
9882     //  x--;
9883     //  ++x;
9884     //  --x;
9885     //  x binop= expr;
9886     //  x = x binop expr;
9887     //  x = expr binop x;
9888     OpenMPAtomicUpdateChecker Checker(*this);
9889     if (Checker.checkStatement(
9890             Body, (AtomicKind == OMPC_update)
9891                       ? diag::err_omp_atomic_update_not_expression_statement
9892                       : diag::err_omp_atomic_not_expression_statement,
9893             diag::note_omp_atomic_update))
9894       return StmtError();
9895     if (!CurContext->isDependentContext()) {
9896       E = Checker.getExpr();
9897       X = Checker.getX();
9898       UE = Checker.getUpdateExpr();
9899       IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
9900     }
9901   } else if (AtomicKind == OMPC_capture) {
9902     enum {
9903       NotAnAssignmentOp,
9904       NotACompoundStatement,
9905       NotTwoSubstatements,
9906       NotASpecificExpression,
9907       NoError
9908     } ErrorFound = NoError;
9909     SourceLocation ErrorLoc, NoteLoc;
9910     SourceRange ErrorRange, NoteRange;
9911     if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
9912       // If clause is a capture:
9913       //  v = x++;
9914       //  v = x--;
9915       //  v = ++x;
9916       //  v = --x;
9917       //  v = x binop= expr;
9918       //  v = x = x binop expr;
9919       //  v = x = expr binop x;
9920       const auto *AtomicBinOp =
9921           dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
9922       if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
9923         V = AtomicBinOp->getLHS();
9924         Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
9925         OpenMPAtomicUpdateChecker Checker(*this);
9926         if (Checker.checkStatement(
9927                 Body, diag::err_omp_atomic_capture_not_expression_statement,
9928                 diag::note_omp_atomic_update))
9929           return StmtError();
9930         E = Checker.getExpr();
9931         X = Checker.getX();
9932         UE = Checker.getUpdateExpr();
9933         IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
9934         IsPostfixUpdate = Checker.isPostfixUpdate();
9935       } else if (!AtomicBody->isInstantiationDependent()) {
9936         ErrorLoc = AtomicBody->getExprLoc();
9937         ErrorRange = AtomicBody->getSourceRange();
9938         NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
9939                               : AtomicBody->getExprLoc();
9940         NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
9941                                 : AtomicBody->getSourceRange();
9942         ErrorFound = NotAnAssignmentOp;
9943       }
9944       if (ErrorFound != NoError) {
9945         Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement)
9946             << ErrorRange;
9947         Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
9948         return StmtError();
9949       }
9950       if (CurContext->isDependentContext())
9951         UE = V = E = X = nullptr;
9952     } else {
9953       // If clause is a capture:
9954       //  { v = x; x = expr; }
9955       //  { v = x; x++; }
9956       //  { v = x; x--; }
9957       //  { v = x; ++x; }
9958       //  { v = x; --x; }
9959       //  { v = x; x binop= expr; }
9960       //  { v = x; x = x binop expr; }
9961       //  { v = x; x = expr binop x; }
9962       //  { x++; v = x; }
9963       //  { x--; v = x; }
9964       //  { ++x; v = x; }
9965       //  { --x; v = x; }
9966       //  { x binop= expr; v = x; }
9967       //  { x = x binop expr; v = x; }
9968       //  { x = expr binop x; v = x; }
9969       if (auto *CS = dyn_cast<CompoundStmt>(Body)) {
9970         // Check that this is { expr1; expr2; }
9971         if (CS->size() == 2) {
9972           Stmt *First = CS->body_front();
9973           Stmt *Second = CS->body_back();
9974           if (auto *EWC = dyn_cast<ExprWithCleanups>(First))
9975             First = EWC->getSubExpr()->IgnoreParenImpCasts();
9976           if (auto *EWC = dyn_cast<ExprWithCleanups>(Second))
9977             Second = EWC->getSubExpr()->IgnoreParenImpCasts();
9978           // Need to find what subexpression is 'v' and what is 'x'.
9979           OpenMPAtomicUpdateChecker Checker(*this);
9980           bool IsUpdateExprFound = !Checker.checkStatement(Second);
9981           BinaryOperator *BinOp = nullptr;
9982           if (IsUpdateExprFound) {
9983             BinOp = dyn_cast<BinaryOperator>(First);
9984             IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
9985           }
9986           if (IsUpdateExprFound && !CurContext->isDependentContext()) {
9987             //  { v = x; x++; }
9988             //  { v = x; x--; }
9989             //  { v = x; ++x; }
9990             //  { v = x; --x; }
9991             //  { v = x; x binop= expr; }
9992             //  { v = x; x = x binop expr; }
9993             //  { v = x; x = expr binop x; }
9994             // Check that the first expression has form v = x.
9995             Expr *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
9996             llvm::FoldingSetNodeID XId, PossibleXId;
9997             Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
9998             PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
9999             IsUpdateExprFound = XId == PossibleXId;
10000             if (IsUpdateExprFound) {
10001               V = BinOp->getLHS();
10002               X = Checker.getX();
10003               E = Checker.getExpr();
10004               UE = Checker.getUpdateExpr();
10005               IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
10006               IsPostfixUpdate = true;
10007             }
10008           }
10009           if (!IsUpdateExprFound) {
10010             IsUpdateExprFound = !Checker.checkStatement(First);
10011             BinOp = nullptr;
10012             if (IsUpdateExprFound) {
10013               BinOp = dyn_cast<BinaryOperator>(Second);
10014               IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
10015             }
10016             if (IsUpdateExprFound && !CurContext->isDependentContext()) {
10017               //  { x++; v = x; }
10018               //  { x--; v = x; }
10019               //  { ++x; v = x; }
10020               //  { --x; v = x; }
10021               //  { x binop= expr; v = x; }
10022               //  { x = x binop expr; v = x; }
10023               //  { x = expr binop x; v = x; }
10024               // Check that the second expression has form v = x.
10025               Expr *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
10026               llvm::FoldingSetNodeID XId, PossibleXId;
10027               Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
10028               PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
10029               IsUpdateExprFound = XId == PossibleXId;
10030               if (IsUpdateExprFound) {
10031                 V = BinOp->getLHS();
10032                 X = Checker.getX();
10033                 E = Checker.getExpr();
10034                 UE = Checker.getUpdateExpr();
10035                 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
10036                 IsPostfixUpdate = false;
10037               }
10038             }
10039           }
10040           if (!IsUpdateExprFound) {
10041             //  { v = x; x = expr; }
10042             auto *FirstExpr = dyn_cast<Expr>(First);
10043             auto *SecondExpr = dyn_cast<Expr>(Second);
10044             if (!FirstExpr || !SecondExpr ||
10045                 !(FirstExpr->isInstantiationDependent() ||
10046                   SecondExpr->isInstantiationDependent())) {
10047               auto *FirstBinOp = dyn_cast<BinaryOperator>(First);
10048               if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) {
10049                 ErrorFound = NotAnAssignmentOp;
10050                 NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc()
10051                                                 : First->getBeginLoc();
10052                 NoteRange = ErrorRange = FirstBinOp
10053                                              ? FirstBinOp->getSourceRange()
10054                                              : SourceRange(ErrorLoc, ErrorLoc);
10055               } else {
10056                 auto *SecondBinOp = dyn_cast<BinaryOperator>(Second);
10057                 if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) {
10058                   ErrorFound = NotAnAssignmentOp;
10059                   NoteLoc = ErrorLoc = SecondBinOp
10060                                            ? SecondBinOp->getOperatorLoc()
10061                                            : Second->getBeginLoc();
10062                   NoteRange = ErrorRange =
10063                       SecondBinOp ? SecondBinOp->getSourceRange()
10064                                   : SourceRange(ErrorLoc, ErrorLoc);
10065                 } else {
10066                   Expr *PossibleXRHSInFirst =
10067                       FirstBinOp->getRHS()->IgnoreParenImpCasts();
10068                   Expr *PossibleXLHSInSecond =
10069                       SecondBinOp->getLHS()->IgnoreParenImpCasts();
10070                   llvm::FoldingSetNodeID X1Id, X2Id;
10071                   PossibleXRHSInFirst->Profile(X1Id, Context,
10072                                                /*Canonical=*/true);
10073                   PossibleXLHSInSecond->Profile(X2Id, Context,
10074                                                 /*Canonical=*/true);
10075                   IsUpdateExprFound = X1Id == X2Id;
10076                   if (IsUpdateExprFound) {
10077                     V = FirstBinOp->getLHS();
10078                     X = SecondBinOp->getLHS();
10079                     E = SecondBinOp->getRHS();
10080                     UE = nullptr;
10081                     IsXLHSInRHSPart = false;
10082                     IsPostfixUpdate = true;
10083                   } else {
10084                     ErrorFound = NotASpecificExpression;
10085                     ErrorLoc = FirstBinOp->getExprLoc();
10086                     ErrorRange = FirstBinOp->getSourceRange();
10087                     NoteLoc = SecondBinOp->getLHS()->getExprLoc();
10088                     NoteRange = SecondBinOp->getRHS()->getSourceRange();
10089                   }
10090                 }
10091               }
10092             }
10093           }
10094         } else {
10095           NoteLoc = ErrorLoc = Body->getBeginLoc();
10096           NoteRange = ErrorRange =
10097               SourceRange(Body->getBeginLoc(), Body->getBeginLoc());
10098           ErrorFound = NotTwoSubstatements;
10099         }
10100       } else {
10101         NoteLoc = ErrorLoc = Body->getBeginLoc();
10102         NoteRange = ErrorRange =
10103             SourceRange(Body->getBeginLoc(), Body->getBeginLoc());
10104         ErrorFound = NotACompoundStatement;
10105       }
10106       if (ErrorFound != NoError) {
10107         Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement)
10108             << ErrorRange;
10109         Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
10110         return StmtError();
10111       }
10112       if (CurContext->isDependentContext())
10113         UE = V = E = X = nullptr;
10114     }
10115   }
10116 
10117   setFunctionHasBranchProtectedScope();
10118 
10119   return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
10120                                     X, V, E, UE, IsXLHSInRHSPart,
10121                                     IsPostfixUpdate);
10122 }
10123 
10124 StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
10125                                             Stmt *AStmt,
10126                                             SourceLocation StartLoc,
10127                                             SourceLocation EndLoc) {
10128   if (!AStmt)
10129     return StmtError();
10130 
10131   auto *CS = cast<CapturedStmt>(AStmt);
10132   // 1.2.2 OpenMP Language Terminology
10133   // Structured block - An executable statement with a single entry at the
10134   // top and a single exit at the bottom.
10135   // The point of exit cannot be a branch out of the structured block.
10136   // longjmp() and throw() must not violate the entry/exit criteria.
10137   CS->getCapturedDecl()->setNothrow();
10138   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target);
10139        ThisCaptureLevel > 1; --ThisCaptureLevel) {
10140     CS = cast<CapturedStmt>(CS->getCapturedStmt());
10141     // 1.2.2 OpenMP Language Terminology
10142     // Structured block - An executable statement with a single entry at the
10143     // top and a single exit at the bottom.
10144     // The point of exit cannot be a branch out of the structured block.
10145     // longjmp() and throw() must not violate the entry/exit criteria.
10146     CS->getCapturedDecl()->setNothrow();
10147   }
10148 
10149   // OpenMP [2.16, Nesting of Regions]
10150   // If specified, a teams construct must be contained within a target
10151   // construct. That target construct must contain no statements or directives
10152   // outside of the teams construct.
10153   if (DSAStack->hasInnerTeamsRegion()) {
10154     const Stmt *S = CS->IgnoreContainers(/*IgnoreCaptured=*/true);
10155     bool OMPTeamsFound = true;
10156     if (const auto *CS = dyn_cast<CompoundStmt>(S)) {
10157       auto I = CS->body_begin();
10158       while (I != CS->body_end()) {
10159         const auto *OED = dyn_cast<OMPExecutableDirective>(*I);
10160         if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind()) ||
10161             OMPTeamsFound) {
10162 
10163           OMPTeamsFound = false;
10164           break;
10165         }
10166         ++I;
10167       }
10168       assert(I != CS->body_end() && "Not found statement");
10169       S = *I;
10170     } else {
10171       const auto *OED = dyn_cast<OMPExecutableDirective>(S);
10172       OMPTeamsFound = OED && isOpenMPTeamsDirective(OED->getDirectiveKind());
10173     }
10174     if (!OMPTeamsFound) {
10175       Diag(StartLoc, diag::err_omp_target_contains_not_only_teams);
10176       Diag(DSAStack->getInnerTeamsRegionLoc(),
10177            diag::note_omp_nested_teams_construct_here);
10178       Diag(S->getBeginLoc(), diag::note_omp_nested_statement_here)
10179           << isa<OMPExecutableDirective>(S);
10180       return StmtError();
10181     }
10182   }
10183 
10184   setFunctionHasBranchProtectedScope();
10185 
10186   return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
10187 }
10188 
10189 StmtResult
10190 Sema::ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
10191                                          Stmt *AStmt, SourceLocation StartLoc,
10192                                          SourceLocation EndLoc) {
10193   if (!AStmt)
10194     return StmtError();
10195 
10196   auto *CS = cast<CapturedStmt>(AStmt);
10197   // 1.2.2 OpenMP Language Terminology
10198   // Structured block - An executable statement with a single entry at the
10199   // top and a single exit at the bottom.
10200   // The point of exit cannot be a branch out of the structured block.
10201   // longjmp() and throw() must not violate the entry/exit criteria.
10202   CS->getCapturedDecl()->setNothrow();
10203   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel);
10204        ThisCaptureLevel > 1; --ThisCaptureLevel) {
10205     CS = cast<CapturedStmt>(CS->getCapturedStmt());
10206     // 1.2.2 OpenMP Language Terminology
10207     // Structured block - An executable statement with a single entry at the
10208     // top and a single exit at the bottom.
10209     // The point of exit cannot be a branch out of the structured block.
10210     // longjmp() and throw() must not violate the entry/exit criteria.
10211     CS->getCapturedDecl()->setNothrow();
10212   }
10213 
10214   setFunctionHasBranchProtectedScope();
10215 
10216   return OMPTargetParallelDirective::Create(
10217       Context, StartLoc, EndLoc, Clauses, AStmt,
10218       DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion());
10219 }
10220 
10221 StmtResult Sema::ActOnOpenMPTargetParallelForDirective(
10222     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10223     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
10224   if (!AStmt)
10225     return StmtError();
10226 
10227   auto *CS = cast<CapturedStmt>(AStmt);
10228   // 1.2.2 OpenMP Language Terminology
10229   // Structured block - An executable statement with a single entry at the
10230   // top and a single exit at the bottom.
10231   // The point of exit cannot be a branch out of the structured block.
10232   // longjmp() and throw() must not violate the entry/exit criteria.
10233   CS->getCapturedDecl()->setNothrow();
10234   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
10235        ThisCaptureLevel > 1; --ThisCaptureLevel) {
10236     CS = cast<CapturedStmt>(CS->getCapturedStmt());
10237     // 1.2.2 OpenMP Language Terminology
10238     // Structured block - An executable statement with a single entry at the
10239     // top and a single exit at the bottom.
10240     // The point of exit cannot be a branch out of the structured block.
10241     // longjmp() and throw() must not violate the entry/exit criteria.
10242     CS->getCapturedDecl()->setNothrow();
10243   }
10244 
10245   OMPLoopDirective::HelperExprs B;
10246   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
10247   // define the nested loops number.
10248   unsigned NestedLoopCount =
10249       checkOpenMPLoop(OMPD_target_parallel_for, getCollapseNumberExpr(Clauses),
10250                       getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
10251                       VarsWithImplicitDSA, B);
10252   if (NestedLoopCount == 0)
10253     return StmtError();
10254 
10255   assert((CurContext->isDependentContext() || B.builtAll()) &&
10256          "omp target parallel for loop exprs were not built");
10257 
10258   if (!CurContext->isDependentContext()) {
10259     // Finalize the clauses that need pre-built expressions for CodeGen.
10260     for (OMPClause *C : Clauses) {
10261       if (auto *LC = dyn_cast<OMPLinearClause>(C))
10262         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
10263                                      B.NumIterations, *this, CurScope,
10264                                      DSAStack))
10265           return StmtError();
10266     }
10267   }
10268 
10269   setFunctionHasBranchProtectedScope();
10270   return OMPTargetParallelForDirective::Create(
10271       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
10272       DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion());
10273 }
10274 
10275 /// Check for existence of a map clause in the list of clauses.
10276 static bool hasClauses(ArrayRef<OMPClause *> Clauses,
10277                        const OpenMPClauseKind K) {
10278   return llvm::any_of(
10279       Clauses, [K](const OMPClause *C) { return C->getClauseKind() == K; });
10280 }
10281 
10282 template <typename... Params>
10283 static bool hasClauses(ArrayRef<OMPClause *> Clauses, const OpenMPClauseKind K,
10284                        const Params... ClauseTypes) {
10285   return hasClauses(Clauses, K) || hasClauses(Clauses, ClauseTypes...);
10286 }
10287 
10288 StmtResult Sema::ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
10289                                                 Stmt *AStmt,
10290                                                 SourceLocation StartLoc,
10291                                                 SourceLocation EndLoc) {
10292   if (!AStmt)
10293     return StmtError();
10294 
10295   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
10296 
10297   // OpenMP [2.12.2, target data Construct, Restrictions]
10298   // At least one map, use_device_addr or use_device_ptr clause must appear on
10299   // the directive.
10300   if (!hasClauses(Clauses, OMPC_map, OMPC_use_device_ptr) &&
10301       (LangOpts.OpenMP < 50 || !hasClauses(Clauses, OMPC_use_device_addr))) {
10302     StringRef Expected;
10303     if (LangOpts.OpenMP < 50)
10304       Expected = "'map' or 'use_device_ptr'";
10305     else
10306       Expected = "'map', 'use_device_ptr', or 'use_device_addr'";
10307     Diag(StartLoc, diag::err_omp_no_clause_for_directive)
10308         << Expected << getOpenMPDirectiveName(OMPD_target_data);
10309     return StmtError();
10310   }
10311 
10312   setFunctionHasBranchProtectedScope();
10313 
10314   return OMPTargetDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
10315                                         AStmt);
10316 }
10317 
10318 StmtResult
10319 Sema::ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
10320                                           SourceLocation StartLoc,
10321                                           SourceLocation EndLoc, Stmt *AStmt) {
10322   if (!AStmt)
10323     return StmtError();
10324 
10325   auto *CS = cast<CapturedStmt>(AStmt);
10326   // 1.2.2 OpenMP Language Terminology
10327   // Structured block - An executable statement with a single entry at the
10328   // top and a single exit at the bottom.
10329   // The point of exit cannot be a branch out of the structured block.
10330   // longjmp() and throw() must not violate the entry/exit criteria.
10331   CS->getCapturedDecl()->setNothrow();
10332   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_enter_data);
10333        ThisCaptureLevel > 1; --ThisCaptureLevel) {
10334     CS = cast<CapturedStmt>(CS->getCapturedStmt());
10335     // 1.2.2 OpenMP Language Terminology
10336     // Structured block - An executable statement with a single entry at the
10337     // top and a single exit at the bottom.
10338     // The point of exit cannot be a branch out of the structured block.
10339     // longjmp() and throw() must not violate the entry/exit criteria.
10340     CS->getCapturedDecl()->setNothrow();
10341   }
10342 
10343   // OpenMP [2.10.2, Restrictions, p. 99]
10344   // At least one map clause must appear on the directive.
10345   if (!hasClauses(Clauses, OMPC_map)) {
10346     Diag(StartLoc, diag::err_omp_no_clause_for_directive)
10347         << "'map'" << getOpenMPDirectiveName(OMPD_target_enter_data);
10348     return StmtError();
10349   }
10350 
10351   return OMPTargetEnterDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
10352                                              AStmt);
10353 }
10354 
10355 StmtResult
10356 Sema::ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
10357                                          SourceLocation StartLoc,
10358                                          SourceLocation EndLoc, Stmt *AStmt) {
10359   if (!AStmt)
10360     return StmtError();
10361 
10362   auto *CS = cast<CapturedStmt>(AStmt);
10363   // 1.2.2 OpenMP Language Terminology
10364   // Structured block - An executable statement with a single entry at the
10365   // top and a single exit at the bottom.
10366   // The point of exit cannot be a branch out of the structured block.
10367   // longjmp() and throw() must not violate the entry/exit criteria.
10368   CS->getCapturedDecl()->setNothrow();
10369   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_exit_data);
10370        ThisCaptureLevel > 1; --ThisCaptureLevel) {
10371     CS = cast<CapturedStmt>(CS->getCapturedStmt());
10372     // 1.2.2 OpenMP Language Terminology
10373     // Structured block - An executable statement with a single entry at the
10374     // top and a single exit at the bottom.
10375     // The point of exit cannot be a branch out of the structured block.
10376     // longjmp() and throw() must not violate the entry/exit criteria.
10377     CS->getCapturedDecl()->setNothrow();
10378   }
10379 
10380   // OpenMP [2.10.3, Restrictions, p. 102]
10381   // At least one map clause must appear on the directive.
10382   if (!hasClauses(Clauses, OMPC_map)) {
10383     Diag(StartLoc, diag::err_omp_no_clause_for_directive)
10384         << "'map'" << getOpenMPDirectiveName(OMPD_target_exit_data);
10385     return StmtError();
10386   }
10387 
10388   return OMPTargetExitDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
10389                                             AStmt);
10390 }
10391 
10392 StmtResult Sema::ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
10393                                                   SourceLocation StartLoc,
10394                                                   SourceLocation EndLoc,
10395                                                   Stmt *AStmt) {
10396   if (!AStmt)
10397     return StmtError();
10398 
10399   auto *CS = cast<CapturedStmt>(AStmt);
10400   // 1.2.2 OpenMP Language Terminology
10401   // Structured block - An executable statement with a single entry at the
10402   // top and a single exit at the bottom.
10403   // The point of exit cannot be a branch out of the structured block.
10404   // longjmp() and throw() must not violate the entry/exit criteria.
10405   CS->getCapturedDecl()->setNothrow();
10406   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_update);
10407        ThisCaptureLevel > 1; --ThisCaptureLevel) {
10408     CS = cast<CapturedStmt>(CS->getCapturedStmt());
10409     // 1.2.2 OpenMP Language Terminology
10410     // Structured block - An executable statement with a single entry at the
10411     // top and a single exit at the bottom.
10412     // The point of exit cannot be a branch out of the structured block.
10413     // longjmp() and throw() must not violate the entry/exit criteria.
10414     CS->getCapturedDecl()->setNothrow();
10415   }
10416 
10417   if (!hasClauses(Clauses, OMPC_to, OMPC_from)) {
10418     Diag(StartLoc, diag::err_omp_at_least_one_motion_clause_required);
10419     return StmtError();
10420   }
10421   return OMPTargetUpdateDirective::Create(Context, StartLoc, EndLoc, Clauses,
10422                                           AStmt);
10423 }
10424 
10425 StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
10426                                            Stmt *AStmt, SourceLocation StartLoc,
10427                                            SourceLocation EndLoc) {
10428   if (!AStmt)
10429     return StmtError();
10430 
10431   auto *CS = cast<CapturedStmt>(AStmt);
10432   // 1.2.2 OpenMP Language Terminology
10433   // Structured block - An executable statement with a single entry at the
10434   // top and a single exit at the bottom.
10435   // The point of exit cannot be a branch out of the structured block.
10436   // longjmp() and throw() must not violate the entry/exit criteria.
10437   CS->getCapturedDecl()->setNothrow();
10438 
10439   setFunctionHasBranchProtectedScope();
10440 
10441   DSAStack->setParentTeamsRegionLoc(StartLoc);
10442 
10443   return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
10444 }
10445 
10446 StmtResult
10447 Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
10448                                             SourceLocation EndLoc,
10449                                             OpenMPDirectiveKind CancelRegion) {
10450   if (DSAStack->isParentNowaitRegion()) {
10451     Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0;
10452     return StmtError();
10453   }
10454   if (DSAStack->isParentOrderedRegion()) {
10455     Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0;
10456     return StmtError();
10457   }
10458   return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc,
10459                                                CancelRegion);
10460 }
10461 
10462 StmtResult Sema::ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
10463                                             SourceLocation StartLoc,
10464                                             SourceLocation EndLoc,
10465                                             OpenMPDirectiveKind CancelRegion) {
10466   if (DSAStack->isParentNowaitRegion()) {
10467     Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1;
10468     return StmtError();
10469   }
10470   if (DSAStack->isParentOrderedRegion()) {
10471     Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1;
10472     return StmtError();
10473   }
10474   DSAStack->setParentCancelRegion(/*Cancel=*/true);
10475   return OMPCancelDirective::Create(Context, StartLoc, EndLoc, Clauses,
10476                                     CancelRegion);
10477 }
10478 
10479 static bool checkGrainsizeNumTasksClauses(Sema &S,
10480                                           ArrayRef<OMPClause *> Clauses) {
10481   const OMPClause *PrevClause = nullptr;
10482   bool ErrorFound = false;
10483   for (const OMPClause *C : Clauses) {
10484     if (C->getClauseKind() == OMPC_grainsize ||
10485         C->getClauseKind() == OMPC_num_tasks) {
10486       if (!PrevClause)
10487         PrevClause = C;
10488       else if (PrevClause->getClauseKind() != C->getClauseKind()) {
10489         S.Diag(C->getBeginLoc(), diag::err_omp_clauses_mutually_exclusive)
10490             << getOpenMPClauseName(C->getClauseKind())
10491             << getOpenMPClauseName(PrevClause->getClauseKind());
10492         S.Diag(PrevClause->getBeginLoc(), diag::note_omp_previous_clause)
10493             << getOpenMPClauseName(PrevClause->getClauseKind());
10494         ErrorFound = true;
10495       }
10496     }
10497   }
10498   return ErrorFound;
10499 }
10500 
10501 static bool checkReductionClauseWithNogroup(Sema &S,
10502                                             ArrayRef<OMPClause *> Clauses) {
10503   const OMPClause *ReductionClause = nullptr;
10504   const OMPClause *NogroupClause = nullptr;
10505   for (const OMPClause *C : Clauses) {
10506     if (C->getClauseKind() == OMPC_reduction) {
10507       ReductionClause = C;
10508       if (NogroupClause)
10509         break;
10510       continue;
10511     }
10512     if (C->getClauseKind() == OMPC_nogroup) {
10513       NogroupClause = C;
10514       if (ReductionClause)
10515         break;
10516       continue;
10517     }
10518   }
10519   if (ReductionClause && NogroupClause) {
10520     S.Diag(ReductionClause->getBeginLoc(), diag::err_omp_reduction_with_nogroup)
10521         << SourceRange(NogroupClause->getBeginLoc(),
10522                        NogroupClause->getEndLoc());
10523     return true;
10524   }
10525   return false;
10526 }
10527 
10528 StmtResult Sema::ActOnOpenMPTaskLoopDirective(
10529     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10530     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
10531   if (!AStmt)
10532     return StmtError();
10533 
10534   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
10535   OMPLoopDirective::HelperExprs B;
10536   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
10537   // define the nested loops number.
10538   unsigned NestedLoopCount =
10539       checkOpenMPLoop(OMPD_taskloop, getCollapseNumberExpr(Clauses),
10540                       /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
10541                       VarsWithImplicitDSA, B);
10542   if (NestedLoopCount == 0)
10543     return StmtError();
10544 
10545   assert((CurContext->isDependentContext() || B.builtAll()) &&
10546          "omp for loop exprs were not built");
10547 
10548   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
10549   // The grainsize clause and num_tasks clause are mutually exclusive and may
10550   // not appear on the same taskloop directive.
10551   if (checkGrainsizeNumTasksClauses(*this, Clauses))
10552     return StmtError();
10553   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
10554   // If a reduction clause is present on the taskloop directive, the nogroup
10555   // clause must not be specified.
10556   if (checkReductionClauseWithNogroup(*this, Clauses))
10557     return StmtError();
10558 
10559   setFunctionHasBranchProtectedScope();
10560   return OMPTaskLoopDirective::Create(Context, StartLoc, EndLoc,
10561                                       NestedLoopCount, Clauses, AStmt, B,
10562                                       DSAStack->isCancelRegion());
10563 }
10564 
10565 StmtResult Sema::ActOnOpenMPTaskLoopSimdDirective(
10566     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10567     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
10568   if (!AStmt)
10569     return StmtError();
10570 
10571   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
10572   OMPLoopDirective::HelperExprs B;
10573   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
10574   // define the nested loops number.
10575   unsigned NestedLoopCount =
10576       checkOpenMPLoop(OMPD_taskloop_simd, getCollapseNumberExpr(Clauses),
10577                       /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
10578                       VarsWithImplicitDSA, B);
10579   if (NestedLoopCount == 0)
10580     return StmtError();
10581 
10582   assert((CurContext->isDependentContext() || B.builtAll()) &&
10583          "omp for loop exprs were not built");
10584 
10585   if (!CurContext->isDependentContext()) {
10586     // Finalize the clauses that need pre-built expressions for CodeGen.
10587     for (OMPClause *C : Clauses) {
10588       if (auto *LC = dyn_cast<OMPLinearClause>(C))
10589         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
10590                                      B.NumIterations, *this, CurScope,
10591                                      DSAStack))
10592           return StmtError();
10593     }
10594   }
10595 
10596   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
10597   // The grainsize clause and num_tasks clause are mutually exclusive and may
10598   // not appear on the same taskloop directive.
10599   if (checkGrainsizeNumTasksClauses(*this, Clauses))
10600     return StmtError();
10601   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
10602   // If a reduction clause is present on the taskloop directive, the nogroup
10603   // clause must not be specified.
10604   if (checkReductionClauseWithNogroup(*this, Clauses))
10605     return StmtError();
10606   if (checkSimdlenSafelenSpecified(*this, Clauses))
10607     return StmtError();
10608 
10609   setFunctionHasBranchProtectedScope();
10610   return OMPTaskLoopSimdDirective::Create(Context, StartLoc, EndLoc,
10611                                           NestedLoopCount, Clauses, AStmt, B);
10612 }
10613 
10614 StmtResult Sema::ActOnOpenMPMasterTaskLoopDirective(
10615     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10616     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
10617   if (!AStmt)
10618     return StmtError();
10619 
10620   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
10621   OMPLoopDirective::HelperExprs B;
10622   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
10623   // define the nested loops number.
10624   unsigned NestedLoopCount =
10625       checkOpenMPLoop(OMPD_master_taskloop, getCollapseNumberExpr(Clauses),
10626                       /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
10627                       VarsWithImplicitDSA, B);
10628   if (NestedLoopCount == 0)
10629     return StmtError();
10630 
10631   assert((CurContext->isDependentContext() || B.builtAll()) &&
10632          "omp for loop exprs were not built");
10633 
10634   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
10635   // The grainsize clause and num_tasks clause are mutually exclusive and may
10636   // not appear on the same taskloop directive.
10637   if (checkGrainsizeNumTasksClauses(*this, Clauses))
10638     return StmtError();
10639   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
10640   // If a reduction clause is present on the taskloop directive, the nogroup
10641   // clause must not be specified.
10642   if (checkReductionClauseWithNogroup(*this, Clauses))
10643     return StmtError();
10644 
10645   setFunctionHasBranchProtectedScope();
10646   return OMPMasterTaskLoopDirective::Create(Context, StartLoc, EndLoc,
10647                                             NestedLoopCount, Clauses, AStmt, B,
10648                                             DSAStack->isCancelRegion());
10649 }
10650 
10651 StmtResult Sema::ActOnOpenMPMasterTaskLoopSimdDirective(
10652     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10653     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
10654   if (!AStmt)
10655     return StmtError();
10656 
10657   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
10658   OMPLoopDirective::HelperExprs B;
10659   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
10660   // define the nested loops number.
10661   unsigned NestedLoopCount =
10662       checkOpenMPLoop(OMPD_master_taskloop_simd, getCollapseNumberExpr(Clauses),
10663                       /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
10664                       VarsWithImplicitDSA, B);
10665   if (NestedLoopCount == 0)
10666     return StmtError();
10667 
10668   assert((CurContext->isDependentContext() || B.builtAll()) &&
10669          "omp for loop exprs were not built");
10670 
10671   if (!CurContext->isDependentContext()) {
10672     // Finalize the clauses that need pre-built expressions for CodeGen.
10673     for (OMPClause *C : Clauses) {
10674       if (auto *LC = dyn_cast<OMPLinearClause>(C))
10675         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
10676                                      B.NumIterations, *this, CurScope,
10677                                      DSAStack))
10678           return StmtError();
10679     }
10680   }
10681 
10682   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
10683   // The grainsize clause and num_tasks clause are mutually exclusive and may
10684   // not appear on the same taskloop directive.
10685   if (checkGrainsizeNumTasksClauses(*this, Clauses))
10686     return StmtError();
10687   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
10688   // If a reduction clause is present on the taskloop directive, the nogroup
10689   // clause must not be specified.
10690   if (checkReductionClauseWithNogroup(*this, Clauses))
10691     return StmtError();
10692   if (checkSimdlenSafelenSpecified(*this, Clauses))
10693     return StmtError();
10694 
10695   setFunctionHasBranchProtectedScope();
10696   return OMPMasterTaskLoopSimdDirective::Create(
10697       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
10698 }
10699 
10700 StmtResult Sema::ActOnOpenMPParallelMasterTaskLoopDirective(
10701     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10702     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
10703   if (!AStmt)
10704     return StmtError();
10705 
10706   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
10707   auto *CS = cast<CapturedStmt>(AStmt);
10708   // 1.2.2 OpenMP Language Terminology
10709   // Structured block - An executable statement with a single entry at the
10710   // top and a single exit at the bottom.
10711   // The point of exit cannot be a branch out of the structured block.
10712   // longjmp() and throw() must not violate the entry/exit criteria.
10713   CS->getCapturedDecl()->setNothrow();
10714   for (int ThisCaptureLevel =
10715            getOpenMPCaptureLevels(OMPD_parallel_master_taskloop);
10716        ThisCaptureLevel > 1; --ThisCaptureLevel) {
10717     CS = cast<CapturedStmt>(CS->getCapturedStmt());
10718     // 1.2.2 OpenMP Language Terminology
10719     // Structured block - An executable statement with a single entry at the
10720     // top and a single exit at the bottom.
10721     // The point of exit cannot be a branch out of the structured block.
10722     // longjmp() and throw() must not violate the entry/exit criteria.
10723     CS->getCapturedDecl()->setNothrow();
10724   }
10725 
10726   OMPLoopDirective::HelperExprs B;
10727   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
10728   // define the nested loops number.
10729   unsigned NestedLoopCount = checkOpenMPLoop(
10730       OMPD_parallel_master_taskloop, getCollapseNumberExpr(Clauses),
10731       /*OrderedLoopCountExpr=*/nullptr, CS, *this, *DSAStack,
10732       VarsWithImplicitDSA, B);
10733   if (NestedLoopCount == 0)
10734     return StmtError();
10735 
10736   assert((CurContext->isDependentContext() || B.builtAll()) &&
10737          "omp for loop exprs were not built");
10738 
10739   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
10740   // The grainsize clause and num_tasks clause are mutually exclusive and may
10741   // not appear on the same taskloop directive.
10742   if (checkGrainsizeNumTasksClauses(*this, Clauses))
10743     return StmtError();
10744   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
10745   // If a reduction clause is present on the taskloop directive, the nogroup
10746   // clause must not be specified.
10747   if (checkReductionClauseWithNogroup(*this, Clauses))
10748     return StmtError();
10749 
10750   setFunctionHasBranchProtectedScope();
10751   return OMPParallelMasterTaskLoopDirective::Create(
10752       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
10753       DSAStack->isCancelRegion());
10754 }
10755 
10756 StmtResult Sema::ActOnOpenMPParallelMasterTaskLoopSimdDirective(
10757     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10758     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
10759   if (!AStmt)
10760     return StmtError();
10761 
10762   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
10763   auto *CS = cast<CapturedStmt>(AStmt);
10764   // 1.2.2 OpenMP Language Terminology
10765   // Structured block - An executable statement with a single entry at the
10766   // top and a single exit at the bottom.
10767   // The point of exit cannot be a branch out of the structured block.
10768   // longjmp() and throw() must not violate the entry/exit criteria.
10769   CS->getCapturedDecl()->setNothrow();
10770   for (int ThisCaptureLevel =
10771            getOpenMPCaptureLevels(OMPD_parallel_master_taskloop_simd);
10772        ThisCaptureLevel > 1; --ThisCaptureLevel) {
10773     CS = cast<CapturedStmt>(CS->getCapturedStmt());
10774     // 1.2.2 OpenMP Language Terminology
10775     // Structured block - An executable statement with a single entry at the
10776     // top and a single exit at the bottom.
10777     // The point of exit cannot be a branch out of the structured block.
10778     // longjmp() and throw() must not violate the entry/exit criteria.
10779     CS->getCapturedDecl()->setNothrow();
10780   }
10781 
10782   OMPLoopDirective::HelperExprs B;
10783   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
10784   // define the nested loops number.
10785   unsigned NestedLoopCount = checkOpenMPLoop(
10786       OMPD_parallel_master_taskloop_simd, getCollapseNumberExpr(Clauses),
10787       /*OrderedLoopCountExpr=*/nullptr, CS, *this, *DSAStack,
10788       VarsWithImplicitDSA, B);
10789   if (NestedLoopCount == 0)
10790     return StmtError();
10791 
10792   assert((CurContext->isDependentContext() || B.builtAll()) &&
10793          "omp for loop exprs were not built");
10794 
10795   if (!CurContext->isDependentContext()) {
10796     // Finalize the clauses that need pre-built expressions for CodeGen.
10797     for (OMPClause *C : Clauses) {
10798       if (auto *LC = dyn_cast<OMPLinearClause>(C))
10799         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
10800                                      B.NumIterations, *this, CurScope,
10801                                      DSAStack))
10802           return StmtError();
10803     }
10804   }
10805 
10806   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
10807   // The grainsize clause and num_tasks clause are mutually exclusive and may
10808   // not appear on the same taskloop directive.
10809   if (checkGrainsizeNumTasksClauses(*this, Clauses))
10810     return StmtError();
10811   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
10812   // If a reduction clause is present on the taskloop directive, the nogroup
10813   // clause must not be specified.
10814   if (checkReductionClauseWithNogroup(*this, Clauses))
10815     return StmtError();
10816   if (checkSimdlenSafelenSpecified(*this, Clauses))
10817     return StmtError();
10818 
10819   setFunctionHasBranchProtectedScope();
10820   return OMPParallelMasterTaskLoopSimdDirective::Create(
10821       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
10822 }
10823 
10824 StmtResult Sema::ActOnOpenMPDistributeDirective(
10825     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10826     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
10827   if (!AStmt)
10828     return StmtError();
10829 
10830   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
10831   OMPLoopDirective::HelperExprs B;
10832   // In presence of clause 'collapse' with number of loops, it will
10833   // define the nested loops number.
10834   unsigned NestedLoopCount =
10835       checkOpenMPLoop(OMPD_distribute, getCollapseNumberExpr(Clauses),
10836                       nullptr /*ordered not a clause on distribute*/, AStmt,
10837                       *this, *DSAStack, VarsWithImplicitDSA, B);
10838   if (NestedLoopCount == 0)
10839     return StmtError();
10840 
10841   assert((CurContext->isDependentContext() || B.builtAll()) &&
10842          "omp for loop exprs were not built");
10843 
10844   setFunctionHasBranchProtectedScope();
10845   return OMPDistributeDirective::Create(Context, StartLoc, EndLoc,
10846                                         NestedLoopCount, Clauses, AStmt, B);
10847 }
10848 
10849 StmtResult Sema::ActOnOpenMPDistributeParallelForDirective(
10850     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10851     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
10852   if (!AStmt)
10853     return StmtError();
10854 
10855   auto *CS = cast<CapturedStmt>(AStmt);
10856   // 1.2.2 OpenMP Language Terminology
10857   // Structured block - An executable statement with a single entry at the
10858   // top and a single exit at the bottom.
10859   // The point of exit cannot be a branch out of the structured block.
10860   // longjmp() and throw() must not violate the entry/exit criteria.
10861   CS->getCapturedDecl()->setNothrow();
10862   for (int ThisCaptureLevel =
10863            getOpenMPCaptureLevels(OMPD_distribute_parallel_for);
10864        ThisCaptureLevel > 1; --ThisCaptureLevel) {
10865     CS = cast<CapturedStmt>(CS->getCapturedStmt());
10866     // 1.2.2 OpenMP Language Terminology
10867     // Structured block - An executable statement with a single entry at the
10868     // top and a single exit at the bottom.
10869     // The point of exit cannot be a branch out of the structured block.
10870     // longjmp() and throw() must not violate the entry/exit criteria.
10871     CS->getCapturedDecl()->setNothrow();
10872   }
10873 
10874   OMPLoopDirective::HelperExprs B;
10875   // In presence of clause 'collapse' with number of loops, it will
10876   // define the nested loops number.
10877   unsigned NestedLoopCount = checkOpenMPLoop(
10878       OMPD_distribute_parallel_for, getCollapseNumberExpr(Clauses),
10879       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
10880       VarsWithImplicitDSA, B);
10881   if (NestedLoopCount == 0)
10882     return StmtError();
10883 
10884   assert((CurContext->isDependentContext() || B.builtAll()) &&
10885          "omp for loop exprs were not built");
10886 
10887   setFunctionHasBranchProtectedScope();
10888   return OMPDistributeParallelForDirective::Create(
10889       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
10890       DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion());
10891 }
10892 
10893 StmtResult Sema::ActOnOpenMPDistributeParallelForSimdDirective(
10894     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10895     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
10896   if (!AStmt)
10897     return StmtError();
10898 
10899   auto *CS = cast<CapturedStmt>(AStmt);
10900   // 1.2.2 OpenMP Language Terminology
10901   // Structured block - An executable statement with a single entry at the
10902   // top and a single exit at the bottom.
10903   // The point of exit cannot be a branch out of the structured block.
10904   // longjmp() and throw() must not violate the entry/exit criteria.
10905   CS->getCapturedDecl()->setNothrow();
10906   for (int ThisCaptureLevel =
10907            getOpenMPCaptureLevels(OMPD_distribute_parallel_for_simd);
10908        ThisCaptureLevel > 1; --ThisCaptureLevel) {
10909     CS = cast<CapturedStmt>(CS->getCapturedStmt());
10910     // 1.2.2 OpenMP Language Terminology
10911     // Structured block - An executable statement with a single entry at the
10912     // top and a single exit at the bottom.
10913     // The point of exit cannot be a branch out of the structured block.
10914     // longjmp() and throw() must not violate the entry/exit criteria.
10915     CS->getCapturedDecl()->setNothrow();
10916   }
10917 
10918   OMPLoopDirective::HelperExprs B;
10919   // In presence of clause 'collapse' with number of loops, it will
10920   // define the nested loops number.
10921   unsigned NestedLoopCount = checkOpenMPLoop(
10922       OMPD_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
10923       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
10924       VarsWithImplicitDSA, B);
10925   if (NestedLoopCount == 0)
10926     return StmtError();
10927 
10928   assert((CurContext->isDependentContext() || B.builtAll()) &&
10929          "omp for loop exprs were not built");
10930 
10931   if (!CurContext->isDependentContext()) {
10932     // Finalize the clauses that need pre-built expressions for CodeGen.
10933     for (OMPClause *C : Clauses) {
10934       if (auto *LC = dyn_cast<OMPLinearClause>(C))
10935         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
10936                                      B.NumIterations, *this, CurScope,
10937                                      DSAStack))
10938           return StmtError();
10939     }
10940   }
10941 
10942   if (checkSimdlenSafelenSpecified(*this, Clauses))
10943     return StmtError();
10944 
10945   setFunctionHasBranchProtectedScope();
10946   return OMPDistributeParallelForSimdDirective::Create(
10947       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
10948 }
10949 
10950 StmtResult Sema::ActOnOpenMPDistributeSimdDirective(
10951     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10952     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
10953   if (!AStmt)
10954     return StmtError();
10955 
10956   auto *CS = cast<CapturedStmt>(AStmt);
10957   // 1.2.2 OpenMP Language Terminology
10958   // Structured block - An executable statement with a single entry at the
10959   // top and a single exit at the bottom.
10960   // The point of exit cannot be a branch out of the structured block.
10961   // longjmp() and throw() must not violate the entry/exit criteria.
10962   CS->getCapturedDecl()->setNothrow();
10963   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_distribute_simd);
10964        ThisCaptureLevel > 1; --ThisCaptureLevel) {
10965     CS = cast<CapturedStmt>(CS->getCapturedStmt());
10966     // 1.2.2 OpenMP Language Terminology
10967     // Structured block - An executable statement with a single entry at the
10968     // top and a single exit at the bottom.
10969     // The point of exit cannot be a branch out of the structured block.
10970     // longjmp() and throw() must not violate the entry/exit criteria.
10971     CS->getCapturedDecl()->setNothrow();
10972   }
10973 
10974   OMPLoopDirective::HelperExprs B;
10975   // In presence of clause 'collapse' with number of loops, it will
10976   // define the nested loops number.
10977   unsigned NestedLoopCount =
10978       checkOpenMPLoop(OMPD_distribute_simd, getCollapseNumberExpr(Clauses),
10979                       nullptr /*ordered not a clause on distribute*/, CS, *this,
10980                       *DSAStack, VarsWithImplicitDSA, B);
10981   if (NestedLoopCount == 0)
10982     return StmtError();
10983 
10984   assert((CurContext->isDependentContext() || B.builtAll()) &&
10985          "omp for loop exprs were not built");
10986 
10987   if (!CurContext->isDependentContext()) {
10988     // Finalize the clauses that need pre-built expressions for CodeGen.
10989     for (OMPClause *C : Clauses) {
10990       if (auto *LC = dyn_cast<OMPLinearClause>(C))
10991         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
10992                                      B.NumIterations, *this, CurScope,
10993                                      DSAStack))
10994           return StmtError();
10995     }
10996   }
10997 
10998   if (checkSimdlenSafelenSpecified(*this, Clauses))
10999     return StmtError();
11000 
11001   setFunctionHasBranchProtectedScope();
11002   return OMPDistributeSimdDirective::Create(Context, StartLoc, EndLoc,
11003                                             NestedLoopCount, Clauses, AStmt, B);
11004 }
11005 
11006 StmtResult Sema::ActOnOpenMPTargetParallelForSimdDirective(
11007     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11008     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
11009   if (!AStmt)
11010     return StmtError();
11011 
11012   auto *CS = cast<CapturedStmt>(AStmt);
11013   // 1.2.2 OpenMP Language Terminology
11014   // Structured block - An executable statement with a single entry at the
11015   // top and a single exit at the bottom.
11016   // The point of exit cannot be a branch out of the structured block.
11017   // longjmp() and throw() must not violate the entry/exit criteria.
11018   CS->getCapturedDecl()->setNothrow();
11019   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
11020        ThisCaptureLevel > 1; --ThisCaptureLevel) {
11021     CS = cast<CapturedStmt>(CS->getCapturedStmt());
11022     // 1.2.2 OpenMP Language Terminology
11023     // Structured block - An executable statement with a single entry at the
11024     // top and a single exit at the bottom.
11025     // The point of exit cannot be a branch out of the structured block.
11026     // longjmp() and throw() must not violate the entry/exit criteria.
11027     CS->getCapturedDecl()->setNothrow();
11028   }
11029 
11030   OMPLoopDirective::HelperExprs B;
11031   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
11032   // define the nested loops number.
11033   unsigned NestedLoopCount = checkOpenMPLoop(
11034       OMPD_target_parallel_for_simd, getCollapseNumberExpr(Clauses),
11035       getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
11036       VarsWithImplicitDSA, B);
11037   if (NestedLoopCount == 0)
11038     return StmtError();
11039 
11040   assert((CurContext->isDependentContext() || B.builtAll()) &&
11041          "omp target parallel for simd loop exprs were not built");
11042 
11043   if (!CurContext->isDependentContext()) {
11044     // Finalize the clauses that need pre-built expressions for CodeGen.
11045     for (OMPClause *C : Clauses) {
11046       if (auto *LC = dyn_cast<OMPLinearClause>(C))
11047         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
11048                                      B.NumIterations, *this, CurScope,
11049                                      DSAStack))
11050           return StmtError();
11051     }
11052   }
11053   if (checkSimdlenSafelenSpecified(*this, Clauses))
11054     return StmtError();
11055 
11056   setFunctionHasBranchProtectedScope();
11057   return OMPTargetParallelForSimdDirective::Create(
11058       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
11059 }
11060 
11061 StmtResult Sema::ActOnOpenMPTargetSimdDirective(
11062     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11063     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
11064   if (!AStmt)
11065     return StmtError();
11066 
11067   auto *CS = cast<CapturedStmt>(AStmt);
11068   // 1.2.2 OpenMP Language Terminology
11069   // Structured block - An executable statement with a single entry at the
11070   // top and a single exit at the bottom.
11071   // The point of exit cannot be a branch out of the structured block.
11072   // longjmp() and throw() must not violate the entry/exit criteria.
11073   CS->getCapturedDecl()->setNothrow();
11074   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_simd);
11075        ThisCaptureLevel > 1; --ThisCaptureLevel) {
11076     CS = cast<CapturedStmt>(CS->getCapturedStmt());
11077     // 1.2.2 OpenMP Language Terminology
11078     // Structured block - An executable statement with a single entry at the
11079     // top and a single exit at the bottom.
11080     // The point of exit cannot be a branch out of the structured block.
11081     // longjmp() and throw() must not violate the entry/exit criteria.
11082     CS->getCapturedDecl()->setNothrow();
11083   }
11084 
11085   OMPLoopDirective::HelperExprs B;
11086   // In presence of clause 'collapse' with number of loops, it will define the
11087   // nested loops number.
11088   unsigned NestedLoopCount =
11089       checkOpenMPLoop(OMPD_target_simd, getCollapseNumberExpr(Clauses),
11090                       getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
11091                       VarsWithImplicitDSA, B);
11092   if (NestedLoopCount == 0)
11093     return StmtError();
11094 
11095   assert((CurContext->isDependentContext() || B.builtAll()) &&
11096          "omp target simd loop exprs were not built");
11097 
11098   if (!CurContext->isDependentContext()) {
11099     // Finalize the clauses that need pre-built expressions for CodeGen.
11100     for (OMPClause *C : Clauses) {
11101       if (auto *LC = dyn_cast<OMPLinearClause>(C))
11102         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
11103                                      B.NumIterations, *this, CurScope,
11104                                      DSAStack))
11105           return StmtError();
11106     }
11107   }
11108 
11109   if (checkSimdlenSafelenSpecified(*this, Clauses))
11110     return StmtError();
11111 
11112   setFunctionHasBranchProtectedScope();
11113   return OMPTargetSimdDirective::Create(Context, StartLoc, EndLoc,
11114                                         NestedLoopCount, Clauses, AStmt, B);
11115 }
11116 
11117 StmtResult Sema::ActOnOpenMPTeamsDistributeDirective(
11118     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11119     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
11120   if (!AStmt)
11121     return StmtError();
11122 
11123   auto *CS = cast<CapturedStmt>(AStmt);
11124   // 1.2.2 OpenMP Language Terminology
11125   // Structured block - An executable statement with a single entry at the
11126   // top and a single exit at the bottom.
11127   // The point of exit cannot be a branch out of the structured block.
11128   // longjmp() and throw() must not violate the entry/exit criteria.
11129   CS->getCapturedDecl()->setNothrow();
11130   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_teams_distribute);
11131        ThisCaptureLevel > 1; --ThisCaptureLevel) {
11132     CS = cast<CapturedStmt>(CS->getCapturedStmt());
11133     // 1.2.2 OpenMP Language Terminology
11134     // Structured block - An executable statement with a single entry at the
11135     // top and a single exit at the bottom.
11136     // The point of exit cannot be a branch out of the structured block.
11137     // longjmp() and throw() must not violate the entry/exit criteria.
11138     CS->getCapturedDecl()->setNothrow();
11139   }
11140 
11141   OMPLoopDirective::HelperExprs B;
11142   // In presence of clause 'collapse' with number of loops, it will
11143   // define the nested loops number.
11144   unsigned NestedLoopCount =
11145       checkOpenMPLoop(OMPD_teams_distribute, getCollapseNumberExpr(Clauses),
11146                       nullptr /*ordered not a clause on distribute*/, CS, *this,
11147                       *DSAStack, VarsWithImplicitDSA, B);
11148   if (NestedLoopCount == 0)
11149     return StmtError();
11150 
11151   assert((CurContext->isDependentContext() || B.builtAll()) &&
11152          "omp teams distribute loop exprs were not built");
11153 
11154   setFunctionHasBranchProtectedScope();
11155 
11156   DSAStack->setParentTeamsRegionLoc(StartLoc);
11157 
11158   return OMPTeamsDistributeDirective::Create(
11159       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
11160 }
11161 
11162 StmtResult Sema::ActOnOpenMPTeamsDistributeSimdDirective(
11163     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11164     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
11165   if (!AStmt)
11166     return StmtError();
11167 
11168   auto *CS = cast<CapturedStmt>(AStmt);
11169   // 1.2.2 OpenMP Language Terminology
11170   // Structured block - An executable statement with a single entry at the
11171   // top and a single exit at the bottom.
11172   // The point of exit cannot be a branch out of the structured block.
11173   // longjmp() and throw() must not violate the entry/exit criteria.
11174   CS->getCapturedDecl()->setNothrow();
11175   for (int ThisCaptureLevel =
11176            getOpenMPCaptureLevels(OMPD_teams_distribute_simd);
11177        ThisCaptureLevel > 1; --ThisCaptureLevel) {
11178     CS = cast<CapturedStmt>(CS->getCapturedStmt());
11179     // 1.2.2 OpenMP Language Terminology
11180     // Structured block - An executable statement with a single entry at the
11181     // top and a single exit at the bottom.
11182     // The point of exit cannot be a branch out of the structured block.
11183     // longjmp() and throw() must not violate the entry/exit criteria.
11184     CS->getCapturedDecl()->setNothrow();
11185   }
11186 
11187   OMPLoopDirective::HelperExprs B;
11188   // In presence of clause 'collapse' with number of loops, it will
11189   // define the nested loops number.
11190   unsigned NestedLoopCount = checkOpenMPLoop(
11191       OMPD_teams_distribute_simd, getCollapseNumberExpr(Clauses),
11192       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
11193       VarsWithImplicitDSA, B);
11194 
11195   if (NestedLoopCount == 0)
11196     return StmtError();
11197 
11198   assert((CurContext->isDependentContext() || B.builtAll()) &&
11199          "omp teams distribute simd loop exprs were not built");
11200 
11201   if (!CurContext->isDependentContext()) {
11202     // Finalize the clauses that need pre-built expressions for CodeGen.
11203     for (OMPClause *C : Clauses) {
11204       if (auto *LC = dyn_cast<OMPLinearClause>(C))
11205         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
11206                                      B.NumIterations, *this, CurScope,
11207                                      DSAStack))
11208           return StmtError();
11209     }
11210   }
11211 
11212   if (checkSimdlenSafelenSpecified(*this, Clauses))
11213     return StmtError();
11214 
11215   setFunctionHasBranchProtectedScope();
11216 
11217   DSAStack->setParentTeamsRegionLoc(StartLoc);
11218 
11219   return OMPTeamsDistributeSimdDirective::Create(
11220       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
11221 }
11222 
11223 StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForSimdDirective(
11224     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11225     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
11226   if (!AStmt)
11227     return StmtError();
11228 
11229   auto *CS = cast<CapturedStmt>(AStmt);
11230   // 1.2.2 OpenMP Language Terminology
11231   // Structured block - An executable statement with a single entry at the
11232   // top and a single exit at the bottom.
11233   // The point of exit cannot be a branch out of the structured block.
11234   // longjmp() and throw() must not violate the entry/exit criteria.
11235   CS->getCapturedDecl()->setNothrow();
11236 
11237   for (int ThisCaptureLevel =
11238            getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for_simd);
11239        ThisCaptureLevel > 1; --ThisCaptureLevel) {
11240     CS = cast<CapturedStmt>(CS->getCapturedStmt());
11241     // 1.2.2 OpenMP Language Terminology
11242     // Structured block - An executable statement with a single entry at the
11243     // top and a single exit at the bottom.
11244     // The point of exit cannot be a branch out of the structured block.
11245     // longjmp() and throw() must not violate the entry/exit criteria.
11246     CS->getCapturedDecl()->setNothrow();
11247   }
11248 
11249   OMPLoopDirective::HelperExprs B;
11250   // In presence of clause 'collapse' with number of loops, it will
11251   // define the nested loops number.
11252   unsigned NestedLoopCount = checkOpenMPLoop(
11253       OMPD_teams_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
11254       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
11255       VarsWithImplicitDSA, B);
11256 
11257   if (NestedLoopCount == 0)
11258     return StmtError();
11259 
11260   assert((CurContext->isDependentContext() || B.builtAll()) &&
11261          "omp for loop exprs were not built");
11262 
11263   if (!CurContext->isDependentContext()) {
11264     // Finalize the clauses that need pre-built expressions for CodeGen.
11265     for (OMPClause *C : Clauses) {
11266       if (auto *LC = dyn_cast<OMPLinearClause>(C))
11267         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
11268                                      B.NumIterations, *this, CurScope,
11269                                      DSAStack))
11270           return StmtError();
11271     }
11272   }
11273 
11274   if (checkSimdlenSafelenSpecified(*this, Clauses))
11275     return StmtError();
11276 
11277   setFunctionHasBranchProtectedScope();
11278 
11279   DSAStack->setParentTeamsRegionLoc(StartLoc);
11280 
11281   return OMPTeamsDistributeParallelForSimdDirective::Create(
11282       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
11283 }
11284 
11285 StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForDirective(
11286     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11287     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
11288   if (!AStmt)
11289     return StmtError();
11290 
11291   auto *CS = cast<CapturedStmt>(AStmt);
11292   // 1.2.2 OpenMP Language Terminology
11293   // Structured block - An executable statement with a single entry at the
11294   // top and a single exit at the bottom.
11295   // The point of exit cannot be a branch out of the structured block.
11296   // longjmp() and throw() must not violate the entry/exit criteria.
11297   CS->getCapturedDecl()->setNothrow();
11298 
11299   for (int ThisCaptureLevel =
11300            getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for);
11301        ThisCaptureLevel > 1; --ThisCaptureLevel) {
11302     CS = cast<CapturedStmt>(CS->getCapturedStmt());
11303     // 1.2.2 OpenMP Language Terminology
11304     // Structured block - An executable statement with a single entry at the
11305     // top and a single exit at the bottom.
11306     // The point of exit cannot be a branch out of the structured block.
11307     // longjmp() and throw() must not violate the entry/exit criteria.
11308     CS->getCapturedDecl()->setNothrow();
11309   }
11310 
11311   OMPLoopDirective::HelperExprs B;
11312   // In presence of clause 'collapse' with number of loops, it will
11313   // define the nested loops number.
11314   unsigned NestedLoopCount = checkOpenMPLoop(
11315       OMPD_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
11316       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
11317       VarsWithImplicitDSA, B);
11318 
11319   if (NestedLoopCount == 0)
11320     return StmtError();
11321 
11322   assert((CurContext->isDependentContext() || B.builtAll()) &&
11323          "omp for loop exprs were not built");
11324 
11325   setFunctionHasBranchProtectedScope();
11326 
11327   DSAStack->setParentTeamsRegionLoc(StartLoc);
11328 
11329   return OMPTeamsDistributeParallelForDirective::Create(
11330       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
11331       DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion());
11332 }
11333 
11334 StmtResult Sema::ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses,
11335                                                  Stmt *AStmt,
11336                                                  SourceLocation StartLoc,
11337                                                  SourceLocation EndLoc) {
11338   if (!AStmt)
11339     return StmtError();
11340 
11341   auto *CS = cast<CapturedStmt>(AStmt);
11342   // 1.2.2 OpenMP Language Terminology
11343   // Structured block - An executable statement with a single entry at the
11344   // top and a single exit at the bottom.
11345   // The point of exit cannot be a branch out of the structured block.
11346   // longjmp() and throw() must not violate the entry/exit criteria.
11347   CS->getCapturedDecl()->setNothrow();
11348 
11349   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_teams);
11350        ThisCaptureLevel > 1; --ThisCaptureLevel) {
11351     CS = cast<CapturedStmt>(CS->getCapturedStmt());
11352     // 1.2.2 OpenMP Language Terminology
11353     // Structured block - An executable statement with a single entry at the
11354     // top and a single exit at the bottom.
11355     // The point of exit cannot be a branch out of the structured block.
11356     // longjmp() and throw() must not violate the entry/exit criteria.
11357     CS->getCapturedDecl()->setNothrow();
11358   }
11359   setFunctionHasBranchProtectedScope();
11360 
11361   return OMPTargetTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses,
11362                                          AStmt);
11363 }
11364 
11365 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeDirective(
11366     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11367     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
11368   if (!AStmt)
11369     return StmtError();
11370 
11371   auto *CS = cast<CapturedStmt>(AStmt);
11372   // 1.2.2 OpenMP Language Terminology
11373   // Structured block - An executable statement with a single entry at the
11374   // top and a single exit at the bottom.
11375   // The point of exit cannot be a branch out of the structured block.
11376   // longjmp() and throw() must not violate the entry/exit criteria.
11377   CS->getCapturedDecl()->setNothrow();
11378   for (int ThisCaptureLevel =
11379            getOpenMPCaptureLevels(OMPD_target_teams_distribute);
11380        ThisCaptureLevel > 1; --ThisCaptureLevel) {
11381     CS = cast<CapturedStmt>(CS->getCapturedStmt());
11382     // 1.2.2 OpenMP Language Terminology
11383     // Structured block - An executable statement with a single entry at the
11384     // top and a single exit at the bottom.
11385     // The point of exit cannot be a branch out of the structured block.
11386     // longjmp() and throw() must not violate the entry/exit criteria.
11387     CS->getCapturedDecl()->setNothrow();
11388   }
11389 
11390   OMPLoopDirective::HelperExprs B;
11391   // In presence of clause 'collapse' with number of loops, it will
11392   // define the nested loops number.
11393   unsigned NestedLoopCount = checkOpenMPLoop(
11394       OMPD_target_teams_distribute, getCollapseNumberExpr(Clauses),
11395       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
11396       VarsWithImplicitDSA, B);
11397   if (NestedLoopCount == 0)
11398     return StmtError();
11399 
11400   assert((CurContext->isDependentContext() || B.builtAll()) &&
11401          "omp target teams distribute loop exprs were not built");
11402 
11403   setFunctionHasBranchProtectedScope();
11404   return OMPTargetTeamsDistributeDirective::Create(
11405       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
11406 }
11407 
11408 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForDirective(
11409     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11410     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
11411   if (!AStmt)
11412     return StmtError();
11413 
11414   auto *CS = cast<CapturedStmt>(AStmt);
11415   // 1.2.2 OpenMP Language Terminology
11416   // Structured block - An executable statement with a single entry at the
11417   // top and a single exit at the bottom.
11418   // The point of exit cannot be a branch out of the structured block.
11419   // longjmp() and throw() must not violate the entry/exit criteria.
11420   CS->getCapturedDecl()->setNothrow();
11421   for (int ThisCaptureLevel =
11422            getOpenMPCaptureLevels(OMPD_target_teams_distribute_parallel_for);
11423        ThisCaptureLevel > 1; --ThisCaptureLevel) {
11424     CS = cast<CapturedStmt>(CS->getCapturedStmt());
11425     // 1.2.2 OpenMP Language Terminology
11426     // Structured block - An executable statement with a single entry at the
11427     // top and a single exit at the bottom.
11428     // The point of exit cannot be a branch out of the structured block.
11429     // longjmp() and throw() must not violate the entry/exit criteria.
11430     CS->getCapturedDecl()->setNothrow();
11431   }
11432 
11433   OMPLoopDirective::HelperExprs B;
11434   // In presence of clause 'collapse' with number of loops, it will
11435   // define the nested loops number.
11436   unsigned NestedLoopCount = checkOpenMPLoop(
11437       OMPD_target_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
11438       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
11439       VarsWithImplicitDSA, B);
11440   if (NestedLoopCount == 0)
11441     return StmtError();
11442 
11443   assert((CurContext->isDependentContext() || B.builtAll()) &&
11444          "omp target teams distribute parallel for loop exprs were not built");
11445 
11446   if (!CurContext->isDependentContext()) {
11447     // Finalize the clauses that need pre-built expressions for CodeGen.
11448     for (OMPClause *C : Clauses) {
11449       if (auto *LC = dyn_cast<OMPLinearClause>(C))
11450         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
11451                                      B.NumIterations, *this, CurScope,
11452                                      DSAStack))
11453           return StmtError();
11454     }
11455   }
11456 
11457   setFunctionHasBranchProtectedScope();
11458   return OMPTargetTeamsDistributeParallelForDirective::Create(
11459       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
11460       DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion());
11461 }
11462 
11463 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
11464     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11465     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
11466   if (!AStmt)
11467     return StmtError();
11468 
11469   auto *CS = cast<CapturedStmt>(AStmt);
11470   // 1.2.2 OpenMP Language Terminology
11471   // Structured block - An executable statement with a single entry at the
11472   // top and a single exit at the bottom.
11473   // The point of exit cannot be a branch out of the structured block.
11474   // longjmp() and throw() must not violate the entry/exit criteria.
11475   CS->getCapturedDecl()->setNothrow();
11476   for (int ThisCaptureLevel = getOpenMPCaptureLevels(
11477            OMPD_target_teams_distribute_parallel_for_simd);
11478        ThisCaptureLevel > 1; --ThisCaptureLevel) {
11479     CS = cast<CapturedStmt>(CS->getCapturedStmt());
11480     // 1.2.2 OpenMP Language Terminology
11481     // Structured block - An executable statement with a single entry at the
11482     // top and a single exit at the bottom.
11483     // The point of exit cannot be a branch out of the structured block.
11484     // longjmp() and throw() must not violate the entry/exit criteria.
11485     CS->getCapturedDecl()->setNothrow();
11486   }
11487 
11488   OMPLoopDirective::HelperExprs B;
11489   // In presence of clause 'collapse' with number of loops, it will
11490   // define the nested loops number.
11491   unsigned NestedLoopCount =
11492       checkOpenMPLoop(OMPD_target_teams_distribute_parallel_for_simd,
11493                       getCollapseNumberExpr(Clauses),
11494                       nullptr /*ordered not a clause on distribute*/, CS, *this,
11495                       *DSAStack, VarsWithImplicitDSA, B);
11496   if (NestedLoopCount == 0)
11497     return StmtError();
11498 
11499   assert((CurContext->isDependentContext() || B.builtAll()) &&
11500          "omp target teams distribute parallel for simd loop exprs were not "
11501          "built");
11502 
11503   if (!CurContext->isDependentContext()) {
11504     // Finalize the clauses that need pre-built expressions for CodeGen.
11505     for (OMPClause *C : Clauses) {
11506       if (auto *LC = dyn_cast<OMPLinearClause>(C))
11507         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
11508                                      B.NumIterations, *this, CurScope,
11509                                      DSAStack))
11510           return StmtError();
11511     }
11512   }
11513 
11514   if (checkSimdlenSafelenSpecified(*this, Clauses))
11515     return StmtError();
11516 
11517   setFunctionHasBranchProtectedScope();
11518   return OMPTargetTeamsDistributeParallelForSimdDirective::Create(
11519       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
11520 }
11521 
11522 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeSimdDirective(
11523     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11524     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
11525   if (!AStmt)
11526     return StmtError();
11527 
11528   auto *CS = cast<CapturedStmt>(AStmt);
11529   // 1.2.2 OpenMP Language Terminology
11530   // Structured block - An executable statement with a single entry at the
11531   // top and a single exit at the bottom.
11532   // The point of exit cannot be a branch out of the structured block.
11533   // longjmp() and throw() must not violate the entry/exit criteria.
11534   CS->getCapturedDecl()->setNothrow();
11535   for (int ThisCaptureLevel =
11536            getOpenMPCaptureLevels(OMPD_target_teams_distribute_simd);
11537        ThisCaptureLevel > 1; --ThisCaptureLevel) {
11538     CS = cast<CapturedStmt>(CS->getCapturedStmt());
11539     // 1.2.2 OpenMP Language Terminology
11540     // Structured block - An executable statement with a single entry at the
11541     // top and a single exit at the bottom.
11542     // The point of exit cannot be a branch out of the structured block.
11543     // longjmp() and throw() must not violate the entry/exit criteria.
11544     CS->getCapturedDecl()->setNothrow();
11545   }
11546 
11547   OMPLoopDirective::HelperExprs B;
11548   // In presence of clause 'collapse' with number of loops, it will
11549   // define the nested loops number.
11550   unsigned NestedLoopCount = checkOpenMPLoop(
11551       OMPD_target_teams_distribute_simd, getCollapseNumberExpr(Clauses),
11552       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
11553       VarsWithImplicitDSA, B);
11554   if (NestedLoopCount == 0)
11555     return StmtError();
11556 
11557   assert((CurContext->isDependentContext() || B.builtAll()) &&
11558          "omp target teams distribute simd loop exprs were not built");
11559 
11560   if (!CurContext->isDependentContext()) {
11561     // Finalize the clauses that need pre-built expressions for CodeGen.
11562     for (OMPClause *C : Clauses) {
11563       if (auto *LC = dyn_cast<OMPLinearClause>(C))
11564         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
11565                                      B.NumIterations, *this, CurScope,
11566                                      DSAStack))
11567           return StmtError();
11568     }
11569   }
11570 
11571   if (checkSimdlenSafelenSpecified(*this, Clauses))
11572     return StmtError();
11573 
11574   setFunctionHasBranchProtectedScope();
11575   return OMPTargetTeamsDistributeSimdDirective::Create(
11576       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
11577 }
11578 
11579 OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
11580                                              SourceLocation StartLoc,
11581                                              SourceLocation LParenLoc,
11582                                              SourceLocation EndLoc) {
11583   OMPClause *Res = nullptr;
11584   switch (Kind) {
11585   case OMPC_final:
11586     Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc);
11587     break;
11588   case OMPC_num_threads:
11589     Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc);
11590     break;
11591   case OMPC_safelen:
11592     Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
11593     break;
11594   case OMPC_simdlen:
11595     Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc);
11596     break;
11597   case OMPC_allocator:
11598     Res = ActOnOpenMPAllocatorClause(Expr, StartLoc, LParenLoc, EndLoc);
11599     break;
11600   case OMPC_collapse:
11601     Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc);
11602     break;
11603   case OMPC_ordered:
11604     Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr);
11605     break;
11606   case OMPC_num_teams:
11607     Res = ActOnOpenMPNumTeamsClause(Expr, StartLoc, LParenLoc, EndLoc);
11608     break;
11609   case OMPC_thread_limit:
11610     Res = ActOnOpenMPThreadLimitClause(Expr, StartLoc, LParenLoc, EndLoc);
11611     break;
11612   case OMPC_priority:
11613     Res = ActOnOpenMPPriorityClause(Expr, StartLoc, LParenLoc, EndLoc);
11614     break;
11615   case OMPC_grainsize:
11616     Res = ActOnOpenMPGrainsizeClause(Expr, StartLoc, LParenLoc, EndLoc);
11617     break;
11618   case OMPC_num_tasks:
11619     Res = ActOnOpenMPNumTasksClause(Expr, StartLoc, LParenLoc, EndLoc);
11620     break;
11621   case OMPC_hint:
11622     Res = ActOnOpenMPHintClause(Expr, StartLoc, LParenLoc, EndLoc);
11623     break;
11624   case OMPC_depobj:
11625     Res = ActOnOpenMPDepobjClause(Expr, StartLoc, LParenLoc, EndLoc);
11626     break;
11627   case OMPC_detach:
11628     Res = ActOnOpenMPDetachClause(Expr, StartLoc, LParenLoc, EndLoc);
11629     break;
11630   case OMPC_device:
11631   case OMPC_if:
11632   case OMPC_default:
11633   case OMPC_proc_bind:
11634   case OMPC_schedule:
11635   case OMPC_private:
11636   case OMPC_firstprivate:
11637   case OMPC_lastprivate:
11638   case OMPC_shared:
11639   case OMPC_reduction:
11640   case OMPC_task_reduction:
11641   case OMPC_in_reduction:
11642   case OMPC_linear:
11643   case OMPC_aligned:
11644   case OMPC_copyin:
11645   case OMPC_copyprivate:
11646   case OMPC_nowait:
11647   case OMPC_untied:
11648   case OMPC_mergeable:
11649   case OMPC_threadprivate:
11650   case OMPC_allocate:
11651   case OMPC_flush:
11652   case OMPC_read:
11653   case OMPC_write:
11654   case OMPC_update:
11655   case OMPC_capture:
11656   case OMPC_seq_cst:
11657   case OMPC_acq_rel:
11658   case OMPC_acquire:
11659   case OMPC_release:
11660   case OMPC_relaxed:
11661   case OMPC_depend:
11662   case OMPC_threads:
11663   case OMPC_simd:
11664   case OMPC_map:
11665   case OMPC_nogroup:
11666   case OMPC_dist_schedule:
11667   case OMPC_defaultmap:
11668   case OMPC_unknown:
11669   case OMPC_uniform:
11670   case OMPC_to:
11671   case OMPC_from:
11672   case OMPC_use_device_ptr:
11673   case OMPC_use_device_addr:
11674   case OMPC_is_device_ptr:
11675   case OMPC_unified_address:
11676   case OMPC_unified_shared_memory:
11677   case OMPC_reverse_offload:
11678   case OMPC_dynamic_allocators:
11679   case OMPC_atomic_default_mem_order:
11680   case OMPC_device_type:
11681   case OMPC_match:
11682   case OMPC_nontemporal:
11683   case OMPC_order:
11684   case OMPC_destroy:
11685   case OMPC_inclusive:
11686   case OMPC_exclusive:
11687   case OMPC_uses_allocators:
11688   case OMPC_affinity:
11689   default:
11690     llvm_unreachable("Clause is not allowed.");
11691   }
11692   return Res;
11693 }
11694 
11695 // An OpenMP directive such as 'target parallel' has two captured regions:
11696 // for the 'target' and 'parallel' respectively.  This function returns
11697 // the region in which to capture expressions associated with a clause.
11698 // A return value of OMPD_unknown signifies that the expression should not
11699 // be captured.
11700 static OpenMPDirectiveKind getOpenMPCaptureRegionForClause(
11701     OpenMPDirectiveKind DKind, OpenMPClauseKind CKind, unsigned OpenMPVersion,
11702     OpenMPDirectiveKind NameModifier = OMPD_unknown) {
11703   OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
11704   switch (CKind) {
11705   case OMPC_if:
11706     switch (DKind) {
11707     case OMPD_target_parallel_for_simd:
11708       if (OpenMPVersion >= 50 &&
11709           (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)) {
11710         CaptureRegion = OMPD_parallel;
11711         break;
11712       }
11713       LLVM_FALLTHROUGH;
11714     case OMPD_target_parallel:
11715     case OMPD_target_parallel_for:
11716       // If this clause applies to the nested 'parallel' region, capture within
11717       // the 'target' region, otherwise do not capture.
11718       if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
11719         CaptureRegion = OMPD_target;
11720       break;
11721     case OMPD_target_teams_distribute_parallel_for_simd:
11722       if (OpenMPVersion >= 50 &&
11723           (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)) {
11724         CaptureRegion = OMPD_parallel;
11725         break;
11726       }
11727       LLVM_FALLTHROUGH;
11728     case OMPD_target_teams_distribute_parallel_for:
11729       // If this clause applies to the nested 'parallel' region, capture within
11730       // the 'teams' region, otherwise do not capture.
11731       if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
11732         CaptureRegion = OMPD_teams;
11733       break;
11734     case OMPD_teams_distribute_parallel_for_simd:
11735       if (OpenMPVersion >= 50 &&
11736           (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)) {
11737         CaptureRegion = OMPD_parallel;
11738         break;
11739       }
11740       LLVM_FALLTHROUGH;
11741     case OMPD_teams_distribute_parallel_for:
11742       CaptureRegion = OMPD_teams;
11743       break;
11744     case OMPD_target_update:
11745     case OMPD_target_enter_data:
11746     case OMPD_target_exit_data:
11747       CaptureRegion = OMPD_task;
11748       break;
11749     case OMPD_parallel_master_taskloop:
11750       if (NameModifier == OMPD_unknown || NameModifier == OMPD_taskloop)
11751         CaptureRegion = OMPD_parallel;
11752       break;
11753     case OMPD_parallel_master_taskloop_simd:
11754       if ((OpenMPVersion <= 45 && NameModifier == OMPD_unknown) ||
11755           NameModifier == OMPD_taskloop) {
11756         CaptureRegion = OMPD_parallel;
11757         break;
11758       }
11759       if (OpenMPVersion <= 45)
11760         break;
11761       if (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)
11762         CaptureRegion = OMPD_taskloop;
11763       break;
11764     case OMPD_parallel_for_simd:
11765       if (OpenMPVersion <= 45)
11766         break;
11767       if (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)
11768         CaptureRegion = OMPD_parallel;
11769       break;
11770     case OMPD_taskloop_simd:
11771     case OMPD_master_taskloop_simd:
11772       if (OpenMPVersion <= 45)
11773         break;
11774       if (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)
11775         CaptureRegion = OMPD_taskloop;
11776       break;
11777     case OMPD_distribute_parallel_for_simd:
11778       if (OpenMPVersion <= 45)
11779         break;
11780       if (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)
11781         CaptureRegion = OMPD_parallel;
11782       break;
11783     case OMPD_target_simd:
11784       if (OpenMPVersion >= 50 &&
11785           (NameModifier == OMPD_unknown || NameModifier == OMPD_simd))
11786         CaptureRegion = OMPD_target;
11787       break;
11788     case OMPD_teams_distribute_simd:
11789     case OMPD_target_teams_distribute_simd:
11790       if (OpenMPVersion >= 50 &&
11791           (NameModifier == OMPD_unknown || NameModifier == OMPD_simd))
11792         CaptureRegion = OMPD_teams;
11793       break;
11794     case OMPD_cancel:
11795     case OMPD_parallel:
11796     case OMPD_parallel_master:
11797     case OMPD_parallel_sections:
11798     case OMPD_parallel_for:
11799     case OMPD_target:
11800     case OMPD_target_teams:
11801     case OMPD_target_teams_distribute:
11802     case OMPD_distribute_parallel_for:
11803     case OMPD_task:
11804     case OMPD_taskloop:
11805     case OMPD_master_taskloop:
11806     case OMPD_target_data:
11807     case OMPD_simd:
11808     case OMPD_for_simd:
11809     case OMPD_distribute_simd:
11810       // Do not capture if-clause expressions.
11811       break;
11812     case OMPD_threadprivate:
11813     case OMPD_allocate:
11814     case OMPD_taskyield:
11815     case OMPD_barrier:
11816     case OMPD_taskwait:
11817     case OMPD_cancellation_point:
11818     case OMPD_flush:
11819     case OMPD_depobj:
11820     case OMPD_scan:
11821     case OMPD_declare_reduction:
11822     case OMPD_declare_mapper:
11823     case OMPD_declare_simd:
11824     case OMPD_declare_variant:
11825     case OMPD_begin_declare_variant:
11826     case OMPD_end_declare_variant:
11827     case OMPD_declare_target:
11828     case OMPD_end_declare_target:
11829     case OMPD_teams:
11830     case OMPD_for:
11831     case OMPD_sections:
11832     case OMPD_section:
11833     case OMPD_single:
11834     case OMPD_master:
11835     case OMPD_critical:
11836     case OMPD_taskgroup:
11837     case OMPD_distribute:
11838     case OMPD_ordered:
11839     case OMPD_atomic:
11840     case OMPD_teams_distribute:
11841     case OMPD_requires:
11842       llvm_unreachable("Unexpected OpenMP directive with if-clause");
11843     case OMPD_unknown:
11844     default:
11845       llvm_unreachable("Unknown OpenMP directive");
11846     }
11847     break;
11848   case OMPC_num_threads:
11849     switch (DKind) {
11850     case OMPD_target_parallel:
11851     case OMPD_target_parallel_for:
11852     case OMPD_target_parallel_for_simd:
11853       CaptureRegion = OMPD_target;
11854       break;
11855     case OMPD_teams_distribute_parallel_for:
11856     case OMPD_teams_distribute_parallel_for_simd:
11857     case OMPD_target_teams_distribute_parallel_for:
11858     case OMPD_target_teams_distribute_parallel_for_simd:
11859       CaptureRegion = OMPD_teams;
11860       break;
11861     case OMPD_parallel:
11862     case OMPD_parallel_master:
11863     case OMPD_parallel_sections:
11864     case OMPD_parallel_for:
11865     case OMPD_parallel_for_simd:
11866     case OMPD_distribute_parallel_for:
11867     case OMPD_distribute_parallel_for_simd:
11868     case OMPD_parallel_master_taskloop:
11869     case OMPD_parallel_master_taskloop_simd:
11870       // Do not capture num_threads-clause expressions.
11871       break;
11872     case OMPD_target_data:
11873     case OMPD_target_enter_data:
11874     case OMPD_target_exit_data:
11875     case OMPD_target_update:
11876     case OMPD_target:
11877     case OMPD_target_simd:
11878     case OMPD_target_teams:
11879     case OMPD_target_teams_distribute:
11880     case OMPD_target_teams_distribute_simd:
11881     case OMPD_cancel:
11882     case OMPD_task:
11883     case OMPD_taskloop:
11884     case OMPD_taskloop_simd:
11885     case OMPD_master_taskloop:
11886     case OMPD_master_taskloop_simd:
11887     case OMPD_threadprivate:
11888     case OMPD_allocate:
11889     case OMPD_taskyield:
11890     case OMPD_barrier:
11891     case OMPD_taskwait:
11892     case OMPD_cancellation_point:
11893     case OMPD_flush:
11894     case OMPD_depobj:
11895     case OMPD_scan:
11896     case OMPD_declare_reduction:
11897     case OMPD_declare_mapper:
11898     case OMPD_declare_simd:
11899     case OMPD_declare_variant:
11900     case OMPD_begin_declare_variant:
11901     case OMPD_end_declare_variant:
11902     case OMPD_declare_target:
11903     case OMPD_end_declare_target:
11904     case OMPD_teams:
11905     case OMPD_simd:
11906     case OMPD_for:
11907     case OMPD_for_simd:
11908     case OMPD_sections:
11909     case OMPD_section:
11910     case OMPD_single:
11911     case OMPD_master:
11912     case OMPD_critical:
11913     case OMPD_taskgroup:
11914     case OMPD_distribute:
11915     case OMPD_ordered:
11916     case OMPD_atomic:
11917     case OMPD_distribute_simd:
11918     case OMPD_teams_distribute:
11919     case OMPD_teams_distribute_simd:
11920     case OMPD_requires:
11921       llvm_unreachable("Unexpected OpenMP directive with num_threads-clause");
11922     case OMPD_unknown:
11923     default:
11924       llvm_unreachable("Unknown OpenMP directive");
11925     }
11926     break;
11927   case OMPC_num_teams:
11928     switch (DKind) {
11929     case OMPD_target_teams:
11930     case OMPD_target_teams_distribute:
11931     case OMPD_target_teams_distribute_simd:
11932     case OMPD_target_teams_distribute_parallel_for:
11933     case OMPD_target_teams_distribute_parallel_for_simd:
11934       CaptureRegion = OMPD_target;
11935       break;
11936     case OMPD_teams_distribute_parallel_for:
11937     case OMPD_teams_distribute_parallel_for_simd:
11938     case OMPD_teams:
11939     case OMPD_teams_distribute:
11940     case OMPD_teams_distribute_simd:
11941       // Do not capture num_teams-clause expressions.
11942       break;
11943     case OMPD_distribute_parallel_for:
11944     case OMPD_distribute_parallel_for_simd:
11945     case OMPD_task:
11946     case OMPD_taskloop:
11947     case OMPD_taskloop_simd:
11948     case OMPD_master_taskloop:
11949     case OMPD_master_taskloop_simd:
11950     case OMPD_parallel_master_taskloop:
11951     case OMPD_parallel_master_taskloop_simd:
11952     case OMPD_target_data:
11953     case OMPD_target_enter_data:
11954     case OMPD_target_exit_data:
11955     case OMPD_target_update:
11956     case OMPD_cancel:
11957     case OMPD_parallel:
11958     case OMPD_parallel_master:
11959     case OMPD_parallel_sections:
11960     case OMPD_parallel_for:
11961     case OMPD_parallel_for_simd:
11962     case OMPD_target:
11963     case OMPD_target_simd:
11964     case OMPD_target_parallel:
11965     case OMPD_target_parallel_for:
11966     case OMPD_target_parallel_for_simd:
11967     case OMPD_threadprivate:
11968     case OMPD_allocate:
11969     case OMPD_taskyield:
11970     case OMPD_barrier:
11971     case OMPD_taskwait:
11972     case OMPD_cancellation_point:
11973     case OMPD_flush:
11974     case OMPD_depobj:
11975     case OMPD_scan:
11976     case OMPD_declare_reduction:
11977     case OMPD_declare_mapper:
11978     case OMPD_declare_simd:
11979     case OMPD_declare_variant:
11980     case OMPD_begin_declare_variant:
11981     case OMPD_end_declare_variant:
11982     case OMPD_declare_target:
11983     case OMPD_end_declare_target:
11984     case OMPD_simd:
11985     case OMPD_for:
11986     case OMPD_for_simd:
11987     case OMPD_sections:
11988     case OMPD_section:
11989     case OMPD_single:
11990     case OMPD_master:
11991     case OMPD_critical:
11992     case OMPD_taskgroup:
11993     case OMPD_distribute:
11994     case OMPD_ordered:
11995     case OMPD_atomic:
11996     case OMPD_distribute_simd:
11997     case OMPD_requires:
11998       llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
11999     case OMPD_unknown:
12000     default:
12001       llvm_unreachable("Unknown OpenMP directive");
12002     }
12003     break;
12004   case OMPC_thread_limit:
12005     switch (DKind) {
12006     case OMPD_target_teams:
12007     case OMPD_target_teams_distribute:
12008     case OMPD_target_teams_distribute_simd:
12009     case OMPD_target_teams_distribute_parallel_for:
12010     case OMPD_target_teams_distribute_parallel_for_simd:
12011       CaptureRegion = OMPD_target;
12012       break;
12013     case OMPD_teams_distribute_parallel_for:
12014     case OMPD_teams_distribute_parallel_for_simd:
12015     case OMPD_teams:
12016     case OMPD_teams_distribute:
12017     case OMPD_teams_distribute_simd:
12018       // Do not capture thread_limit-clause expressions.
12019       break;
12020     case OMPD_distribute_parallel_for:
12021     case OMPD_distribute_parallel_for_simd:
12022     case OMPD_task:
12023     case OMPD_taskloop:
12024     case OMPD_taskloop_simd:
12025     case OMPD_master_taskloop:
12026     case OMPD_master_taskloop_simd:
12027     case OMPD_parallel_master_taskloop:
12028     case OMPD_parallel_master_taskloop_simd:
12029     case OMPD_target_data:
12030     case OMPD_target_enter_data:
12031     case OMPD_target_exit_data:
12032     case OMPD_target_update:
12033     case OMPD_cancel:
12034     case OMPD_parallel:
12035     case OMPD_parallel_master:
12036     case OMPD_parallel_sections:
12037     case OMPD_parallel_for:
12038     case OMPD_parallel_for_simd:
12039     case OMPD_target:
12040     case OMPD_target_simd:
12041     case OMPD_target_parallel:
12042     case OMPD_target_parallel_for:
12043     case OMPD_target_parallel_for_simd:
12044     case OMPD_threadprivate:
12045     case OMPD_allocate:
12046     case OMPD_taskyield:
12047     case OMPD_barrier:
12048     case OMPD_taskwait:
12049     case OMPD_cancellation_point:
12050     case OMPD_flush:
12051     case OMPD_depobj:
12052     case OMPD_scan:
12053     case OMPD_declare_reduction:
12054     case OMPD_declare_mapper:
12055     case OMPD_declare_simd:
12056     case OMPD_declare_variant:
12057     case OMPD_begin_declare_variant:
12058     case OMPD_end_declare_variant:
12059     case OMPD_declare_target:
12060     case OMPD_end_declare_target:
12061     case OMPD_simd:
12062     case OMPD_for:
12063     case OMPD_for_simd:
12064     case OMPD_sections:
12065     case OMPD_section:
12066     case OMPD_single:
12067     case OMPD_master:
12068     case OMPD_critical:
12069     case OMPD_taskgroup:
12070     case OMPD_distribute:
12071     case OMPD_ordered:
12072     case OMPD_atomic:
12073     case OMPD_distribute_simd:
12074     case OMPD_requires:
12075       llvm_unreachable("Unexpected OpenMP directive with thread_limit-clause");
12076     case OMPD_unknown:
12077     default:
12078       llvm_unreachable("Unknown OpenMP directive");
12079     }
12080     break;
12081   case OMPC_schedule:
12082     switch (DKind) {
12083     case OMPD_parallel_for:
12084     case OMPD_parallel_for_simd:
12085     case OMPD_distribute_parallel_for:
12086     case OMPD_distribute_parallel_for_simd:
12087     case OMPD_teams_distribute_parallel_for:
12088     case OMPD_teams_distribute_parallel_for_simd:
12089     case OMPD_target_parallel_for:
12090     case OMPD_target_parallel_for_simd:
12091     case OMPD_target_teams_distribute_parallel_for:
12092     case OMPD_target_teams_distribute_parallel_for_simd:
12093       CaptureRegion = OMPD_parallel;
12094       break;
12095     case OMPD_for:
12096     case OMPD_for_simd:
12097       // Do not capture schedule-clause expressions.
12098       break;
12099     case OMPD_task:
12100     case OMPD_taskloop:
12101     case OMPD_taskloop_simd:
12102     case OMPD_master_taskloop:
12103     case OMPD_master_taskloop_simd:
12104     case OMPD_parallel_master_taskloop:
12105     case OMPD_parallel_master_taskloop_simd:
12106     case OMPD_target_data:
12107     case OMPD_target_enter_data:
12108     case OMPD_target_exit_data:
12109     case OMPD_target_update:
12110     case OMPD_teams:
12111     case OMPD_teams_distribute:
12112     case OMPD_teams_distribute_simd:
12113     case OMPD_target_teams_distribute:
12114     case OMPD_target_teams_distribute_simd:
12115     case OMPD_target:
12116     case OMPD_target_simd:
12117     case OMPD_target_parallel:
12118     case OMPD_cancel:
12119     case OMPD_parallel:
12120     case OMPD_parallel_master:
12121     case OMPD_parallel_sections:
12122     case OMPD_threadprivate:
12123     case OMPD_allocate:
12124     case OMPD_taskyield:
12125     case OMPD_barrier:
12126     case OMPD_taskwait:
12127     case OMPD_cancellation_point:
12128     case OMPD_flush:
12129     case OMPD_depobj:
12130     case OMPD_scan:
12131     case OMPD_declare_reduction:
12132     case OMPD_declare_mapper:
12133     case OMPD_declare_simd:
12134     case OMPD_declare_variant:
12135     case OMPD_begin_declare_variant:
12136     case OMPD_end_declare_variant:
12137     case OMPD_declare_target:
12138     case OMPD_end_declare_target:
12139     case OMPD_simd:
12140     case OMPD_sections:
12141     case OMPD_section:
12142     case OMPD_single:
12143     case OMPD_master:
12144     case OMPD_critical:
12145     case OMPD_taskgroup:
12146     case OMPD_distribute:
12147     case OMPD_ordered:
12148     case OMPD_atomic:
12149     case OMPD_distribute_simd:
12150     case OMPD_target_teams:
12151     case OMPD_requires:
12152       llvm_unreachable("Unexpected OpenMP directive with schedule clause");
12153     case OMPD_unknown:
12154     default:
12155       llvm_unreachable("Unknown OpenMP directive");
12156     }
12157     break;
12158   case OMPC_dist_schedule:
12159     switch (DKind) {
12160     case OMPD_teams_distribute_parallel_for:
12161     case OMPD_teams_distribute_parallel_for_simd:
12162     case OMPD_teams_distribute:
12163     case OMPD_teams_distribute_simd:
12164     case OMPD_target_teams_distribute_parallel_for:
12165     case OMPD_target_teams_distribute_parallel_for_simd:
12166     case OMPD_target_teams_distribute:
12167     case OMPD_target_teams_distribute_simd:
12168       CaptureRegion = OMPD_teams;
12169       break;
12170     case OMPD_distribute_parallel_for:
12171     case OMPD_distribute_parallel_for_simd:
12172     case OMPD_distribute:
12173     case OMPD_distribute_simd:
12174       // Do not capture thread_limit-clause expressions.
12175       break;
12176     case OMPD_parallel_for:
12177     case OMPD_parallel_for_simd:
12178     case OMPD_target_parallel_for_simd:
12179     case OMPD_target_parallel_for:
12180     case OMPD_task:
12181     case OMPD_taskloop:
12182     case OMPD_taskloop_simd:
12183     case OMPD_master_taskloop:
12184     case OMPD_master_taskloop_simd:
12185     case OMPD_parallel_master_taskloop:
12186     case OMPD_parallel_master_taskloop_simd:
12187     case OMPD_target_data:
12188     case OMPD_target_enter_data:
12189     case OMPD_target_exit_data:
12190     case OMPD_target_update:
12191     case OMPD_teams:
12192     case OMPD_target:
12193     case OMPD_target_simd:
12194     case OMPD_target_parallel:
12195     case OMPD_cancel:
12196     case OMPD_parallel:
12197     case OMPD_parallel_master:
12198     case OMPD_parallel_sections:
12199     case OMPD_threadprivate:
12200     case OMPD_allocate:
12201     case OMPD_taskyield:
12202     case OMPD_barrier:
12203     case OMPD_taskwait:
12204     case OMPD_cancellation_point:
12205     case OMPD_flush:
12206     case OMPD_depobj:
12207     case OMPD_scan:
12208     case OMPD_declare_reduction:
12209     case OMPD_declare_mapper:
12210     case OMPD_declare_simd:
12211     case OMPD_declare_variant:
12212     case OMPD_begin_declare_variant:
12213     case OMPD_end_declare_variant:
12214     case OMPD_declare_target:
12215     case OMPD_end_declare_target:
12216     case OMPD_simd:
12217     case OMPD_for:
12218     case OMPD_for_simd:
12219     case OMPD_sections:
12220     case OMPD_section:
12221     case OMPD_single:
12222     case OMPD_master:
12223     case OMPD_critical:
12224     case OMPD_taskgroup:
12225     case OMPD_ordered:
12226     case OMPD_atomic:
12227     case OMPD_target_teams:
12228     case OMPD_requires:
12229       llvm_unreachable("Unexpected OpenMP directive with schedule clause");
12230     case OMPD_unknown:
12231     default:
12232       llvm_unreachable("Unknown OpenMP directive");
12233     }
12234     break;
12235   case OMPC_device:
12236     switch (DKind) {
12237     case OMPD_target_update:
12238     case OMPD_target_enter_data:
12239     case OMPD_target_exit_data:
12240     case OMPD_target:
12241     case OMPD_target_simd:
12242     case OMPD_target_teams:
12243     case OMPD_target_parallel:
12244     case OMPD_target_teams_distribute:
12245     case OMPD_target_teams_distribute_simd:
12246     case OMPD_target_parallel_for:
12247     case OMPD_target_parallel_for_simd:
12248     case OMPD_target_teams_distribute_parallel_for:
12249     case OMPD_target_teams_distribute_parallel_for_simd:
12250       CaptureRegion = OMPD_task;
12251       break;
12252     case OMPD_target_data:
12253       // Do not capture device-clause expressions.
12254       break;
12255     case OMPD_teams_distribute_parallel_for:
12256     case OMPD_teams_distribute_parallel_for_simd:
12257     case OMPD_teams:
12258     case OMPD_teams_distribute:
12259     case OMPD_teams_distribute_simd:
12260     case OMPD_distribute_parallel_for:
12261     case OMPD_distribute_parallel_for_simd:
12262     case OMPD_task:
12263     case OMPD_taskloop:
12264     case OMPD_taskloop_simd:
12265     case OMPD_master_taskloop:
12266     case OMPD_master_taskloop_simd:
12267     case OMPD_parallel_master_taskloop:
12268     case OMPD_parallel_master_taskloop_simd:
12269     case OMPD_cancel:
12270     case OMPD_parallel:
12271     case OMPD_parallel_master:
12272     case OMPD_parallel_sections:
12273     case OMPD_parallel_for:
12274     case OMPD_parallel_for_simd:
12275     case OMPD_threadprivate:
12276     case OMPD_allocate:
12277     case OMPD_taskyield:
12278     case OMPD_barrier:
12279     case OMPD_taskwait:
12280     case OMPD_cancellation_point:
12281     case OMPD_flush:
12282     case OMPD_depobj:
12283     case OMPD_scan:
12284     case OMPD_declare_reduction:
12285     case OMPD_declare_mapper:
12286     case OMPD_declare_simd:
12287     case OMPD_declare_variant:
12288     case OMPD_begin_declare_variant:
12289     case OMPD_end_declare_variant:
12290     case OMPD_declare_target:
12291     case OMPD_end_declare_target:
12292     case OMPD_simd:
12293     case OMPD_for:
12294     case OMPD_for_simd:
12295     case OMPD_sections:
12296     case OMPD_section:
12297     case OMPD_single:
12298     case OMPD_master:
12299     case OMPD_critical:
12300     case OMPD_taskgroup:
12301     case OMPD_distribute:
12302     case OMPD_ordered:
12303     case OMPD_atomic:
12304     case OMPD_distribute_simd:
12305     case OMPD_requires:
12306       llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
12307     case OMPD_unknown:
12308     default:
12309       llvm_unreachable("Unknown OpenMP directive");
12310     }
12311     break;
12312   case OMPC_grainsize:
12313   case OMPC_num_tasks:
12314   case OMPC_final:
12315   case OMPC_priority:
12316     switch (DKind) {
12317     case OMPD_task:
12318     case OMPD_taskloop:
12319     case OMPD_taskloop_simd:
12320     case OMPD_master_taskloop:
12321     case OMPD_master_taskloop_simd:
12322       break;
12323     case OMPD_parallel_master_taskloop:
12324     case OMPD_parallel_master_taskloop_simd:
12325       CaptureRegion = OMPD_parallel;
12326       break;
12327     case OMPD_target_update:
12328     case OMPD_target_enter_data:
12329     case OMPD_target_exit_data:
12330     case OMPD_target:
12331     case OMPD_target_simd:
12332     case OMPD_target_teams:
12333     case OMPD_target_parallel:
12334     case OMPD_target_teams_distribute:
12335     case OMPD_target_teams_distribute_simd:
12336     case OMPD_target_parallel_for:
12337     case OMPD_target_parallel_for_simd:
12338     case OMPD_target_teams_distribute_parallel_for:
12339     case OMPD_target_teams_distribute_parallel_for_simd:
12340     case OMPD_target_data:
12341     case OMPD_teams_distribute_parallel_for:
12342     case OMPD_teams_distribute_parallel_for_simd:
12343     case OMPD_teams:
12344     case OMPD_teams_distribute:
12345     case OMPD_teams_distribute_simd:
12346     case OMPD_distribute_parallel_for:
12347     case OMPD_distribute_parallel_for_simd:
12348     case OMPD_cancel:
12349     case OMPD_parallel:
12350     case OMPD_parallel_master:
12351     case OMPD_parallel_sections:
12352     case OMPD_parallel_for:
12353     case OMPD_parallel_for_simd:
12354     case OMPD_threadprivate:
12355     case OMPD_allocate:
12356     case OMPD_taskyield:
12357     case OMPD_barrier:
12358     case OMPD_taskwait:
12359     case OMPD_cancellation_point:
12360     case OMPD_flush:
12361     case OMPD_depobj:
12362     case OMPD_scan:
12363     case OMPD_declare_reduction:
12364     case OMPD_declare_mapper:
12365     case OMPD_declare_simd:
12366     case OMPD_declare_variant:
12367     case OMPD_begin_declare_variant:
12368     case OMPD_end_declare_variant:
12369     case OMPD_declare_target:
12370     case OMPD_end_declare_target:
12371     case OMPD_simd:
12372     case OMPD_for:
12373     case OMPD_for_simd:
12374     case OMPD_sections:
12375     case OMPD_section:
12376     case OMPD_single:
12377     case OMPD_master:
12378     case OMPD_critical:
12379     case OMPD_taskgroup:
12380     case OMPD_distribute:
12381     case OMPD_ordered:
12382     case OMPD_atomic:
12383     case OMPD_distribute_simd:
12384     case OMPD_requires:
12385       llvm_unreachable("Unexpected OpenMP directive with grainsize-clause");
12386     case OMPD_unknown:
12387     default:
12388       llvm_unreachable("Unknown OpenMP directive");
12389     }
12390     break;
12391   case OMPC_firstprivate:
12392   case OMPC_lastprivate:
12393   case OMPC_reduction:
12394   case OMPC_task_reduction:
12395   case OMPC_in_reduction:
12396   case OMPC_linear:
12397   case OMPC_default:
12398   case OMPC_proc_bind:
12399   case OMPC_safelen:
12400   case OMPC_simdlen:
12401   case OMPC_allocator:
12402   case OMPC_collapse:
12403   case OMPC_private:
12404   case OMPC_shared:
12405   case OMPC_aligned:
12406   case OMPC_copyin:
12407   case OMPC_copyprivate:
12408   case OMPC_ordered:
12409   case OMPC_nowait:
12410   case OMPC_untied:
12411   case OMPC_mergeable:
12412   case OMPC_threadprivate:
12413   case OMPC_allocate:
12414   case OMPC_flush:
12415   case OMPC_depobj:
12416   case OMPC_read:
12417   case OMPC_write:
12418   case OMPC_update:
12419   case OMPC_capture:
12420   case OMPC_seq_cst:
12421   case OMPC_acq_rel:
12422   case OMPC_acquire:
12423   case OMPC_release:
12424   case OMPC_relaxed:
12425   case OMPC_depend:
12426   case OMPC_threads:
12427   case OMPC_simd:
12428   case OMPC_map:
12429   case OMPC_nogroup:
12430   case OMPC_hint:
12431   case OMPC_defaultmap:
12432   case OMPC_unknown:
12433   case OMPC_uniform:
12434   case OMPC_to:
12435   case OMPC_from:
12436   case OMPC_use_device_ptr:
12437   case OMPC_use_device_addr:
12438   case OMPC_is_device_ptr:
12439   case OMPC_unified_address:
12440   case OMPC_unified_shared_memory:
12441   case OMPC_reverse_offload:
12442   case OMPC_dynamic_allocators:
12443   case OMPC_atomic_default_mem_order:
12444   case OMPC_device_type:
12445   case OMPC_match:
12446   case OMPC_nontemporal:
12447   case OMPC_order:
12448   case OMPC_destroy:
12449   case OMPC_detach:
12450   case OMPC_inclusive:
12451   case OMPC_exclusive:
12452   case OMPC_uses_allocators:
12453   case OMPC_affinity:
12454   default:
12455     llvm_unreachable("Unexpected OpenMP clause.");
12456   }
12457   return CaptureRegion;
12458 }
12459 
12460 OMPClause *Sema::ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
12461                                      Expr *Condition, SourceLocation StartLoc,
12462                                      SourceLocation LParenLoc,
12463                                      SourceLocation NameModifierLoc,
12464                                      SourceLocation ColonLoc,
12465                                      SourceLocation EndLoc) {
12466   Expr *ValExpr = Condition;
12467   Stmt *HelperValStmt = nullptr;
12468   OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
12469   if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
12470       !Condition->isInstantiationDependent() &&
12471       !Condition->containsUnexpandedParameterPack()) {
12472     ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
12473     if (Val.isInvalid())
12474       return nullptr;
12475 
12476     ValExpr = Val.get();
12477 
12478     OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
12479     CaptureRegion = getOpenMPCaptureRegionForClause(
12480         DKind, OMPC_if, LangOpts.OpenMP, NameModifier);
12481     if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
12482       ValExpr = MakeFullExpr(ValExpr).get();
12483       llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
12484       ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
12485       HelperValStmt = buildPreInits(Context, Captures);
12486     }
12487   }
12488 
12489   return new (Context)
12490       OMPIfClause(NameModifier, ValExpr, HelperValStmt, CaptureRegion, StartLoc,
12491                   LParenLoc, NameModifierLoc, ColonLoc, EndLoc);
12492 }
12493 
12494 OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition,
12495                                         SourceLocation StartLoc,
12496                                         SourceLocation LParenLoc,
12497                                         SourceLocation EndLoc) {
12498   Expr *ValExpr = Condition;
12499   Stmt *HelperValStmt = nullptr;
12500   OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
12501   if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
12502       !Condition->isInstantiationDependent() &&
12503       !Condition->containsUnexpandedParameterPack()) {
12504     ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
12505     if (Val.isInvalid())
12506       return nullptr;
12507 
12508     ValExpr = MakeFullExpr(Val.get()).get();
12509 
12510     OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
12511     CaptureRegion =
12512         getOpenMPCaptureRegionForClause(DKind, OMPC_final, LangOpts.OpenMP);
12513     if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
12514       ValExpr = MakeFullExpr(ValExpr).get();
12515       llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
12516       ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
12517       HelperValStmt = buildPreInits(Context, Captures);
12518     }
12519   }
12520 
12521   return new (Context) OMPFinalClause(ValExpr, HelperValStmt, CaptureRegion,
12522                                       StartLoc, LParenLoc, EndLoc);
12523 }
12524 
12525 ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc,
12526                                                         Expr *Op) {
12527   if (!Op)
12528     return ExprError();
12529 
12530   class IntConvertDiagnoser : public ICEConvertDiagnoser {
12531   public:
12532     IntConvertDiagnoser()
12533         : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {}
12534     SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
12535                                          QualType T) override {
12536       return S.Diag(Loc, diag::err_omp_not_integral) << T;
12537     }
12538     SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
12539                                              QualType T) override {
12540       return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
12541     }
12542     SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
12543                                                QualType T,
12544                                                QualType ConvTy) override {
12545       return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
12546     }
12547     SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
12548                                            QualType ConvTy) override {
12549       return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
12550              << ConvTy->isEnumeralType() << ConvTy;
12551     }
12552     SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
12553                                             QualType T) override {
12554       return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
12555     }
12556     SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
12557                                         QualType ConvTy) override {
12558       return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
12559              << ConvTy->isEnumeralType() << ConvTy;
12560     }
12561     SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType,
12562                                              QualType) override {
12563       llvm_unreachable("conversion functions are permitted");
12564     }
12565   } ConvertDiagnoser;
12566   return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
12567 }
12568 
12569 static bool
12570 isNonNegativeIntegerValue(Expr *&ValExpr, Sema &SemaRef, OpenMPClauseKind CKind,
12571                           bool StrictlyPositive, bool BuildCapture = false,
12572                           OpenMPDirectiveKind DKind = OMPD_unknown,
12573                           OpenMPDirectiveKind *CaptureRegion = nullptr,
12574                           Stmt **HelperValStmt = nullptr) {
12575   if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() &&
12576       !ValExpr->isInstantiationDependent()) {
12577     SourceLocation Loc = ValExpr->getExprLoc();
12578     ExprResult Value =
12579         SemaRef.PerformOpenMPImplicitIntegerConversion(Loc, ValExpr);
12580     if (Value.isInvalid())
12581       return false;
12582 
12583     ValExpr = Value.get();
12584     // The expression must evaluate to a non-negative integer value.
12585     llvm::APSInt Result;
12586     if (ValExpr->isIntegerConstantExpr(Result, SemaRef.Context) &&
12587         Result.isSigned() &&
12588         !((!StrictlyPositive && Result.isNonNegative()) ||
12589           (StrictlyPositive && Result.isStrictlyPositive()))) {
12590       SemaRef.Diag(Loc, diag::err_omp_negative_expression_in_clause)
12591           << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
12592           << ValExpr->getSourceRange();
12593       return false;
12594     }
12595     if (!BuildCapture)
12596       return true;
12597     *CaptureRegion =
12598         getOpenMPCaptureRegionForClause(DKind, CKind, SemaRef.LangOpts.OpenMP);
12599     if (*CaptureRegion != OMPD_unknown &&
12600         !SemaRef.CurContext->isDependentContext()) {
12601       ValExpr = SemaRef.MakeFullExpr(ValExpr).get();
12602       llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
12603       ValExpr = tryBuildCapture(SemaRef, ValExpr, Captures).get();
12604       *HelperValStmt = buildPreInits(SemaRef.Context, Captures);
12605     }
12606   }
12607   return true;
12608 }
12609 
12610 OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
12611                                              SourceLocation StartLoc,
12612                                              SourceLocation LParenLoc,
12613                                              SourceLocation EndLoc) {
12614   Expr *ValExpr = NumThreads;
12615   Stmt *HelperValStmt = nullptr;
12616 
12617   // OpenMP [2.5, Restrictions]
12618   //  The num_threads expression must evaluate to a positive integer value.
12619   if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_threads,
12620                                  /*StrictlyPositive=*/true))
12621     return nullptr;
12622 
12623   OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
12624   OpenMPDirectiveKind CaptureRegion =
12625       getOpenMPCaptureRegionForClause(DKind, OMPC_num_threads, LangOpts.OpenMP);
12626   if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
12627     ValExpr = MakeFullExpr(ValExpr).get();
12628     llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
12629     ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
12630     HelperValStmt = buildPreInits(Context, Captures);
12631   }
12632 
12633   return new (Context) OMPNumThreadsClause(
12634       ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
12635 }
12636 
12637 ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
12638                                                        OpenMPClauseKind CKind,
12639                                                        bool StrictlyPositive) {
12640   if (!E)
12641     return ExprError();
12642   if (E->isValueDependent() || E->isTypeDependent() ||
12643       E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
12644     return E;
12645   llvm::APSInt Result;
12646   ExprResult ICE = VerifyIntegerConstantExpression(E, &Result);
12647   if (ICE.isInvalid())
12648     return ExprError();
12649   if ((StrictlyPositive && !Result.isStrictlyPositive()) ||
12650       (!StrictlyPositive && !Result.isNonNegative())) {
12651     Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
12652         << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
12653         << E->getSourceRange();
12654     return ExprError();
12655   }
12656   if (CKind == OMPC_aligned && !Result.isPowerOf2()) {
12657     Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two)
12658         << E->getSourceRange();
12659     return ExprError();
12660   }
12661   if (CKind == OMPC_collapse && DSAStack->getAssociatedLoops() == 1)
12662     DSAStack->setAssociatedLoops(Result.getExtValue());
12663   else if (CKind == OMPC_ordered)
12664     DSAStack->setAssociatedLoops(Result.getExtValue());
12665   return ICE;
12666 }
12667 
12668 OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
12669                                           SourceLocation LParenLoc,
12670                                           SourceLocation EndLoc) {
12671   // OpenMP [2.8.1, simd construct, Description]
12672   // The parameter of the safelen clause must be a constant
12673   // positive integer expression.
12674   ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen);
12675   if (Safelen.isInvalid())
12676     return nullptr;
12677   return new (Context)
12678       OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc);
12679 }
12680 
12681 OMPClause *Sema::ActOnOpenMPSimdlenClause(Expr *Len, SourceLocation StartLoc,
12682                                           SourceLocation LParenLoc,
12683                                           SourceLocation EndLoc) {
12684   // OpenMP [2.8.1, simd construct, Description]
12685   // The parameter of the simdlen clause must be a constant
12686   // positive integer expression.
12687   ExprResult Simdlen = VerifyPositiveIntegerConstantInClause(Len, OMPC_simdlen);
12688   if (Simdlen.isInvalid())
12689     return nullptr;
12690   return new (Context)
12691       OMPSimdlenClause(Simdlen.get(), StartLoc, LParenLoc, EndLoc);
12692 }
12693 
12694 /// Tries to find omp_allocator_handle_t type.
12695 static bool findOMPAllocatorHandleT(Sema &S, SourceLocation Loc,
12696                                     DSAStackTy *Stack) {
12697   QualType OMPAllocatorHandleT = Stack->getOMPAllocatorHandleT();
12698   if (!OMPAllocatorHandleT.isNull())
12699     return true;
12700   // Build the predefined allocator expressions.
12701   bool ErrorFound = false;
12702   for (int I = 0; I < OMPAllocateDeclAttr::OMPUserDefinedMemAlloc; ++I) {
12703     auto AllocatorKind = static_cast<OMPAllocateDeclAttr::AllocatorTypeTy>(I);
12704     StringRef Allocator =
12705         OMPAllocateDeclAttr::ConvertAllocatorTypeTyToStr(AllocatorKind);
12706     DeclarationName AllocatorName = &S.getASTContext().Idents.get(Allocator);
12707     auto *VD = dyn_cast_or_null<ValueDecl>(
12708         S.LookupSingleName(S.TUScope, AllocatorName, Loc, Sema::LookupAnyName));
12709     if (!VD) {
12710       ErrorFound = true;
12711       break;
12712     }
12713     QualType AllocatorType =
12714         VD->getType().getNonLValueExprType(S.getASTContext());
12715     ExprResult Res = S.BuildDeclRefExpr(VD, AllocatorType, VK_LValue, Loc);
12716     if (!Res.isUsable()) {
12717       ErrorFound = true;
12718       break;
12719     }
12720     if (OMPAllocatorHandleT.isNull())
12721       OMPAllocatorHandleT = AllocatorType;
12722     if (!S.getASTContext().hasSameType(OMPAllocatorHandleT, AllocatorType)) {
12723       ErrorFound = true;
12724       break;
12725     }
12726     Stack->setAllocator(AllocatorKind, Res.get());
12727   }
12728   if (ErrorFound) {
12729     S.Diag(Loc, diag::err_omp_implied_type_not_found)
12730         << "omp_allocator_handle_t";
12731     return false;
12732   }
12733   OMPAllocatorHandleT.addConst();
12734   Stack->setOMPAllocatorHandleT(OMPAllocatorHandleT);
12735   return true;
12736 }
12737 
12738 OMPClause *Sema::ActOnOpenMPAllocatorClause(Expr *A, SourceLocation StartLoc,
12739                                             SourceLocation LParenLoc,
12740                                             SourceLocation EndLoc) {
12741   // OpenMP [2.11.3, allocate Directive, Description]
12742   // allocator is an expression of omp_allocator_handle_t type.
12743   if (!findOMPAllocatorHandleT(*this, A->getExprLoc(), DSAStack))
12744     return nullptr;
12745 
12746   ExprResult Allocator = DefaultLvalueConversion(A);
12747   if (Allocator.isInvalid())
12748     return nullptr;
12749   Allocator = PerformImplicitConversion(Allocator.get(),
12750                                         DSAStack->getOMPAllocatorHandleT(),
12751                                         Sema::AA_Initializing,
12752                                         /*AllowExplicit=*/true);
12753   if (Allocator.isInvalid())
12754     return nullptr;
12755   return new (Context)
12756       OMPAllocatorClause(Allocator.get(), StartLoc, LParenLoc, EndLoc);
12757 }
12758 
12759 OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops,
12760                                            SourceLocation StartLoc,
12761                                            SourceLocation LParenLoc,
12762                                            SourceLocation EndLoc) {
12763   // OpenMP [2.7.1, loop construct, Description]
12764   // OpenMP [2.8.1, simd construct, Description]
12765   // OpenMP [2.9.6, distribute construct, Description]
12766   // The parameter of the collapse clause must be a constant
12767   // positive integer expression.
12768   ExprResult NumForLoopsResult =
12769       VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse);
12770   if (NumForLoopsResult.isInvalid())
12771     return nullptr;
12772   return new (Context)
12773       OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc);
12774 }
12775 
12776 OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc,
12777                                           SourceLocation EndLoc,
12778                                           SourceLocation LParenLoc,
12779                                           Expr *NumForLoops) {
12780   // OpenMP [2.7.1, loop construct, Description]
12781   // OpenMP [2.8.1, simd construct, Description]
12782   // OpenMP [2.9.6, distribute construct, Description]
12783   // The parameter of the ordered clause must be a constant
12784   // positive integer expression if any.
12785   if (NumForLoops && LParenLoc.isValid()) {
12786     ExprResult NumForLoopsResult =
12787         VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_ordered);
12788     if (NumForLoopsResult.isInvalid())
12789       return nullptr;
12790     NumForLoops = NumForLoopsResult.get();
12791   } else {
12792     NumForLoops = nullptr;
12793   }
12794   auto *Clause = OMPOrderedClause::Create(
12795       Context, NumForLoops, NumForLoops ? DSAStack->getAssociatedLoops() : 0,
12796       StartLoc, LParenLoc, EndLoc);
12797   DSAStack->setOrderedRegion(/*IsOrdered=*/true, NumForLoops, Clause);
12798   return Clause;
12799 }
12800 
12801 OMPClause *Sema::ActOnOpenMPSimpleClause(
12802     OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc,
12803     SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
12804   OMPClause *Res = nullptr;
12805   switch (Kind) {
12806   case OMPC_default:
12807     Res = ActOnOpenMPDefaultClause(static_cast<DefaultKind>(Argument),
12808                                    ArgumentLoc, StartLoc, LParenLoc, EndLoc);
12809     break;
12810   case OMPC_proc_bind:
12811     Res = ActOnOpenMPProcBindClause(static_cast<ProcBindKind>(Argument),
12812                                     ArgumentLoc, StartLoc, LParenLoc, EndLoc);
12813     break;
12814   case OMPC_atomic_default_mem_order:
12815     Res = ActOnOpenMPAtomicDefaultMemOrderClause(
12816         static_cast<OpenMPAtomicDefaultMemOrderClauseKind>(Argument),
12817         ArgumentLoc, StartLoc, LParenLoc, EndLoc);
12818     break;
12819   case OMPC_order:
12820     Res = ActOnOpenMPOrderClause(static_cast<OpenMPOrderClauseKind>(Argument),
12821                                  ArgumentLoc, StartLoc, LParenLoc, EndLoc);
12822     break;
12823   case OMPC_update:
12824     Res = ActOnOpenMPUpdateClause(static_cast<OpenMPDependClauseKind>(Argument),
12825                                   ArgumentLoc, StartLoc, LParenLoc, EndLoc);
12826     break;
12827   case OMPC_if:
12828   case OMPC_final:
12829   case OMPC_num_threads:
12830   case OMPC_safelen:
12831   case OMPC_simdlen:
12832   case OMPC_allocator:
12833   case OMPC_collapse:
12834   case OMPC_schedule:
12835   case OMPC_private:
12836   case OMPC_firstprivate:
12837   case OMPC_lastprivate:
12838   case OMPC_shared:
12839   case OMPC_reduction:
12840   case OMPC_task_reduction:
12841   case OMPC_in_reduction:
12842   case OMPC_linear:
12843   case OMPC_aligned:
12844   case OMPC_copyin:
12845   case OMPC_copyprivate:
12846   case OMPC_ordered:
12847   case OMPC_nowait:
12848   case OMPC_untied:
12849   case OMPC_mergeable:
12850   case OMPC_threadprivate:
12851   case OMPC_allocate:
12852   case OMPC_flush:
12853   case OMPC_depobj:
12854   case OMPC_read:
12855   case OMPC_write:
12856   case OMPC_capture:
12857   case OMPC_seq_cst:
12858   case OMPC_acq_rel:
12859   case OMPC_acquire:
12860   case OMPC_release:
12861   case OMPC_relaxed:
12862   case OMPC_depend:
12863   case OMPC_device:
12864   case OMPC_threads:
12865   case OMPC_simd:
12866   case OMPC_map:
12867   case OMPC_num_teams:
12868   case OMPC_thread_limit:
12869   case OMPC_priority:
12870   case OMPC_grainsize:
12871   case OMPC_nogroup:
12872   case OMPC_num_tasks:
12873   case OMPC_hint:
12874   case OMPC_dist_schedule:
12875   case OMPC_defaultmap:
12876   case OMPC_unknown:
12877   case OMPC_uniform:
12878   case OMPC_to:
12879   case OMPC_from:
12880   case OMPC_use_device_ptr:
12881   case OMPC_use_device_addr:
12882   case OMPC_is_device_ptr:
12883   case OMPC_unified_address:
12884   case OMPC_unified_shared_memory:
12885   case OMPC_reverse_offload:
12886   case OMPC_dynamic_allocators:
12887   case OMPC_device_type:
12888   case OMPC_match:
12889   case OMPC_nontemporal:
12890   case OMPC_destroy:
12891   case OMPC_detach:
12892   case OMPC_inclusive:
12893   case OMPC_exclusive:
12894   case OMPC_uses_allocators:
12895   case OMPC_affinity:
12896   default:
12897     llvm_unreachable("Clause is not allowed.");
12898   }
12899   return Res;
12900 }
12901 
12902 static std::string
12903 getListOfPossibleValues(OpenMPClauseKind K, unsigned First, unsigned Last,
12904                         ArrayRef<unsigned> Exclude = llvm::None) {
12905   SmallString<256> Buffer;
12906   llvm::raw_svector_ostream Out(Buffer);
12907   unsigned Skipped = Exclude.size();
12908   auto S = Exclude.begin(), E = Exclude.end();
12909   for (unsigned I = First; I < Last; ++I) {
12910     if (std::find(S, E, I) != E) {
12911       --Skipped;
12912       continue;
12913     }
12914     Out << "'" << getOpenMPSimpleClauseTypeName(K, I) << "'";
12915     if (I + Skipped + 2 == Last)
12916       Out << " or ";
12917     else if (I + Skipped + 1 != Last)
12918       Out << ", ";
12919   }
12920   return std::string(Out.str());
12921 }
12922 
12923 OMPClause *Sema::ActOnOpenMPDefaultClause(DefaultKind Kind,
12924                                           SourceLocation KindKwLoc,
12925                                           SourceLocation StartLoc,
12926                                           SourceLocation LParenLoc,
12927                                           SourceLocation EndLoc) {
12928   if (Kind == OMP_DEFAULT_unknown) {
12929     Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
12930         << getListOfPossibleValues(OMPC_default, /*First=*/0,
12931                                    /*Last=*/unsigned(OMP_DEFAULT_unknown))
12932         << getOpenMPClauseName(OMPC_default);
12933     return nullptr;
12934   }
12935   if (Kind == OMP_DEFAULT_none)
12936     DSAStack->setDefaultDSANone(KindKwLoc);
12937   else if (Kind == OMP_DEFAULT_shared)
12938     DSAStack->setDefaultDSAShared(KindKwLoc);
12939 
12940   return new (Context)
12941       OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
12942 }
12943 
12944 OMPClause *Sema::ActOnOpenMPProcBindClause(ProcBindKind Kind,
12945                                            SourceLocation KindKwLoc,
12946                                            SourceLocation StartLoc,
12947                                            SourceLocation LParenLoc,
12948                                            SourceLocation EndLoc) {
12949   if (Kind == OMP_PROC_BIND_unknown) {
12950     Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
12951         << getListOfPossibleValues(OMPC_proc_bind,
12952                                    /*First=*/unsigned(OMP_PROC_BIND_master),
12953                                    /*Last=*/5)
12954         << getOpenMPClauseName(OMPC_proc_bind);
12955     return nullptr;
12956   }
12957   return new (Context)
12958       OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
12959 }
12960 
12961 OMPClause *Sema::ActOnOpenMPAtomicDefaultMemOrderClause(
12962     OpenMPAtomicDefaultMemOrderClauseKind Kind, SourceLocation KindKwLoc,
12963     SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
12964   if (Kind == OMPC_ATOMIC_DEFAULT_MEM_ORDER_unknown) {
12965     Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
12966         << getListOfPossibleValues(
12967                OMPC_atomic_default_mem_order, /*First=*/0,
12968                /*Last=*/OMPC_ATOMIC_DEFAULT_MEM_ORDER_unknown)
12969         << getOpenMPClauseName(OMPC_atomic_default_mem_order);
12970     return nullptr;
12971   }
12972   return new (Context) OMPAtomicDefaultMemOrderClause(Kind, KindKwLoc, StartLoc,
12973                                                       LParenLoc, EndLoc);
12974 }
12975 
12976 OMPClause *Sema::ActOnOpenMPOrderClause(OpenMPOrderClauseKind Kind,
12977                                         SourceLocation KindKwLoc,
12978                                         SourceLocation StartLoc,
12979                                         SourceLocation LParenLoc,
12980                                         SourceLocation EndLoc) {
12981   if (Kind == OMPC_ORDER_unknown) {
12982     static_assert(OMPC_ORDER_unknown > 0,
12983                   "OMPC_ORDER_unknown not greater than 0");
12984     Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
12985         << getListOfPossibleValues(OMPC_order, /*First=*/0,
12986                                    /*Last=*/OMPC_ORDER_unknown)
12987         << getOpenMPClauseName(OMPC_order);
12988     return nullptr;
12989   }
12990   return new (Context)
12991       OMPOrderClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
12992 }
12993 
12994 OMPClause *Sema::ActOnOpenMPUpdateClause(OpenMPDependClauseKind Kind,
12995                                          SourceLocation KindKwLoc,
12996                                          SourceLocation StartLoc,
12997                                          SourceLocation LParenLoc,
12998                                          SourceLocation EndLoc) {
12999   if (Kind == OMPC_DEPEND_unknown || Kind == OMPC_DEPEND_source ||
13000       Kind == OMPC_DEPEND_sink || Kind == OMPC_DEPEND_depobj) {
13001     unsigned Except[] = {OMPC_DEPEND_source, OMPC_DEPEND_sink,
13002                          OMPC_DEPEND_depobj};
13003     Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
13004         << getListOfPossibleValues(OMPC_depend, /*First=*/0,
13005                                    /*Last=*/OMPC_DEPEND_unknown, Except)
13006         << getOpenMPClauseName(OMPC_update);
13007     return nullptr;
13008   }
13009   return OMPUpdateClause::Create(Context, StartLoc, LParenLoc, KindKwLoc, Kind,
13010                                  EndLoc);
13011 }
13012 
13013 OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause(
13014     OpenMPClauseKind Kind, ArrayRef<unsigned> Argument, Expr *Expr,
13015     SourceLocation StartLoc, SourceLocation LParenLoc,
13016     ArrayRef<SourceLocation> ArgumentLoc, SourceLocation DelimLoc,
13017     SourceLocation EndLoc) {
13018   OMPClause *Res = nullptr;
13019   switch (Kind) {
13020   case OMPC_schedule:
13021     enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements };
13022     assert(Argument.size() == NumberOfElements &&
13023            ArgumentLoc.size() == NumberOfElements);
13024     Res = ActOnOpenMPScheduleClause(
13025         static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier1]),
13026         static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier2]),
13027         static_cast<OpenMPScheduleClauseKind>(Argument[ScheduleKind]), Expr,
13028         StartLoc, LParenLoc, ArgumentLoc[Modifier1], ArgumentLoc[Modifier2],
13029         ArgumentLoc[ScheduleKind], DelimLoc, EndLoc);
13030     break;
13031   case OMPC_if:
13032     assert(Argument.size() == 1 && ArgumentLoc.size() == 1);
13033     Res = ActOnOpenMPIfClause(static_cast<OpenMPDirectiveKind>(Argument.back()),
13034                               Expr, StartLoc, LParenLoc, ArgumentLoc.back(),
13035                               DelimLoc, EndLoc);
13036     break;
13037   case OMPC_dist_schedule:
13038     Res = ActOnOpenMPDistScheduleClause(
13039         static_cast<OpenMPDistScheduleClauseKind>(Argument.back()), Expr,
13040         StartLoc, LParenLoc, ArgumentLoc.back(), DelimLoc, EndLoc);
13041     break;
13042   case OMPC_defaultmap:
13043     enum { Modifier, DefaultmapKind };
13044     Res = ActOnOpenMPDefaultmapClause(
13045         static_cast<OpenMPDefaultmapClauseModifier>(Argument[Modifier]),
13046         static_cast<OpenMPDefaultmapClauseKind>(Argument[DefaultmapKind]),
13047         StartLoc, LParenLoc, ArgumentLoc[Modifier], ArgumentLoc[DefaultmapKind],
13048         EndLoc);
13049     break;
13050   case OMPC_device:
13051     assert(Argument.size() == 1 && ArgumentLoc.size() == 1);
13052     Res = ActOnOpenMPDeviceClause(
13053         static_cast<OpenMPDeviceClauseModifier>(Argument.back()), Expr,
13054         StartLoc, LParenLoc, ArgumentLoc.back(), EndLoc);
13055     break;
13056   case OMPC_final:
13057   case OMPC_num_threads:
13058   case OMPC_safelen:
13059   case OMPC_simdlen:
13060   case OMPC_allocator:
13061   case OMPC_collapse:
13062   case OMPC_default:
13063   case OMPC_proc_bind:
13064   case OMPC_private:
13065   case OMPC_firstprivate:
13066   case OMPC_lastprivate:
13067   case OMPC_shared:
13068   case OMPC_reduction:
13069   case OMPC_task_reduction:
13070   case OMPC_in_reduction:
13071   case OMPC_linear:
13072   case OMPC_aligned:
13073   case OMPC_copyin:
13074   case OMPC_copyprivate:
13075   case OMPC_ordered:
13076   case OMPC_nowait:
13077   case OMPC_untied:
13078   case OMPC_mergeable:
13079   case OMPC_threadprivate:
13080   case OMPC_allocate:
13081   case OMPC_flush:
13082   case OMPC_depobj:
13083   case OMPC_read:
13084   case OMPC_write:
13085   case OMPC_update:
13086   case OMPC_capture:
13087   case OMPC_seq_cst:
13088   case OMPC_acq_rel:
13089   case OMPC_acquire:
13090   case OMPC_release:
13091   case OMPC_relaxed:
13092   case OMPC_depend:
13093   case OMPC_threads:
13094   case OMPC_simd:
13095   case OMPC_map:
13096   case OMPC_num_teams:
13097   case OMPC_thread_limit:
13098   case OMPC_priority:
13099   case OMPC_grainsize:
13100   case OMPC_nogroup:
13101   case OMPC_num_tasks:
13102   case OMPC_hint:
13103   case OMPC_unknown:
13104   case OMPC_uniform:
13105   case OMPC_to:
13106   case OMPC_from:
13107   case OMPC_use_device_ptr:
13108   case OMPC_use_device_addr:
13109   case OMPC_is_device_ptr:
13110   case OMPC_unified_address:
13111   case OMPC_unified_shared_memory:
13112   case OMPC_reverse_offload:
13113   case OMPC_dynamic_allocators:
13114   case OMPC_atomic_default_mem_order:
13115   case OMPC_device_type:
13116   case OMPC_match:
13117   case OMPC_nontemporal:
13118   case OMPC_order:
13119   case OMPC_destroy:
13120   case OMPC_detach:
13121   case OMPC_inclusive:
13122   case OMPC_exclusive:
13123   case OMPC_uses_allocators:
13124   case OMPC_affinity:
13125   default:
13126     llvm_unreachable("Clause is not allowed.");
13127   }
13128   return Res;
13129 }
13130 
13131 static bool checkScheduleModifiers(Sema &S, OpenMPScheduleClauseModifier M1,
13132                                    OpenMPScheduleClauseModifier M2,
13133                                    SourceLocation M1Loc, SourceLocation M2Loc) {
13134   if (M1 == OMPC_SCHEDULE_MODIFIER_unknown && M1Loc.isValid()) {
13135     SmallVector<unsigned, 2> Excluded;
13136     if (M2 != OMPC_SCHEDULE_MODIFIER_unknown)
13137       Excluded.push_back(M2);
13138     if (M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic)
13139       Excluded.push_back(OMPC_SCHEDULE_MODIFIER_monotonic);
13140     if (M2 == OMPC_SCHEDULE_MODIFIER_monotonic)
13141       Excluded.push_back(OMPC_SCHEDULE_MODIFIER_nonmonotonic);
13142     S.Diag(M1Loc, diag::err_omp_unexpected_clause_value)
13143         << getListOfPossibleValues(OMPC_schedule,
13144                                    /*First=*/OMPC_SCHEDULE_MODIFIER_unknown + 1,
13145                                    /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
13146                                    Excluded)
13147         << getOpenMPClauseName(OMPC_schedule);
13148     return true;
13149   }
13150   return false;
13151 }
13152 
13153 OMPClause *Sema::ActOnOpenMPScheduleClause(
13154     OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
13155     OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
13156     SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
13157     SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) {
13158   if (checkScheduleModifiers(*this, M1, M2, M1Loc, M2Loc) ||
13159       checkScheduleModifiers(*this, M2, M1, M2Loc, M1Loc))
13160     return nullptr;
13161   // OpenMP, 2.7.1, Loop Construct, Restrictions
13162   // Either the monotonic modifier or the nonmonotonic modifier can be specified
13163   // but not both.
13164   if ((M1 == M2 && M1 != OMPC_SCHEDULE_MODIFIER_unknown) ||
13165       (M1 == OMPC_SCHEDULE_MODIFIER_monotonic &&
13166        M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) ||
13167       (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic &&
13168        M2 == OMPC_SCHEDULE_MODIFIER_monotonic)) {
13169     Diag(M2Loc, diag::err_omp_unexpected_schedule_modifier)
13170         << getOpenMPSimpleClauseTypeName(OMPC_schedule, M2)
13171         << getOpenMPSimpleClauseTypeName(OMPC_schedule, M1);
13172     return nullptr;
13173   }
13174   if (Kind == OMPC_SCHEDULE_unknown) {
13175     std::string Values;
13176     if (M1Loc.isInvalid() && M2Loc.isInvalid()) {
13177       unsigned Exclude[] = {OMPC_SCHEDULE_unknown};
13178       Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
13179                                        /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
13180                                        Exclude);
13181     } else {
13182       Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
13183                                        /*Last=*/OMPC_SCHEDULE_unknown);
13184     }
13185     Diag(KindLoc, diag::err_omp_unexpected_clause_value)
13186         << Values << getOpenMPClauseName(OMPC_schedule);
13187     return nullptr;
13188   }
13189   // OpenMP, 2.7.1, Loop Construct, Restrictions
13190   // The nonmonotonic modifier can only be specified with schedule(dynamic) or
13191   // schedule(guided).
13192   // OpenMP 5.0 does not have this restriction.
13193   if (LangOpts.OpenMP < 50 &&
13194       (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
13195        M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
13196       Kind != OMPC_SCHEDULE_dynamic && Kind != OMPC_SCHEDULE_guided) {
13197     Diag(M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ? M1Loc : M2Loc,
13198          diag::err_omp_schedule_nonmonotonic_static);
13199     return nullptr;
13200   }
13201   Expr *ValExpr = ChunkSize;
13202   Stmt *HelperValStmt = nullptr;
13203   if (ChunkSize) {
13204     if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
13205         !ChunkSize->isInstantiationDependent() &&
13206         !ChunkSize->containsUnexpandedParameterPack()) {
13207       SourceLocation ChunkSizeLoc = ChunkSize->getBeginLoc();
13208       ExprResult Val =
13209           PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
13210       if (Val.isInvalid())
13211         return nullptr;
13212 
13213       ValExpr = Val.get();
13214 
13215       // OpenMP [2.7.1, Restrictions]
13216       //  chunk_size must be a loop invariant integer expression with a positive
13217       //  value.
13218       llvm::APSInt Result;
13219       if (ValExpr->isIntegerConstantExpr(Result, Context)) {
13220         if (Result.isSigned() && !Result.isStrictlyPositive()) {
13221           Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
13222               << "schedule" << 1 << ChunkSize->getSourceRange();
13223           return nullptr;
13224         }
13225       } else if (getOpenMPCaptureRegionForClause(
13226                      DSAStack->getCurrentDirective(), OMPC_schedule,
13227                      LangOpts.OpenMP) != OMPD_unknown &&
13228                  !CurContext->isDependentContext()) {
13229         ValExpr = MakeFullExpr(ValExpr).get();
13230         llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
13231         ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
13232         HelperValStmt = buildPreInits(Context, Captures);
13233       }
13234     }
13235   }
13236 
13237   return new (Context)
13238       OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, Kind,
13239                         ValExpr, HelperValStmt, M1, M1Loc, M2, M2Loc);
13240 }
13241 
13242 OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind,
13243                                    SourceLocation StartLoc,
13244                                    SourceLocation EndLoc) {
13245   OMPClause *Res = nullptr;
13246   switch (Kind) {
13247   case OMPC_ordered:
13248     Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc);
13249     break;
13250   case OMPC_nowait:
13251     Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc);
13252     break;
13253   case OMPC_untied:
13254     Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc);
13255     break;
13256   case OMPC_mergeable:
13257     Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc);
13258     break;
13259   case OMPC_read:
13260     Res = ActOnOpenMPReadClause(StartLoc, EndLoc);
13261     break;
13262   case OMPC_write:
13263     Res = ActOnOpenMPWriteClause(StartLoc, EndLoc);
13264     break;
13265   case OMPC_update:
13266     Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc);
13267     break;
13268   case OMPC_capture:
13269     Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc);
13270     break;
13271   case OMPC_seq_cst:
13272     Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc);
13273     break;
13274   case OMPC_acq_rel:
13275     Res = ActOnOpenMPAcqRelClause(StartLoc, EndLoc);
13276     break;
13277   case OMPC_acquire:
13278     Res = ActOnOpenMPAcquireClause(StartLoc, EndLoc);
13279     break;
13280   case OMPC_release:
13281     Res = ActOnOpenMPReleaseClause(StartLoc, EndLoc);
13282     break;
13283   case OMPC_relaxed:
13284     Res = ActOnOpenMPRelaxedClause(StartLoc, EndLoc);
13285     break;
13286   case OMPC_threads:
13287     Res = ActOnOpenMPThreadsClause(StartLoc, EndLoc);
13288     break;
13289   case OMPC_simd:
13290     Res = ActOnOpenMPSIMDClause(StartLoc, EndLoc);
13291     break;
13292   case OMPC_nogroup:
13293     Res = ActOnOpenMPNogroupClause(StartLoc, EndLoc);
13294     break;
13295   case OMPC_unified_address:
13296     Res = ActOnOpenMPUnifiedAddressClause(StartLoc, EndLoc);
13297     break;
13298   case OMPC_unified_shared_memory:
13299     Res = ActOnOpenMPUnifiedSharedMemoryClause(StartLoc, EndLoc);
13300     break;
13301   case OMPC_reverse_offload:
13302     Res = ActOnOpenMPReverseOffloadClause(StartLoc, EndLoc);
13303     break;
13304   case OMPC_dynamic_allocators:
13305     Res = ActOnOpenMPDynamicAllocatorsClause(StartLoc, EndLoc);
13306     break;
13307   case OMPC_destroy:
13308     Res = ActOnOpenMPDestroyClause(StartLoc, EndLoc);
13309     break;
13310   case OMPC_if:
13311   case OMPC_final:
13312   case OMPC_num_threads:
13313   case OMPC_safelen:
13314   case OMPC_simdlen:
13315   case OMPC_allocator:
13316   case OMPC_collapse:
13317   case OMPC_schedule:
13318   case OMPC_private:
13319   case OMPC_firstprivate:
13320   case OMPC_lastprivate:
13321   case OMPC_shared:
13322   case OMPC_reduction:
13323   case OMPC_task_reduction:
13324   case OMPC_in_reduction:
13325   case OMPC_linear:
13326   case OMPC_aligned:
13327   case OMPC_copyin:
13328   case OMPC_copyprivate:
13329   case OMPC_default:
13330   case OMPC_proc_bind:
13331   case OMPC_threadprivate:
13332   case OMPC_allocate:
13333   case OMPC_flush:
13334   case OMPC_depobj:
13335   case OMPC_depend:
13336   case OMPC_device:
13337   case OMPC_map:
13338   case OMPC_num_teams:
13339   case OMPC_thread_limit:
13340   case OMPC_priority:
13341   case OMPC_grainsize:
13342   case OMPC_num_tasks:
13343   case OMPC_hint:
13344   case OMPC_dist_schedule:
13345   case OMPC_defaultmap:
13346   case OMPC_unknown:
13347   case OMPC_uniform:
13348   case OMPC_to:
13349   case OMPC_from:
13350   case OMPC_use_device_ptr:
13351   case OMPC_use_device_addr:
13352   case OMPC_is_device_ptr:
13353   case OMPC_atomic_default_mem_order:
13354   case OMPC_device_type:
13355   case OMPC_match:
13356   case OMPC_nontemporal:
13357   case OMPC_order:
13358   case OMPC_detach:
13359   case OMPC_inclusive:
13360   case OMPC_exclusive:
13361   case OMPC_uses_allocators:
13362   case OMPC_affinity:
13363   default:
13364     llvm_unreachable("Clause is not allowed.");
13365   }
13366   return Res;
13367 }
13368 
13369 OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc,
13370                                          SourceLocation EndLoc) {
13371   DSAStack->setNowaitRegion();
13372   return new (Context) OMPNowaitClause(StartLoc, EndLoc);
13373 }
13374 
13375 OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc,
13376                                          SourceLocation EndLoc) {
13377   return new (Context) OMPUntiedClause(StartLoc, EndLoc);
13378 }
13379 
13380 OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc,
13381                                             SourceLocation EndLoc) {
13382   return new (Context) OMPMergeableClause(StartLoc, EndLoc);
13383 }
13384 
13385 OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc,
13386                                        SourceLocation EndLoc) {
13387   return new (Context) OMPReadClause(StartLoc, EndLoc);
13388 }
13389 
13390 OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc,
13391                                         SourceLocation EndLoc) {
13392   return new (Context) OMPWriteClause(StartLoc, EndLoc);
13393 }
13394 
13395 OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc,
13396                                          SourceLocation EndLoc) {
13397   return OMPUpdateClause::Create(Context, StartLoc, EndLoc);
13398 }
13399 
13400 OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc,
13401                                           SourceLocation EndLoc) {
13402   return new (Context) OMPCaptureClause(StartLoc, EndLoc);
13403 }
13404 
13405 OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
13406                                          SourceLocation EndLoc) {
13407   return new (Context) OMPSeqCstClause(StartLoc, EndLoc);
13408 }
13409 
13410 OMPClause *Sema::ActOnOpenMPAcqRelClause(SourceLocation StartLoc,
13411                                          SourceLocation EndLoc) {
13412   return new (Context) OMPAcqRelClause(StartLoc, EndLoc);
13413 }
13414 
13415 OMPClause *Sema::ActOnOpenMPAcquireClause(SourceLocation StartLoc,
13416                                           SourceLocation EndLoc) {
13417   return new (Context) OMPAcquireClause(StartLoc, EndLoc);
13418 }
13419 
13420 OMPClause *Sema::ActOnOpenMPReleaseClause(SourceLocation StartLoc,
13421                                           SourceLocation EndLoc) {
13422   return new (Context) OMPReleaseClause(StartLoc, EndLoc);
13423 }
13424 
13425 OMPClause *Sema::ActOnOpenMPRelaxedClause(SourceLocation StartLoc,
13426                                           SourceLocation EndLoc) {
13427   return new (Context) OMPRelaxedClause(StartLoc, EndLoc);
13428 }
13429 
13430 OMPClause *Sema::ActOnOpenMPThreadsClause(SourceLocation StartLoc,
13431                                           SourceLocation EndLoc) {
13432   return new (Context) OMPThreadsClause(StartLoc, EndLoc);
13433 }
13434 
13435 OMPClause *Sema::ActOnOpenMPSIMDClause(SourceLocation StartLoc,
13436                                        SourceLocation EndLoc) {
13437   return new (Context) OMPSIMDClause(StartLoc, EndLoc);
13438 }
13439 
13440 OMPClause *Sema::ActOnOpenMPNogroupClause(SourceLocation StartLoc,
13441                                           SourceLocation EndLoc) {
13442   return new (Context) OMPNogroupClause(StartLoc, EndLoc);
13443 }
13444 
13445 OMPClause *Sema::ActOnOpenMPUnifiedAddressClause(SourceLocation StartLoc,
13446                                                  SourceLocation EndLoc) {
13447   return new (Context) OMPUnifiedAddressClause(StartLoc, EndLoc);
13448 }
13449 
13450 OMPClause *Sema::ActOnOpenMPUnifiedSharedMemoryClause(SourceLocation StartLoc,
13451                                                       SourceLocation EndLoc) {
13452   return new (Context) OMPUnifiedSharedMemoryClause(StartLoc, EndLoc);
13453 }
13454 
13455 OMPClause *Sema::ActOnOpenMPReverseOffloadClause(SourceLocation StartLoc,
13456                                                  SourceLocation EndLoc) {
13457   return new (Context) OMPReverseOffloadClause(StartLoc, EndLoc);
13458 }
13459 
13460 OMPClause *Sema::ActOnOpenMPDynamicAllocatorsClause(SourceLocation StartLoc,
13461                                                     SourceLocation EndLoc) {
13462   return new (Context) OMPDynamicAllocatorsClause(StartLoc, EndLoc);
13463 }
13464 
13465 OMPClause *Sema::ActOnOpenMPDestroyClause(SourceLocation StartLoc,
13466                                           SourceLocation EndLoc) {
13467   return new (Context) OMPDestroyClause(StartLoc, EndLoc);
13468 }
13469 
13470 OMPClause *Sema::ActOnOpenMPVarListClause(
13471     OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *DepModOrTailExpr,
13472     const OMPVarListLocTy &Locs, SourceLocation ColonLoc,
13473     CXXScopeSpec &ReductionOrMapperIdScopeSpec,
13474     DeclarationNameInfo &ReductionOrMapperId, int ExtraModifier,
13475     ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
13476     ArrayRef<SourceLocation> MapTypeModifiersLoc, bool IsMapTypeImplicit,
13477     SourceLocation ExtraModifierLoc) {
13478   SourceLocation StartLoc = Locs.StartLoc;
13479   SourceLocation LParenLoc = Locs.LParenLoc;
13480   SourceLocation EndLoc = Locs.EndLoc;
13481   OMPClause *Res = nullptr;
13482   switch (Kind) {
13483   case OMPC_private:
13484     Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
13485     break;
13486   case OMPC_firstprivate:
13487     Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
13488     break;
13489   case OMPC_lastprivate:
13490     assert(0 <= ExtraModifier && ExtraModifier <= OMPC_LASTPRIVATE_unknown &&
13491            "Unexpected lastprivate modifier.");
13492     Res = ActOnOpenMPLastprivateClause(
13493         VarList, static_cast<OpenMPLastprivateModifier>(ExtraModifier),
13494         ExtraModifierLoc, ColonLoc, StartLoc, LParenLoc, EndLoc);
13495     break;
13496   case OMPC_shared:
13497     Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
13498     break;
13499   case OMPC_reduction:
13500     assert(0 <= ExtraModifier && ExtraModifier <= OMPC_REDUCTION_unknown &&
13501            "Unexpected lastprivate modifier.");
13502     Res = ActOnOpenMPReductionClause(
13503         VarList, static_cast<OpenMPReductionClauseModifier>(ExtraModifier),
13504         StartLoc, LParenLoc, ExtraModifierLoc, ColonLoc, EndLoc,
13505         ReductionOrMapperIdScopeSpec, ReductionOrMapperId);
13506     break;
13507   case OMPC_task_reduction:
13508     Res = ActOnOpenMPTaskReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
13509                                          EndLoc, ReductionOrMapperIdScopeSpec,
13510                                          ReductionOrMapperId);
13511     break;
13512   case OMPC_in_reduction:
13513     Res = ActOnOpenMPInReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
13514                                        EndLoc, ReductionOrMapperIdScopeSpec,
13515                                        ReductionOrMapperId);
13516     break;
13517   case OMPC_linear:
13518     assert(0 <= ExtraModifier && ExtraModifier <= OMPC_LINEAR_unknown &&
13519            "Unexpected linear modifier.");
13520     Res = ActOnOpenMPLinearClause(
13521         VarList, DepModOrTailExpr, StartLoc, LParenLoc,
13522         static_cast<OpenMPLinearClauseKind>(ExtraModifier), ExtraModifierLoc,
13523         ColonLoc, EndLoc);
13524     break;
13525   case OMPC_aligned:
13526     Res = ActOnOpenMPAlignedClause(VarList, DepModOrTailExpr, StartLoc,
13527                                    LParenLoc, ColonLoc, EndLoc);
13528     break;
13529   case OMPC_copyin:
13530     Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
13531     break;
13532   case OMPC_copyprivate:
13533     Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
13534     break;
13535   case OMPC_flush:
13536     Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc);
13537     break;
13538   case OMPC_depend:
13539     assert(0 <= ExtraModifier && ExtraModifier <= OMPC_DEPEND_unknown &&
13540            "Unexpected depend modifier.");
13541     Res = ActOnOpenMPDependClause(
13542         DepModOrTailExpr, static_cast<OpenMPDependClauseKind>(ExtraModifier),
13543         ExtraModifierLoc, ColonLoc, VarList, StartLoc, LParenLoc, EndLoc);
13544     break;
13545   case OMPC_map:
13546     assert(0 <= ExtraModifier && ExtraModifier <= OMPC_MAP_unknown &&
13547            "Unexpected map modifier.");
13548     Res = ActOnOpenMPMapClause(
13549         MapTypeModifiers, MapTypeModifiersLoc, ReductionOrMapperIdScopeSpec,
13550         ReductionOrMapperId, static_cast<OpenMPMapClauseKind>(ExtraModifier),
13551         IsMapTypeImplicit, ExtraModifierLoc, ColonLoc, VarList, Locs);
13552     break;
13553   case OMPC_to:
13554     Res = ActOnOpenMPToClause(VarList, ReductionOrMapperIdScopeSpec,
13555                               ReductionOrMapperId, Locs);
13556     break;
13557   case OMPC_from:
13558     Res = ActOnOpenMPFromClause(VarList, ReductionOrMapperIdScopeSpec,
13559                                 ReductionOrMapperId, Locs);
13560     break;
13561   case OMPC_use_device_ptr:
13562     Res = ActOnOpenMPUseDevicePtrClause(VarList, Locs);
13563     break;
13564   case OMPC_use_device_addr:
13565     Res = ActOnOpenMPUseDeviceAddrClause(VarList, Locs);
13566     break;
13567   case OMPC_is_device_ptr:
13568     Res = ActOnOpenMPIsDevicePtrClause(VarList, Locs);
13569     break;
13570   case OMPC_allocate:
13571     Res = ActOnOpenMPAllocateClause(DepModOrTailExpr, VarList, StartLoc,
13572                                     LParenLoc, ColonLoc, EndLoc);
13573     break;
13574   case OMPC_nontemporal:
13575     Res = ActOnOpenMPNontemporalClause(VarList, StartLoc, LParenLoc, EndLoc);
13576     break;
13577   case OMPC_inclusive:
13578     Res = ActOnOpenMPInclusiveClause(VarList, StartLoc, LParenLoc, EndLoc);
13579     break;
13580   case OMPC_exclusive:
13581     Res = ActOnOpenMPExclusiveClause(VarList, StartLoc, LParenLoc, EndLoc);
13582     break;
13583   case OMPC_affinity:
13584     Res = ActOnOpenMPAffinityClause(StartLoc, LParenLoc, ColonLoc, EndLoc,
13585                                     DepModOrTailExpr, VarList);
13586     break;
13587   case OMPC_if:
13588   case OMPC_depobj:
13589   case OMPC_final:
13590   case OMPC_num_threads:
13591   case OMPC_safelen:
13592   case OMPC_simdlen:
13593   case OMPC_allocator:
13594   case OMPC_collapse:
13595   case OMPC_default:
13596   case OMPC_proc_bind:
13597   case OMPC_schedule:
13598   case OMPC_ordered:
13599   case OMPC_nowait:
13600   case OMPC_untied:
13601   case OMPC_mergeable:
13602   case OMPC_threadprivate:
13603   case OMPC_read:
13604   case OMPC_write:
13605   case OMPC_update:
13606   case OMPC_capture:
13607   case OMPC_seq_cst:
13608   case OMPC_acq_rel:
13609   case OMPC_acquire:
13610   case OMPC_release:
13611   case OMPC_relaxed:
13612   case OMPC_device:
13613   case OMPC_threads:
13614   case OMPC_simd:
13615   case OMPC_num_teams:
13616   case OMPC_thread_limit:
13617   case OMPC_priority:
13618   case OMPC_grainsize:
13619   case OMPC_nogroup:
13620   case OMPC_num_tasks:
13621   case OMPC_hint:
13622   case OMPC_dist_schedule:
13623   case OMPC_defaultmap:
13624   case OMPC_unknown:
13625   case OMPC_uniform:
13626   case OMPC_unified_address:
13627   case OMPC_unified_shared_memory:
13628   case OMPC_reverse_offload:
13629   case OMPC_dynamic_allocators:
13630   case OMPC_atomic_default_mem_order:
13631   case OMPC_device_type:
13632   case OMPC_match:
13633   case OMPC_order:
13634   case OMPC_destroy:
13635   case OMPC_detach:
13636   case OMPC_uses_allocators:
13637   default:
13638     llvm_unreachable("Clause is not allowed.");
13639   }
13640   return Res;
13641 }
13642 
13643 ExprResult Sema::getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
13644                                        ExprObjectKind OK, SourceLocation Loc) {
13645   ExprResult Res = BuildDeclRefExpr(
13646       Capture, Capture->getType().getNonReferenceType(), VK_LValue, Loc);
13647   if (!Res.isUsable())
13648     return ExprError();
13649   if (OK == OK_Ordinary && !getLangOpts().CPlusPlus) {
13650     Res = CreateBuiltinUnaryOp(Loc, UO_Deref, Res.get());
13651     if (!Res.isUsable())
13652       return ExprError();
13653   }
13654   if (VK != VK_LValue && Res.get()->isGLValue()) {
13655     Res = DefaultLvalueConversion(Res.get());
13656     if (!Res.isUsable())
13657       return ExprError();
13658   }
13659   return Res;
13660 }
13661 
13662 OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
13663                                           SourceLocation StartLoc,
13664                                           SourceLocation LParenLoc,
13665                                           SourceLocation EndLoc) {
13666   SmallVector<Expr *, 8> Vars;
13667   SmallVector<Expr *, 8> PrivateCopies;
13668   for (Expr *RefExpr : VarList) {
13669     assert(RefExpr && "NULL expr in OpenMP private clause.");
13670     SourceLocation ELoc;
13671     SourceRange ERange;
13672     Expr *SimpleRefExpr = RefExpr;
13673     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
13674     if (Res.second) {
13675       // It will be analyzed later.
13676       Vars.push_back(RefExpr);
13677       PrivateCopies.push_back(nullptr);
13678     }
13679     ValueDecl *D = Res.first;
13680     if (!D)
13681       continue;
13682 
13683     QualType Type = D->getType();
13684     auto *VD = dyn_cast<VarDecl>(D);
13685 
13686     // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
13687     //  A variable that appears in a private clause must not have an incomplete
13688     //  type or a reference type.
13689     if (RequireCompleteType(ELoc, Type, diag::err_omp_private_incomplete_type))
13690       continue;
13691     Type = Type.getNonReferenceType();
13692 
13693     // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
13694     // A variable that is privatized must not have a const-qualified type
13695     // unless it is of class type with a mutable member. This restriction does
13696     // not apply to the firstprivate clause.
13697     //
13698     // OpenMP 3.1 [2.9.3.3, private clause, Restrictions]
13699     // A variable that appears in a private clause must not have a
13700     // const-qualified type unless it is of class type with a mutable member.
13701     if (rejectConstNotMutableType(*this, D, Type, OMPC_private, ELoc))
13702       continue;
13703 
13704     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
13705     // in a Construct]
13706     //  Variables with the predetermined data-sharing attributes may not be
13707     //  listed in data-sharing attributes clauses, except for the cases
13708     //  listed below. For these exceptions only, listing a predetermined
13709     //  variable in a data-sharing attribute clause is allowed and overrides
13710     //  the variable's predetermined data-sharing attributes.
13711     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
13712     if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
13713       Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
13714                                           << getOpenMPClauseName(OMPC_private);
13715       reportOriginalDsa(*this, DSAStack, D, DVar);
13716       continue;
13717     }
13718 
13719     OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
13720     // Variably modified types are not supported for tasks.
13721     if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
13722         isOpenMPTaskingDirective(CurrDir)) {
13723       Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
13724           << getOpenMPClauseName(OMPC_private) << Type
13725           << getOpenMPDirectiveName(CurrDir);
13726       bool IsDecl =
13727           !VD ||
13728           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
13729       Diag(D->getLocation(),
13730            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
13731           << D;
13732       continue;
13733     }
13734 
13735     // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
13736     // A list item cannot appear in both a map clause and a data-sharing
13737     // attribute clause on the same construct
13738     //
13739     // OpenMP 5.0 [2.19.7.1, Restrictions, p.7]
13740     // A list item cannot appear in both a map clause and a data-sharing
13741     // attribute clause on the same construct unless the construct is a
13742     // combined construct.
13743     if ((LangOpts.OpenMP <= 45 && isOpenMPTargetExecutionDirective(CurrDir)) ||
13744         CurrDir == OMPD_target) {
13745       OpenMPClauseKind ConflictKind;
13746       if (DSAStack->checkMappableExprComponentListsForDecl(
13747               VD, /*CurrentRegionOnly=*/true,
13748               [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
13749                   OpenMPClauseKind WhereFoundClauseKind) -> bool {
13750                 ConflictKind = WhereFoundClauseKind;
13751                 return true;
13752               })) {
13753         Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
13754             << getOpenMPClauseName(OMPC_private)
13755             << getOpenMPClauseName(ConflictKind)
13756             << getOpenMPDirectiveName(CurrDir);
13757         reportOriginalDsa(*this, DSAStack, D, DVar);
13758         continue;
13759       }
13760     }
13761 
13762     // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
13763     //  A variable of class type (or array thereof) that appears in a private
13764     //  clause requires an accessible, unambiguous default constructor for the
13765     //  class type.
13766     // Generate helper private variable and initialize it with the default
13767     // value. The address of the original variable is replaced by the address of
13768     // the new private variable in CodeGen. This new variable is not added to
13769     // IdResolver, so the code in the OpenMP region uses original variable for
13770     // proper diagnostics.
13771     Type = Type.getUnqualifiedType();
13772     VarDecl *VDPrivate =
13773         buildVarDecl(*this, ELoc, Type, D->getName(),
13774                      D->hasAttrs() ? &D->getAttrs() : nullptr,
13775                      VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
13776     ActOnUninitializedDecl(VDPrivate);
13777     if (VDPrivate->isInvalidDecl())
13778       continue;
13779     DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
13780         *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
13781 
13782     DeclRefExpr *Ref = nullptr;
13783     if (!VD && !CurContext->isDependentContext())
13784       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
13785     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_private, Ref);
13786     Vars.push_back((VD || CurContext->isDependentContext())
13787                        ? RefExpr->IgnoreParens()
13788                        : Ref);
13789     PrivateCopies.push_back(VDPrivateRefExpr);
13790   }
13791 
13792   if (Vars.empty())
13793     return nullptr;
13794 
13795   return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
13796                                   PrivateCopies);
13797 }
13798 
13799 namespace {
13800 class DiagsUninitializedSeveretyRAII {
13801 private:
13802   DiagnosticsEngine &Diags;
13803   SourceLocation SavedLoc;
13804   bool IsIgnored = false;
13805 
13806 public:
13807   DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc,
13808                                  bool IsIgnored)
13809       : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) {
13810     if (!IsIgnored) {
13811       Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init,
13812                         /*Map*/ diag::Severity::Ignored, Loc);
13813     }
13814   }
13815   ~DiagsUninitializedSeveretyRAII() {
13816     if (!IsIgnored)
13817       Diags.popMappings(SavedLoc);
13818   }
13819 };
13820 }
13821 
13822 OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
13823                                                SourceLocation StartLoc,
13824                                                SourceLocation LParenLoc,
13825                                                SourceLocation EndLoc) {
13826   SmallVector<Expr *, 8> Vars;
13827   SmallVector<Expr *, 8> PrivateCopies;
13828   SmallVector<Expr *, 8> Inits;
13829   SmallVector<Decl *, 4> ExprCaptures;
13830   bool IsImplicitClause =
13831       StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid();
13832   SourceLocation ImplicitClauseLoc = DSAStack->getConstructLoc();
13833 
13834   for (Expr *RefExpr : VarList) {
13835     assert(RefExpr && "NULL expr in OpenMP firstprivate clause.");
13836     SourceLocation ELoc;
13837     SourceRange ERange;
13838     Expr *SimpleRefExpr = RefExpr;
13839     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
13840     if (Res.second) {
13841       // It will be analyzed later.
13842       Vars.push_back(RefExpr);
13843       PrivateCopies.push_back(nullptr);
13844       Inits.push_back(nullptr);
13845     }
13846     ValueDecl *D = Res.first;
13847     if (!D)
13848       continue;
13849 
13850     ELoc = IsImplicitClause ? ImplicitClauseLoc : ELoc;
13851     QualType Type = D->getType();
13852     auto *VD = dyn_cast<VarDecl>(D);
13853 
13854     // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
13855     //  A variable that appears in a private clause must not have an incomplete
13856     //  type or a reference type.
13857     if (RequireCompleteType(ELoc, Type,
13858                             diag::err_omp_firstprivate_incomplete_type))
13859       continue;
13860     Type = Type.getNonReferenceType();
13861 
13862     // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
13863     //  A variable of class type (or array thereof) that appears in a private
13864     //  clause requires an accessible, unambiguous copy constructor for the
13865     //  class type.
13866     QualType ElemType = Context.getBaseElementType(Type).getNonReferenceType();
13867 
13868     // If an implicit firstprivate variable found it was checked already.
13869     DSAStackTy::DSAVarData TopDVar;
13870     if (!IsImplicitClause) {
13871       DSAStackTy::DSAVarData DVar =
13872           DSAStack->getTopDSA(D, /*FromParent=*/false);
13873       TopDVar = DVar;
13874       OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
13875       bool IsConstant = ElemType.isConstant(Context);
13876       // OpenMP [2.4.13, Data-sharing Attribute Clauses]
13877       //  A list item that specifies a given variable may not appear in more
13878       // than one clause on the same directive, except that a variable may be
13879       //  specified in both firstprivate and lastprivate clauses.
13880       // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
13881       // A list item may appear in a firstprivate or lastprivate clause but not
13882       // both.
13883       if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
13884           (isOpenMPDistributeDirective(CurrDir) ||
13885            DVar.CKind != OMPC_lastprivate) &&
13886           DVar.RefExpr) {
13887         Diag(ELoc, diag::err_omp_wrong_dsa)
13888             << getOpenMPClauseName(DVar.CKind)
13889             << getOpenMPClauseName(OMPC_firstprivate);
13890         reportOriginalDsa(*this, DSAStack, D, DVar);
13891         continue;
13892       }
13893 
13894       // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
13895       // in a Construct]
13896       //  Variables with the predetermined data-sharing attributes may not be
13897       //  listed in data-sharing attributes clauses, except for the cases
13898       //  listed below. For these exceptions only, listing a predetermined
13899       //  variable in a data-sharing attribute clause is allowed and overrides
13900       //  the variable's predetermined data-sharing attributes.
13901       // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
13902       // in a Construct, C/C++, p.2]
13903       //  Variables with const-qualified type having no mutable member may be
13904       //  listed in a firstprivate clause, even if they are static data members.
13905       if (!(IsConstant || (VD && VD->isStaticDataMember())) && !DVar.RefExpr &&
13906           DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
13907         Diag(ELoc, diag::err_omp_wrong_dsa)
13908             << getOpenMPClauseName(DVar.CKind)
13909             << getOpenMPClauseName(OMPC_firstprivate);
13910         reportOriginalDsa(*this, DSAStack, D, DVar);
13911         continue;
13912       }
13913 
13914       // OpenMP [2.9.3.4, Restrictions, p.2]
13915       //  A list item that is private within a parallel region must not appear
13916       //  in a firstprivate clause on a worksharing construct if any of the
13917       //  worksharing regions arising from the worksharing construct ever bind
13918       //  to any of the parallel regions arising from the parallel construct.
13919       // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
13920       // A list item that is private within a teams region must not appear in a
13921       // firstprivate clause on a distribute construct if any of the distribute
13922       // regions arising from the distribute construct ever bind to any of the
13923       // teams regions arising from the teams construct.
13924       // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
13925       // A list item that appears in a reduction clause of a teams construct
13926       // must not appear in a firstprivate clause on a distribute construct if
13927       // any of the distribute regions arising from the distribute construct
13928       // ever bind to any of the teams regions arising from the teams construct.
13929       if ((isOpenMPWorksharingDirective(CurrDir) ||
13930            isOpenMPDistributeDirective(CurrDir)) &&
13931           !isOpenMPParallelDirective(CurrDir) &&
13932           !isOpenMPTeamsDirective(CurrDir)) {
13933         DVar = DSAStack->getImplicitDSA(D, true);
13934         if (DVar.CKind != OMPC_shared &&
13935             (isOpenMPParallelDirective(DVar.DKind) ||
13936              isOpenMPTeamsDirective(DVar.DKind) ||
13937              DVar.DKind == OMPD_unknown)) {
13938           Diag(ELoc, diag::err_omp_required_access)
13939               << getOpenMPClauseName(OMPC_firstprivate)
13940               << getOpenMPClauseName(OMPC_shared);
13941           reportOriginalDsa(*this, DSAStack, D, DVar);
13942           continue;
13943         }
13944       }
13945       // OpenMP [2.9.3.4, Restrictions, p.3]
13946       //  A list item that appears in a reduction clause of a parallel construct
13947       //  must not appear in a firstprivate clause on a worksharing or task
13948       //  construct if any of the worksharing or task regions arising from the
13949       //  worksharing or task construct ever bind to any of the parallel regions
13950       //  arising from the parallel construct.
13951       // OpenMP [2.9.3.4, Restrictions, p.4]
13952       //  A list item that appears in a reduction clause in worksharing
13953       //  construct must not appear in a firstprivate clause in a task construct
13954       //  encountered during execution of any of the worksharing regions arising
13955       //  from the worksharing construct.
13956       if (isOpenMPTaskingDirective(CurrDir)) {
13957         DVar = DSAStack->hasInnermostDSA(
13958             D, [](OpenMPClauseKind C) { return C == OMPC_reduction; },
13959             [](OpenMPDirectiveKind K) {
13960               return isOpenMPParallelDirective(K) ||
13961                      isOpenMPWorksharingDirective(K) ||
13962                      isOpenMPTeamsDirective(K);
13963             },
13964             /*FromParent=*/true);
13965         if (DVar.CKind == OMPC_reduction &&
13966             (isOpenMPParallelDirective(DVar.DKind) ||
13967              isOpenMPWorksharingDirective(DVar.DKind) ||
13968              isOpenMPTeamsDirective(DVar.DKind))) {
13969           Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate)
13970               << getOpenMPDirectiveName(DVar.DKind);
13971           reportOriginalDsa(*this, DSAStack, D, DVar);
13972           continue;
13973         }
13974       }
13975 
13976       // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
13977       // A list item cannot appear in both a map clause and a data-sharing
13978       // attribute clause on the same construct
13979       //
13980       // OpenMP 5.0 [2.19.7.1, Restrictions, p.7]
13981       // A list item cannot appear in both a map clause and a data-sharing
13982       // attribute clause on the same construct unless the construct is a
13983       // combined construct.
13984       if ((LangOpts.OpenMP <= 45 &&
13985            isOpenMPTargetExecutionDirective(CurrDir)) ||
13986           CurrDir == OMPD_target) {
13987         OpenMPClauseKind ConflictKind;
13988         if (DSAStack->checkMappableExprComponentListsForDecl(
13989                 VD, /*CurrentRegionOnly=*/true,
13990                 [&ConflictKind](
13991                     OMPClauseMappableExprCommon::MappableExprComponentListRef,
13992                     OpenMPClauseKind WhereFoundClauseKind) {
13993                   ConflictKind = WhereFoundClauseKind;
13994                   return true;
13995                 })) {
13996           Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
13997               << getOpenMPClauseName(OMPC_firstprivate)
13998               << getOpenMPClauseName(ConflictKind)
13999               << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
14000           reportOriginalDsa(*this, DSAStack, D, DVar);
14001           continue;
14002         }
14003       }
14004     }
14005 
14006     // Variably modified types are not supported for tasks.
14007     if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
14008         isOpenMPTaskingDirective(DSAStack->getCurrentDirective())) {
14009       Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
14010           << getOpenMPClauseName(OMPC_firstprivate) << Type
14011           << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
14012       bool IsDecl =
14013           !VD ||
14014           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
14015       Diag(D->getLocation(),
14016            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
14017           << D;
14018       continue;
14019     }
14020 
14021     Type = Type.getUnqualifiedType();
14022     VarDecl *VDPrivate =
14023         buildVarDecl(*this, ELoc, Type, D->getName(),
14024                      D->hasAttrs() ? &D->getAttrs() : nullptr,
14025                      VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
14026     // Generate helper private variable and initialize it with the value of the
14027     // original variable. The address of the original variable is replaced by
14028     // the address of the new private variable in the CodeGen. This new variable
14029     // is not added to IdResolver, so the code in the OpenMP region uses
14030     // original variable for proper diagnostics and variable capturing.
14031     Expr *VDInitRefExpr = nullptr;
14032     // For arrays generate initializer for single element and replace it by the
14033     // original array element in CodeGen.
14034     if (Type->isArrayType()) {
14035       VarDecl *VDInit =
14036           buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, D->getName());
14037       VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc);
14038       Expr *Init = DefaultLvalueConversion(VDInitRefExpr).get();
14039       ElemType = ElemType.getUnqualifiedType();
14040       VarDecl *VDInitTemp = buildVarDecl(*this, RefExpr->getExprLoc(), ElemType,
14041                                          ".firstprivate.temp");
14042       InitializedEntity Entity =
14043           InitializedEntity::InitializeVariable(VDInitTemp);
14044       InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc);
14045 
14046       InitializationSequence InitSeq(*this, Entity, Kind, Init);
14047       ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init);
14048       if (Result.isInvalid())
14049         VDPrivate->setInvalidDecl();
14050       else
14051         VDPrivate->setInit(Result.getAs<Expr>());
14052       // Remove temp variable declaration.
14053       Context.Deallocate(VDInitTemp);
14054     } else {
14055       VarDecl *VDInit = buildVarDecl(*this, RefExpr->getExprLoc(), Type,
14056                                      ".firstprivate.temp");
14057       VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
14058                                        RefExpr->getExprLoc());
14059       AddInitializerToDecl(VDPrivate,
14060                            DefaultLvalueConversion(VDInitRefExpr).get(),
14061                            /*DirectInit=*/false);
14062     }
14063     if (VDPrivate->isInvalidDecl()) {
14064       if (IsImplicitClause) {
14065         Diag(RefExpr->getExprLoc(),
14066              diag::note_omp_task_predetermined_firstprivate_here);
14067       }
14068       continue;
14069     }
14070     CurContext->addDecl(VDPrivate);
14071     DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
14072         *this, VDPrivate, RefExpr->getType().getUnqualifiedType(),
14073         RefExpr->getExprLoc());
14074     DeclRefExpr *Ref = nullptr;
14075     if (!VD && !CurContext->isDependentContext()) {
14076       if (TopDVar.CKind == OMPC_lastprivate) {
14077         Ref = TopDVar.PrivateCopy;
14078       } else {
14079         Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
14080         if (!isOpenMPCapturedDecl(D))
14081           ExprCaptures.push_back(Ref->getDecl());
14082       }
14083     }
14084     if (!IsImplicitClause)
14085       DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
14086     Vars.push_back((VD || CurContext->isDependentContext())
14087                        ? RefExpr->IgnoreParens()
14088                        : Ref);
14089     PrivateCopies.push_back(VDPrivateRefExpr);
14090     Inits.push_back(VDInitRefExpr);
14091   }
14092 
14093   if (Vars.empty())
14094     return nullptr;
14095 
14096   return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
14097                                        Vars, PrivateCopies, Inits,
14098                                        buildPreInits(Context, ExprCaptures));
14099 }
14100 
14101 OMPClause *Sema::ActOnOpenMPLastprivateClause(
14102     ArrayRef<Expr *> VarList, OpenMPLastprivateModifier LPKind,
14103     SourceLocation LPKindLoc, SourceLocation ColonLoc, SourceLocation StartLoc,
14104     SourceLocation LParenLoc, SourceLocation EndLoc) {
14105   if (LPKind == OMPC_LASTPRIVATE_unknown && LPKindLoc.isValid()) {
14106     assert(ColonLoc.isValid() && "Colon location must be valid.");
14107     Diag(LPKindLoc, diag::err_omp_unexpected_clause_value)
14108         << getListOfPossibleValues(OMPC_lastprivate, /*First=*/0,
14109                                    /*Last=*/OMPC_LASTPRIVATE_unknown)
14110         << getOpenMPClauseName(OMPC_lastprivate);
14111     return nullptr;
14112   }
14113 
14114   SmallVector<Expr *, 8> Vars;
14115   SmallVector<Expr *, 8> SrcExprs;
14116   SmallVector<Expr *, 8> DstExprs;
14117   SmallVector<Expr *, 8> AssignmentOps;
14118   SmallVector<Decl *, 4> ExprCaptures;
14119   SmallVector<Expr *, 4> ExprPostUpdates;
14120   for (Expr *RefExpr : VarList) {
14121     assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
14122     SourceLocation ELoc;
14123     SourceRange ERange;
14124     Expr *SimpleRefExpr = RefExpr;
14125     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
14126     if (Res.second) {
14127       // It will be analyzed later.
14128       Vars.push_back(RefExpr);
14129       SrcExprs.push_back(nullptr);
14130       DstExprs.push_back(nullptr);
14131       AssignmentOps.push_back(nullptr);
14132     }
14133     ValueDecl *D = Res.first;
14134     if (!D)
14135       continue;
14136 
14137     QualType Type = D->getType();
14138     auto *VD = dyn_cast<VarDecl>(D);
14139 
14140     // OpenMP [2.14.3.5, Restrictions, C/C++, p.2]
14141     //  A variable that appears in a lastprivate clause must not have an
14142     //  incomplete type or a reference type.
14143     if (RequireCompleteType(ELoc, Type,
14144                             diag::err_omp_lastprivate_incomplete_type))
14145       continue;
14146     Type = Type.getNonReferenceType();
14147 
14148     // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
14149     // A variable that is privatized must not have a const-qualified type
14150     // unless it is of class type with a mutable member. This restriction does
14151     // not apply to the firstprivate clause.
14152     //
14153     // OpenMP 3.1 [2.9.3.5, lastprivate clause, Restrictions]
14154     // A variable that appears in a lastprivate clause must not have a
14155     // const-qualified type unless it is of class type with a mutable member.
14156     if (rejectConstNotMutableType(*this, D, Type, OMPC_lastprivate, ELoc))
14157       continue;
14158 
14159     // OpenMP 5.0 [2.19.4.5 lastprivate Clause, Restrictions]
14160     // A list item that appears in a lastprivate clause with the conditional
14161     // modifier must be a scalar variable.
14162     if (LPKind == OMPC_LASTPRIVATE_conditional && !Type->isScalarType()) {
14163       Diag(ELoc, diag::err_omp_lastprivate_conditional_non_scalar);
14164       bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
14165                                VarDecl::DeclarationOnly;
14166       Diag(D->getLocation(),
14167            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
14168           << D;
14169       continue;
14170     }
14171 
14172     OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
14173     // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
14174     // in a Construct]
14175     //  Variables with the predetermined data-sharing attributes may not be
14176     //  listed in data-sharing attributes clauses, except for the cases
14177     //  listed below.
14178     // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
14179     // A list item may appear in a firstprivate or lastprivate clause but not
14180     // both.
14181     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
14182     if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate &&
14183         (isOpenMPDistributeDirective(CurrDir) ||
14184          DVar.CKind != OMPC_firstprivate) &&
14185         (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
14186       Diag(ELoc, diag::err_omp_wrong_dsa)
14187           << getOpenMPClauseName(DVar.CKind)
14188           << getOpenMPClauseName(OMPC_lastprivate);
14189       reportOriginalDsa(*this, DSAStack, D, DVar);
14190       continue;
14191     }
14192 
14193     // OpenMP [2.14.3.5, Restrictions, p.2]
14194     // A list item that is private within a parallel region, or that appears in
14195     // the reduction clause of a parallel construct, must not appear in a
14196     // lastprivate clause on a worksharing construct if any of the corresponding
14197     // worksharing regions ever binds to any of the corresponding parallel
14198     // regions.
14199     DSAStackTy::DSAVarData TopDVar = DVar;
14200     if (isOpenMPWorksharingDirective(CurrDir) &&
14201         !isOpenMPParallelDirective(CurrDir) &&
14202         !isOpenMPTeamsDirective(CurrDir)) {
14203       DVar = DSAStack->getImplicitDSA(D, true);
14204       if (DVar.CKind != OMPC_shared) {
14205         Diag(ELoc, diag::err_omp_required_access)
14206             << getOpenMPClauseName(OMPC_lastprivate)
14207             << getOpenMPClauseName(OMPC_shared);
14208         reportOriginalDsa(*this, DSAStack, D, DVar);
14209         continue;
14210       }
14211     }
14212 
14213     // OpenMP [2.14.3.5, Restrictions, C++, p.1,2]
14214     //  A variable of class type (or array thereof) that appears in a
14215     //  lastprivate clause requires an accessible, unambiguous default
14216     //  constructor for the class type, unless the list item is also specified
14217     //  in a firstprivate clause.
14218     //  A variable of class type (or array thereof) that appears in a
14219     //  lastprivate clause requires an accessible, unambiguous copy assignment
14220     //  operator for the class type.
14221     Type = Context.getBaseElementType(Type).getNonReferenceType();
14222     VarDecl *SrcVD = buildVarDecl(*this, ERange.getBegin(),
14223                                   Type.getUnqualifiedType(), ".lastprivate.src",
14224                                   D->hasAttrs() ? &D->getAttrs() : nullptr);
14225     DeclRefExpr *PseudoSrcExpr =
14226         buildDeclRefExpr(*this, SrcVD, Type.getUnqualifiedType(), ELoc);
14227     VarDecl *DstVD =
14228         buildVarDecl(*this, ERange.getBegin(), Type, ".lastprivate.dst",
14229                      D->hasAttrs() ? &D->getAttrs() : nullptr);
14230     DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
14231     // For arrays generate assignment operation for single element and replace
14232     // it by the original array element in CodeGen.
14233     ExprResult AssignmentOp = BuildBinOp(/*S=*/nullptr, ELoc, BO_Assign,
14234                                          PseudoDstExpr, PseudoSrcExpr);
14235     if (AssignmentOp.isInvalid())
14236       continue;
14237     AssignmentOp =
14238         ActOnFinishFullExpr(AssignmentOp.get(), ELoc, /*DiscardedValue*/ false);
14239     if (AssignmentOp.isInvalid())
14240       continue;
14241 
14242     DeclRefExpr *Ref = nullptr;
14243     if (!VD && !CurContext->isDependentContext()) {
14244       if (TopDVar.CKind == OMPC_firstprivate) {
14245         Ref = TopDVar.PrivateCopy;
14246       } else {
14247         Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
14248         if (!isOpenMPCapturedDecl(D))
14249           ExprCaptures.push_back(Ref->getDecl());
14250       }
14251       if (TopDVar.CKind == OMPC_firstprivate ||
14252           (!isOpenMPCapturedDecl(D) &&
14253            Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>())) {
14254         ExprResult RefRes = DefaultLvalueConversion(Ref);
14255         if (!RefRes.isUsable())
14256           continue;
14257         ExprResult PostUpdateRes =
14258             BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
14259                        RefRes.get());
14260         if (!PostUpdateRes.isUsable())
14261           continue;
14262         ExprPostUpdates.push_back(
14263             IgnoredValueConversions(PostUpdateRes.get()).get());
14264       }
14265     }
14266     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_lastprivate, Ref);
14267     Vars.push_back((VD || CurContext->isDependentContext())
14268                        ? RefExpr->IgnoreParens()
14269                        : Ref);
14270     SrcExprs.push_back(PseudoSrcExpr);
14271     DstExprs.push_back(PseudoDstExpr);
14272     AssignmentOps.push_back(AssignmentOp.get());
14273   }
14274 
14275   if (Vars.empty())
14276     return nullptr;
14277 
14278   return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
14279                                       Vars, SrcExprs, DstExprs, AssignmentOps,
14280                                       LPKind, LPKindLoc, ColonLoc,
14281                                       buildPreInits(Context, ExprCaptures),
14282                                       buildPostUpdate(*this, ExprPostUpdates));
14283 }
14284 
14285 OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
14286                                          SourceLocation StartLoc,
14287                                          SourceLocation LParenLoc,
14288                                          SourceLocation EndLoc) {
14289   SmallVector<Expr *, 8> Vars;
14290   for (Expr *RefExpr : VarList) {
14291     assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
14292     SourceLocation ELoc;
14293     SourceRange ERange;
14294     Expr *SimpleRefExpr = RefExpr;
14295     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
14296     if (Res.second) {
14297       // It will be analyzed later.
14298       Vars.push_back(RefExpr);
14299     }
14300     ValueDecl *D = Res.first;
14301     if (!D)
14302       continue;
14303 
14304     auto *VD = dyn_cast<VarDecl>(D);
14305     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
14306     // in a Construct]
14307     //  Variables with the predetermined data-sharing attributes may not be
14308     //  listed in data-sharing attributes clauses, except for the cases
14309     //  listed below. For these exceptions only, listing a predetermined
14310     //  variable in a data-sharing attribute clause is allowed and overrides
14311     //  the variable's predetermined data-sharing attributes.
14312     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
14313     if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared &&
14314         DVar.RefExpr) {
14315       Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
14316                                           << getOpenMPClauseName(OMPC_shared);
14317       reportOriginalDsa(*this, DSAStack, D, DVar);
14318       continue;
14319     }
14320 
14321     DeclRefExpr *Ref = nullptr;
14322     if (!VD && isOpenMPCapturedDecl(D) && !CurContext->isDependentContext())
14323       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
14324     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_shared, Ref);
14325     Vars.push_back((VD || !Ref || CurContext->isDependentContext())
14326                        ? RefExpr->IgnoreParens()
14327                        : Ref);
14328   }
14329 
14330   if (Vars.empty())
14331     return nullptr;
14332 
14333   return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
14334 }
14335 
14336 namespace {
14337 class DSARefChecker : public StmtVisitor<DSARefChecker, bool> {
14338   DSAStackTy *Stack;
14339 
14340 public:
14341   bool VisitDeclRefExpr(DeclRefExpr *E) {
14342     if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
14343       DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, /*FromParent=*/false);
14344       if (DVar.CKind == OMPC_shared && !DVar.RefExpr)
14345         return false;
14346       if (DVar.CKind != OMPC_unknown)
14347         return true;
14348       DSAStackTy::DSAVarData DVarPrivate = Stack->hasDSA(
14349           VD, isOpenMPPrivate, [](OpenMPDirectiveKind) { return true; },
14350           /*FromParent=*/true);
14351       return DVarPrivate.CKind != OMPC_unknown;
14352     }
14353     return false;
14354   }
14355   bool VisitStmt(Stmt *S) {
14356     for (Stmt *Child : S->children()) {
14357       if (Child && Visit(Child))
14358         return true;
14359     }
14360     return false;
14361   }
14362   explicit DSARefChecker(DSAStackTy *S) : Stack(S) {}
14363 };
14364 } // namespace
14365 
14366 namespace {
14367 // Transform MemberExpression for specified FieldDecl of current class to
14368 // DeclRefExpr to specified OMPCapturedExprDecl.
14369 class TransformExprToCaptures : public TreeTransform<TransformExprToCaptures> {
14370   typedef TreeTransform<TransformExprToCaptures> BaseTransform;
14371   ValueDecl *Field = nullptr;
14372   DeclRefExpr *CapturedExpr = nullptr;
14373 
14374 public:
14375   TransformExprToCaptures(Sema &SemaRef, ValueDecl *FieldDecl)
14376       : BaseTransform(SemaRef), Field(FieldDecl), CapturedExpr(nullptr) {}
14377 
14378   ExprResult TransformMemberExpr(MemberExpr *E) {
14379     if (isa<CXXThisExpr>(E->getBase()->IgnoreParenImpCasts()) &&
14380         E->getMemberDecl() == Field) {
14381       CapturedExpr = buildCapture(SemaRef, Field, E, /*WithInit=*/false);
14382       return CapturedExpr;
14383     }
14384     return BaseTransform::TransformMemberExpr(E);
14385   }
14386   DeclRefExpr *getCapturedExpr() { return CapturedExpr; }
14387 };
14388 } // namespace
14389 
14390 template <typename T, typename U>
14391 static T filterLookupForUDReductionAndMapper(
14392     SmallVectorImpl<U> &Lookups, const llvm::function_ref<T(ValueDecl *)> Gen) {
14393   for (U &Set : Lookups) {
14394     for (auto *D : Set) {
14395       if (T Res = Gen(cast<ValueDecl>(D)))
14396         return Res;
14397     }
14398   }
14399   return T();
14400 }
14401 
14402 static NamedDecl *findAcceptableDecl(Sema &SemaRef, NamedDecl *D) {
14403   assert(!LookupResult::isVisible(SemaRef, D) && "not in slow case");
14404 
14405   for (auto RD : D->redecls()) {
14406     // Don't bother with extra checks if we already know this one isn't visible.
14407     if (RD == D)
14408       continue;
14409 
14410     auto ND = cast<NamedDecl>(RD);
14411     if (LookupResult::isVisible(SemaRef, ND))
14412       return ND;
14413   }
14414 
14415   return nullptr;
14416 }
14417 
14418 static void
14419 argumentDependentLookup(Sema &SemaRef, const DeclarationNameInfo &Id,
14420                         SourceLocation Loc, QualType Ty,
14421                         SmallVectorImpl<UnresolvedSet<8>> &Lookups) {
14422   // Find all of the associated namespaces and classes based on the
14423   // arguments we have.
14424   Sema::AssociatedNamespaceSet AssociatedNamespaces;
14425   Sema::AssociatedClassSet AssociatedClasses;
14426   OpaqueValueExpr OVE(Loc, Ty, VK_LValue);
14427   SemaRef.FindAssociatedClassesAndNamespaces(Loc, &OVE, AssociatedNamespaces,
14428                                              AssociatedClasses);
14429 
14430   // C++ [basic.lookup.argdep]p3:
14431   //   Let X be the lookup set produced by unqualified lookup (3.4.1)
14432   //   and let Y be the lookup set produced by argument dependent
14433   //   lookup (defined as follows). If X contains [...] then Y is
14434   //   empty. Otherwise Y is the set of declarations found in the
14435   //   namespaces associated with the argument types as described
14436   //   below. The set of declarations found by the lookup of the name
14437   //   is the union of X and Y.
14438   //
14439   // Here, we compute Y and add its members to the overloaded
14440   // candidate set.
14441   for (auto *NS : AssociatedNamespaces) {
14442     //   When considering an associated namespace, the lookup is the
14443     //   same as the lookup performed when the associated namespace is
14444     //   used as a qualifier (3.4.3.2) except that:
14445     //
14446     //     -- Any using-directives in the associated namespace are
14447     //        ignored.
14448     //
14449     //     -- Any namespace-scope friend functions declared in
14450     //        associated classes are visible within their respective
14451     //        namespaces even if they are not visible during an ordinary
14452     //        lookup (11.4).
14453     DeclContext::lookup_result R = NS->lookup(Id.getName());
14454     for (auto *D : R) {
14455       auto *Underlying = D;
14456       if (auto *USD = dyn_cast<UsingShadowDecl>(D))
14457         Underlying = USD->getTargetDecl();
14458 
14459       if (!isa<OMPDeclareReductionDecl>(Underlying) &&
14460           !isa<OMPDeclareMapperDecl>(Underlying))
14461         continue;
14462 
14463       if (!SemaRef.isVisible(D)) {
14464         D = findAcceptableDecl(SemaRef, D);
14465         if (!D)
14466           continue;
14467         if (auto *USD = dyn_cast<UsingShadowDecl>(D))
14468           Underlying = USD->getTargetDecl();
14469       }
14470       Lookups.emplace_back();
14471       Lookups.back().addDecl(Underlying);
14472     }
14473   }
14474 }
14475 
14476 static ExprResult
14477 buildDeclareReductionRef(Sema &SemaRef, SourceLocation Loc, SourceRange Range,
14478                          Scope *S, CXXScopeSpec &ReductionIdScopeSpec,
14479                          const DeclarationNameInfo &ReductionId, QualType Ty,
14480                          CXXCastPath &BasePath, Expr *UnresolvedReduction) {
14481   if (ReductionIdScopeSpec.isInvalid())
14482     return ExprError();
14483   SmallVector<UnresolvedSet<8>, 4> Lookups;
14484   if (S) {
14485     LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
14486     Lookup.suppressDiagnostics();
14487     while (S && SemaRef.LookupParsedName(Lookup, S, &ReductionIdScopeSpec)) {
14488       NamedDecl *D = Lookup.getRepresentativeDecl();
14489       do {
14490         S = S->getParent();
14491       } while (S && !S->isDeclScope(D));
14492       if (S)
14493         S = S->getParent();
14494       Lookups.emplace_back();
14495       Lookups.back().append(Lookup.begin(), Lookup.end());
14496       Lookup.clear();
14497     }
14498   } else if (auto *ULE =
14499                  cast_or_null<UnresolvedLookupExpr>(UnresolvedReduction)) {
14500     Lookups.push_back(UnresolvedSet<8>());
14501     Decl *PrevD = nullptr;
14502     for (NamedDecl *D : ULE->decls()) {
14503       if (D == PrevD)
14504         Lookups.push_back(UnresolvedSet<8>());
14505       else if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(D))
14506         Lookups.back().addDecl(DRD);
14507       PrevD = D;
14508     }
14509   }
14510   if (SemaRef.CurContext->isDependentContext() || Ty->isDependentType() ||
14511       Ty->isInstantiationDependentType() ||
14512       Ty->containsUnexpandedParameterPack() ||
14513       filterLookupForUDReductionAndMapper<bool>(Lookups, [](ValueDecl *D) {
14514         return !D->isInvalidDecl() &&
14515                (D->getType()->isDependentType() ||
14516                 D->getType()->isInstantiationDependentType() ||
14517                 D->getType()->containsUnexpandedParameterPack());
14518       })) {
14519     UnresolvedSet<8> ResSet;
14520     for (const UnresolvedSet<8> &Set : Lookups) {
14521       if (Set.empty())
14522         continue;
14523       ResSet.append(Set.begin(), Set.end());
14524       // The last item marks the end of all declarations at the specified scope.
14525       ResSet.addDecl(Set[Set.size() - 1]);
14526     }
14527     return UnresolvedLookupExpr::Create(
14528         SemaRef.Context, /*NamingClass=*/nullptr,
14529         ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), ReductionId,
14530         /*ADL=*/true, /*Overloaded=*/true, ResSet.begin(), ResSet.end());
14531   }
14532   // Lookup inside the classes.
14533   // C++ [over.match.oper]p3:
14534   //   For a unary operator @ with an operand of a type whose
14535   //   cv-unqualified version is T1, and for a binary operator @ with
14536   //   a left operand of a type whose cv-unqualified version is T1 and
14537   //   a right operand of a type whose cv-unqualified version is T2,
14538   //   three sets of candidate functions, designated member
14539   //   candidates, non-member candidates and built-in candidates, are
14540   //   constructed as follows:
14541   //     -- If T1 is a complete class type or a class currently being
14542   //        defined, the set of member candidates is the result of the
14543   //        qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
14544   //        the set of member candidates is empty.
14545   LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
14546   Lookup.suppressDiagnostics();
14547   if (const auto *TyRec = Ty->getAs<RecordType>()) {
14548     // Complete the type if it can be completed.
14549     // If the type is neither complete nor being defined, bail out now.
14550     if (SemaRef.isCompleteType(Loc, Ty) || TyRec->isBeingDefined() ||
14551         TyRec->getDecl()->getDefinition()) {
14552       Lookup.clear();
14553       SemaRef.LookupQualifiedName(Lookup, TyRec->getDecl());
14554       if (Lookup.empty()) {
14555         Lookups.emplace_back();
14556         Lookups.back().append(Lookup.begin(), Lookup.end());
14557       }
14558     }
14559   }
14560   // Perform ADL.
14561   if (SemaRef.getLangOpts().CPlusPlus)
14562     argumentDependentLookup(SemaRef, ReductionId, Loc, Ty, Lookups);
14563   if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
14564           Lookups, [&SemaRef, Ty](ValueDecl *D) -> ValueDecl * {
14565             if (!D->isInvalidDecl() &&
14566                 SemaRef.Context.hasSameType(D->getType(), Ty))
14567               return D;
14568             return nullptr;
14569           }))
14570     return SemaRef.BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(),
14571                                     VK_LValue, Loc);
14572   if (SemaRef.getLangOpts().CPlusPlus) {
14573     if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
14574             Lookups, [&SemaRef, Ty, Loc](ValueDecl *D) -> ValueDecl * {
14575               if (!D->isInvalidDecl() &&
14576                   SemaRef.IsDerivedFrom(Loc, Ty, D->getType()) &&
14577                   !Ty.isMoreQualifiedThan(D->getType()))
14578                 return D;
14579               return nullptr;
14580             })) {
14581       CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
14582                          /*DetectVirtual=*/false);
14583       if (SemaRef.IsDerivedFrom(Loc, Ty, VD->getType(), Paths)) {
14584         if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
14585                 VD->getType().getUnqualifiedType()))) {
14586           if (SemaRef.CheckBaseClassAccess(
14587                   Loc, VD->getType(), Ty, Paths.front(),
14588                   /*DiagID=*/0) != Sema::AR_inaccessible) {
14589             SemaRef.BuildBasePathArray(Paths, BasePath);
14590             return SemaRef.BuildDeclRefExpr(
14591                 VD, VD->getType().getNonReferenceType(), VK_LValue, Loc);
14592           }
14593         }
14594       }
14595     }
14596   }
14597   if (ReductionIdScopeSpec.isSet()) {
14598     SemaRef.Diag(Loc, diag::err_omp_not_resolved_reduction_identifier)
14599         << Ty << Range;
14600     return ExprError();
14601   }
14602   return ExprEmpty();
14603 }
14604 
14605 namespace {
14606 /// Data for the reduction-based clauses.
14607 struct ReductionData {
14608   /// List of original reduction items.
14609   SmallVector<Expr *, 8> Vars;
14610   /// List of private copies of the reduction items.
14611   SmallVector<Expr *, 8> Privates;
14612   /// LHS expressions for the reduction_op expressions.
14613   SmallVector<Expr *, 8> LHSs;
14614   /// RHS expressions for the reduction_op expressions.
14615   SmallVector<Expr *, 8> RHSs;
14616   /// Reduction operation expression.
14617   SmallVector<Expr *, 8> ReductionOps;
14618   /// inscan copy operation expressions.
14619   SmallVector<Expr *, 8> InscanCopyOps;
14620   /// inscan copy temp array expressions for prefix sums.
14621   SmallVector<Expr *, 8> InscanCopyArrayTemps;
14622   /// inscan copy temp array element expressions for prefix sums.
14623   SmallVector<Expr *, 8> InscanCopyArrayElems;
14624   /// Taskgroup descriptors for the corresponding reduction items in
14625   /// in_reduction clauses.
14626   SmallVector<Expr *, 8> TaskgroupDescriptors;
14627   /// List of captures for clause.
14628   SmallVector<Decl *, 4> ExprCaptures;
14629   /// List of postupdate expressions.
14630   SmallVector<Expr *, 4> ExprPostUpdates;
14631   /// Reduction modifier.
14632   unsigned RedModifier = 0;
14633   ReductionData() = delete;
14634   /// Reserves required memory for the reduction data.
14635   ReductionData(unsigned Size, unsigned Modifier = 0) : RedModifier(Modifier) {
14636     Vars.reserve(Size);
14637     Privates.reserve(Size);
14638     LHSs.reserve(Size);
14639     RHSs.reserve(Size);
14640     ReductionOps.reserve(Size);
14641     if (RedModifier == OMPC_REDUCTION_inscan) {
14642       InscanCopyOps.reserve(Size);
14643       InscanCopyArrayTemps.reserve(Size);
14644       InscanCopyArrayElems.reserve(Size);
14645     }
14646     TaskgroupDescriptors.reserve(Size);
14647     ExprCaptures.reserve(Size);
14648     ExprPostUpdates.reserve(Size);
14649   }
14650   /// Stores reduction item and reduction operation only (required for dependent
14651   /// reduction item).
14652   void push(Expr *Item, Expr *ReductionOp) {
14653     Vars.emplace_back(Item);
14654     Privates.emplace_back(nullptr);
14655     LHSs.emplace_back(nullptr);
14656     RHSs.emplace_back(nullptr);
14657     ReductionOps.emplace_back(ReductionOp);
14658     TaskgroupDescriptors.emplace_back(nullptr);
14659     if (RedModifier == OMPC_REDUCTION_inscan) {
14660       InscanCopyOps.push_back(nullptr);
14661       InscanCopyArrayTemps.push_back(nullptr);
14662       InscanCopyArrayElems.push_back(nullptr);
14663     }
14664   }
14665   /// Stores reduction data.
14666   void push(Expr *Item, Expr *Private, Expr *LHS, Expr *RHS, Expr *ReductionOp,
14667             Expr *TaskgroupDescriptor, Expr *CopyOp, Expr *CopyArrayTemp,
14668             Expr *CopyArrayElem) {
14669     Vars.emplace_back(Item);
14670     Privates.emplace_back(Private);
14671     LHSs.emplace_back(LHS);
14672     RHSs.emplace_back(RHS);
14673     ReductionOps.emplace_back(ReductionOp);
14674     TaskgroupDescriptors.emplace_back(TaskgroupDescriptor);
14675     if (RedModifier == OMPC_REDUCTION_inscan) {
14676       InscanCopyOps.push_back(CopyOp);
14677       InscanCopyArrayTemps.push_back(CopyArrayTemp);
14678       InscanCopyArrayElems.push_back(CopyArrayElem);
14679     } else {
14680       assert(CopyOp == nullptr && CopyArrayTemp == nullptr &&
14681              CopyArrayElem == nullptr &&
14682              "Copy operation must be used for inscan reductions only.");
14683     }
14684   }
14685 };
14686 } // namespace
14687 
14688 static bool checkOMPArraySectionConstantForReduction(
14689     ASTContext &Context, const OMPArraySectionExpr *OASE, bool &SingleElement,
14690     SmallVectorImpl<llvm::APSInt> &ArraySizes) {
14691   const Expr *Length = OASE->getLength();
14692   if (Length == nullptr) {
14693     // For array sections of the form [1:] or [:], we would need to analyze
14694     // the lower bound...
14695     if (OASE->getColonLoc().isValid())
14696       return false;
14697 
14698     // This is an array subscript which has implicit length 1!
14699     SingleElement = true;
14700     ArraySizes.push_back(llvm::APSInt::get(1));
14701   } else {
14702     Expr::EvalResult Result;
14703     if (!Length->EvaluateAsInt(Result, Context))
14704       return false;
14705 
14706     llvm::APSInt ConstantLengthValue = Result.Val.getInt();
14707     SingleElement = (ConstantLengthValue.getSExtValue() == 1);
14708     ArraySizes.push_back(ConstantLengthValue);
14709   }
14710 
14711   // Get the base of this array section and walk up from there.
14712   const Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
14713 
14714   // We require length = 1 for all array sections except the right-most to
14715   // guarantee that the memory region is contiguous and has no holes in it.
14716   while (const auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base)) {
14717     Length = TempOASE->getLength();
14718     if (Length == nullptr) {
14719       // For array sections of the form [1:] or [:], we would need to analyze
14720       // the lower bound...
14721       if (OASE->getColonLoc().isValid())
14722         return false;
14723 
14724       // This is an array subscript which has implicit length 1!
14725       ArraySizes.push_back(llvm::APSInt::get(1));
14726     } else {
14727       Expr::EvalResult Result;
14728       if (!Length->EvaluateAsInt(Result, Context))
14729         return false;
14730 
14731       llvm::APSInt ConstantLengthValue = Result.Val.getInt();
14732       if (ConstantLengthValue.getSExtValue() != 1)
14733         return false;
14734 
14735       ArraySizes.push_back(ConstantLengthValue);
14736     }
14737     Base = TempOASE->getBase()->IgnoreParenImpCasts();
14738   }
14739 
14740   // If we have a single element, we don't need to add the implicit lengths.
14741   if (!SingleElement) {
14742     while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) {
14743       // Has implicit length 1!
14744       ArraySizes.push_back(llvm::APSInt::get(1));
14745       Base = TempASE->getBase()->IgnoreParenImpCasts();
14746     }
14747   }
14748 
14749   // This array section can be privatized as a single value or as a constant
14750   // sized array.
14751   return true;
14752 }
14753 
14754 static bool actOnOMPReductionKindClause(
14755     Sema &S, DSAStackTy *Stack, OpenMPClauseKind ClauseKind,
14756     ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
14757     SourceLocation ColonLoc, SourceLocation EndLoc,
14758     CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
14759     ArrayRef<Expr *> UnresolvedReductions, ReductionData &RD) {
14760   DeclarationName DN = ReductionId.getName();
14761   OverloadedOperatorKind OOK = DN.getCXXOverloadedOperator();
14762   BinaryOperatorKind BOK = BO_Comma;
14763 
14764   ASTContext &Context = S.Context;
14765   // OpenMP [2.14.3.6, reduction clause]
14766   // C
14767   // reduction-identifier is either an identifier or one of the following
14768   // operators: +, -, *,  &, |, ^, && and ||
14769   // C++
14770   // reduction-identifier is either an id-expression or one of the following
14771   // operators: +, -, *, &, |, ^, && and ||
14772   switch (OOK) {
14773   case OO_Plus:
14774   case OO_Minus:
14775     BOK = BO_Add;
14776     break;
14777   case OO_Star:
14778     BOK = BO_Mul;
14779     break;
14780   case OO_Amp:
14781     BOK = BO_And;
14782     break;
14783   case OO_Pipe:
14784     BOK = BO_Or;
14785     break;
14786   case OO_Caret:
14787     BOK = BO_Xor;
14788     break;
14789   case OO_AmpAmp:
14790     BOK = BO_LAnd;
14791     break;
14792   case OO_PipePipe:
14793     BOK = BO_LOr;
14794     break;
14795   case OO_New:
14796   case OO_Delete:
14797   case OO_Array_New:
14798   case OO_Array_Delete:
14799   case OO_Slash:
14800   case OO_Percent:
14801   case OO_Tilde:
14802   case OO_Exclaim:
14803   case OO_Equal:
14804   case OO_Less:
14805   case OO_Greater:
14806   case OO_LessEqual:
14807   case OO_GreaterEqual:
14808   case OO_PlusEqual:
14809   case OO_MinusEqual:
14810   case OO_StarEqual:
14811   case OO_SlashEqual:
14812   case OO_PercentEqual:
14813   case OO_CaretEqual:
14814   case OO_AmpEqual:
14815   case OO_PipeEqual:
14816   case OO_LessLess:
14817   case OO_GreaterGreater:
14818   case OO_LessLessEqual:
14819   case OO_GreaterGreaterEqual:
14820   case OO_EqualEqual:
14821   case OO_ExclaimEqual:
14822   case OO_Spaceship:
14823   case OO_PlusPlus:
14824   case OO_MinusMinus:
14825   case OO_Comma:
14826   case OO_ArrowStar:
14827   case OO_Arrow:
14828   case OO_Call:
14829   case OO_Subscript:
14830   case OO_Conditional:
14831   case OO_Coawait:
14832   case NUM_OVERLOADED_OPERATORS:
14833     llvm_unreachable("Unexpected reduction identifier");
14834   case OO_None:
14835     if (IdentifierInfo *II = DN.getAsIdentifierInfo()) {
14836       if (II->isStr("max"))
14837         BOK = BO_GT;
14838       else if (II->isStr("min"))
14839         BOK = BO_LT;
14840     }
14841     break;
14842   }
14843   SourceRange ReductionIdRange;
14844   if (ReductionIdScopeSpec.isValid())
14845     ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc());
14846   else
14847     ReductionIdRange.setBegin(ReductionId.getBeginLoc());
14848   ReductionIdRange.setEnd(ReductionId.getEndLoc());
14849 
14850   auto IR = UnresolvedReductions.begin(), ER = UnresolvedReductions.end();
14851   bool FirstIter = true;
14852   for (Expr *RefExpr : VarList) {
14853     assert(RefExpr && "nullptr expr in OpenMP reduction clause.");
14854     // OpenMP [2.1, C/C++]
14855     //  A list item is a variable or array section, subject to the restrictions
14856     //  specified in Section 2.4 on page 42 and in each of the sections
14857     // describing clauses and directives for which a list appears.
14858     // OpenMP  [2.14.3.3, Restrictions, p.1]
14859     //  A variable that is part of another variable (as an array or
14860     //  structure element) cannot appear in a private clause.
14861     if (!FirstIter && IR != ER)
14862       ++IR;
14863     FirstIter = false;
14864     SourceLocation ELoc;
14865     SourceRange ERange;
14866     Expr *SimpleRefExpr = RefExpr;
14867     auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange,
14868                               /*AllowArraySection=*/true);
14869     if (Res.second) {
14870       // Try to find 'declare reduction' corresponding construct before using
14871       // builtin/overloaded operators.
14872       QualType Type = Context.DependentTy;
14873       CXXCastPath BasePath;
14874       ExprResult DeclareReductionRef = buildDeclareReductionRef(
14875           S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
14876           ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
14877       Expr *ReductionOp = nullptr;
14878       if (S.CurContext->isDependentContext() &&
14879           (DeclareReductionRef.isUnset() ||
14880            isa<UnresolvedLookupExpr>(DeclareReductionRef.get())))
14881         ReductionOp = DeclareReductionRef.get();
14882       // It will be analyzed later.
14883       RD.push(RefExpr, ReductionOp);
14884     }
14885     ValueDecl *D = Res.first;
14886     if (!D)
14887       continue;
14888 
14889     Expr *TaskgroupDescriptor = nullptr;
14890     QualType Type;
14891     auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr->IgnoreParens());
14892     auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr->IgnoreParens());
14893     if (ASE) {
14894       Type = ASE->getType().getNonReferenceType();
14895     } else if (OASE) {
14896       QualType BaseType =
14897           OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
14898       if (const auto *ATy = BaseType->getAsArrayTypeUnsafe())
14899         Type = ATy->getElementType();
14900       else
14901         Type = BaseType->getPointeeType();
14902       Type = Type.getNonReferenceType();
14903     } else {
14904       Type = Context.getBaseElementType(D->getType().getNonReferenceType());
14905     }
14906     auto *VD = dyn_cast<VarDecl>(D);
14907 
14908     // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
14909     //  A variable that appears in a private clause must not have an incomplete
14910     //  type or a reference type.
14911     if (S.RequireCompleteType(ELoc, D->getType(),
14912                               diag::err_omp_reduction_incomplete_type))
14913       continue;
14914     // OpenMP [2.14.3.6, reduction clause, Restrictions]
14915     // A list item that appears in a reduction clause must not be
14916     // const-qualified.
14917     if (rejectConstNotMutableType(S, D, Type, ClauseKind, ELoc,
14918                                   /*AcceptIfMutable*/ false, ASE || OASE))
14919       continue;
14920 
14921     OpenMPDirectiveKind CurrDir = Stack->getCurrentDirective();
14922     // OpenMP [2.9.3.6, Restrictions, C/C++, p.4]
14923     //  If a list-item is a reference type then it must bind to the same object
14924     //  for all threads of the team.
14925     if (!ASE && !OASE) {
14926       if (VD) {
14927         VarDecl *VDDef = VD->getDefinition();
14928         if (VD->getType()->isReferenceType() && VDDef && VDDef->hasInit()) {
14929           DSARefChecker Check(Stack);
14930           if (Check.Visit(VDDef->getInit())) {
14931             S.Diag(ELoc, diag::err_omp_reduction_ref_type_arg)
14932                 << getOpenMPClauseName(ClauseKind) << ERange;
14933             S.Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef;
14934             continue;
14935           }
14936         }
14937       }
14938 
14939       // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
14940       // in a Construct]
14941       //  Variables with the predetermined data-sharing attributes may not be
14942       //  listed in data-sharing attributes clauses, except for the cases
14943       //  listed below. For these exceptions only, listing a predetermined
14944       //  variable in a data-sharing attribute clause is allowed and overrides
14945       //  the variable's predetermined data-sharing attributes.
14946       // OpenMP [2.14.3.6, Restrictions, p.3]
14947       //  Any number of reduction clauses can be specified on the directive,
14948       //  but a list item can appear only once in the reduction clauses for that
14949       //  directive.
14950       DSAStackTy::DSAVarData DVar = Stack->getTopDSA(D, /*FromParent=*/false);
14951       if (DVar.CKind == OMPC_reduction) {
14952         S.Diag(ELoc, diag::err_omp_once_referenced)
14953             << getOpenMPClauseName(ClauseKind);
14954         if (DVar.RefExpr)
14955           S.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced);
14956         continue;
14957       }
14958       if (DVar.CKind != OMPC_unknown) {
14959         S.Diag(ELoc, diag::err_omp_wrong_dsa)
14960             << getOpenMPClauseName(DVar.CKind)
14961             << getOpenMPClauseName(OMPC_reduction);
14962         reportOriginalDsa(S, Stack, D, DVar);
14963         continue;
14964       }
14965 
14966       // OpenMP [2.14.3.6, Restrictions, p.1]
14967       //  A list item that appears in a reduction clause of a worksharing
14968       //  construct must be shared in the parallel regions to which any of the
14969       //  worksharing regions arising from the worksharing construct bind.
14970       if (isOpenMPWorksharingDirective(CurrDir) &&
14971           !isOpenMPParallelDirective(CurrDir) &&
14972           !isOpenMPTeamsDirective(CurrDir)) {
14973         DVar = Stack->getImplicitDSA(D, true);
14974         if (DVar.CKind != OMPC_shared) {
14975           S.Diag(ELoc, diag::err_omp_required_access)
14976               << getOpenMPClauseName(OMPC_reduction)
14977               << getOpenMPClauseName(OMPC_shared);
14978           reportOriginalDsa(S, Stack, D, DVar);
14979           continue;
14980         }
14981       }
14982     }
14983 
14984     // Try to find 'declare reduction' corresponding construct before using
14985     // builtin/overloaded operators.
14986     CXXCastPath BasePath;
14987     ExprResult DeclareReductionRef = buildDeclareReductionRef(
14988         S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
14989         ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
14990     if (DeclareReductionRef.isInvalid())
14991       continue;
14992     if (S.CurContext->isDependentContext() &&
14993         (DeclareReductionRef.isUnset() ||
14994          isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) {
14995       RD.push(RefExpr, DeclareReductionRef.get());
14996       continue;
14997     }
14998     if (BOK == BO_Comma && DeclareReductionRef.isUnset()) {
14999       // Not allowed reduction identifier is found.
15000       S.Diag(ReductionId.getBeginLoc(),
15001              diag::err_omp_unknown_reduction_identifier)
15002           << Type << ReductionIdRange;
15003       continue;
15004     }
15005 
15006     // OpenMP [2.14.3.6, reduction clause, Restrictions]
15007     // The type of a list item that appears in a reduction clause must be valid
15008     // for the reduction-identifier. For a max or min reduction in C, the type
15009     // of the list item must be an allowed arithmetic data type: char, int,
15010     // float, double, or _Bool, possibly modified with long, short, signed, or
15011     // unsigned. For a max or min reduction in C++, the type of the list item
15012     // must be an allowed arithmetic data type: char, wchar_t, int, float,
15013     // double, or bool, possibly modified with long, short, signed, or unsigned.
15014     if (DeclareReductionRef.isUnset()) {
15015       if ((BOK == BO_GT || BOK == BO_LT) &&
15016           !(Type->isScalarType() ||
15017             (S.getLangOpts().CPlusPlus && Type->isArithmeticType()))) {
15018         S.Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg)
15019             << getOpenMPClauseName(ClauseKind) << S.getLangOpts().CPlusPlus;
15020         if (!ASE && !OASE) {
15021           bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
15022                                    VarDecl::DeclarationOnly;
15023           S.Diag(D->getLocation(),
15024                  IsDecl ? diag::note_previous_decl : diag::note_defined_here)
15025               << D;
15026         }
15027         continue;
15028       }
15029       if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) &&
15030           !S.getLangOpts().CPlusPlus && Type->isFloatingType()) {
15031         S.Diag(ELoc, diag::err_omp_clause_floating_type_arg)
15032             << getOpenMPClauseName(ClauseKind);
15033         if (!ASE && !OASE) {
15034           bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
15035                                    VarDecl::DeclarationOnly;
15036           S.Diag(D->getLocation(),
15037                  IsDecl ? diag::note_previous_decl : diag::note_defined_here)
15038               << D;
15039         }
15040         continue;
15041       }
15042     }
15043 
15044     Type = Type.getNonLValueExprType(Context).getUnqualifiedType();
15045     VarDecl *LHSVD = buildVarDecl(S, ELoc, Type, ".reduction.lhs",
15046                                   D->hasAttrs() ? &D->getAttrs() : nullptr);
15047     VarDecl *RHSVD = buildVarDecl(S, ELoc, Type, D->getName(),
15048                                   D->hasAttrs() ? &D->getAttrs() : nullptr);
15049     QualType PrivateTy = Type;
15050 
15051     // Try if we can determine constant lengths for all array sections and avoid
15052     // the VLA.
15053     bool ConstantLengthOASE = false;
15054     if (OASE) {
15055       bool SingleElement;
15056       llvm::SmallVector<llvm::APSInt, 4> ArraySizes;
15057       ConstantLengthOASE = checkOMPArraySectionConstantForReduction(
15058           Context, OASE, SingleElement, ArraySizes);
15059 
15060       // If we don't have a single element, we must emit a constant array type.
15061       if (ConstantLengthOASE && !SingleElement) {
15062         for (llvm::APSInt &Size : ArraySizes)
15063           PrivateTy = Context.getConstantArrayType(PrivateTy, Size, nullptr,
15064                                                    ArrayType::Normal,
15065                                                    /*IndexTypeQuals=*/0);
15066       }
15067     }
15068 
15069     if ((OASE && !ConstantLengthOASE) ||
15070         (!OASE && !ASE &&
15071          D->getType().getNonReferenceType()->isVariablyModifiedType())) {
15072       if (!Context.getTargetInfo().isVLASupported()) {
15073         if (isOpenMPTargetExecutionDirective(Stack->getCurrentDirective())) {
15074           S.Diag(ELoc, diag::err_omp_reduction_vla_unsupported) << !!OASE;
15075           S.Diag(ELoc, diag::note_vla_unsupported);
15076           continue;
15077         } else {
15078           S.targetDiag(ELoc, diag::err_omp_reduction_vla_unsupported) << !!OASE;
15079           S.targetDiag(ELoc, diag::note_vla_unsupported);
15080         }
15081       }
15082       // For arrays/array sections only:
15083       // Create pseudo array type for private copy. The size for this array will
15084       // be generated during codegen.
15085       // For array subscripts or single variables Private Ty is the same as Type
15086       // (type of the variable or single array element).
15087       PrivateTy = Context.getVariableArrayType(
15088           Type,
15089           new (Context) OpaqueValueExpr(ELoc, Context.getSizeType(), VK_RValue),
15090           ArrayType::Normal, /*IndexTypeQuals=*/0, SourceRange());
15091     } else if (!ASE && !OASE &&
15092                Context.getAsArrayType(D->getType().getNonReferenceType())) {
15093       PrivateTy = D->getType().getNonReferenceType();
15094     }
15095     // Private copy.
15096     VarDecl *PrivateVD =
15097         buildVarDecl(S, ELoc, PrivateTy, D->getName(),
15098                      D->hasAttrs() ? &D->getAttrs() : nullptr,
15099                      VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
15100     // Add initializer for private variable.
15101     Expr *Init = nullptr;
15102     DeclRefExpr *LHSDRE = buildDeclRefExpr(S, LHSVD, Type, ELoc);
15103     DeclRefExpr *RHSDRE = buildDeclRefExpr(S, RHSVD, Type, ELoc);
15104     if (DeclareReductionRef.isUsable()) {
15105       auto *DRDRef = DeclareReductionRef.getAs<DeclRefExpr>();
15106       auto *DRD = cast<OMPDeclareReductionDecl>(DRDRef->getDecl());
15107       if (DRD->getInitializer()) {
15108         Init = DRDRef;
15109         RHSVD->setInit(DRDRef);
15110         RHSVD->setInitStyle(VarDecl::CallInit);
15111       }
15112     } else {
15113       switch (BOK) {
15114       case BO_Add:
15115       case BO_Xor:
15116       case BO_Or:
15117       case BO_LOr:
15118         // '+', '-', '^', '|', '||' reduction ops - initializer is '0'.
15119         if (Type->isScalarType() || Type->isAnyComplexType())
15120           Init = S.ActOnIntegerConstant(ELoc, /*Val=*/0).get();
15121         break;
15122       case BO_Mul:
15123       case BO_LAnd:
15124         if (Type->isScalarType() || Type->isAnyComplexType()) {
15125           // '*' and '&&' reduction ops - initializer is '1'.
15126           Init = S.ActOnIntegerConstant(ELoc, /*Val=*/1).get();
15127         }
15128         break;
15129       case BO_And: {
15130         // '&' reduction op - initializer is '~0'.
15131         QualType OrigType = Type;
15132         if (auto *ComplexTy = OrigType->getAs<ComplexType>())
15133           Type = ComplexTy->getElementType();
15134         if (Type->isRealFloatingType()) {
15135           llvm::APFloat InitValue = llvm::APFloat::getAllOnesValue(
15136               Context.getFloatTypeSemantics(Type),
15137               Context.getTypeSize(Type));
15138           Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
15139                                          Type, ELoc);
15140         } else if (Type->isScalarType()) {
15141           uint64_t Size = Context.getTypeSize(Type);
15142           QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0);
15143           llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size);
15144           Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
15145         }
15146         if (Init && OrigType->isAnyComplexType()) {
15147           // Init = 0xFFFF + 0xFFFFi;
15148           auto *Im = new (Context) ImaginaryLiteral(Init, OrigType);
15149           Init = S.CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get();
15150         }
15151         Type = OrigType;
15152         break;
15153       }
15154       case BO_LT:
15155       case BO_GT: {
15156         // 'min' reduction op - initializer is 'Largest representable number in
15157         // the reduction list item type'.
15158         // 'max' reduction op - initializer is 'Least representable number in
15159         // the reduction list item type'.
15160         if (Type->isIntegerType() || Type->isPointerType()) {
15161           bool IsSigned = Type->hasSignedIntegerRepresentation();
15162           uint64_t Size = Context.getTypeSize(Type);
15163           QualType IntTy =
15164               Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned);
15165           llvm::APInt InitValue =
15166               (BOK != BO_LT) ? IsSigned ? llvm::APInt::getSignedMinValue(Size)
15167                                         : llvm::APInt::getMinValue(Size)
15168                              : IsSigned ? llvm::APInt::getSignedMaxValue(Size)
15169                                         : llvm::APInt::getMaxValue(Size);
15170           Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
15171           if (Type->isPointerType()) {
15172             // Cast to pointer type.
15173             ExprResult CastExpr = S.BuildCStyleCastExpr(
15174                 ELoc, Context.getTrivialTypeSourceInfo(Type, ELoc), ELoc, Init);
15175             if (CastExpr.isInvalid())
15176               continue;
15177             Init = CastExpr.get();
15178           }
15179         } else if (Type->isRealFloatingType()) {
15180           llvm::APFloat InitValue = llvm::APFloat::getLargest(
15181               Context.getFloatTypeSemantics(Type), BOK != BO_LT);
15182           Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
15183                                          Type, ELoc);
15184         }
15185         break;
15186       }
15187       case BO_PtrMemD:
15188       case BO_PtrMemI:
15189       case BO_MulAssign:
15190       case BO_Div:
15191       case BO_Rem:
15192       case BO_Sub:
15193       case BO_Shl:
15194       case BO_Shr:
15195       case BO_LE:
15196       case BO_GE:
15197       case BO_EQ:
15198       case BO_NE:
15199       case BO_Cmp:
15200       case BO_AndAssign:
15201       case BO_XorAssign:
15202       case BO_OrAssign:
15203       case BO_Assign:
15204       case BO_AddAssign:
15205       case BO_SubAssign:
15206       case BO_DivAssign:
15207       case BO_RemAssign:
15208       case BO_ShlAssign:
15209       case BO_ShrAssign:
15210       case BO_Comma:
15211         llvm_unreachable("Unexpected reduction operation");
15212       }
15213     }
15214     if (Init && DeclareReductionRef.isUnset())
15215       S.AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false);
15216     else if (!Init)
15217       S.ActOnUninitializedDecl(RHSVD);
15218     if (RHSVD->isInvalidDecl())
15219       continue;
15220     if (!RHSVD->hasInit() &&
15221         (DeclareReductionRef.isUnset() || !S.LangOpts.CPlusPlus)) {
15222       S.Diag(ELoc, diag::err_omp_reduction_id_not_compatible)
15223           << Type << ReductionIdRange;
15224       bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
15225                                VarDecl::DeclarationOnly;
15226       S.Diag(D->getLocation(),
15227              IsDecl ? diag::note_previous_decl : diag::note_defined_here)
15228           << D;
15229       continue;
15230     }
15231     // Store initializer for single element in private copy. Will be used during
15232     // codegen.
15233     PrivateVD->setInit(RHSVD->getInit());
15234     PrivateVD->setInitStyle(RHSVD->getInitStyle());
15235     DeclRefExpr *PrivateDRE = buildDeclRefExpr(S, PrivateVD, PrivateTy, ELoc);
15236     ExprResult ReductionOp;
15237     if (DeclareReductionRef.isUsable()) {
15238       QualType RedTy = DeclareReductionRef.get()->getType();
15239       QualType PtrRedTy = Context.getPointerType(RedTy);
15240       ExprResult LHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, LHSDRE);
15241       ExprResult RHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RHSDRE);
15242       if (!BasePath.empty()) {
15243         LHS = S.DefaultLvalueConversion(LHS.get());
15244         RHS = S.DefaultLvalueConversion(RHS.get());
15245         LHS = ImplicitCastExpr::Create(Context, PtrRedTy,
15246                                        CK_UncheckedDerivedToBase, LHS.get(),
15247                                        &BasePath, LHS.get()->getValueKind());
15248         RHS = ImplicitCastExpr::Create(Context, PtrRedTy,
15249                                        CK_UncheckedDerivedToBase, RHS.get(),
15250                                        &BasePath, RHS.get()->getValueKind());
15251       }
15252       FunctionProtoType::ExtProtoInfo EPI;
15253       QualType Params[] = {PtrRedTy, PtrRedTy};
15254       QualType FnTy = Context.getFunctionType(Context.VoidTy, Params, EPI);
15255       auto *OVE = new (Context) OpaqueValueExpr(
15256           ELoc, Context.getPointerType(FnTy), VK_RValue, OK_Ordinary,
15257           S.DefaultLvalueConversion(DeclareReductionRef.get()).get());
15258       Expr *Args[] = {LHS.get(), RHS.get()};
15259       ReductionOp =
15260           CallExpr::Create(Context, OVE, Args, Context.VoidTy, VK_RValue, ELoc);
15261     } else {
15262       ReductionOp = S.BuildBinOp(
15263           Stack->getCurScope(), ReductionId.getBeginLoc(), BOK, LHSDRE, RHSDRE);
15264       if (ReductionOp.isUsable()) {
15265         if (BOK != BO_LT && BOK != BO_GT) {
15266           ReductionOp =
15267               S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(),
15268                            BO_Assign, LHSDRE, ReductionOp.get());
15269         } else {
15270           auto *ConditionalOp = new (Context)
15271               ConditionalOperator(ReductionOp.get(), ELoc, LHSDRE, ELoc, RHSDRE,
15272                                   Type, VK_LValue, OK_Ordinary);
15273           ReductionOp =
15274               S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(),
15275                            BO_Assign, LHSDRE, ConditionalOp);
15276         }
15277         if (ReductionOp.isUsable())
15278           ReductionOp = S.ActOnFinishFullExpr(ReductionOp.get(),
15279                                               /*DiscardedValue*/ false);
15280       }
15281       if (!ReductionOp.isUsable())
15282         continue;
15283     }
15284 
15285     // Add copy operations for inscan reductions.
15286     // LHS = RHS;
15287     ExprResult CopyOpRes, TempArrayRes, TempArrayElem;
15288     if (ClauseKind == OMPC_reduction &&
15289         RD.RedModifier == OMPC_REDUCTION_inscan) {
15290       ExprResult RHS = S.DefaultLvalueConversion(RHSDRE);
15291       CopyOpRes = S.BuildBinOp(Stack->getCurScope(), ELoc, BO_Assign, LHSDRE,
15292                                RHS.get());
15293       if (!CopyOpRes.isUsable())
15294         continue;
15295       CopyOpRes =
15296           S.ActOnFinishFullExpr(CopyOpRes.get(), /*DiscardedValue=*/true);
15297       if (!CopyOpRes.isUsable())
15298         continue;
15299       // For simd directive and simd-based directives in simd mode no need to
15300       // construct temp array, need just a single temp element.
15301       if (Stack->getCurrentDirective() == OMPD_simd ||
15302           (S.getLangOpts().OpenMPSimd &&
15303            isOpenMPSimdDirective(Stack->getCurrentDirective()))) {
15304         VarDecl *TempArrayVD =
15305             buildVarDecl(S, ELoc, PrivateTy, D->getName(),
15306                          D->hasAttrs() ? &D->getAttrs() : nullptr);
15307         // Add a constructor to the temp decl.
15308         S.ActOnUninitializedDecl(TempArrayVD);
15309         TempArrayRes = buildDeclRefExpr(S, TempArrayVD, PrivateTy, ELoc);
15310       } else {
15311         // Build temp array for prefix sum.
15312         auto *Dim = new (S.Context)
15313             OpaqueValueExpr(ELoc, S.Context.getSizeType(), VK_RValue);
15314         QualType ArrayTy =
15315             S.Context.getVariableArrayType(PrivateTy, Dim, ArrayType::Normal,
15316                                            /*IndexTypeQuals=*/0, {ELoc, ELoc});
15317         VarDecl *TempArrayVD =
15318             buildVarDecl(S, ELoc, ArrayTy, D->getName(),
15319                          D->hasAttrs() ? &D->getAttrs() : nullptr);
15320         // Add a constructor to the temp decl.
15321         S.ActOnUninitializedDecl(TempArrayVD);
15322         TempArrayRes = buildDeclRefExpr(S, TempArrayVD, ArrayTy, ELoc);
15323         TempArrayElem =
15324             S.DefaultFunctionArrayLvalueConversion(TempArrayRes.get());
15325         auto *Idx = new (S.Context)
15326             OpaqueValueExpr(ELoc, S.Context.getSizeType(), VK_RValue);
15327         TempArrayElem = S.CreateBuiltinArraySubscriptExpr(TempArrayElem.get(),
15328                                                           ELoc, Idx, ELoc);
15329       }
15330     }
15331 
15332     // OpenMP [2.15.4.6, Restrictions, p.2]
15333     // A list item that appears in an in_reduction clause of a task construct
15334     // must appear in a task_reduction clause of a construct associated with a
15335     // taskgroup region that includes the participating task in its taskgroup
15336     // set. The construct associated with the innermost region that meets this
15337     // condition must specify the same reduction-identifier as the in_reduction
15338     // clause.
15339     if (ClauseKind == OMPC_in_reduction) {
15340       SourceRange ParentSR;
15341       BinaryOperatorKind ParentBOK;
15342       const Expr *ParentReductionOp = nullptr;
15343       Expr *ParentBOKTD = nullptr, *ParentReductionOpTD = nullptr;
15344       DSAStackTy::DSAVarData ParentBOKDSA =
15345           Stack->getTopMostTaskgroupReductionData(D, ParentSR, ParentBOK,
15346                                                   ParentBOKTD);
15347       DSAStackTy::DSAVarData ParentReductionOpDSA =
15348           Stack->getTopMostTaskgroupReductionData(
15349               D, ParentSR, ParentReductionOp, ParentReductionOpTD);
15350       bool IsParentBOK = ParentBOKDSA.DKind != OMPD_unknown;
15351       bool IsParentReductionOp = ParentReductionOpDSA.DKind != OMPD_unknown;
15352       if ((DeclareReductionRef.isUnset() && IsParentReductionOp) ||
15353           (DeclareReductionRef.isUsable() && IsParentBOK) ||
15354           (IsParentBOK && BOK != ParentBOK) || IsParentReductionOp) {
15355         bool EmitError = true;
15356         if (IsParentReductionOp && DeclareReductionRef.isUsable()) {
15357           llvm::FoldingSetNodeID RedId, ParentRedId;
15358           ParentReductionOp->Profile(ParentRedId, Context, /*Canonical=*/true);
15359           DeclareReductionRef.get()->Profile(RedId, Context,
15360                                              /*Canonical=*/true);
15361           EmitError = RedId != ParentRedId;
15362         }
15363         if (EmitError) {
15364           S.Diag(ReductionId.getBeginLoc(),
15365                  diag::err_omp_reduction_identifier_mismatch)
15366               << ReductionIdRange << RefExpr->getSourceRange();
15367           S.Diag(ParentSR.getBegin(),
15368                  diag::note_omp_previous_reduction_identifier)
15369               << ParentSR
15370               << (IsParentBOK ? ParentBOKDSA.RefExpr
15371                               : ParentReductionOpDSA.RefExpr)
15372                      ->getSourceRange();
15373           continue;
15374         }
15375       }
15376       TaskgroupDescriptor = IsParentBOK ? ParentBOKTD : ParentReductionOpTD;
15377     }
15378 
15379     DeclRefExpr *Ref = nullptr;
15380     Expr *VarsExpr = RefExpr->IgnoreParens();
15381     if (!VD && !S.CurContext->isDependentContext()) {
15382       if (ASE || OASE) {
15383         TransformExprToCaptures RebuildToCapture(S, D);
15384         VarsExpr =
15385             RebuildToCapture.TransformExpr(RefExpr->IgnoreParens()).get();
15386         Ref = RebuildToCapture.getCapturedExpr();
15387       } else {
15388         VarsExpr = Ref = buildCapture(S, D, SimpleRefExpr, /*WithInit=*/false);
15389       }
15390       if (!S.isOpenMPCapturedDecl(D)) {
15391         RD.ExprCaptures.emplace_back(Ref->getDecl());
15392         if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
15393           ExprResult RefRes = S.DefaultLvalueConversion(Ref);
15394           if (!RefRes.isUsable())
15395             continue;
15396           ExprResult PostUpdateRes =
15397               S.BuildBinOp(Stack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
15398                            RefRes.get());
15399           if (!PostUpdateRes.isUsable())
15400             continue;
15401           if (isOpenMPTaskingDirective(Stack->getCurrentDirective()) ||
15402               Stack->getCurrentDirective() == OMPD_taskgroup) {
15403             S.Diag(RefExpr->getExprLoc(),
15404                    diag::err_omp_reduction_non_addressable_expression)
15405                 << RefExpr->getSourceRange();
15406             continue;
15407           }
15408           RD.ExprPostUpdates.emplace_back(
15409               S.IgnoredValueConversions(PostUpdateRes.get()).get());
15410         }
15411       }
15412     }
15413     // All reduction items are still marked as reduction (to do not increase
15414     // code base size).
15415     unsigned Modifier = RD.RedModifier;
15416     // Consider task_reductions as reductions with task modifier. Required for
15417     // correct analysis of in_reduction clauses.
15418     if (CurrDir == OMPD_taskgroup && ClauseKind == OMPC_task_reduction)
15419       Modifier = OMPC_REDUCTION_task;
15420     Stack->addDSA(D, RefExpr->IgnoreParens(), OMPC_reduction, Ref, Modifier);
15421     if (Modifier == OMPC_REDUCTION_task &&
15422         (CurrDir == OMPD_taskgroup ||
15423          ((isOpenMPParallelDirective(CurrDir) ||
15424            isOpenMPWorksharingDirective(CurrDir)) &&
15425           !isOpenMPSimdDirective(CurrDir)))) {
15426       if (DeclareReductionRef.isUsable())
15427         Stack->addTaskgroupReductionData(D, ReductionIdRange,
15428                                          DeclareReductionRef.get());
15429       else
15430         Stack->addTaskgroupReductionData(D, ReductionIdRange, BOK);
15431     }
15432     RD.push(VarsExpr, PrivateDRE, LHSDRE, RHSDRE, ReductionOp.get(),
15433             TaskgroupDescriptor, CopyOpRes.get(), TempArrayRes.get(),
15434             TempArrayElem.get());
15435   }
15436   return RD.Vars.empty();
15437 }
15438 
15439 OMPClause *Sema::ActOnOpenMPReductionClause(
15440     ArrayRef<Expr *> VarList, OpenMPReductionClauseModifier Modifier,
15441     SourceLocation StartLoc, SourceLocation LParenLoc,
15442     SourceLocation ModifierLoc, SourceLocation ColonLoc, SourceLocation EndLoc,
15443     CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
15444     ArrayRef<Expr *> UnresolvedReductions) {
15445   if (ModifierLoc.isValid() && Modifier == OMPC_REDUCTION_unknown) {
15446     Diag(LParenLoc, diag::err_omp_unexpected_clause_value)
15447         << getListOfPossibleValues(OMPC_reduction, /*First=*/0,
15448                                    /*Last=*/OMPC_REDUCTION_unknown)
15449         << getOpenMPClauseName(OMPC_reduction);
15450     return nullptr;
15451   }
15452   // OpenMP 5.0, 2.19.5.4 reduction Clause, Restrictions
15453   // A reduction clause with the inscan reduction-modifier may only appear on a
15454   // worksharing-loop construct, a worksharing-loop SIMD construct, a simd
15455   // construct, a parallel worksharing-loop construct or a parallel
15456   // worksharing-loop SIMD construct.
15457   if (Modifier == OMPC_REDUCTION_inscan &&
15458       (DSAStack->getCurrentDirective() != OMPD_for &&
15459        DSAStack->getCurrentDirective() != OMPD_for_simd &&
15460        DSAStack->getCurrentDirective() != OMPD_simd &&
15461        DSAStack->getCurrentDirective() != OMPD_parallel_for &&
15462        DSAStack->getCurrentDirective() != OMPD_parallel_for_simd)) {
15463     Diag(ModifierLoc, diag::err_omp_wrong_inscan_reduction);
15464     return nullptr;
15465   }
15466 
15467   ReductionData RD(VarList.size(), Modifier);
15468   if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_reduction, VarList,
15469                                   StartLoc, LParenLoc, ColonLoc, EndLoc,
15470                                   ReductionIdScopeSpec, ReductionId,
15471                                   UnresolvedReductions, RD))
15472     return nullptr;
15473 
15474   return OMPReductionClause::Create(
15475       Context, StartLoc, LParenLoc, ModifierLoc, ColonLoc, EndLoc, Modifier,
15476       RD.Vars, ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
15477       RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, RD.InscanCopyOps,
15478       RD.InscanCopyArrayTemps, RD.InscanCopyArrayElems,
15479       buildPreInits(Context, RD.ExprCaptures),
15480       buildPostUpdate(*this, RD.ExprPostUpdates));
15481 }
15482 
15483 OMPClause *Sema::ActOnOpenMPTaskReductionClause(
15484     ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
15485     SourceLocation ColonLoc, SourceLocation EndLoc,
15486     CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
15487     ArrayRef<Expr *> UnresolvedReductions) {
15488   ReductionData RD(VarList.size());
15489   if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_task_reduction, VarList,
15490                                   StartLoc, LParenLoc, ColonLoc, EndLoc,
15491                                   ReductionIdScopeSpec, ReductionId,
15492                                   UnresolvedReductions, RD))
15493     return nullptr;
15494 
15495   return OMPTaskReductionClause::Create(
15496       Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
15497       ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
15498       RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
15499       buildPreInits(Context, RD.ExprCaptures),
15500       buildPostUpdate(*this, RD.ExprPostUpdates));
15501 }
15502 
15503 OMPClause *Sema::ActOnOpenMPInReductionClause(
15504     ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
15505     SourceLocation ColonLoc, SourceLocation EndLoc,
15506     CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
15507     ArrayRef<Expr *> UnresolvedReductions) {
15508   ReductionData RD(VarList.size());
15509   if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_in_reduction, VarList,
15510                                   StartLoc, LParenLoc, ColonLoc, EndLoc,
15511                                   ReductionIdScopeSpec, ReductionId,
15512                                   UnresolvedReductions, RD))
15513     return nullptr;
15514 
15515   return OMPInReductionClause::Create(
15516       Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
15517       ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
15518       RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, RD.TaskgroupDescriptors,
15519       buildPreInits(Context, RD.ExprCaptures),
15520       buildPostUpdate(*this, RD.ExprPostUpdates));
15521 }
15522 
15523 bool Sema::CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
15524                                      SourceLocation LinLoc) {
15525   if ((!LangOpts.CPlusPlus && LinKind != OMPC_LINEAR_val) ||
15526       LinKind == OMPC_LINEAR_unknown) {
15527     Diag(LinLoc, diag::err_omp_wrong_linear_modifier) << LangOpts.CPlusPlus;
15528     return true;
15529   }
15530   return false;
15531 }
15532 
15533 bool Sema::CheckOpenMPLinearDecl(const ValueDecl *D, SourceLocation ELoc,
15534                                  OpenMPLinearClauseKind LinKind, QualType Type,
15535                                  bool IsDeclareSimd) {
15536   const auto *VD = dyn_cast_or_null<VarDecl>(D);
15537   // A variable must not have an incomplete type or a reference type.
15538   if (RequireCompleteType(ELoc, Type, diag::err_omp_linear_incomplete_type))
15539     return true;
15540   if ((LinKind == OMPC_LINEAR_uval || LinKind == OMPC_LINEAR_ref) &&
15541       !Type->isReferenceType()) {
15542     Diag(ELoc, diag::err_omp_wrong_linear_modifier_non_reference)
15543         << Type << getOpenMPSimpleClauseTypeName(OMPC_linear, LinKind);
15544     return true;
15545   }
15546   Type = Type.getNonReferenceType();
15547 
15548   // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
15549   // A variable that is privatized must not have a const-qualified type
15550   // unless it is of class type with a mutable member. This restriction does
15551   // not apply to the firstprivate clause, nor to the linear clause on
15552   // declarative directives (like declare simd).
15553   if (!IsDeclareSimd &&
15554       rejectConstNotMutableType(*this, D, Type, OMPC_linear, ELoc))
15555     return true;
15556 
15557   // A list item must be of integral or pointer type.
15558   Type = Type.getUnqualifiedType().getCanonicalType();
15559   const auto *Ty = Type.getTypePtrOrNull();
15560   if (!Ty || (LinKind != OMPC_LINEAR_ref && !Ty->isDependentType() &&
15561               !Ty->isIntegralType(Context) && !Ty->isPointerType())) {
15562     Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << Type;
15563     if (D) {
15564       bool IsDecl =
15565           !VD ||
15566           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
15567       Diag(D->getLocation(),
15568            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
15569           << D;
15570     }
15571     return true;
15572   }
15573   return false;
15574 }
15575 
15576 OMPClause *Sema::ActOnOpenMPLinearClause(
15577     ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc,
15578     SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind,
15579     SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
15580   SmallVector<Expr *, 8> Vars;
15581   SmallVector<Expr *, 8> Privates;
15582   SmallVector<Expr *, 8> Inits;
15583   SmallVector<Decl *, 4> ExprCaptures;
15584   SmallVector<Expr *, 4> ExprPostUpdates;
15585   if (CheckOpenMPLinearModifier(LinKind, LinLoc))
15586     LinKind = OMPC_LINEAR_val;
15587   for (Expr *RefExpr : VarList) {
15588     assert(RefExpr && "NULL expr in OpenMP linear clause.");
15589     SourceLocation ELoc;
15590     SourceRange ERange;
15591     Expr *SimpleRefExpr = RefExpr;
15592     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
15593     if (Res.second) {
15594       // It will be analyzed later.
15595       Vars.push_back(RefExpr);
15596       Privates.push_back(nullptr);
15597       Inits.push_back(nullptr);
15598     }
15599     ValueDecl *D = Res.first;
15600     if (!D)
15601       continue;
15602 
15603     QualType Type = D->getType();
15604     auto *VD = dyn_cast<VarDecl>(D);
15605 
15606     // OpenMP [2.14.3.7, linear clause]
15607     //  A list-item cannot appear in more than one linear clause.
15608     //  A list-item that appears in a linear clause cannot appear in any
15609     //  other data-sharing attribute clause.
15610     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
15611     if (DVar.RefExpr) {
15612       Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
15613                                           << getOpenMPClauseName(OMPC_linear);
15614       reportOriginalDsa(*this, DSAStack, D, DVar);
15615       continue;
15616     }
15617 
15618     if (CheckOpenMPLinearDecl(D, ELoc, LinKind, Type))
15619       continue;
15620     Type = Type.getNonReferenceType().getUnqualifiedType().getCanonicalType();
15621 
15622     // Build private copy of original var.
15623     VarDecl *Private =
15624         buildVarDecl(*this, ELoc, Type, D->getName(),
15625                      D->hasAttrs() ? &D->getAttrs() : nullptr,
15626                      VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
15627     DeclRefExpr *PrivateRef = buildDeclRefExpr(*this, Private, Type, ELoc);
15628     // Build var to save initial value.
15629     VarDecl *Init = buildVarDecl(*this, ELoc, Type, ".linear.start");
15630     Expr *InitExpr;
15631     DeclRefExpr *Ref = nullptr;
15632     if (!VD && !CurContext->isDependentContext()) {
15633       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
15634       if (!isOpenMPCapturedDecl(D)) {
15635         ExprCaptures.push_back(Ref->getDecl());
15636         if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
15637           ExprResult RefRes = DefaultLvalueConversion(Ref);
15638           if (!RefRes.isUsable())
15639             continue;
15640           ExprResult PostUpdateRes =
15641               BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
15642                          SimpleRefExpr, RefRes.get());
15643           if (!PostUpdateRes.isUsable())
15644             continue;
15645           ExprPostUpdates.push_back(
15646               IgnoredValueConversions(PostUpdateRes.get()).get());
15647         }
15648       }
15649     }
15650     if (LinKind == OMPC_LINEAR_uval)
15651       InitExpr = VD ? VD->getInit() : SimpleRefExpr;
15652     else
15653       InitExpr = VD ? SimpleRefExpr : Ref;
15654     AddInitializerToDecl(Init, DefaultLvalueConversion(InitExpr).get(),
15655                          /*DirectInit=*/false);
15656     DeclRefExpr *InitRef = buildDeclRefExpr(*this, Init, Type, ELoc);
15657 
15658     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_linear, Ref);
15659     Vars.push_back((VD || CurContext->isDependentContext())
15660                        ? RefExpr->IgnoreParens()
15661                        : Ref);
15662     Privates.push_back(PrivateRef);
15663     Inits.push_back(InitRef);
15664   }
15665 
15666   if (Vars.empty())
15667     return nullptr;
15668 
15669   Expr *StepExpr = Step;
15670   Expr *CalcStepExpr = nullptr;
15671   if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
15672       !Step->isInstantiationDependent() &&
15673       !Step->containsUnexpandedParameterPack()) {
15674     SourceLocation StepLoc = Step->getBeginLoc();
15675     ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step);
15676     if (Val.isInvalid())
15677       return nullptr;
15678     StepExpr = Val.get();
15679 
15680     // Build var to save the step value.
15681     VarDecl *SaveVar =
15682         buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step");
15683     ExprResult SaveRef =
15684         buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc);
15685     ExprResult CalcStep =
15686         BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr);
15687     CalcStep = ActOnFinishFullExpr(CalcStep.get(), /*DiscardedValue*/ false);
15688 
15689     // Warn about zero linear step (it would be probably better specified as
15690     // making corresponding variables 'const').
15691     llvm::APSInt Result;
15692     bool IsConstant = StepExpr->isIntegerConstantExpr(Result, Context);
15693     if (IsConstant && !Result.isNegative() && !Result.isStrictlyPositive())
15694       Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0]
15695                                                      << (Vars.size() > 1);
15696     if (!IsConstant && CalcStep.isUsable()) {
15697       // Calculate the step beforehand instead of doing this on each iteration.
15698       // (This is not used if the number of iterations may be kfold-ed).
15699       CalcStepExpr = CalcStep.get();
15700     }
15701   }
15702 
15703   return OMPLinearClause::Create(Context, StartLoc, LParenLoc, LinKind, LinLoc,
15704                                  ColonLoc, EndLoc, Vars, Privates, Inits,
15705                                  StepExpr, CalcStepExpr,
15706                                  buildPreInits(Context, ExprCaptures),
15707                                  buildPostUpdate(*this, ExprPostUpdates));
15708 }
15709 
15710 static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
15711                                      Expr *NumIterations, Sema &SemaRef,
15712                                      Scope *S, DSAStackTy *Stack) {
15713   // Walk the vars and build update/final expressions for the CodeGen.
15714   SmallVector<Expr *, 8> Updates;
15715   SmallVector<Expr *, 8> Finals;
15716   SmallVector<Expr *, 8> UsedExprs;
15717   Expr *Step = Clause.getStep();
15718   Expr *CalcStep = Clause.getCalcStep();
15719   // OpenMP [2.14.3.7, linear clause]
15720   // If linear-step is not specified it is assumed to be 1.
15721   if (!Step)
15722     Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
15723   else if (CalcStep)
15724     Step = cast<BinaryOperator>(CalcStep)->getLHS();
15725   bool HasErrors = false;
15726   auto CurInit = Clause.inits().begin();
15727   auto CurPrivate = Clause.privates().begin();
15728   OpenMPLinearClauseKind LinKind = Clause.getModifier();
15729   for (Expr *RefExpr : Clause.varlists()) {
15730     SourceLocation ELoc;
15731     SourceRange ERange;
15732     Expr *SimpleRefExpr = RefExpr;
15733     auto Res = getPrivateItem(SemaRef, SimpleRefExpr, ELoc, ERange);
15734     ValueDecl *D = Res.first;
15735     if (Res.second || !D) {
15736       Updates.push_back(nullptr);
15737       Finals.push_back(nullptr);
15738       HasErrors = true;
15739       continue;
15740     }
15741     auto &&Info = Stack->isLoopControlVariable(D);
15742     // OpenMP [2.15.11, distribute simd Construct]
15743     // A list item may not appear in a linear clause, unless it is the loop
15744     // iteration variable.
15745     if (isOpenMPDistributeDirective(Stack->getCurrentDirective()) &&
15746         isOpenMPSimdDirective(Stack->getCurrentDirective()) && !Info.first) {
15747       SemaRef.Diag(ELoc,
15748                    diag::err_omp_linear_distribute_var_non_loop_iteration);
15749       Updates.push_back(nullptr);
15750       Finals.push_back(nullptr);
15751       HasErrors = true;
15752       continue;
15753     }
15754     Expr *InitExpr = *CurInit;
15755 
15756     // Build privatized reference to the current linear var.
15757     auto *DE = cast<DeclRefExpr>(SimpleRefExpr);
15758     Expr *CapturedRef;
15759     if (LinKind == OMPC_LINEAR_uval)
15760       CapturedRef = cast<VarDecl>(DE->getDecl())->getInit();
15761     else
15762       CapturedRef =
15763           buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()),
15764                            DE->getType().getUnqualifiedType(), DE->getExprLoc(),
15765                            /*RefersToCapture=*/true);
15766 
15767     // Build update: Var = InitExpr + IV * Step
15768     ExprResult Update;
15769     if (!Info.first)
15770       Update = buildCounterUpdate(
15771           SemaRef, S, RefExpr->getExprLoc(), *CurPrivate, InitExpr, IV, Step,
15772           /*Subtract=*/false, /*IsNonRectangularLB=*/false);
15773     else
15774       Update = *CurPrivate;
15775     Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getBeginLoc(),
15776                                          /*DiscardedValue*/ false);
15777 
15778     // Build final: Var = InitExpr + NumIterations * Step
15779     ExprResult Final;
15780     if (!Info.first)
15781       Final =
15782           buildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), CapturedRef,
15783                              InitExpr, NumIterations, Step, /*Subtract=*/false,
15784                              /*IsNonRectangularLB=*/false);
15785     else
15786       Final = *CurPrivate;
15787     Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getBeginLoc(),
15788                                         /*DiscardedValue*/ false);
15789 
15790     if (!Update.isUsable() || !Final.isUsable()) {
15791       Updates.push_back(nullptr);
15792       Finals.push_back(nullptr);
15793       UsedExprs.push_back(nullptr);
15794       HasErrors = true;
15795     } else {
15796       Updates.push_back(Update.get());
15797       Finals.push_back(Final.get());
15798       if (!Info.first)
15799         UsedExprs.push_back(SimpleRefExpr);
15800     }
15801     ++CurInit;
15802     ++CurPrivate;
15803   }
15804   if (Expr *S = Clause.getStep())
15805     UsedExprs.push_back(S);
15806   // Fill the remaining part with the nullptr.
15807   UsedExprs.append(Clause.varlist_size() + 1 - UsedExprs.size(), nullptr);
15808   Clause.setUpdates(Updates);
15809   Clause.setFinals(Finals);
15810   Clause.setUsedExprs(UsedExprs);
15811   return HasErrors;
15812 }
15813 
15814 OMPClause *Sema::ActOnOpenMPAlignedClause(
15815     ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc,
15816     SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
15817   SmallVector<Expr *, 8> Vars;
15818   for (Expr *RefExpr : VarList) {
15819     assert(RefExpr && "NULL expr in OpenMP linear clause.");
15820     SourceLocation ELoc;
15821     SourceRange ERange;
15822     Expr *SimpleRefExpr = RefExpr;
15823     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
15824     if (Res.second) {
15825       // It will be analyzed later.
15826       Vars.push_back(RefExpr);
15827     }
15828     ValueDecl *D = Res.first;
15829     if (!D)
15830       continue;
15831 
15832     QualType QType = D->getType();
15833     auto *VD = dyn_cast<VarDecl>(D);
15834 
15835     // OpenMP  [2.8.1, simd construct, Restrictions]
15836     // The type of list items appearing in the aligned clause must be
15837     // array, pointer, reference to array, or reference to pointer.
15838     QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType();
15839     const Type *Ty = QType.getTypePtrOrNull();
15840     if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
15841       Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr)
15842           << QType << getLangOpts().CPlusPlus << ERange;
15843       bool IsDecl =
15844           !VD ||
15845           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
15846       Diag(D->getLocation(),
15847            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
15848           << D;
15849       continue;
15850     }
15851 
15852     // OpenMP  [2.8.1, simd construct, Restrictions]
15853     // A list-item cannot appear in more than one aligned clause.
15854     if (const Expr *PrevRef = DSAStack->addUniqueAligned(D, SimpleRefExpr)) {
15855       Diag(ELoc, diag::err_omp_used_in_clause_twice)
15856           << 0 << getOpenMPClauseName(OMPC_aligned) << ERange;
15857       Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
15858           << getOpenMPClauseName(OMPC_aligned);
15859       continue;
15860     }
15861 
15862     DeclRefExpr *Ref = nullptr;
15863     if (!VD && isOpenMPCapturedDecl(D))
15864       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
15865     Vars.push_back(DefaultFunctionArrayConversion(
15866                        (VD || !Ref) ? RefExpr->IgnoreParens() : Ref)
15867                        .get());
15868   }
15869 
15870   // OpenMP [2.8.1, simd construct, Description]
15871   // The parameter of the aligned clause, alignment, must be a constant
15872   // positive integer expression.
15873   // If no optional parameter is specified, implementation-defined default
15874   // alignments for SIMD instructions on the target platforms are assumed.
15875   if (Alignment != nullptr) {
15876     ExprResult AlignResult =
15877         VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned);
15878     if (AlignResult.isInvalid())
15879       return nullptr;
15880     Alignment = AlignResult.get();
15881   }
15882   if (Vars.empty())
15883     return nullptr;
15884 
15885   return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
15886                                   EndLoc, Vars, Alignment);
15887 }
15888 
15889 OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
15890                                          SourceLocation StartLoc,
15891                                          SourceLocation LParenLoc,
15892                                          SourceLocation EndLoc) {
15893   SmallVector<Expr *, 8> Vars;
15894   SmallVector<Expr *, 8> SrcExprs;
15895   SmallVector<Expr *, 8> DstExprs;
15896   SmallVector<Expr *, 8> AssignmentOps;
15897   for (Expr *RefExpr : VarList) {
15898     assert(RefExpr && "NULL expr in OpenMP copyin clause.");
15899     if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
15900       // It will be analyzed later.
15901       Vars.push_back(RefExpr);
15902       SrcExprs.push_back(nullptr);
15903       DstExprs.push_back(nullptr);
15904       AssignmentOps.push_back(nullptr);
15905       continue;
15906     }
15907 
15908     SourceLocation ELoc = RefExpr->getExprLoc();
15909     // OpenMP [2.1, C/C++]
15910     //  A list item is a variable name.
15911     // OpenMP  [2.14.4.1, Restrictions, p.1]
15912     //  A list item that appears in a copyin clause must be threadprivate.
15913     auto *DE = dyn_cast<DeclRefExpr>(RefExpr);
15914     if (!DE || !isa<VarDecl>(DE->getDecl())) {
15915       Diag(ELoc, diag::err_omp_expected_var_name_member_expr)
15916           << 0 << RefExpr->getSourceRange();
15917       continue;
15918     }
15919 
15920     Decl *D = DE->getDecl();
15921     auto *VD = cast<VarDecl>(D);
15922 
15923     QualType Type = VD->getType();
15924     if (Type->isDependentType() || Type->isInstantiationDependentType()) {
15925       // It will be analyzed later.
15926       Vars.push_back(DE);
15927       SrcExprs.push_back(nullptr);
15928       DstExprs.push_back(nullptr);
15929       AssignmentOps.push_back(nullptr);
15930       continue;
15931     }
15932 
15933     // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
15934     //  A list item that appears in a copyin clause must be threadprivate.
15935     if (!DSAStack->isThreadPrivate(VD)) {
15936       Diag(ELoc, diag::err_omp_required_access)
15937           << getOpenMPClauseName(OMPC_copyin)
15938           << getOpenMPDirectiveName(OMPD_threadprivate);
15939       continue;
15940     }
15941 
15942     // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
15943     //  A variable of class type (or array thereof) that appears in a
15944     //  copyin clause requires an accessible, unambiguous copy assignment
15945     //  operator for the class type.
15946     QualType ElemType = Context.getBaseElementType(Type).getNonReferenceType();
15947     VarDecl *SrcVD =
15948         buildVarDecl(*this, DE->getBeginLoc(), ElemType.getUnqualifiedType(),
15949                      ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr);
15950     DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr(
15951         *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc());
15952     VarDecl *DstVD =
15953         buildVarDecl(*this, DE->getBeginLoc(), ElemType, ".copyin.dst",
15954                      VD->hasAttrs() ? &VD->getAttrs() : nullptr);
15955     DeclRefExpr *PseudoDstExpr =
15956         buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc());
15957     // For arrays generate assignment operation for single element and replace
15958     // it by the original array element in CodeGen.
15959     ExprResult AssignmentOp =
15960         BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign, PseudoDstExpr,
15961                    PseudoSrcExpr);
15962     if (AssignmentOp.isInvalid())
15963       continue;
15964     AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
15965                                        /*DiscardedValue*/ false);
15966     if (AssignmentOp.isInvalid())
15967       continue;
15968 
15969     DSAStack->addDSA(VD, DE, OMPC_copyin);
15970     Vars.push_back(DE);
15971     SrcExprs.push_back(PseudoSrcExpr);
15972     DstExprs.push_back(PseudoDstExpr);
15973     AssignmentOps.push_back(AssignmentOp.get());
15974   }
15975 
15976   if (Vars.empty())
15977     return nullptr;
15978 
15979   return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
15980                                  SrcExprs, DstExprs, AssignmentOps);
15981 }
15982 
15983 OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
15984                                               SourceLocation StartLoc,
15985                                               SourceLocation LParenLoc,
15986                                               SourceLocation EndLoc) {
15987   SmallVector<Expr *, 8> Vars;
15988   SmallVector<Expr *, 8> SrcExprs;
15989   SmallVector<Expr *, 8> DstExprs;
15990   SmallVector<Expr *, 8> AssignmentOps;
15991   for (Expr *RefExpr : VarList) {
15992     assert(RefExpr && "NULL expr in OpenMP linear clause.");
15993     SourceLocation ELoc;
15994     SourceRange ERange;
15995     Expr *SimpleRefExpr = RefExpr;
15996     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
15997     if (Res.second) {
15998       // It will be analyzed later.
15999       Vars.push_back(RefExpr);
16000       SrcExprs.push_back(nullptr);
16001       DstExprs.push_back(nullptr);
16002       AssignmentOps.push_back(nullptr);
16003     }
16004     ValueDecl *D = Res.first;
16005     if (!D)
16006       continue;
16007 
16008     QualType Type = D->getType();
16009     auto *VD = dyn_cast<VarDecl>(D);
16010 
16011     // OpenMP [2.14.4.2, Restrictions, p.2]
16012     //  A list item that appears in a copyprivate clause may not appear in a
16013     //  private or firstprivate clause on the single construct.
16014     if (!VD || !DSAStack->isThreadPrivate(VD)) {
16015       DSAStackTy::DSAVarData DVar =
16016           DSAStack->getTopDSA(D, /*FromParent=*/false);
16017       if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate &&
16018           DVar.RefExpr) {
16019         Diag(ELoc, diag::err_omp_wrong_dsa)
16020             << getOpenMPClauseName(DVar.CKind)
16021             << getOpenMPClauseName(OMPC_copyprivate);
16022         reportOriginalDsa(*this, DSAStack, D, DVar);
16023         continue;
16024       }
16025 
16026       // OpenMP [2.11.4.2, Restrictions, p.1]
16027       //  All list items that appear in a copyprivate clause must be either
16028       //  threadprivate or private in the enclosing context.
16029       if (DVar.CKind == OMPC_unknown) {
16030         DVar = DSAStack->getImplicitDSA(D, false);
16031         if (DVar.CKind == OMPC_shared) {
16032           Diag(ELoc, diag::err_omp_required_access)
16033               << getOpenMPClauseName(OMPC_copyprivate)
16034               << "threadprivate or private in the enclosing context";
16035           reportOriginalDsa(*this, DSAStack, D, DVar);
16036           continue;
16037         }
16038       }
16039     }
16040 
16041     // Variably modified types are not supported.
16042     if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) {
16043       Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
16044           << getOpenMPClauseName(OMPC_copyprivate) << Type
16045           << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
16046       bool IsDecl =
16047           !VD ||
16048           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
16049       Diag(D->getLocation(),
16050            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
16051           << D;
16052       continue;
16053     }
16054 
16055     // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
16056     //  A variable of class type (or array thereof) that appears in a
16057     //  copyin clause requires an accessible, unambiguous copy assignment
16058     //  operator for the class type.
16059     Type = Context.getBaseElementType(Type.getNonReferenceType())
16060                .getUnqualifiedType();
16061     VarDecl *SrcVD =
16062         buildVarDecl(*this, RefExpr->getBeginLoc(), Type, ".copyprivate.src",
16063                      D->hasAttrs() ? &D->getAttrs() : nullptr);
16064     DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr(*this, SrcVD, Type, ELoc);
16065     VarDecl *DstVD =
16066         buildVarDecl(*this, RefExpr->getBeginLoc(), Type, ".copyprivate.dst",
16067                      D->hasAttrs() ? &D->getAttrs() : nullptr);
16068     DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
16069     ExprResult AssignmentOp = BuildBinOp(
16070         DSAStack->getCurScope(), ELoc, BO_Assign, PseudoDstExpr, PseudoSrcExpr);
16071     if (AssignmentOp.isInvalid())
16072       continue;
16073     AssignmentOp =
16074         ActOnFinishFullExpr(AssignmentOp.get(), ELoc, /*DiscardedValue*/ false);
16075     if (AssignmentOp.isInvalid())
16076       continue;
16077 
16078     // No need to mark vars as copyprivate, they are already threadprivate or
16079     // implicitly private.
16080     assert(VD || isOpenMPCapturedDecl(D));
16081     Vars.push_back(
16082         VD ? RefExpr->IgnoreParens()
16083            : buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false));
16084     SrcExprs.push_back(PseudoSrcExpr);
16085     DstExprs.push_back(PseudoDstExpr);
16086     AssignmentOps.push_back(AssignmentOp.get());
16087   }
16088 
16089   if (Vars.empty())
16090     return nullptr;
16091 
16092   return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
16093                                       Vars, SrcExprs, DstExprs, AssignmentOps);
16094 }
16095 
16096 OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
16097                                         SourceLocation StartLoc,
16098                                         SourceLocation LParenLoc,
16099                                         SourceLocation EndLoc) {
16100   if (VarList.empty())
16101     return nullptr;
16102 
16103   return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList);
16104 }
16105 
16106 /// Tries to find omp_depend_t. type.
16107 static bool findOMPDependT(Sema &S, SourceLocation Loc, DSAStackTy *Stack,
16108                            bool Diagnose = true) {
16109   QualType OMPDependT = Stack->getOMPDependT();
16110   if (!OMPDependT.isNull())
16111     return true;
16112   IdentifierInfo *II = &S.PP.getIdentifierTable().get("omp_depend_t");
16113   ParsedType PT = S.getTypeName(*II, Loc, S.getCurScope());
16114   if (!PT.getAsOpaquePtr() || PT.get().isNull()) {
16115     if (Diagnose)
16116       S.Diag(Loc, diag::err_omp_implied_type_not_found) << "omp_depend_t";
16117     return false;
16118   }
16119   Stack->setOMPDependT(PT.get());
16120   return true;
16121 }
16122 
16123 OMPClause *Sema::ActOnOpenMPDepobjClause(Expr *Depobj, SourceLocation StartLoc,
16124                                          SourceLocation LParenLoc,
16125                                          SourceLocation EndLoc) {
16126   if (!Depobj)
16127     return nullptr;
16128 
16129   bool OMPDependTFound = findOMPDependT(*this, StartLoc, DSAStack);
16130 
16131   // OpenMP 5.0, 2.17.10.1 depobj Construct
16132   // depobj is an lvalue expression of type omp_depend_t.
16133   if (!Depobj->isTypeDependent() && !Depobj->isValueDependent() &&
16134       !Depobj->isInstantiationDependent() &&
16135       !Depobj->containsUnexpandedParameterPack() &&
16136       (OMPDependTFound &&
16137        !Context.typesAreCompatible(DSAStack->getOMPDependT(), Depobj->getType(),
16138                                    /*CompareUnqualified=*/true))) {
16139     Diag(Depobj->getExprLoc(), diag::err_omp_expected_omp_depend_t_lvalue)
16140         << 0 << Depobj->getType() << Depobj->getSourceRange();
16141   }
16142 
16143   if (!Depobj->isLValue()) {
16144     Diag(Depobj->getExprLoc(), diag::err_omp_expected_omp_depend_t_lvalue)
16145         << 1 << Depobj->getSourceRange();
16146   }
16147 
16148   return OMPDepobjClause::Create(Context, StartLoc, LParenLoc, EndLoc, Depobj);
16149 }
16150 
16151 OMPClause *
16152 Sema::ActOnOpenMPDependClause(Expr *DepModifier, OpenMPDependClauseKind DepKind,
16153                               SourceLocation DepLoc, SourceLocation ColonLoc,
16154                               ArrayRef<Expr *> VarList, SourceLocation StartLoc,
16155                               SourceLocation LParenLoc, SourceLocation EndLoc) {
16156   if (DSAStack->getCurrentDirective() == OMPD_ordered &&
16157       DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink) {
16158     Diag(DepLoc, diag::err_omp_unexpected_clause_value)
16159         << "'source' or 'sink'" << getOpenMPClauseName(OMPC_depend);
16160     return nullptr;
16161   }
16162   if ((DSAStack->getCurrentDirective() != OMPD_ordered ||
16163        DSAStack->getCurrentDirective() == OMPD_depobj) &&
16164       (DepKind == OMPC_DEPEND_unknown || DepKind == OMPC_DEPEND_source ||
16165        DepKind == OMPC_DEPEND_sink ||
16166        ((LangOpts.OpenMP < 50 ||
16167          DSAStack->getCurrentDirective() == OMPD_depobj) &&
16168         DepKind == OMPC_DEPEND_depobj))) {
16169     SmallVector<unsigned, 3> Except;
16170     Except.push_back(OMPC_DEPEND_source);
16171     Except.push_back(OMPC_DEPEND_sink);
16172     if (LangOpts.OpenMP < 50 || DSAStack->getCurrentDirective() == OMPD_depobj)
16173       Except.push_back(OMPC_DEPEND_depobj);
16174     std::string Expected = (LangOpts.OpenMP >= 50 && !DepModifier)
16175                                ? "depend modifier(iterator) or "
16176                                : "";
16177     Diag(DepLoc, diag::err_omp_unexpected_clause_value)
16178         << Expected + getListOfPossibleValues(OMPC_depend, /*First=*/0,
16179                                               /*Last=*/OMPC_DEPEND_unknown,
16180                                               Except)
16181         << getOpenMPClauseName(OMPC_depend);
16182     return nullptr;
16183   }
16184   if (DepModifier &&
16185       (DepKind == OMPC_DEPEND_source || DepKind == OMPC_DEPEND_sink)) {
16186     Diag(DepModifier->getExprLoc(),
16187          diag::err_omp_depend_sink_source_with_modifier);
16188     return nullptr;
16189   }
16190   if (DepModifier &&
16191       !DepModifier->getType()->isSpecificBuiltinType(BuiltinType::OMPIterator))
16192     Diag(DepModifier->getExprLoc(), diag::err_omp_depend_modifier_not_iterator);
16193 
16194   SmallVector<Expr *, 8> Vars;
16195   DSAStackTy::OperatorOffsetTy OpsOffs;
16196   llvm::APSInt DepCounter(/*BitWidth=*/32);
16197   llvm::APSInt TotalDepCount(/*BitWidth=*/32);
16198   if (DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) {
16199     if (const Expr *OrderedCountExpr =
16200             DSAStack->getParentOrderedRegionParam().first) {
16201       TotalDepCount = OrderedCountExpr->EvaluateKnownConstInt(Context);
16202       TotalDepCount.setIsUnsigned(/*Val=*/true);
16203     }
16204   }
16205   for (Expr *RefExpr : VarList) {
16206     assert(RefExpr && "NULL expr in OpenMP shared clause.");
16207     if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
16208       // It will be analyzed later.
16209       Vars.push_back(RefExpr);
16210       continue;
16211     }
16212 
16213     SourceLocation ELoc = RefExpr->getExprLoc();
16214     Expr *SimpleExpr = RefExpr->IgnoreParenCasts();
16215     if (DepKind == OMPC_DEPEND_sink) {
16216       if (DSAStack->getParentOrderedRegionParam().first &&
16217           DepCounter >= TotalDepCount) {
16218         Diag(ELoc, diag::err_omp_depend_sink_unexpected_expr);
16219         continue;
16220       }
16221       ++DepCounter;
16222       // OpenMP  [2.13.9, Summary]
16223       // depend(dependence-type : vec), where dependence-type is:
16224       // 'sink' and where vec is the iteration vector, which has the form:
16225       //  x1 [+- d1], x2 [+- d2 ], . . . , xn [+- dn]
16226       // where n is the value specified by the ordered clause in the loop
16227       // directive, xi denotes the loop iteration variable of the i-th nested
16228       // loop associated with the loop directive, and di is a constant
16229       // non-negative integer.
16230       if (CurContext->isDependentContext()) {
16231         // It will be analyzed later.
16232         Vars.push_back(RefExpr);
16233         continue;
16234       }
16235       SimpleExpr = SimpleExpr->IgnoreImplicit();
16236       OverloadedOperatorKind OOK = OO_None;
16237       SourceLocation OOLoc;
16238       Expr *LHS = SimpleExpr;
16239       Expr *RHS = nullptr;
16240       if (auto *BO = dyn_cast<BinaryOperator>(SimpleExpr)) {
16241         OOK = BinaryOperator::getOverloadedOperator(BO->getOpcode());
16242         OOLoc = BO->getOperatorLoc();
16243         LHS = BO->getLHS()->IgnoreParenImpCasts();
16244         RHS = BO->getRHS()->IgnoreParenImpCasts();
16245       } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(SimpleExpr)) {
16246         OOK = OCE->getOperator();
16247         OOLoc = OCE->getOperatorLoc();
16248         LHS = OCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
16249         RHS = OCE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
16250       } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SimpleExpr)) {
16251         OOK = MCE->getMethodDecl()
16252                   ->getNameInfo()
16253                   .getName()
16254                   .getCXXOverloadedOperator();
16255         OOLoc = MCE->getCallee()->getExprLoc();
16256         LHS = MCE->getImplicitObjectArgument()->IgnoreParenImpCasts();
16257         RHS = MCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
16258       }
16259       SourceLocation ELoc;
16260       SourceRange ERange;
16261       auto Res = getPrivateItem(*this, LHS, ELoc, ERange);
16262       if (Res.second) {
16263         // It will be analyzed later.
16264         Vars.push_back(RefExpr);
16265       }
16266       ValueDecl *D = Res.first;
16267       if (!D)
16268         continue;
16269 
16270       if (OOK != OO_Plus && OOK != OO_Minus && (RHS || OOK != OO_None)) {
16271         Diag(OOLoc, diag::err_omp_depend_sink_expected_plus_minus);
16272         continue;
16273       }
16274       if (RHS) {
16275         ExprResult RHSRes = VerifyPositiveIntegerConstantInClause(
16276             RHS, OMPC_depend, /*StrictlyPositive=*/false);
16277         if (RHSRes.isInvalid())
16278           continue;
16279       }
16280       if (!CurContext->isDependentContext() &&
16281           DSAStack->getParentOrderedRegionParam().first &&
16282           DepCounter != DSAStack->isParentLoopControlVariable(D).first) {
16283         const ValueDecl *VD =
16284             DSAStack->getParentLoopControlVariable(DepCounter.getZExtValue());
16285         if (VD)
16286           Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration)
16287               << 1 << VD;
16288         else
16289           Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration) << 0;
16290         continue;
16291       }
16292       OpsOffs.emplace_back(RHS, OOK);
16293     } else {
16294       bool OMPDependTFound = LangOpts.OpenMP >= 50;
16295       if (OMPDependTFound)
16296         OMPDependTFound = findOMPDependT(*this, StartLoc, DSAStack,
16297                                          DepKind == OMPC_DEPEND_depobj);
16298       if (DepKind == OMPC_DEPEND_depobj) {
16299         // OpenMP 5.0, 2.17.11 depend Clause, Restrictions, C/C++
16300         // List items used in depend clauses with the depobj dependence type
16301         // must be expressions of the omp_depend_t type.
16302         if (!RefExpr->isValueDependent() && !RefExpr->isTypeDependent() &&
16303             !RefExpr->isInstantiationDependent() &&
16304             !RefExpr->containsUnexpandedParameterPack() &&
16305             (OMPDependTFound &&
16306              !Context.hasSameUnqualifiedType(DSAStack->getOMPDependT(),
16307                                              RefExpr->getType()))) {
16308           Diag(ELoc, diag::err_omp_expected_omp_depend_t_lvalue)
16309               << 0 << RefExpr->getType() << RefExpr->getSourceRange();
16310           continue;
16311         }
16312         if (!RefExpr->isLValue()) {
16313           Diag(ELoc, diag::err_omp_expected_omp_depend_t_lvalue)
16314               << 1 << RefExpr->getType() << RefExpr->getSourceRange();
16315           continue;
16316         }
16317       } else {
16318         // OpenMP 5.0 [2.17.11, Restrictions]
16319         // List items used in depend clauses cannot be zero-length array
16320         // sections.
16321         QualType ExprTy = RefExpr->getType().getNonReferenceType();
16322         const auto *OASE = dyn_cast<OMPArraySectionExpr>(SimpleExpr);
16323         if (OASE) {
16324           QualType BaseType =
16325               OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
16326           if (const auto *ATy = BaseType->getAsArrayTypeUnsafe())
16327             ExprTy = ATy->getElementType();
16328           else
16329             ExprTy = BaseType->getPointeeType();
16330           ExprTy = ExprTy.getNonReferenceType();
16331           const Expr *Length = OASE->getLength();
16332           Expr::EvalResult Result;
16333           if (Length && !Length->isValueDependent() &&
16334               Length->EvaluateAsInt(Result, Context) &&
16335               Result.Val.getInt().isNullValue()) {
16336             Diag(ELoc,
16337                  diag::err_omp_depend_zero_length_array_section_not_allowed)
16338                 << SimpleExpr->getSourceRange();
16339             continue;
16340           }
16341         }
16342 
16343         // OpenMP 5.0, 2.17.11 depend Clause, Restrictions, C/C++
16344         // List items used in depend clauses with the in, out, inout or
16345         // mutexinoutset dependence types cannot be expressions of the
16346         // omp_depend_t type.
16347         if (!RefExpr->isValueDependent() && !RefExpr->isTypeDependent() &&
16348             !RefExpr->isInstantiationDependent() &&
16349             !RefExpr->containsUnexpandedParameterPack() &&
16350             (OMPDependTFound &&
16351              DSAStack->getOMPDependT().getTypePtr() == ExprTy.getTypePtr())) {
16352           Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
16353               << (LangOpts.OpenMP >= 50 ? 1 : 0) << 1
16354               << RefExpr->getSourceRange();
16355           continue;
16356         }
16357 
16358         auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr);
16359         if (!RefExpr->IgnoreParenImpCasts()->isLValue() ||
16360             (ASE && !ASE->getBase()->isTypeDependent() &&
16361              !ASE->getBase()
16362                   ->getType()
16363                   .getNonReferenceType()
16364                   ->isPointerType() &&
16365              !ASE->getBase()->getType().getNonReferenceType()->isArrayType())) {
16366           Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
16367               << (LangOpts.OpenMP >= 50 ? 1 : 0)
16368               << (LangOpts.OpenMP >= 50 ? 1 : 0) << RefExpr->getSourceRange();
16369           continue;
16370         }
16371 
16372         ExprResult Res;
16373         {
16374           Sema::TentativeAnalysisScope Trap(*this);
16375           Res = CreateBuiltinUnaryOp(ELoc, UO_AddrOf,
16376                                      RefExpr->IgnoreParenImpCasts());
16377         }
16378         if (!Res.isUsable() && !isa<OMPArraySectionExpr>(SimpleExpr) &&
16379             !isa<OMPArrayShapingExpr>(SimpleExpr)) {
16380           Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
16381               << (LangOpts.OpenMP >= 50 ? 1 : 0)
16382               << (LangOpts.OpenMP >= 50 ? 1 : 0) << RefExpr->getSourceRange();
16383           continue;
16384         }
16385       }
16386     }
16387     Vars.push_back(RefExpr->IgnoreParenImpCasts());
16388   }
16389 
16390   if (!CurContext->isDependentContext() && DepKind == OMPC_DEPEND_sink &&
16391       TotalDepCount > VarList.size() &&
16392       DSAStack->getParentOrderedRegionParam().first &&
16393       DSAStack->getParentLoopControlVariable(VarList.size() + 1)) {
16394     Diag(EndLoc, diag::err_omp_depend_sink_expected_loop_iteration)
16395         << 1 << DSAStack->getParentLoopControlVariable(VarList.size() + 1);
16396   }
16397   if (DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink &&
16398       Vars.empty())
16399     return nullptr;
16400 
16401   auto *C = OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc,
16402                                     DepModifier, DepKind, DepLoc, ColonLoc,
16403                                     Vars, TotalDepCount.getZExtValue());
16404   if ((DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) &&
16405       DSAStack->isParentOrderedRegion())
16406     DSAStack->addDoacrossDependClause(C, OpsOffs);
16407   return C;
16408 }
16409 
16410 OMPClause *Sema::ActOnOpenMPDeviceClause(OpenMPDeviceClauseModifier Modifier,
16411                                          Expr *Device, SourceLocation StartLoc,
16412                                          SourceLocation LParenLoc,
16413                                          SourceLocation ModifierLoc,
16414                                          SourceLocation EndLoc) {
16415   assert((ModifierLoc.isInvalid() || LangOpts.OpenMP >= 50) &&
16416          "Unexpected device modifier in OpenMP < 50.");
16417 
16418   bool ErrorFound = false;
16419   if (ModifierLoc.isValid() && Modifier == OMPC_DEVICE_unknown) {
16420     std::string Values =
16421         getListOfPossibleValues(OMPC_device, /*First=*/0, OMPC_DEVICE_unknown);
16422     Diag(ModifierLoc, diag::err_omp_unexpected_clause_value)
16423         << Values << getOpenMPClauseName(OMPC_device);
16424     ErrorFound = true;
16425   }
16426 
16427   Expr *ValExpr = Device;
16428   Stmt *HelperValStmt = nullptr;
16429 
16430   // OpenMP [2.9.1, Restrictions]
16431   // The device expression must evaluate to a non-negative integer value.
16432   ErrorFound = !isNonNegativeIntegerValue(ValExpr, *this, OMPC_device,
16433                                           /*StrictlyPositive=*/false) ||
16434                ErrorFound;
16435   if (ErrorFound)
16436     return nullptr;
16437 
16438   OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
16439   OpenMPDirectiveKind CaptureRegion =
16440       getOpenMPCaptureRegionForClause(DKind, OMPC_device, LangOpts.OpenMP);
16441   if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
16442     ValExpr = MakeFullExpr(ValExpr).get();
16443     llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
16444     ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
16445     HelperValStmt = buildPreInits(Context, Captures);
16446   }
16447 
16448   return new (Context)
16449       OMPDeviceClause(Modifier, ValExpr, HelperValStmt, CaptureRegion, StartLoc,
16450                       LParenLoc, ModifierLoc, EndLoc);
16451 }
16452 
16453 static bool checkTypeMappable(SourceLocation SL, SourceRange SR, Sema &SemaRef,
16454                               DSAStackTy *Stack, QualType QTy,
16455                               bool FullCheck = true) {
16456   NamedDecl *ND;
16457   if (QTy->isIncompleteType(&ND)) {
16458     SemaRef.Diag(SL, diag::err_incomplete_type) << QTy << SR;
16459     return false;
16460   }
16461   if (FullCheck && !SemaRef.CurContext->isDependentContext() &&
16462       !QTy.isTriviallyCopyableType(SemaRef.Context))
16463     SemaRef.Diag(SL, diag::warn_omp_non_trivial_type_mapped) << QTy << SR;
16464   return true;
16465 }
16466 
16467 /// Return true if it can be proven that the provided array expression
16468 /// (array section or array subscript) does NOT specify the whole size of the
16469 /// array whose base type is \a BaseQTy.
16470 static bool checkArrayExpressionDoesNotReferToWholeSize(Sema &SemaRef,
16471                                                         const Expr *E,
16472                                                         QualType BaseQTy) {
16473   const auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
16474 
16475   // If this is an array subscript, it refers to the whole size if the size of
16476   // the dimension is constant and equals 1. Also, an array section assumes the
16477   // format of an array subscript if no colon is used.
16478   if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid())) {
16479     if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
16480       return ATy->getSize().getSExtValue() != 1;
16481     // Size can't be evaluated statically.
16482     return false;
16483   }
16484 
16485   assert(OASE && "Expecting array section if not an array subscript.");
16486   const Expr *LowerBound = OASE->getLowerBound();
16487   const Expr *Length = OASE->getLength();
16488 
16489   // If there is a lower bound that does not evaluates to zero, we are not
16490   // covering the whole dimension.
16491   if (LowerBound) {
16492     Expr::EvalResult Result;
16493     if (!LowerBound->EvaluateAsInt(Result, SemaRef.getASTContext()))
16494       return false; // Can't get the integer value as a constant.
16495 
16496     llvm::APSInt ConstLowerBound = Result.Val.getInt();
16497     if (ConstLowerBound.getSExtValue())
16498       return true;
16499   }
16500 
16501   // If we don't have a length we covering the whole dimension.
16502   if (!Length)
16503     return false;
16504 
16505   // If the base is a pointer, we don't have a way to get the size of the
16506   // pointee.
16507   if (BaseQTy->isPointerType())
16508     return false;
16509 
16510   // We can only check if the length is the same as the size of the dimension
16511   // if we have a constant array.
16512   const auto *CATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr());
16513   if (!CATy)
16514     return false;
16515 
16516   Expr::EvalResult Result;
16517   if (!Length->EvaluateAsInt(Result, SemaRef.getASTContext()))
16518     return false; // Can't get the integer value as a constant.
16519 
16520   llvm::APSInt ConstLength = Result.Val.getInt();
16521   return CATy->getSize().getSExtValue() != ConstLength.getSExtValue();
16522 }
16523 
16524 // Return true if it can be proven that the provided array expression (array
16525 // section or array subscript) does NOT specify a single element of the array
16526 // whose base type is \a BaseQTy.
16527 static bool checkArrayExpressionDoesNotReferToUnitySize(Sema &SemaRef,
16528                                                         const Expr *E,
16529                                                         QualType BaseQTy) {
16530   const auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
16531 
16532   // An array subscript always refer to a single element. Also, an array section
16533   // assumes the format of an array subscript if no colon is used.
16534   if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid()))
16535     return false;
16536 
16537   assert(OASE && "Expecting array section if not an array subscript.");
16538   const Expr *Length = OASE->getLength();
16539 
16540   // If we don't have a length we have to check if the array has unitary size
16541   // for this dimension. Also, we should always expect a length if the base type
16542   // is pointer.
16543   if (!Length) {
16544     if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
16545       return ATy->getSize().getSExtValue() != 1;
16546     // We cannot assume anything.
16547     return false;
16548   }
16549 
16550   // Check if the length evaluates to 1.
16551   Expr::EvalResult Result;
16552   if (!Length->EvaluateAsInt(Result, SemaRef.getASTContext()))
16553     return false; // Can't get the integer value as a constant.
16554 
16555   llvm::APSInt ConstLength = Result.Val.getInt();
16556   return ConstLength.getSExtValue() != 1;
16557 }
16558 
16559 // The base of elements of list in a map clause have to be either:
16560 //  - a reference to variable or field.
16561 //  - a member expression.
16562 //  - an array expression.
16563 //
16564 // E.g. if we have the expression 'r.S.Arr[:12]', we want to retrieve the
16565 // reference to 'r'.
16566 //
16567 // If we have:
16568 //
16569 // struct SS {
16570 //   Bla S;
16571 //   foo() {
16572 //     #pragma omp target map (S.Arr[:12]);
16573 //   }
16574 // }
16575 //
16576 // We want to retrieve the member expression 'this->S';
16577 
16578 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.2]
16579 //  If a list item is an array section, it must specify contiguous storage.
16580 //
16581 // For this restriction it is sufficient that we make sure only references
16582 // to variables or fields and array expressions, and that no array sections
16583 // exist except in the rightmost expression (unless they cover the whole
16584 // dimension of the array). E.g. these would be invalid:
16585 //
16586 //   r.ArrS[3:5].Arr[6:7]
16587 //
16588 //   r.ArrS[3:5].x
16589 //
16590 // but these would be valid:
16591 //   r.ArrS[3].Arr[6:7]
16592 //
16593 //   r.ArrS[3].x
16594 namespace {
16595 class MapBaseChecker final : public StmtVisitor<MapBaseChecker, bool> {
16596   Sema &SemaRef;
16597   OpenMPClauseKind CKind = OMPC_unknown;
16598   OMPClauseMappableExprCommon::MappableExprComponentList &Components;
16599   bool NoDiagnose = false;
16600   const Expr *RelevantExpr = nullptr;
16601   bool AllowUnitySizeArraySection = true;
16602   bool AllowWholeSizeArraySection = true;
16603   SourceLocation ELoc;
16604   SourceRange ERange;
16605 
16606   void emitErrorMsg() {
16607     // If nothing else worked, this is not a valid map clause expression.
16608     if (SemaRef.getLangOpts().OpenMP < 50) {
16609       SemaRef.Diag(ELoc,
16610                    diag::err_omp_expected_named_var_member_or_array_expression)
16611           << ERange;
16612     } else {
16613       SemaRef.Diag(ELoc, diag::err_omp_non_lvalue_in_map_or_motion_clauses)
16614           << getOpenMPClauseName(CKind) << ERange;
16615     }
16616   }
16617 
16618 public:
16619   bool VisitDeclRefExpr(DeclRefExpr *DRE) {
16620     if (!isa<VarDecl>(DRE->getDecl())) {
16621       emitErrorMsg();
16622       return false;
16623     }
16624     assert(!RelevantExpr && "RelevantExpr is expected to be nullptr");
16625     RelevantExpr = DRE;
16626     // Record the component.
16627     Components.emplace_back(DRE, DRE->getDecl());
16628     return true;
16629   }
16630 
16631   bool VisitMemberExpr(MemberExpr *ME) {
16632     Expr *E = ME;
16633     Expr *BaseE = ME->getBase()->IgnoreParenCasts();
16634 
16635     if (isa<CXXThisExpr>(BaseE)) {
16636       assert(!RelevantExpr && "RelevantExpr is expected to be nullptr");
16637       // We found a base expression: this->Val.
16638       RelevantExpr = ME;
16639     } else {
16640       E = BaseE;
16641     }
16642 
16643     if (!isa<FieldDecl>(ME->getMemberDecl())) {
16644       if (!NoDiagnose) {
16645         SemaRef.Diag(ELoc, diag::err_omp_expected_access_to_data_field)
16646           << ME->getSourceRange();
16647         return false;
16648       }
16649       if (RelevantExpr)
16650         return false;
16651       return Visit(E);
16652     }
16653 
16654     auto *FD = cast<FieldDecl>(ME->getMemberDecl());
16655 
16656     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
16657     //  A bit-field cannot appear in a map clause.
16658     //
16659     if (FD->isBitField()) {
16660       if (!NoDiagnose) {
16661         SemaRef.Diag(ELoc, diag::err_omp_bit_fields_forbidden_in_clause)
16662           << ME->getSourceRange() << getOpenMPClauseName(CKind);
16663         return false;
16664       }
16665       if (RelevantExpr)
16666         return false;
16667       return Visit(E);
16668     }
16669 
16670     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
16671     //  If the type of a list item is a reference to a type T then the type
16672     //  will be considered to be T for all purposes of this clause.
16673     QualType CurType = BaseE->getType().getNonReferenceType();
16674 
16675     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.2]
16676     //  A list item cannot be a variable that is a member of a structure with
16677     //  a union type.
16678     //
16679     if (CurType->isUnionType()) {
16680       if (!NoDiagnose) {
16681         SemaRef.Diag(ELoc, diag::err_omp_union_type_not_allowed)
16682           << ME->getSourceRange();
16683         return false;
16684       }
16685       return RelevantExpr || Visit(E);
16686     }
16687 
16688     // If we got a member expression, we should not expect any array section
16689     // before that:
16690     //
16691     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.7]
16692     //  If a list item is an element of a structure, only the rightmost symbol
16693     //  of the variable reference can be an array section.
16694     //
16695     AllowUnitySizeArraySection = false;
16696     AllowWholeSizeArraySection = false;
16697 
16698     // Record the component.
16699     Components.emplace_back(ME, FD);
16700     return RelevantExpr || Visit(E);
16701   }
16702 
16703   bool VisitArraySubscriptExpr(ArraySubscriptExpr *AE) {
16704     Expr *E = AE->getBase()->IgnoreParenImpCasts();
16705 
16706     if (!E->getType()->isAnyPointerType() && !E->getType()->isArrayType()) {
16707       if (!NoDiagnose) {
16708         SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
16709           << 0 << AE->getSourceRange();
16710         return false;
16711       }
16712       return RelevantExpr || Visit(E);
16713     }
16714 
16715     // If we got an array subscript that express the whole dimension we
16716     // can have any array expressions before. If it only expressing part of
16717     // the dimension, we can only have unitary-size array expressions.
16718     if (checkArrayExpressionDoesNotReferToWholeSize(SemaRef, AE,
16719                                                     E->getType()))
16720       AllowWholeSizeArraySection = false;
16721 
16722     if (const auto *TE = dyn_cast<CXXThisExpr>(E->IgnoreParenCasts())) {
16723       Expr::EvalResult Result;
16724       if (!AE->getIdx()->isValueDependent() &&
16725           AE->getIdx()->EvaluateAsInt(Result, SemaRef.getASTContext()) &&
16726           !Result.Val.getInt().isNullValue()) {
16727         SemaRef.Diag(AE->getIdx()->getExprLoc(),
16728                      diag::err_omp_invalid_map_this_expr);
16729         SemaRef.Diag(AE->getIdx()->getExprLoc(),
16730                      diag::note_omp_invalid_subscript_on_this_ptr_map);
16731       }
16732       assert(!RelevantExpr && "RelevantExpr is expected to be nullptr");
16733       RelevantExpr = TE;
16734     }
16735 
16736     // Record the component - we don't have any declaration associated.
16737     Components.emplace_back(AE, nullptr);
16738 
16739     return RelevantExpr || Visit(E);
16740   }
16741 
16742   bool VisitOMPArraySectionExpr(OMPArraySectionExpr *OASE) {
16743     assert(!NoDiagnose && "Array sections cannot be implicitly mapped.");
16744     Expr *E = OASE->getBase()->IgnoreParenImpCasts();
16745     QualType CurType =
16746       OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
16747 
16748     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
16749     //  If the type of a list item is a reference to a type T then the type
16750     //  will be considered to be T for all purposes of this clause.
16751     if (CurType->isReferenceType())
16752       CurType = CurType->getPointeeType();
16753 
16754     bool IsPointer = CurType->isAnyPointerType();
16755 
16756     if (!IsPointer && !CurType->isArrayType()) {
16757       SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
16758         << 0 << OASE->getSourceRange();
16759       return false;
16760     }
16761 
16762     bool NotWhole =
16763       checkArrayExpressionDoesNotReferToWholeSize(SemaRef, OASE, CurType);
16764     bool NotUnity =
16765       checkArrayExpressionDoesNotReferToUnitySize(SemaRef, OASE, CurType);
16766 
16767     if (AllowWholeSizeArraySection) {
16768       // Any array section is currently allowed. Allowing a whole size array
16769       // section implies allowing a unity array section as well.
16770       //
16771       // If this array section refers to the whole dimension we can still
16772       // accept other array sections before this one, except if the base is a
16773       // pointer. Otherwise, only unitary sections are accepted.
16774       if (NotWhole || IsPointer)
16775         AllowWholeSizeArraySection = false;
16776     } else if (AllowUnitySizeArraySection && NotUnity) {
16777       // A unity or whole array section is not allowed and that is not
16778       // compatible with the properties of the current array section.
16779       SemaRef.Diag(
16780         ELoc, diag::err_array_section_does_not_specify_contiguous_storage)
16781         << OASE->getSourceRange();
16782       return false;
16783     }
16784 
16785     if (const auto *TE = dyn_cast<CXXThisExpr>(E)) {
16786       Expr::EvalResult ResultR;
16787       Expr::EvalResult ResultL;
16788       if (!OASE->getLength()->isValueDependent() &&
16789           OASE->getLength()->EvaluateAsInt(ResultR, SemaRef.getASTContext()) &&
16790           !ResultR.Val.getInt().isOneValue()) {
16791         SemaRef.Diag(OASE->getLength()->getExprLoc(),
16792                      diag::err_omp_invalid_map_this_expr);
16793         SemaRef.Diag(OASE->getLength()->getExprLoc(),
16794                      diag::note_omp_invalid_length_on_this_ptr_mapping);
16795       }
16796       if (OASE->getLowerBound() && !OASE->getLowerBound()->isValueDependent() &&
16797           OASE->getLowerBound()->EvaluateAsInt(ResultL,
16798                                                SemaRef.getASTContext()) &&
16799           !ResultL.Val.getInt().isNullValue()) {
16800         SemaRef.Diag(OASE->getLowerBound()->getExprLoc(),
16801                      diag::err_omp_invalid_map_this_expr);
16802         SemaRef.Diag(OASE->getLowerBound()->getExprLoc(),
16803                      diag::note_omp_invalid_lower_bound_on_this_ptr_mapping);
16804       }
16805       assert(!RelevantExpr && "RelevantExpr is expected to be nullptr");
16806       RelevantExpr = TE;
16807     }
16808 
16809     // Record the component - we don't have any declaration associated.
16810     Components.emplace_back(OASE, nullptr);
16811     return RelevantExpr || Visit(E);
16812   }
16813   bool VisitOMPArrayShapingExpr(OMPArrayShapingExpr *E) {
16814     Expr *Base = E->getBase();
16815 
16816     // Record the component - we don't have any declaration associated.
16817     Components.emplace_back(E, nullptr);
16818 
16819     return Visit(Base->IgnoreParenImpCasts());
16820   }
16821 
16822   bool VisitUnaryOperator(UnaryOperator *UO) {
16823     if (SemaRef.getLangOpts().OpenMP < 50 || !UO->isLValue() ||
16824         UO->getOpcode() != UO_Deref) {
16825       emitErrorMsg();
16826       return false;
16827     }
16828     if (!RelevantExpr) {
16829       // Record the component if haven't found base decl.
16830       Components.emplace_back(UO, nullptr);
16831     }
16832     return RelevantExpr || Visit(UO->getSubExpr()->IgnoreParenImpCasts());
16833   }
16834   bool VisitBinaryOperator(BinaryOperator *BO) {
16835     if (SemaRef.getLangOpts().OpenMP < 50 || !BO->getType()->isPointerType()) {
16836       emitErrorMsg();
16837       return false;
16838     }
16839 
16840     // Pointer arithmetic is the only thing we expect to happen here so after we
16841     // make sure the binary operator is a pointer type, the we only thing need
16842     // to to is to visit the subtree that has the same type as root (so that we
16843     // know the other subtree is just an offset)
16844     Expr *LE = BO->getLHS()->IgnoreParenImpCasts();
16845     Expr *RE = BO->getRHS()->IgnoreParenImpCasts();
16846     Components.emplace_back(BO, nullptr);
16847     assert((LE->getType().getTypePtr() == BO->getType().getTypePtr() ||
16848             RE->getType().getTypePtr() == BO->getType().getTypePtr()) &&
16849            "Either LHS or RHS have base decl inside");
16850     if (BO->getType().getTypePtr() == LE->getType().getTypePtr())
16851       return RelevantExpr || Visit(LE);
16852     return RelevantExpr || Visit(RE);
16853   }
16854   bool VisitCXXThisExpr(CXXThisExpr *CTE) {
16855     assert(!RelevantExpr && "RelevantExpr is expected to be nullptr");
16856     RelevantExpr = CTE;
16857     Components.emplace_back(CTE, nullptr);
16858     return true;
16859   }
16860   bool VisitStmt(Stmt *) {
16861     emitErrorMsg();
16862     return false;
16863   }
16864   const Expr *getFoundBase() const {
16865     return RelevantExpr;
16866   }
16867   explicit MapBaseChecker(
16868       Sema &SemaRef, OpenMPClauseKind CKind,
16869       OMPClauseMappableExprCommon::MappableExprComponentList &Components,
16870       bool NoDiagnose, SourceLocation &ELoc, SourceRange &ERange)
16871       : SemaRef(SemaRef), CKind(CKind), Components(Components),
16872         NoDiagnose(NoDiagnose), ELoc(ELoc), ERange(ERange) {}
16873 };
16874 } // namespace
16875 
16876 /// Return the expression of the base of the mappable expression or null if it
16877 /// cannot be determined and do all the necessary checks to see if the expression
16878 /// is valid as a standalone mappable expression. In the process, record all the
16879 /// components of the expression.
16880 static const Expr *checkMapClauseExpressionBase(
16881     Sema &SemaRef, Expr *E,
16882     OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
16883     OpenMPClauseKind CKind, bool NoDiagnose) {
16884   SourceLocation ELoc = E->getExprLoc();
16885   SourceRange ERange = E->getSourceRange();
16886   MapBaseChecker Checker(SemaRef, CKind, CurComponents, NoDiagnose, ELoc,
16887                          ERange);
16888   if (Checker.Visit(E->IgnoreParens()))
16889     return Checker.getFoundBase();
16890   return nullptr;
16891 }
16892 
16893 // Return true if expression E associated with value VD has conflicts with other
16894 // map information.
16895 static bool checkMapConflicts(
16896     Sema &SemaRef, DSAStackTy *DSAS, const ValueDecl *VD, const Expr *E,
16897     bool CurrentRegionOnly,
16898     OMPClauseMappableExprCommon::MappableExprComponentListRef CurComponents,
16899     OpenMPClauseKind CKind) {
16900   assert(VD && E);
16901   SourceLocation ELoc = E->getExprLoc();
16902   SourceRange ERange = E->getSourceRange();
16903 
16904   // In order to easily check the conflicts we need to match each component of
16905   // the expression under test with the components of the expressions that are
16906   // already in the stack.
16907 
16908   assert(!CurComponents.empty() && "Map clause expression with no components!");
16909   assert(CurComponents.back().getAssociatedDeclaration() == VD &&
16910          "Map clause expression with unexpected base!");
16911 
16912   // Variables to help detecting enclosing problems in data environment nests.
16913   bool IsEnclosedByDataEnvironmentExpr = false;
16914   const Expr *EnclosingExpr = nullptr;
16915 
16916   bool FoundError = DSAS->checkMappableExprComponentListsForDecl(
16917       VD, CurrentRegionOnly,
16918       [&IsEnclosedByDataEnvironmentExpr, &SemaRef, VD, CurrentRegionOnly, ELoc,
16919        ERange, CKind, &EnclosingExpr,
16920        CurComponents](OMPClauseMappableExprCommon::MappableExprComponentListRef
16921                           StackComponents,
16922                       OpenMPClauseKind) {
16923         assert(!StackComponents.empty() &&
16924                "Map clause expression with no components!");
16925         assert(StackComponents.back().getAssociatedDeclaration() == VD &&
16926                "Map clause expression with unexpected base!");
16927         (void)VD;
16928 
16929         // The whole expression in the stack.
16930         const Expr *RE = StackComponents.front().getAssociatedExpression();
16931 
16932         // Expressions must start from the same base. Here we detect at which
16933         // point both expressions diverge from each other and see if we can
16934         // detect if the memory referred to both expressions is contiguous and
16935         // do not overlap.
16936         auto CI = CurComponents.rbegin();
16937         auto CE = CurComponents.rend();
16938         auto SI = StackComponents.rbegin();
16939         auto SE = StackComponents.rend();
16940         for (; CI != CE && SI != SE; ++CI, ++SI) {
16941 
16942           // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.3]
16943           //  At most one list item can be an array item derived from a given
16944           //  variable in map clauses of the same construct.
16945           if (CurrentRegionOnly &&
16946               (isa<ArraySubscriptExpr>(CI->getAssociatedExpression()) ||
16947                isa<OMPArraySectionExpr>(CI->getAssociatedExpression()) ||
16948                isa<OMPArrayShapingExpr>(CI->getAssociatedExpression())) &&
16949               (isa<ArraySubscriptExpr>(SI->getAssociatedExpression()) ||
16950                isa<OMPArraySectionExpr>(SI->getAssociatedExpression()) ||
16951                isa<OMPArrayShapingExpr>(SI->getAssociatedExpression()))) {
16952             SemaRef.Diag(CI->getAssociatedExpression()->getExprLoc(),
16953                          diag::err_omp_multiple_array_items_in_map_clause)
16954                 << CI->getAssociatedExpression()->getSourceRange();
16955             SemaRef.Diag(SI->getAssociatedExpression()->getExprLoc(),
16956                          diag::note_used_here)
16957                 << SI->getAssociatedExpression()->getSourceRange();
16958             return true;
16959           }
16960 
16961           // Do both expressions have the same kind?
16962           if (CI->getAssociatedExpression()->getStmtClass() !=
16963               SI->getAssociatedExpression()->getStmtClass())
16964             break;
16965 
16966           // Are we dealing with different variables/fields?
16967           if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration())
16968             break;
16969         }
16970         // Check if the extra components of the expressions in the enclosing
16971         // data environment are redundant for the current base declaration.
16972         // If they are, the maps completely overlap, which is legal.
16973         for (; SI != SE; ++SI) {
16974           QualType Type;
16975           if (const auto *ASE =
16976                   dyn_cast<ArraySubscriptExpr>(SI->getAssociatedExpression())) {
16977             Type = ASE->getBase()->IgnoreParenImpCasts()->getType();
16978           } else if (const auto *OASE = dyn_cast<OMPArraySectionExpr>(
16979                          SI->getAssociatedExpression())) {
16980             const Expr *E = OASE->getBase()->IgnoreParenImpCasts();
16981             Type =
16982                 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
16983           } else if (const auto *OASE = dyn_cast<OMPArrayShapingExpr>(
16984                          SI->getAssociatedExpression())) {
16985             Type = OASE->getBase()->getType()->getPointeeType();
16986           }
16987           if (Type.isNull() || Type->isAnyPointerType() ||
16988               checkArrayExpressionDoesNotReferToWholeSize(
16989                   SemaRef, SI->getAssociatedExpression(), Type))
16990             break;
16991         }
16992 
16993         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
16994         //  List items of map clauses in the same construct must not share
16995         //  original storage.
16996         //
16997         // If the expressions are exactly the same or one is a subset of the
16998         // other, it means they are sharing storage.
16999         if (CI == CE && SI == SE) {
17000           if (CurrentRegionOnly) {
17001             if (CKind == OMPC_map) {
17002               SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
17003             } else {
17004               assert(CKind == OMPC_to || CKind == OMPC_from);
17005               SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
17006                   << ERange;
17007             }
17008             SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
17009                 << RE->getSourceRange();
17010             return true;
17011           }
17012           // If we find the same expression in the enclosing data environment,
17013           // that is legal.
17014           IsEnclosedByDataEnvironmentExpr = true;
17015           return false;
17016         }
17017 
17018         QualType DerivedType =
17019             std::prev(CI)->getAssociatedDeclaration()->getType();
17020         SourceLocation DerivedLoc =
17021             std::prev(CI)->getAssociatedExpression()->getExprLoc();
17022 
17023         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
17024         //  If the type of a list item is a reference to a type T then the type
17025         //  will be considered to be T for all purposes of this clause.
17026         DerivedType = DerivedType.getNonReferenceType();
17027 
17028         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.1]
17029         //  A variable for which the type is pointer and an array section
17030         //  derived from that variable must not appear as list items of map
17031         //  clauses of the same construct.
17032         //
17033         // Also, cover one of the cases in:
17034         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
17035         //  If any part of the original storage of a list item has corresponding
17036         //  storage in the device data environment, all of the original storage
17037         //  must have corresponding storage in the device data environment.
17038         //
17039         if (DerivedType->isAnyPointerType()) {
17040           if (CI == CE || SI == SE) {
17041             SemaRef.Diag(
17042                 DerivedLoc,
17043                 diag::err_omp_pointer_mapped_along_with_derived_section)
17044                 << DerivedLoc;
17045             SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
17046                 << RE->getSourceRange();
17047             return true;
17048           }
17049           if (CI->getAssociatedExpression()->getStmtClass() !=
17050                          SI->getAssociatedExpression()->getStmtClass() ||
17051                      CI->getAssociatedDeclaration()->getCanonicalDecl() ==
17052                          SI->getAssociatedDeclaration()->getCanonicalDecl()) {
17053             assert(CI != CE && SI != SE);
17054             SemaRef.Diag(DerivedLoc, diag::err_omp_same_pointer_dereferenced)
17055                 << DerivedLoc;
17056             SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
17057                 << RE->getSourceRange();
17058             return true;
17059           }
17060         }
17061 
17062         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
17063         //  List items of map clauses in the same construct must not share
17064         //  original storage.
17065         //
17066         // An expression is a subset of the other.
17067         if (CurrentRegionOnly && (CI == CE || SI == SE)) {
17068           if (CKind == OMPC_map) {
17069             if (CI != CE || SI != SE) {
17070               // Allow constructs like this: map(s, s.ptr[0:1]), where s.ptr is
17071               // a pointer.
17072               auto Begin =
17073                   CI != CE ? CurComponents.begin() : StackComponents.begin();
17074               auto End = CI != CE ? CurComponents.end() : StackComponents.end();
17075               auto It = Begin;
17076               while (It != End && !It->getAssociatedDeclaration())
17077                 std::advance(It, 1);
17078               assert(It != End &&
17079                      "Expected at least one component with the declaration.");
17080               if (It != Begin && It->getAssociatedDeclaration()
17081                                      ->getType()
17082                                      .getCanonicalType()
17083                                      ->isAnyPointerType()) {
17084                 IsEnclosedByDataEnvironmentExpr = false;
17085                 EnclosingExpr = nullptr;
17086                 return false;
17087               }
17088             }
17089             SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
17090           } else {
17091             assert(CKind == OMPC_to || CKind == OMPC_from);
17092             SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
17093                 << ERange;
17094           }
17095           SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
17096               << RE->getSourceRange();
17097           return true;
17098         }
17099 
17100         // The current expression uses the same base as other expression in the
17101         // data environment but does not contain it completely.
17102         if (!CurrentRegionOnly && SI != SE)
17103           EnclosingExpr = RE;
17104 
17105         // The current expression is a subset of the expression in the data
17106         // environment.
17107         IsEnclosedByDataEnvironmentExpr |=
17108             (!CurrentRegionOnly && CI != CE && SI == SE);
17109 
17110         return false;
17111       });
17112 
17113   if (CurrentRegionOnly)
17114     return FoundError;
17115 
17116   // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
17117   //  If any part of the original storage of a list item has corresponding
17118   //  storage in the device data environment, all of the original storage must
17119   //  have corresponding storage in the device data environment.
17120   // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.6]
17121   //  If a list item is an element of a structure, and a different element of
17122   //  the structure has a corresponding list item in the device data environment
17123   //  prior to a task encountering the construct associated with the map clause,
17124   //  then the list item must also have a corresponding list item in the device
17125   //  data environment prior to the task encountering the construct.
17126   //
17127   if (EnclosingExpr && !IsEnclosedByDataEnvironmentExpr) {
17128     SemaRef.Diag(ELoc,
17129                  diag::err_omp_original_storage_is_shared_and_does_not_contain)
17130         << ERange;
17131     SemaRef.Diag(EnclosingExpr->getExprLoc(), diag::note_used_here)
17132         << EnclosingExpr->getSourceRange();
17133     return true;
17134   }
17135 
17136   return FoundError;
17137 }
17138 
17139 // Look up the user-defined mapper given the mapper name and mapped type, and
17140 // build a reference to it.
17141 static ExprResult buildUserDefinedMapperRef(Sema &SemaRef, Scope *S,
17142                                             CXXScopeSpec &MapperIdScopeSpec,
17143                                             const DeclarationNameInfo &MapperId,
17144                                             QualType Type,
17145                                             Expr *UnresolvedMapper) {
17146   if (MapperIdScopeSpec.isInvalid())
17147     return ExprError();
17148   // Get the actual type for the array type.
17149   if (Type->isArrayType()) {
17150     assert(Type->getAsArrayTypeUnsafe() && "Expect to get a valid array type");
17151     Type = Type->getAsArrayTypeUnsafe()->getElementType().getCanonicalType();
17152   }
17153   // Find all user-defined mappers with the given MapperId.
17154   SmallVector<UnresolvedSet<8>, 4> Lookups;
17155   LookupResult Lookup(SemaRef, MapperId, Sema::LookupOMPMapperName);
17156   Lookup.suppressDiagnostics();
17157   if (S) {
17158     while (S && SemaRef.LookupParsedName(Lookup, S, &MapperIdScopeSpec)) {
17159       NamedDecl *D = Lookup.getRepresentativeDecl();
17160       while (S && !S->isDeclScope(D))
17161         S = S->getParent();
17162       if (S)
17163         S = S->getParent();
17164       Lookups.emplace_back();
17165       Lookups.back().append(Lookup.begin(), Lookup.end());
17166       Lookup.clear();
17167     }
17168   } else if (auto *ULE = cast_or_null<UnresolvedLookupExpr>(UnresolvedMapper)) {
17169     // Extract the user-defined mappers with the given MapperId.
17170     Lookups.push_back(UnresolvedSet<8>());
17171     for (NamedDecl *D : ULE->decls()) {
17172       auto *DMD = cast<OMPDeclareMapperDecl>(D);
17173       assert(DMD && "Expect valid OMPDeclareMapperDecl during instantiation.");
17174       Lookups.back().addDecl(DMD);
17175     }
17176   }
17177   // Defer the lookup for dependent types. The results will be passed through
17178   // UnresolvedMapper on instantiation.
17179   if (SemaRef.CurContext->isDependentContext() || Type->isDependentType() ||
17180       Type->isInstantiationDependentType() ||
17181       Type->containsUnexpandedParameterPack() ||
17182       filterLookupForUDReductionAndMapper<bool>(Lookups, [](ValueDecl *D) {
17183         return !D->isInvalidDecl() &&
17184                (D->getType()->isDependentType() ||
17185                 D->getType()->isInstantiationDependentType() ||
17186                 D->getType()->containsUnexpandedParameterPack());
17187       })) {
17188     UnresolvedSet<8> URS;
17189     for (const UnresolvedSet<8> &Set : Lookups) {
17190       if (Set.empty())
17191         continue;
17192       URS.append(Set.begin(), Set.end());
17193     }
17194     return UnresolvedLookupExpr::Create(
17195         SemaRef.Context, /*NamingClass=*/nullptr,
17196         MapperIdScopeSpec.getWithLocInContext(SemaRef.Context), MapperId,
17197         /*ADL=*/false, /*Overloaded=*/true, URS.begin(), URS.end());
17198   }
17199   SourceLocation Loc = MapperId.getLoc();
17200   // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
17201   //  The type must be of struct, union or class type in C and C++
17202   if (!Type->isStructureOrClassType() && !Type->isUnionType() &&
17203       (MapperIdScopeSpec.isSet() || MapperId.getAsString() != "default")) {
17204     SemaRef.Diag(Loc, diag::err_omp_mapper_wrong_type);
17205     return ExprError();
17206   }
17207   // Perform argument dependent lookup.
17208   if (SemaRef.getLangOpts().CPlusPlus && !MapperIdScopeSpec.isSet())
17209     argumentDependentLookup(SemaRef, MapperId, Loc, Type, Lookups);
17210   // Return the first user-defined mapper with the desired type.
17211   if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
17212           Lookups, [&SemaRef, Type](ValueDecl *D) -> ValueDecl * {
17213             if (!D->isInvalidDecl() &&
17214                 SemaRef.Context.hasSameType(D->getType(), Type))
17215               return D;
17216             return nullptr;
17217           }))
17218     return SemaRef.BuildDeclRefExpr(VD, Type, VK_LValue, Loc);
17219   // Find the first user-defined mapper with a type derived from the desired
17220   // type.
17221   if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
17222           Lookups, [&SemaRef, Type, Loc](ValueDecl *D) -> ValueDecl * {
17223             if (!D->isInvalidDecl() &&
17224                 SemaRef.IsDerivedFrom(Loc, Type, D->getType()) &&
17225                 !Type.isMoreQualifiedThan(D->getType()))
17226               return D;
17227             return nullptr;
17228           })) {
17229     CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
17230                        /*DetectVirtual=*/false);
17231     if (SemaRef.IsDerivedFrom(Loc, Type, VD->getType(), Paths)) {
17232       if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
17233               VD->getType().getUnqualifiedType()))) {
17234         if (SemaRef.CheckBaseClassAccess(
17235                 Loc, VD->getType(), Type, Paths.front(),
17236                 /*DiagID=*/0) != Sema::AR_inaccessible) {
17237           return SemaRef.BuildDeclRefExpr(VD, Type, VK_LValue, Loc);
17238         }
17239       }
17240     }
17241   }
17242   // Report error if a mapper is specified, but cannot be found.
17243   if (MapperIdScopeSpec.isSet() || MapperId.getAsString() != "default") {
17244     SemaRef.Diag(Loc, diag::err_omp_invalid_mapper)
17245         << Type << MapperId.getName();
17246     return ExprError();
17247   }
17248   return ExprEmpty();
17249 }
17250 
17251 namespace {
17252 // Utility struct that gathers all the related lists associated with a mappable
17253 // expression.
17254 struct MappableVarListInfo {
17255   // The list of expressions.
17256   ArrayRef<Expr *> VarList;
17257   // The list of processed expressions.
17258   SmallVector<Expr *, 16> ProcessedVarList;
17259   // The mappble components for each expression.
17260   OMPClauseMappableExprCommon::MappableExprComponentLists VarComponents;
17261   // The base declaration of the variable.
17262   SmallVector<ValueDecl *, 16> VarBaseDeclarations;
17263   // The reference to the user-defined mapper associated with every expression.
17264   SmallVector<Expr *, 16> UDMapperList;
17265 
17266   MappableVarListInfo(ArrayRef<Expr *> VarList) : VarList(VarList) {
17267     // We have a list of components and base declarations for each entry in the
17268     // variable list.
17269     VarComponents.reserve(VarList.size());
17270     VarBaseDeclarations.reserve(VarList.size());
17271   }
17272 };
17273 }
17274 
17275 // Check the validity of the provided variable list for the provided clause kind
17276 // \a CKind. In the check process the valid expressions, mappable expression
17277 // components, variables, and user-defined mappers are extracted and used to
17278 // fill \a ProcessedVarList, \a VarComponents, \a VarBaseDeclarations, and \a
17279 // UDMapperList in MVLI. \a MapType, \a IsMapTypeImplicit, \a MapperIdScopeSpec,
17280 // and \a MapperId are expected to be valid if the clause kind is 'map'.
17281 static void checkMappableExpressionList(
17282     Sema &SemaRef, DSAStackTy *DSAS, OpenMPClauseKind CKind,
17283     MappableVarListInfo &MVLI, SourceLocation StartLoc,
17284     CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo MapperId,
17285     ArrayRef<Expr *> UnresolvedMappers,
17286     OpenMPMapClauseKind MapType = OMPC_MAP_unknown,
17287     bool IsMapTypeImplicit = false) {
17288   // We only expect mappable expressions in 'to', 'from', and 'map' clauses.
17289   assert((CKind == OMPC_map || CKind == OMPC_to || CKind == OMPC_from) &&
17290          "Unexpected clause kind with mappable expressions!");
17291 
17292   // If the identifier of user-defined mapper is not specified, it is "default".
17293   // We do not change the actual name in this clause to distinguish whether a
17294   // mapper is specified explicitly, i.e., it is not explicitly specified when
17295   // MapperId.getName() is empty.
17296   if (!MapperId.getName() || MapperId.getName().isEmpty()) {
17297     auto &DeclNames = SemaRef.getASTContext().DeclarationNames;
17298     MapperId.setName(DeclNames.getIdentifier(
17299         &SemaRef.getASTContext().Idents.get("default")));
17300   }
17301 
17302   // Iterators to find the current unresolved mapper expression.
17303   auto UMIt = UnresolvedMappers.begin(), UMEnd = UnresolvedMappers.end();
17304   bool UpdateUMIt = false;
17305   Expr *UnresolvedMapper = nullptr;
17306 
17307   // Keep track of the mappable components and base declarations in this clause.
17308   // Each entry in the list is going to have a list of components associated. We
17309   // record each set of the components so that we can build the clause later on.
17310   // In the end we should have the same amount of declarations and component
17311   // lists.
17312 
17313   for (Expr *RE : MVLI.VarList) {
17314     assert(RE && "Null expr in omp to/from/map clause");
17315     SourceLocation ELoc = RE->getExprLoc();
17316 
17317     // Find the current unresolved mapper expression.
17318     if (UpdateUMIt && UMIt != UMEnd) {
17319       UMIt++;
17320       assert(
17321           UMIt != UMEnd &&
17322           "Expect the size of UnresolvedMappers to match with that of VarList");
17323     }
17324     UpdateUMIt = true;
17325     if (UMIt != UMEnd)
17326       UnresolvedMapper = *UMIt;
17327 
17328     const Expr *VE = RE->IgnoreParenLValueCasts();
17329 
17330     if (VE->isValueDependent() || VE->isTypeDependent() ||
17331         VE->isInstantiationDependent() ||
17332         VE->containsUnexpandedParameterPack()) {
17333       // Try to find the associated user-defined mapper.
17334       ExprResult ER = buildUserDefinedMapperRef(
17335           SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
17336           VE->getType().getCanonicalType(), UnresolvedMapper);
17337       if (ER.isInvalid())
17338         continue;
17339       MVLI.UDMapperList.push_back(ER.get());
17340       // We can only analyze this information once the missing information is
17341       // resolved.
17342       MVLI.ProcessedVarList.push_back(RE);
17343       continue;
17344     }
17345 
17346     Expr *SimpleExpr = RE->IgnoreParenCasts();
17347 
17348     if (!RE->isLValue()) {
17349       if (SemaRef.getLangOpts().OpenMP < 50) {
17350         SemaRef.Diag(
17351             ELoc, diag::err_omp_expected_named_var_member_or_array_expression)
17352             << RE->getSourceRange();
17353       } else {
17354         SemaRef.Diag(ELoc, diag::err_omp_non_lvalue_in_map_or_motion_clauses)
17355             << getOpenMPClauseName(CKind) << RE->getSourceRange();
17356       }
17357       continue;
17358     }
17359 
17360     OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
17361     ValueDecl *CurDeclaration = nullptr;
17362 
17363     // Obtain the array or member expression bases if required. Also, fill the
17364     // components array with all the components identified in the process.
17365     const Expr *BE = checkMapClauseExpressionBase(
17366         SemaRef, SimpleExpr, CurComponents, CKind, /*NoDiagnose=*/false);
17367     if (!BE)
17368       continue;
17369 
17370     assert(!CurComponents.empty() &&
17371            "Invalid mappable expression information.");
17372 
17373     if (const auto *TE = dyn_cast<CXXThisExpr>(BE)) {
17374       // Add store "this" pointer to class in DSAStackTy for future checking
17375       DSAS->addMappedClassesQualTypes(TE->getType());
17376       // Try to find the associated user-defined mapper.
17377       ExprResult ER = buildUserDefinedMapperRef(
17378           SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
17379           VE->getType().getCanonicalType(), UnresolvedMapper);
17380       if (ER.isInvalid())
17381         continue;
17382       MVLI.UDMapperList.push_back(ER.get());
17383       // Skip restriction checking for variable or field declarations
17384       MVLI.ProcessedVarList.push_back(RE);
17385       MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
17386       MVLI.VarComponents.back().append(CurComponents.begin(),
17387                                        CurComponents.end());
17388       MVLI.VarBaseDeclarations.push_back(nullptr);
17389       continue;
17390     }
17391 
17392     // For the following checks, we rely on the base declaration which is
17393     // expected to be associated with the last component. The declaration is
17394     // expected to be a variable or a field (if 'this' is being mapped).
17395     CurDeclaration = CurComponents.back().getAssociatedDeclaration();
17396     assert(CurDeclaration && "Null decl on map clause.");
17397     assert(
17398         CurDeclaration->isCanonicalDecl() &&
17399         "Expecting components to have associated only canonical declarations.");
17400 
17401     auto *VD = dyn_cast<VarDecl>(CurDeclaration);
17402     const auto *FD = dyn_cast<FieldDecl>(CurDeclaration);
17403 
17404     assert((VD || FD) && "Only variables or fields are expected here!");
17405     (void)FD;
17406 
17407     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.10]
17408     // threadprivate variables cannot appear in a map clause.
17409     // OpenMP 4.5 [2.10.5, target update Construct]
17410     // threadprivate variables cannot appear in a from clause.
17411     if (VD && DSAS->isThreadPrivate(VD)) {
17412       DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false);
17413       SemaRef.Diag(ELoc, diag::err_omp_threadprivate_in_clause)
17414           << getOpenMPClauseName(CKind);
17415       reportOriginalDsa(SemaRef, DSAS, VD, DVar);
17416       continue;
17417     }
17418 
17419     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
17420     //  A list item cannot appear in both a map clause and a data-sharing
17421     //  attribute clause on the same construct.
17422 
17423     // Check conflicts with other map clause expressions. We check the conflicts
17424     // with the current construct separately from the enclosing data
17425     // environment, because the restrictions are different. We only have to
17426     // check conflicts across regions for the map clauses.
17427     if (checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
17428                           /*CurrentRegionOnly=*/true, CurComponents, CKind))
17429       break;
17430     if (CKind == OMPC_map &&
17431         checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
17432                           /*CurrentRegionOnly=*/false, CurComponents, CKind))
17433       break;
17434 
17435     // OpenMP 4.5 [2.10.5, target update Construct]
17436     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
17437     //  If the type of a list item is a reference to a type T then the type will
17438     //  be considered to be T for all purposes of this clause.
17439     auto I = llvm::find_if(
17440         CurComponents,
17441         [](const OMPClauseMappableExprCommon::MappableComponent &MC) {
17442           return MC.getAssociatedDeclaration();
17443         });
17444     assert(I != CurComponents.end() && "Null decl on map clause.");
17445     QualType Type;
17446     auto *ASE = dyn_cast<ArraySubscriptExpr>(VE->IgnoreParens());
17447     auto *OASE = dyn_cast<OMPArraySectionExpr>(VE->IgnoreParens());
17448     auto *OAShE = dyn_cast<OMPArrayShapingExpr>(VE->IgnoreParens());
17449     if (ASE) {
17450       Type = ASE->getType().getNonReferenceType();
17451     } else if (OASE) {
17452       QualType BaseType =
17453           OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
17454       if (const auto *ATy = BaseType->getAsArrayTypeUnsafe())
17455         Type = ATy->getElementType();
17456       else
17457         Type = BaseType->getPointeeType();
17458       Type = Type.getNonReferenceType();
17459     } else if (OAShE) {
17460       Type = OAShE->getBase()->getType()->getPointeeType();
17461     } else {
17462       Type = VE->getType();
17463     }
17464 
17465     // OpenMP 4.5 [2.10.5, target update Construct, Restrictions, p.4]
17466     // A list item in a to or from clause must have a mappable type.
17467     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
17468     //  A list item must have a mappable type.
17469     if (!checkTypeMappable(VE->getExprLoc(), VE->getSourceRange(), SemaRef,
17470                            DSAS, Type))
17471       continue;
17472 
17473     Type = I->getAssociatedDeclaration()->getType().getNonReferenceType();
17474 
17475     if (CKind == OMPC_map) {
17476       // target enter data
17477       // OpenMP [2.10.2, Restrictions, p. 99]
17478       // A map-type must be specified in all map clauses and must be either
17479       // to or alloc.
17480       OpenMPDirectiveKind DKind = DSAS->getCurrentDirective();
17481       if (DKind == OMPD_target_enter_data &&
17482           !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_alloc)) {
17483         SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
17484             << (IsMapTypeImplicit ? 1 : 0)
17485             << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
17486             << getOpenMPDirectiveName(DKind);
17487         continue;
17488       }
17489 
17490       // target exit_data
17491       // OpenMP [2.10.3, Restrictions, p. 102]
17492       // A map-type must be specified in all map clauses and must be either
17493       // from, release, or delete.
17494       if (DKind == OMPD_target_exit_data &&
17495           !(MapType == OMPC_MAP_from || MapType == OMPC_MAP_release ||
17496             MapType == OMPC_MAP_delete)) {
17497         SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
17498             << (IsMapTypeImplicit ? 1 : 0)
17499             << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
17500             << getOpenMPDirectiveName(DKind);
17501         continue;
17502       }
17503 
17504       // target, target data
17505       // OpenMP 5.0 [2.12.2, Restrictions, p. 163]
17506       // OpenMP 5.0 [2.12.5, Restrictions, p. 174]
17507       // A map-type in a map clause must be to, from, tofrom or alloc
17508       if ((DKind == OMPD_target_data ||
17509            isOpenMPTargetExecutionDirective(DKind)) &&
17510           !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_from ||
17511             MapType == OMPC_MAP_tofrom || MapType == OMPC_MAP_alloc)) {
17512         SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
17513             << (IsMapTypeImplicit ? 1 : 0)
17514             << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
17515             << getOpenMPDirectiveName(DKind);
17516         continue;
17517       }
17518 
17519       // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
17520       // A list item cannot appear in both a map clause and a data-sharing
17521       // attribute clause on the same construct
17522       //
17523       // OpenMP 5.0 [2.19.7.1, Restrictions, p.7]
17524       // A list item cannot appear in both a map clause and a data-sharing
17525       // attribute clause on the same construct unless the construct is a
17526       // combined construct.
17527       if (VD && ((SemaRef.LangOpts.OpenMP <= 45 &&
17528                   isOpenMPTargetExecutionDirective(DKind)) ||
17529                  DKind == OMPD_target)) {
17530         DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false);
17531         if (isOpenMPPrivate(DVar.CKind)) {
17532           SemaRef.Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
17533               << getOpenMPClauseName(DVar.CKind)
17534               << getOpenMPClauseName(OMPC_map)
17535               << getOpenMPDirectiveName(DSAS->getCurrentDirective());
17536           reportOriginalDsa(SemaRef, DSAS, CurDeclaration, DVar);
17537           continue;
17538         }
17539       }
17540     }
17541 
17542     // Try to find the associated user-defined mapper.
17543     ExprResult ER = buildUserDefinedMapperRef(
17544         SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
17545         Type.getCanonicalType(), UnresolvedMapper);
17546     if (ER.isInvalid())
17547       continue;
17548     MVLI.UDMapperList.push_back(ER.get());
17549 
17550     // Save the current expression.
17551     MVLI.ProcessedVarList.push_back(RE);
17552 
17553     // Store the components in the stack so that they can be used to check
17554     // against other clauses later on.
17555     DSAS->addMappableExpressionComponents(CurDeclaration, CurComponents,
17556                                           /*WhereFoundClauseKind=*/OMPC_map);
17557 
17558     // Save the components and declaration to create the clause. For purposes of
17559     // the clause creation, any component list that has has base 'this' uses
17560     // null as base declaration.
17561     MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
17562     MVLI.VarComponents.back().append(CurComponents.begin(),
17563                                      CurComponents.end());
17564     MVLI.VarBaseDeclarations.push_back(isa<MemberExpr>(BE) ? nullptr
17565                                                            : CurDeclaration);
17566   }
17567 }
17568 
17569 OMPClause *Sema::ActOnOpenMPMapClause(
17570     ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
17571     ArrayRef<SourceLocation> MapTypeModifiersLoc,
17572     CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo &MapperId,
17573     OpenMPMapClauseKind MapType, bool IsMapTypeImplicit, SourceLocation MapLoc,
17574     SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
17575     const OMPVarListLocTy &Locs, ArrayRef<Expr *> UnresolvedMappers) {
17576   OpenMPMapModifierKind Modifiers[] = {OMPC_MAP_MODIFIER_unknown,
17577                                        OMPC_MAP_MODIFIER_unknown,
17578                                        OMPC_MAP_MODIFIER_unknown};
17579   SourceLocation ModifiersLoc[NumberOfOMPMapClauseModifiers];
17580 
17581   // Process map-type-modifiers, flag errors for duplicate modifiers.
17582   unsigned Count = 0;
17583   for (unsigned I = 0, E = MapTypeModifiers.size(); I < E; ++I) {
17584     if (MapTypeModifiers[I] != OMPC_MAP_MODIFIER_unknown &&
17585         llvm::find(Modifiers, MapTypeModifiers[I]) != std::end(Modifiers)) {
17586       Diag(MapTypeModifiersLoc[I], diag::err_omp_duplicate_map_type_modifier);
17587       continue;
17588     }
17589     assert(Count < NumberOfOMPMapClauseModifiers &&
17590            "Modifiers exceed the allowed number of map type modifiers");
17591     Modifiers[Count] = MapTypeModifiers[I];
17592     ModifiersLoc[Count] = MapTypeModifiersLoc[I];
17593     ++Count;
17594   }
17595 
17596   MappableVarListInfo MVLI(VarList);
17597   checkMappableExpressionList(*this, DSAStack, OMPC_map, MVLI, Locs.StartLoc,
17598                               MapperIdScopeSpec, MapperId, UnresolvedMappers,
17599                               MapType, IsMapTypeImplicit);
17600 
17601   // We need to produce a map clause even if we don't have variables so that
17602   // other diagnostics related with non-existing map clauses are accurate.
17603   return OMPMapClause::Create(Context, Locs, MVLI.ProcessedVarList,
17604                               MVLI.VarBaseDeclarations, MVLI.VarComponents,
17605                               MVLI.UDMapperList, Modifiers, ModifiersLoc,
17606                               MapperIdScopeSpec.getWithLocInContext(Context),
17607                               MapperId, MapType, IsMapTypeImplicit, MapLoc);
17608 }
17609 
17610 QualType Sema::ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
17611                                                TypeResult ParsedType) {
17612   assert(ParsedType.isUsable());
17613 
17614   QualType ReductionType = GetTypeFromParser(ParsedType.get());
17615   if (ReductionType.isNull())
17616     return QualType();
17617 
17618   // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions, C\C++
17619   // A type name in a declare reduction directive cannot be a function type, an
17620   // array type, a reference type, or a type qualified with const, volatile or
17621   // restrict.
17622   if (ReductionType.hasQualifiers()) {
17623     Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 0;
17624     return QualType();
17625   }
17626 
17627   if (ReductionType->isFunctionType()) {
17628     Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 1;
17629     return QualType();
17630   }
17631   if (ReductionType->isReferenceType()) {
17632     Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 2;
17633     return QualType();
17634   }
17635   if (ReductionType->isArrayType()) {
17636     Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 3;
17637     return QualType();
17638   }
17639   return ReductionType;
17640 }
17641 
17642 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveStart(
17643     Scope *S, DeclContext *DC, DeclarationName Name,
17644     ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
17645     AccessSpecifier AS, Decl *PrevDeclInScope) {
17646   SmallVector<Decl *, 8> Decls;
17647   Decls.reserve(ReductionTypes.size());
17648 
17649   LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPReductionName,
17650                       forRedeclarationInCurContext());
17651   // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
17652   // A reduction-identifier may not be re-declared in the current scope for the
17653   // same type or for a type that is compatible according to the base language
17654   // rules.
17655   llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
17656   OMPDeclareReductionDecl *PrevDRD = nullptr;
17657   bool InCompoundScope = true;
17658   if (S != nullptr) {
17659     // Find previous declaration with the same name not referenced in other
17660     // declarations.
17661     FunctionScopeInfo *ParentFn = getEnclosingFunction();
17662     InCompoundScope =
17663         (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
17664     LookupName(Lookup, S);
17665     FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
17666                          /*AllowInlineNamespace=*/false);
17667     llvm::DenseMap<OMPDeclareReductionDecl *, bool> UsedAsPrevious;
17668     LookupResult::Filter Filter = Lookup.makeFilter();
17669     while (Filter.hasNext()) {
17670       auto *PrevDecl = cast<OMPDeclareReductionDecl>(Filter.next());
17671       if (InCompoundScope) {
17672         auto I = UsedAsPrevious.find(PrevDecl);
17673         if (I == UsedAsPrevious.end())
17674           UsedAsPrevious[PrevDecl] = false;
17675         if (OMPDeclareReductionDecl *D = PrevDecl->getPrevDeclInScope())
17676           UsedAsPrevious[D] = true;
17677       }
17678       PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
17679           PrevDecl->getLocation();
17680     }
17681     Filter.done();
17682     if (InCompoundScope) {
17683       for (const auto &PrevData : UsedAsPrevious) {
17684         if (!PrevData.second) {
17685           PrevDRD = PrevData.first;
17686           break;
17687         }
17688       }
17689     }
17690   } else if (PrevDeclInScope != nullptr) {
17691     auto *PrevDRDInScope = PrevDRD =
17692         cast<OMPDeclareReductionDecl>(PrevDeclInScope);
17693     do {
17694       PreviousRedeclTypes[PrevDRDInScope->getType().getCanonicalType()] =
17695           PrevDRDInScope->getLocation();
17696       PrevDRDInScope = PrevDRDInScope->getPrevDeclInScope();
17697     } while (PrevDRDInScope != nullptr);
17698   }
17699   for (const auto &TyData : ReductionTypes) {
17700     const auto I = PreviousRedeclTypes.find(TyData.first.getCanonicalType());
17701     bool Invalid = false;
17702     if (I != PreviousRedeclTypes.end()) {
17703       Diag(TyData.second, diag::err_omp_declare_reduction_redefinition)
17704           << TyData.first;
17705       Diag(I->second, diag::note_previous_definition);
17706       Invalid = true;
17707     }
17708     PreviousRedeclTypes[TyData.first.getCanonicalType()] = TyData.second;
17709     auto *DRD = OMPDeclareReductionDecl::Create(Context, DC, TyData.second,
17710                                                 Name, TyData.first, PrevDRD);
17711     DC->addDecl(DRD);
17712     DRD->setAccess(AS);
17713     Decls.push_back(DRD);
17714     if (Invalid)
17715       DRD->setInvalidDecl();
17716     else
17717       PrevDRD = DRD;
17718   }
17719 
17720   return DeclGroupPtrTy::make(
17721       DeclGroupRef::Create(Context, Decls.begin(), Decls.size()));
17722 }
17723 
17724 void Sema::ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D) {
17725   auto *DRD = cast<OMPDeclareReductionDecl>(D);
17726 
17727   // Enter new function scope.
17728   PushFunctionScope();
17729   setFunctionHasBranchProtectedScope();
17730   getCurFunction()->setHasOMPDeclareReductionCombiner();
17731 
17732   if (S != nullptr)
17733     PushDeclContext(S, DRD);
17734   else
17735     CurContext = DRD;
17736 
17737   PushExpressionEvaluationContext(
17738       ExpressionEvaluationContext::PotentiallyEvaluated);
17739 
17740   QualType ReductionType = DRD->getType();
17741   // Create 'T* omp_parm;T omp_in;'. All references to 'omp_in' will
17742   // be replaced by '*omp_parm' during codegen. This required because 'omp_in'
17743   // uses semantics of argument handles by value, but it should be passed by
17744   // reference. C lang does not support references, so pass all parameters as
17745   // pointers.
17746   // Create 'T omp_in;' variable.
17747   VarDecl *OmpInParm =
17748       buildVarDecl(*this, D->getLocation(), ReductionType, "omp_in");
17749   // Create 'T* omp_parm;T omp_out;'. All references to 'omp_out' will
17750   // be replaced by '*omp_parm' during codegen. This required because 'omp_out'
17751   // uses semantics of argument handles by value, but it should be passed by
17752   // reference. C lang does not support references, so pass all parameters as
17753   // pointers.
17754   // Create 'T omp_out;' variable.
17755   VarDecl *OmpOutParm =
17756       buildVarDecl(*this, D->getLocation(), ReductionType, "omp_out");
17757   if (S != nullptr) {
17758     PushOnScopeChains(OmpInParm, S);
17759     PushOnScopeChains(OmpOutParm, S);
17760   } else {
17761     DRD->addDecl(OmpInParm);
17762     DRD->addDecl(OmpOutParm);
17763   }
17764   Expr *InE =
17765       ::buildDeclRefExpr(*this, OmpInParm, ReductionType, D->getLocation());
17766   Expr *OutE =
17767       ::buildDeclRefExpr(*this, OmpOutParm, ReductionType, D->getLocation());
17768   DRD->setCombinerData(InE, OutE);
17769 }
17770 
17771 void Sema::ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner) {
17772   auto *DRD = cast<OMPDeclareReductionDecl>(D);
17773   DiscardCleanupsInEvaluationContext();
17774   PopExpressionEvaluationContext();
17775 
17776   PopDeclContext();
17777   PopFunctionScopeInfo();
17778 
17779   if (Combiner != nullptr)
17780     DRD->setCombiner(Combiner);
17781   else
17782     DRD->setInvalidDecl();
17783 }
17784 
17785 VarDecl *Sema::ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D) {
17786   auto *DRD = cast<OMPDeclareReductionDecl>(D);
17787 
17788   // Enter new function scope.
17789   PushFunctionScope();
17790   setFunctionHasBranchProtectedScope();
17791 
17792   if (S != nullptr)
17793     PushDeclContext(S, DRD);
17794   else
17795     CurContext = DRD;
17796 
17797   PushExpressionEvaluationContext(
17798       ExpressionEvaluationContext::PotentiallyEvaluated);
17799 
17800   QualType ReductionType = DRD->getType();
17801   // Create 'T* omp_parm;T omp_priv;'. All references to 'omp_priv' will
17802   // be replaced by '*omp_parm' during codegen. This required because 'omp_priv'
17803   // uses semantics of argument handles by value, but it should be passed by
17804   // reference. C lang does not support references, so pass all parameters as
17805   // pointers.
17806   // Create 'T omp_priv;' variable.
17807   VarDecl *OmpPrivParm =
17808       buildVarDecl(*this, D->getLocation(), ReductionType, "omp_priv");
17809   // Create 'T* omp_parm;T omp_orig;'. All references to 'omp_orig' will
17810   // be replaced by '*omp_parm' during codegen. This required because 'omp_orig'
17811   // uses semantics of argument handles by value, but it should be passed by
17812   // reference. C lang does not support references, so pass all parameters as
17813   // pointers.
17814   // Create 'T omp_orig;' variable.
17815   VarDecl *OmpOrigParm =
17816       buildVarDecl(*this, D->getLocation(), ReductionType, "omp_orig");
17817   if (S != nullptr) {
17818     PushOnScopeChains(OmpPrivParm, S);
17819     PushOnScopeChains(OmpOrigParm, S);
17820   } else {
17821     DRD->addDecl(OmpPrivParm);
17822     DRD->addDecl(OmpOrigParm);
17823   }
17824   Expr *OrigE =
17825       ::buildDeclRefExpr(*this, OmpOrigParm, ReductionType, D->getLocation());
17826   Expr *PrivE =
17827       ::buildDeclRefExpr(*this, OmpPrivParm, ReductionType, D->getLocation());
17828   DRD->setInitializerData(OrigE, PrivE);
17829   return OmpPrivParm;
17830 }
17831 
17832 void Sema::ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer,
17833                                                      VarDecl *OmpPrivParm) {
17834   auto *DRD = cast<OMPDeclareReductionDecl>(D);
17835   DiscardCleanupsInEvaluationContext();
17836   PopExpressionEvaluationContext();
17837 
17838   PopDeclContext();
17839   PopFunctionScopeInfo();
17840 
17841   if (Initializer != nullptr) {
17842     DRD->setInitializer(Initializer, OMPDeclareReductionDecl::CallInit);
17843   } else if (OmpPrivParm->hasInit()) {
17844     DRD->setInitializer(OmpPrivParm->getInit(),
17845                         OmpPrivParm->isDirectInit()
17846                             ? OMPDeclareReductionDecl::DirectInit
17847                             : OMPDeclareReductionDecl::CopyInit);
17848   } else {
17849     DRD->setInvalidDecl();
17850   }
17851 }
17852 
17853 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveEnd(
17854     Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid) {
17855   for (Decl *D : DeclReductions.get()) {
17856     if (IsValid) {
17857       if (S)
17858         PushOnScopeChains(cast<OMPDeclareReductionDecl>(D), S,
17859                           /*AddToContext=*/false);
17860     } else {
17861       D->setInvalidDecl();
17862     }
17863   }
17864   return DeclReductions;
17865 }
17866 
17867 TypeResult Sema::ActOnOpenMPDeclareMapperVarDecl(Scope *S, Declarator &D) {
17868   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
17869   QualType T = TInfo->getType();
17870   if (D.isInvalidType())
17871     return true;
17872 
17873   if (getLangOpts().CPlusPlus) {
17874     // Check that there are no default arguments (C++ only).
17875     CheckExtraCXXDefaultArguments(D);
17876   }
17877 
17878   return CreateParsedType(T, TInfo);
17879 }
17880 
17881 QualType Sema::ActOnOpenMPDeclareMapperType(SourceLocation TyLoc,
17882                                             TypeResult ParsedType) {
17883   assert(ParsedType.isUsable() && "Expect usable parsed mapper type");
17884 
17885   QualType MapperType = GetTypeFromParser(ParsedType.get());
17886   assert(!MapperType.isNull() && "Expect valid mapper type");
17887 
17888   // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
17889   //  The type must be of struct, union or class type in C and C++
17890   if (!MapperType->isStructureOrClassType() && !MapperType->isUnionType()) {
17891     Diag(TyLoc, diag::err_omp_mapper_wrong_type);
17892     return QualType();
17893   }
17894   return MapperType;
17895 }
17896 
17897 OMPDeclareMapperDecl *Sema::ActOnOpenMPDeclareMapperDirectiveStart(
17898     Scope *S, DeclContext *DC, DeclarationName Name, QualType MapperType,
17899     SourceLocation StartLoc, DeclarationName VN, AccessSpecifier AS,
17900     Decl *PrevDeclInScope) {
17901   LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPMapperName,
17902                       forRedeclarationInCurContext());
17903   // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
17904   //  A mapper-identifier may not be redeclared in the current scope for the
17905   //  same type or for a type that is compatible according to the base language
17906   //  rules.
17907   llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
17908   OMPDeclareMapperDecl *PrevDMD = nullptr;
17909   bool InCompoundScope = true;
17910   if (S != nullptr) {
17911     // Find previous declaration with the same name not referenced in other
17912     // declarations.
17913     FunctionScopeInfo *ParentFn = getEnclosingFunction();
17914     InCompoundScope =
17915         (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
17916     LookupName(Lookup, S);
17917     FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
17918                          /*AllowInlineNamespace=*/false);
17919     llvm::DenseMap<OMPDeclareMapperDecl *, bool> UsedAsPrevious;
17920     LookupResult::Filter Filter = Lookup.makeFilter();
17921     while (Filter.hasNext()) {
17922       auto *PrevDecl = cast<OMPDeclareMapperDecl>(Filter.next());
17923       if (InCompoundScope) {
17924         auto I = UsedAsPrevious.find(PrevDecl);
17925         if (I == UsedAsPrevious.end())
17926           UsedAsPrevious[PrevDecl] = false;
17927         if (OMPDeclareMapperDecl *D = PrevDecl->getPrevDeclInScope())
17928           UsedAsPrevious[D] = true;
17929       }
17930       PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
17931           PrevDecl->getLocation();
17932     }
17933     Filter.done();
17934     if (InCompoundScope) {
17935       for (const auto &PrevData : UsedAsPrevious) {
17936         if (!PrevData.second) {
17937           PrevDMD = PrevData.first;
17938           break;
17939         }
17940       }
17941     }
17942   } else if (PrevDeclInScope) {
17943     auto *PrevDMDInScope = PrevDMD =
17944         cast<OMPDeclareMapperDecl>(PrevDeclInScope);
17945     do {
17946       PreviousRedeclTypes[PrevDMDInScope->getType().getCanonicalType()] =
17947           PrevDMDInScope->getLocation();
17948       PrevDMDInScope = PrevDMDInScope->getPrevDeclInScope();
17949     } while (PrevDMDInScope != nullptr);
17950   }
17951   const auto I = PreviousRedeclTypes.find(MapperType.getCanonicalType());
17952   bool Invalid = false;
17953   if (I != PreviousRedeclTypes.end()) {
17954     Diag(StartLoc, diag::err_omp_declare_mapper_redefinition)
17955         << MapperType << Name;
17956     Diag(I->second, diag::note_previous_definition);
17957     Invalid = true;
17958   }
17959   auto *DMD = OMPDeclareMapperDecl::Create(Context, DC, StartLoc, Name,
17960                                            MapperType, VN, PrevDMD);
17961   DC->addDecl(DMD);
17962   DMD->setAccess(AS);
17963   if (Invalid)
17964     DMD->setInvalidDecl();
17965 
17966   // Enter new function scope.
17967   PushFunctionScope();
17968   setFunctionHasBranchProtectedScope();
17969 
17970   CurContext = DMD;
17971 
17972   return DMD;
17973 }
17974 
17975 void Sema::ActOnOpenMPDeclareMapperDirectiveVarDecl(OMPDeclareMapperDecl *DMD,
17976                                                     Scope *S,
17977                                                     QualType MapperType,
17978                                                     SourceLocation StartLoc,
17979                                                     DeclarationName VN) {
17980   VarDecl *VD = buildVarDecl(*this, StartLoc, MapperType, VN.getAsString());
17981   if (S)
17982     PushOnScopeChains(VD, S);
17983   else
17984     DMD->addDecl(VD);
17985   Expr *MapperVarRefExpr = buildDeclRefExpr(*this, VD, MapperType, StartLoc);
17986   DMD->setMapperVarRef(MapperVarRefExpr);
17987 }
17988 
17989 Sema::DeclGroupPtrTy
17990 Sema::ActOnOpenMPDeclareMapperDirectiveEnd(OMPDeclareMapperDecl *D, Scope *S,
17991                                            ArrayRef<OMPClause *> ClauseList) {
17992   PopDeclContext();
17993   PopFunctionScopeInfo();
17994 
17995   if (D) {
17996     if (S)
17997       PushOnScopeChains(D, S, /*AddToContext=*/false);
17998     D->CreateClauses(Context, ClauseList);
17999   }
18000 
18001   return DeclGroupPtrTy::make(DeclGroupRef(D));
18002 }
18003 
18004 OMPClause *Sema::ActOnOpenMPNumTeamsClause(Expr *NumTeams,
18005                                            SourceLocation StartLoc,
18006                                            SourceLocation LParenLoc,
18007                                            SourceLocation EndLoc) {
18008   Expr *ValExpr = NumTeams;
18009   Stmt *HelperValStmt = nullptr;
18010 
18011   // OpenMP [teams Constrcut, Restrictions]
18012   // The num_teams expression must evaluate to a positive integer value.
18013   if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_teams,
18014                                  /*StrictlyPositive=*/true))
18015     return nullptr;
18016 
18017   OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
18018   OpenMPDirectiveKind CaptureRegion =
18019       getOpenMPCaptureRegionForClause(DKind, OMPC_num_teams, LangOpts.OpenMP);
18020   if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
18021     ValExpr = MakeFullExpr(ValExpr).get();
18022     llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
18023     ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
18024     HelperValStmt = buildPreInits(Context, Captures);
18025   }
18026 
18027   return new (Context) OMPNumTeamsClause(ValExpr, HelperValStmt, CaptureRegion,
18028                                          StartLoc, LParenLoc, EndLoc);
18029 }
18030 
18031 OMPClause *Sema::ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
18032                                               SourceLocation StartLoc,
18033                                               SourceLocation LParenLoc,
18034                                               SourceLocation EndLoc) {
18035   Expr *ValExpr = ThreadLimit;
18036   Stmt *HelperValStmt = nullptr;
18037 
18038   // OpenMP [teams Constrcut, Restrictions]
18039   // The thread_limit expression must evaluate to a positive integer value.
18040   if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_thread_limit,
18041                                  /*StrictlyPositive=*/true))
18042     return nullptr;
18043 
18044   OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
18045   OpenMPDirectiveKind CaptureRegion = getOpenMPCaptureRegionForClause(
18046       DKind, OMPC_thread_limit, LangOpts.OpenMP);
18047   if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
18048     ValExpr = MakeFullExpr(ValExpr).get();
18049     llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
18050     ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
18051     HelperValStmt = buildPreInits(Context, Captures);
18052   }
18053 
18054   return new (Context) OMPThreadLimitClause(
18055       ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
18056 }
18057 
18058 OMPClause *Sema::ActOnOpenMPPriorityClause(Expr *Priority,
18059                                            SourceLocation StartLoc,
18060                                            SourceLocation LParenLoc,
18061                                            SourceLocation EndLoc) {
18062   Expr *ValExpr = Priority;
18063   Stmt *HelperValStmt = nullptr;
18064   OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
18065 
18066   // OpenMP [2.9.1, task Constrcut]
18067   // The priority-value is a non-negative numerical scalar expression.
18068   if (!isNonNegativeIntegerValue(
18069           ValExpr, *this, OMPC_priority,
18070           /*StrictlyPositive=*/false, /*BuildCapture=*/true,
18071           DSAStack->getCurrentDirective(), &CaptureRegion, &HelperValStmt))
18072     return nullptr;
18073 
18074   return new (Context) OMPPriorityClause(ValExpr, HelperValStmt, CaptureRegion,
18075                                          StartLoc, LParenLoc, EndLoc);
18076 }
18077 
18078 OMPClause *Sema::ActOnOpenMPGrainsizeClause(Expr *Grainsize,
18079                                             SourceLocation StartLoc,
18080                                             SourceLocation LParenLoc,
18081                                             SourceLocation EndLoc) {
18082   Expr *ValExpr = Grainsize;
18083   Stmt *HelperValStmt = nullptr;
18084   OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
18085 
18086   // OpenMP [2.9.2, taskloop Constrcut]
18087   // The parameter of the grainsize clause must be a positive integer
18088   // expression.
18089   if (!isNonNegativeIntegerValue(
18090           ValExpr, *this, OMPC_grainsize,
18091           /*StrictlyPositive=*/true, /*BuildCapture=*/true,
18092           DSAStack->getCurrentDirective(), &CaptureRegion, &HelperValStmt))
18093     return nullptr;
18094 
18095   return new (Context) OMPGrainsizeClause(ValExpr, HelperValStmt, CaptureRegion,
18096                                           StartLoc, LParenLoc, EndLoc);
18097 }
18098 
18099 OMPClause *Sema::ActOnOpenMPNumTasksClause(Expr *NumTasks,
18100                                            SourceLocation StartLoc,
18101                                            SourceLocation LParenLoc,
18102                                            SourceLocation EndLoc) {
18103   Expr *ValExpr = NumTasks;
18104   Stmt *HelperValStmt = nullptr;
18105   OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
18106 
18107   // OpenMP [2.9.2, taskloop Constrcut]
18108   // The parameter of the num_tasks clause must be a positive integer
18109   // expression.
18110   if (!isNonNegativeIntegerValue(
18111           ValExpr, *this, OMPC_num_tasks,
18112           /*StrictlyPositive=*/true, /*BuildCapture=*/true,
18113           DSAStack->getCurrentDirective(), &CaptureRegion, &HelperValStmt))
18114     return nullptr;
18115 
18116   return new (Context) OMPNumTasksClause(ValExpr, HelperValStmt, CaptureRegion,
18117                                          StartLoc, LParenLoc, EndLoc);
18118 }
18119 
18120 OMPClause *Sema::ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
18121                                        SourceLocation LParenLoc,
18122                                        SourceLocation EndLoc) {
18123   // OpenMP [2.13.2, critical construct, Description]
18124   // ... where hint-expression is an integer constant expression that evaluates
18125   // to a valid lock hint.
18126   ExprResult HintExpr = VerifyPositiveIntegerConstantInClause(Hint, OMPC_hint);
18127   if (HintExpr.isInvalid())
18128     return nullptr;
18129   return new (Context)
18130       OMPHintClause(HintExpr.get(), StartLoc, LParenLoc, EndLoc);
18131 }
18132 
18133 /// Tries to find omp_event_handle_t type.
18134 static bool findOMPEventHandleT(Sema &S, SourceLocation Loc,
18135                                 DSAStackTy *Stack) {
18136   QualType OMPEventHandleT = Stack->getOMPEventHandleT();
18137   if (!OMPEventHandleT.isNull())
18138     return true;
18139   IdentifierInfo *II = &S.PP.getIdentifierTable().get("omp_event_handle_t");
18140   ParsedType PT = S.getTypeName(*II, Loc, S.getCurScope());
18141   if (!PT.getAsOpaquePtr() || PT.get().isNull()) {
18142     S.Diag(Loc, diag::err_omp_implied_type_not_found) << "omp_event_handle_t";
18143     return false;
18144   }
18145   Stack->setOMPEventHandleT(PT.get());
18146   return true;
18147 }
18148 
18149 OMPClause *Sema::ActOnOpenMPDetachClause(Expr *Evt, SourceLocation StartLoc,
18150                                          SourceLocation LParenLoc,
18151                                          SourceLocation EndLoc) {
18152   if (!Evt->isValueDependent() && !Evt->isTypeDependent() &&
18153       !Evt->isInstantiationDependent() &&
18154       !Evt->containsUnexpandedParameterPack()) {
18155     if (!findOMPEventHandleT(*this, Evt->getExprLoc(), DSAStack))
18156       return nullptr;
18157     // OpenMP 5.0, 2.10.1 task Construct.
18158     // event-handle is a variable of the omp_event_handle_t type.
18159     auto *Ref = dyn_cast<DeclRefExpr>(Evt->IgnoreParenImpCasts());
18160     if (!Ref) {
18161       Diag(Evt->getExprLoc(), diag::err_omp_var_expected)
18162           << "omp_event_handle_t" << 0 << Evt->getSourceRange();
18163       return nullptr;
18164     }
18165     auto *VD = dyn_cast_or_null<VarDecl>(Ref->getDecl());
18166     if (!VD) {
18167       Diag(Evt->getExprLoc(), diag::err_omp_var_expected)
18168           << "omp_event_handle_t" << 0 << Evt->getSourceRange();
18169       return nullptr;
18170     }
18171     if (!Context.hasSameUnqualifiedType(DSAStack->getOMPEventHandleT(),
18172                                         VD->getType()) ||
18173         VD->getType().isConstant(Context)) {
18174       Diag(Evt->getExprLoc(), diag::err_omp_var_expected)
18175           << "omp_event_handle_t" << 1 << VD->getType()
18176           << Evt->getSourceRange();
18177       return nullptr;
18178     }
18179     // OpenMP 5.0, 2.10.1 task Construct
18180     // [detach clause]... The event-handle will be considered as if it was
18181     // specified on a firstprivate clause.
18182     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, /*FromParent=*/false);
18183     if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
18184         DVar.RefExpr) {
18185       Diag(Evt->getExprLoc(), diag::err_omp_wrong_dsa)
18186           << getOpenMPClauseName(DVar.CKind)
18187           << getOpenMPClauseName(OMPC_firstprivate);
18188       reportOriginalDsa(*this, DSAStack, VD, DVar);
18189       return nullptr;
18190     }
18191   }
18192 
18193   return new (Context) OMPDetachClause(Evt, StartLoc, LParenLoc, EndLoc);
18194 }
18195 
18196 OMPClause *Sema::ActOnOpenMPDistScheduleClause(
18197     OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
18198     SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc,
18199     SourceLocation EndLoc) {
18200   if (Kind == OMPC_DIST_SCHEDULE_unknown) {
18201     std::string Values;
18202     Values += "'";
18203     Values += getOpenMPSimpleClauseTypeName(OMPC_dist_schedule, 0);
18204     Values += "'";
18205     Diag(KindLoc, diag::err_omp_unexpected_clause_value)
18206         << Values << getOpenMPClauseName(OMPC_dist_schedule);
18207     return nullptr;
18208   }
18209   Expr *ValExpr = ChunkSize;
18210   Stmt *HelperValStmt = nullptr;
18211   if (ChunkSize) {
18212     if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
18213         !ChunkSize->isInstantiationDependent() &&
18214         !ChunkSize->containsUnexpandedParameterPack()) {
18215       SourceLocation ChunkSizeLoc = ChunkSize->getBeginLoc();
18216       ExprResult Val =
18217           PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
18218       if (Val.isInvalid())
18219         return nullptr;
18220 
18221       ValExpr = Val.get();
18222 
18223       // OpenMP [2.7.1, Restrictions]
18224       //  chunk_size must be a loop invariant integer expression with a positive
18225       //  value.
18226       llvm::APSInt Result;
18227       if (ValExpr->isIntegerConstantExpr(Result, Context)) {
18228         if (Result.isSigned() && !Result.isStrictlyPositive()) {
18229           Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
18230               << "dist_schedule" << ChunkSize->getSourceRange();
18231           return nullptr;
18232         }
18233       } else if (getOpenMPCaptureRegionForClause(
18234                      DSAStack->getCurrentDirective(), OMPC_dist_schedule,
18235                      LangOpts.OpenMP) != OMPD_unknown &&
18236                  !CurContext->isDependentContext()) {
18237         ValExpr = MakeFullExpr(ValExpr).get();
18238         llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
18239         ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
18240         HelperValStmt = buildPreInits(Context, Captures);
18241       }
18242     }
18243   }
18244 
18245   return new (Context)
18246       OMPDistScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc,
18247                             Kind, ValExpr, HelperValStmt);
18248 }
18249 
18250 OMPClause *Sema::ActOnOpenMPDefaultmapClause(
18251     OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
18252     SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
18253     SourceLocation KindLoc, SourceLocation EndLoc) {
18254   if (getLangOpts().OpenMP < 50) {
18255     if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom ||
18256         Kind != OMPC_DEFAULTMAP_scalar) {
18257       std::string Value;
18258       SourceLocation Loc;
18259       Value += "'";
18260       if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom) {
18261         Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
18262                                                OMPC_DEFAULTMAP_MODIFIER_tofrom);
18263         Loc = MLoc;
18264       } else {
18265         Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
18266                                                OMPC_DEFAULTMAP_scalar);
18267         Loc = KindLoc;
18268       }
18269       Value += "'";
18270       Diag(Loc, diag::err_omp_unexpected_clause_value)
18271           << Value << getOpenMPClauseName(OMPC_defaultmap);
18272       return nullptr;
18273     }
18274   } else {
18275     bool isDefaultmapModifier = (M != OMPC_DEFAULTMAP_MODIFIER_unknown);
18276     bool isDefaultmapKind = (Kind != OMPC_DEFAULTMAP_unknown) ||
18277                             (LangOpts.OpenMP >= 50 && KindLoc.isInvalid());
18278     if (!isDefaultmapKind || !isDefaultmapModifier) {
18279       std::string ModifierValue = "'alloc', 'from', 'to', 'tofrom', "
18280                                   "'firstprivate', 'none', 'default'";
18281       std::string KindValue = "'scalar', 'aggregate', 'pointer'";
18282       if (!isDefaultmapKind && isDefaultmapModifier) {
18283         Diag(KindLoc, diag::err_omp_unexpected_clause_value)
18284             << KindValue << getOpenMPClauseName(OMPC_defaultmap);
18285       } else if (isDefaultmapKind && !isDefaultmapModifier) {
18286         Diag(MLoc, diag::err_omp_unexpected_clause_value)
18287             << ModifierValue << getOpenMPClauseName(OMPC_defaultmap);
18288       } else {
18289         Diag(MLoc, diag::err_omp_unexpected_clause_value)
18290             << ModifierValue << getOpenMPClauseName(OMPC_defaultmap);
18291         Diag(KindLoc, diag::err_omp_unexpected_clause_value)
18292             << KindValue << getOpenMPClauseName(OMPC_defaultmap);
18293       }
18294       return nullptr;
18295     }
18296 
18297     // OpenMP [5.0, 2.12.5, Restrictions, p. 174]
18298     //  At most one defaultmap clause for each category can appear on the
18299     //  directive.
18300     if (DSAStack->checkDefaultmapCategory(Kind)) {
18301       Diag(StartLoc, diag::err_omp_one_defaultmap_each_category);
18302       return nullptr;
18303     }
18304   }
18305   if (Kind == OMPC_DEFAULTMAP_unknown) {
18306     // Variable category is not specified - mark all categories.
18307     DSAStack->setDefaultDMAAttr(M, OMPC_DEFAULTMAP_aggregate, StartLoc);
18308     DSAStack->setDefaultDMAAttr(M, OMPC_DEFAULTMAP_scalar, StartLoc);
18309     DSAStack->setDefaultDMAAttr(M, OMPC_DEFAULTMAP_pointer, StartLoc);
18310   } else {
18311     DSAStack->setDefaultDMAAttr(M, Kind, StartLoc);
18312   }
18313 
18314   return new (Context)
18315       OMPDefaultmapClause(StartLoc, LParenLoc, MLoc, KindLoc, EndLoc, Kind, M);
18316 }
18317 
18318 bool Sema::ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc) {
18319   DeclContext *CurLexicalContext = getCurLexicalContext();
18320   if (!CurLexicalContext->isFileContext() &&
18321       !CurLexicalContext->isExternCContext() &&
18322       !CurLexicalContext->isExternCXXContext() &&
18323       !isa<CXXRecordDecl>(CurLexicalContext) &&
18324       !isa<ClassTemplateDecl>(CurLexicalContext) &&
18325       !isa<ClassTemplatePartialSpecializationDecl>(CurLexicalContext) &&
18326       !isa<ClassTemplateSpecializationDecl>(CurLexicalContext)) {
18327     Diag(Loc, diag::err_omp_region_not_file_context);
18328     return false;
18329   }
18330   ++DeclareTargetNestingLevel;
18331   return true;
18332 }
18333 
18334 void Sema::ActOnFinishOpenMPDeclareTargetDirective() {
18335   assert(DeclareTargetNestingLevel > 0 &&
18336          "Unexpected ActOnFinishOpenMPDeclareTargetDirective");
18337   --DeclareTargetNestingLevel;
18338 }
18339 
18340 NamedDecl *
18341 Sema::lookupOpenMPDeclareTargetName(Scope *CurScope, CXXScopeSpec &ScopeSpec,
18342                                     const DeclarationNameInfo &Id,
18343                                     NamedDeclSetType &SameDirectiveDecls) {
18344   LookupResult Lookup(*this, Id, LookupOrdinaryName);
18345   LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
18346 
18347   if (Lookup.isAmbiguous())
18348     return nullptr;
18349   Lookup.suppressDiagnostics();
18350 
18351   if (!Lookup.isSingleResult()) {
18352     VarOrFuncDeclFilterCCC CCC(*this);
18353     if (TypoCorrection Corrected =
18354             CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr, CCC,
18355                         CTK_ErrorRecovery)) {
18356       diagnoseTypo(Corrected, PDiag(diag::err_undeclared_var_use_suggest)
18357                                   << Id.getName());
18358       checkDeclIsAllowedInOpenMPTarget(nullptr, Corrected.getCorrectionDecl());
18359       return nullptr;
18360     }
18361 
18362     Diag(Id.getLoc(), diag::err_undeclared_var_use) << Id.getName();
18363     return nullptr;
18364   }
18365 
18366   NamedDecl *ND = Lookup.getAsSingle<NamedDecl>();
18367   if (!isa<VarDecl>(ND) && !isa<FunctionDecl>(ND) &&
18368       !isa<FunctionTemplateDecl>(ND)) {
18369     Diag(Id.getLoc(), diag::err_omp_invalid_target_decl) << Id.getName();
18370     return nullptr;
18371   }
18372   if (!SameDirectiveDecls.insert(cast<NamedDecl>(ND->getCanonicalDecl())))
18373     Diag(Id.getLoc(), diag::err_omp_declare_target_multiple) << Id.getName();
18374   return ND;
18375 }
18376 
18377 void Sema::ActOnOpenMPDeclareTargetName(
18378     NamedDecl *ND, SourceLocation Loc, OMPDeclareTargetDeclAttr::MapTypeTy MT,
18379     OMPDeclareTargetDeclAttr::DevTypeTy DT) {
18380   assert((isa<VarDecl>(ND) || isa<FunctionDecl>(ND) ||
18381           isa<FunctionTemplateDecl>(ND)) &&
18382          "Expected variable, function or function template.");
18383 
18384   // Diagnose marking after use as it may lead to incorrect diagnosis and
18385   // codegen.
18386   if (LangOpts.OpenMP >= 50 &&
18387       (ND->isUsed(/*CheckUsedAttr=*/false) || ND->isReferenced()))
18388     Diag(Loc, diag::warn_omp_declare_target_after_first_use);
18389 
18390   Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
18391       OMPDeclareTargetDeclAttr::getDeviceType(cast<ValueDecl>(ND));
18392   if (DevTy.hasValue() && *DevTy != DT) {
18393     Diag(Loc, diag::err_omp_device_type_mismatch)
18394         << OMPDeclareTargetDeclAttr::ConvertDevTypeTyToStr(DT)
18395         << OMPDeclareTargetDeclAttr::ConvertDevTypeTyToStr(*DevTy);
18396     return;
18397   }
18398   Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
18399       OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(cast<ValueDecl>(ND));
18400   if (!Res) {
18401     auto *A = OMPDeclareTargetDeclAttr::CreateImplicit(Context, MT, DT,
18402                                                        SourceRange(Loc, Loc));
18403     ND->addAttr(A);
18404     if (ASTMutationListener *ML = Context.getASTMutationListener())
18405       ML->DeclarationMarkedOpenMPDeclareTarget(ND, A);
18406     checkDeclIsAllowedInOpenMPTarget(nullptr, ND, Loc);
18407   } else if (*Res != MT) {
18408     Diag(Loc, diag::err_omp_declare_target_to_and_link) << ND;
18409   }
18410 }
18411 
18412 static void checkDeclInTargetContext(SourceLocation SL, SourceRange SR,
18413                                      Sema &SemaRef, Decl *D) {
18414   if (!D || !isa<VarDecl>(D))
18415     return;
18416   auto *VD = cast<VarDecl>(D);
18417   Optional<OMPDeclareTargetDeclAttr::MapTypeTy> MapTy =
18418       OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
18419   if (SemaRef.LangOpts.OpenMP >= 50 &&
18420       (SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true) ||
18421        SemaRef.getCurBlock() || SemaRef.getCurCapturedRegion()) &&
18422       VD->hasGlobalStorage()) {
18423     llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> MapTy =
18424         OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
18425     if (!MapTy || *MapTy != OMPDeclareTargetDeclAttr::MT_To) {
18426       // OpenMP 5.0, 2.12.7 declare target Directive, Restrictions
18427       // If a lambda declaration and definition appears between a
18428       // declare target directive and the matching end declare target
18429       // directive, all variables that are captured by the lambda
18430       // expression must also appear in a to clause.
18431       SemaRef.Diag(VD->getLocation(),
18432                    diag::err_omp_lambda_capture_in_declare_target_not_to);
18433       SemaRef.Diag(SL, diag::note_var_explicitly_captured_here)
18434           << VD << 0 << SR;
18435       return;
18436     }
18437   }
18438   if (MapTy.hasValue())
18439     return;
18440   SemaRef.Diag(VD->getLocation(), diag::warn_omp_not_in_target_context);
18441   SemaRef.Diag(SL, diag::note_used_here) << SR;
18442 }
18443 
18444 static bool checkValueDeclInTarget(SourceLocation SL, SourceRange SR,
18445                                    Sema &SemaRef, DSAStackTy *Stack,
18446                                    ValueDecl *VD) {
18447   return OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD) ||
18448          checkTypeMappable(SL, SR, SemaRef, Stack, VD->getType(),
18449                            /*FullCheck=*/false);
18450 }
18451 
18452 void Sema::checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D,
18453                                             SourceLocation IdLoc) {
18454   if (!D || D->isInvalidDecl())
18455     return;
18456   SourceRange SR = E ? E->getSourceRange() : D->getSourceRange();
18457   SourceLocation SL = E ? E->getBeginLoc() : D->getLocation();
18458   if (auto *VD = dyn_cast<VarDecl>(D)) {
18459     // Only global variables can be marked as declare target.
18460     if (!VD->isFileVarDecl() && !VD->isStaticLocal() &&
18461         !VD->isStaticDataMember())
18462       return;
18463     // 2.10.6: threadprivate variable cannot appear in a declare target
18464     // directive.
18465     if (DSAStack->isThreadPrivate(VD)) {
18466       Diag(SL, diag::err_omp_threadprivate_in_target);
18467       reportOriginalDsa(*this, DSAStack, VD, DSAStack->getTopDSA(VD, false));
18468       return;
18469     }
18470   }
18471   if (const auto *FTD = dyn_cast<FunctionTemplateDecl>(D))
18472     D = FTD->getTemplatedDecl();
18473   if (auto *FD = dyn_cast<FunctionDecl>(D)) {
18474     llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
18475         OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(FD);
18476     if (IdLoc.isValid() && Res && *Res == OMPDeclareTargetDeclAttr::MT_Link) {
18477       Diag(IdLoc, diag::err_omp_function_in_link_clause);
18478       Diag(FD->getLocation(), diag::note_defined_here) << FD;
18479       return;
18480     }
18481   }
18482   if (auto *VD = dyn_cast<ValueDecl>(D)) {
18483     // Problem if any with var declared with incomplete type will be reported
18484     // as normal, so no need to check it here.
18485     if ((E || !VD->getType()->isIncompleteType()) &&
18486         !checkValueDeclInTarget(SL, SR, *this, DSAStack, VD))
18487       return;
18488     if (!E && !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) {
18489       // Checking declaration inside declare target region.
18490       if (isa<VarDecl>(D) || isa<FunctionDecl>(D) ||
18491           isa<FunctionTemplateDecl>(D)) {
18492         auto *A = OMPDeclareTargetDeclAttr::CreateImplicit(
18493             Context, OMPDeclareTargetDeclAttr::MT_To,
18494             OMPDeclareTargetDeclAttr::DT_Any, SourceRange(IdLoc, IdLoc));
18495         D->addAttr(A);
18496         if (ASTMutationListener *ML = Context.getASTMutationListener())
18497           ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
18498       }
18499       return;
18500     }
18501   }
18502   if (!E)
18503     return;
18504   checkDeclInTargetContext(E->getExprLoc(), E->getSourceRange(), *this, D);
18505 }
18506 
18507 OMPClause *Sema::ActOnOpenMPToClause(ArrayRef<Expr *> VarList,
18508                                      CXXScopeSpec &MapperIdScopeSpec,
18509                                      DeclarationNameInfo &MapperId,
18510                                      const OMPVarListLocTy &Locs,
18511                                      ArrayRef<Expr *> UnresolvedMappers) {
18512   MappableVarListInfo MVLI(VarList);
18513   checkMappableExpressionList(*this, DSAStack, OMPC_to, MVLI, Locs.StartLoc,
18514                               MapperIdScopeSpec, MapperId, UnresolvedMappers);
18515   if (MVLI.ProcessedVarList.empty())
18516     return nullptr;
18517 
18518   return OMPToClause::Create(
18519       Context, Locs, MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
18520       MVLI.VarComponents, MVLI.UDMapperList,
18521       MapperIdScopeSpec.getWithLocInContext(Context), MapperId);
18522 }
18523 
18524 OMPClause *Sema::ActOnOpenMPFromClause(ArrayRef<Expr *> VarList,
18525                                        CXXScopeSpec &MapperIdScopeSpec,
18526                                        DeclarationNameInfo &MapperId,
18527                                        const OMPVarListLocTy &Locs,
18528                                        ArrayRef<Expr *> UnresolvedMappers) {
18529   MappableVarListInfo MVLI(VarList);
18530   checkMappableExpressionList(*this, DSAStack, OMPC_from, MVLI, Locs.StartLoc,
18531                               MapperIdScopeSpec, MapperId, UnresolvedMappers);
18532   if (MVLI.ProcessedVarList.empty())
18533     return nullptr;
18534 
18535   return OMPFromClause::Create(
18536       Context, Locs, MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
18537       MVLI.VarComponents, MVLI.UDMapperList,
18538       MapperIdScopeSpec.getWithLocInContext(Context), MapperId);
18539 }
18540 
18541 OMPClause *Sema::ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
18542                                                const OMPVarListLocTy &Locs) {
18543   MappableVarListInfo MVLI(VarList);
18544   SmallVector<Expr *, 8> PrivateCopies;
18545   SmallVector<Expr *, 8> Inits;
18546 
18547   for (Expr *RefExpr : VarList) {
18548     assert(RefExpr && "NULL expr in OpenMP use_device_ptr clause.");
18549     SourceLocation ELoc;
18550     SourceRange ERange;
18551     Expr *SimpleRefExpr = RefExpr;
18552     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
18553     if (Res.second) {
18554       // It will be analyzed later.
18555       MVLI.ProcessedVarList.push_back(RefExpr);
18556       PrivateCopies.push_back(nullptr);
18557       Inits.push_back(nullptr);
18558     }
18559     ValueDecl *D = Res.first;
18560     if (!D)
18561       continue;
18562 
18563     QualType Type = D->getType();
18564     Type = Type.getNonReferenceType().getUnqualifiedType();
18565 
18566     auto *VD = dyn_cast<VarDecl>(D);
18567 
18568     // Item should be a pointer or reference to pointer.
18569     if (!Type->isPointerType()) {
18570       Diag(ELoc, diag::err_omp_usedeviceptr_not_a_pointer)
18571           << 0 << RefExpr->getSourceRange();
18572       continue;
18573     }
18574 
18575     // Build the private variable and the expression that refers to it.
18576     auto VDPrivate =
18577         buildVarDecl(*this, ELoc, Type, D->getName(),
18578                      D->hasAttrs() ? &D->getAttrs() : nullptr,
18579                      VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
18580     if (VDPrivate->isInvalidDecl())
18581       continue;
18582 
18583     CurContext->addDecl(VDPrivate);
18584     DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
18585         *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
18586 
18587     // Add temporary variable to initialize the private copy of the pointer.
18588     VarDecl *VDInit =
18589         buildVarDecl(*this, RefExpr->getExprLoc(), Type, ".devptr.temp");
18590     DeclRefExpr *VDInitRefExpr = buildDeclRefExpr(
18591         *this, VDInit, RefExpr->getType(), RefExpr->getExprLoc());
18592     AddInitializerToDecl(VDPrivate,
18593                          DefaultLvalueConversion(VDInitRefExpr).get(),
18594                          /*DirectInit=*/false);
18595 
18596     // If required, build a capture to implement the privatization initialized
18597     // with the current list item value.
18598     DeclRefExpr *Ref = nullptr;
18599     if (!VD)
18600       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
18601     MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref);
18602     PrivateCopies.push_back(VDPrivateRefExpr);
18603     Inits.push_back(VDInitRefExpr);
18604 
18605     // We need to add a data sharing attribute for this variable to make sure it
18606     // is correctly captured. A variable that shows up in a use_device_ptr has
18607     // similar properties of a first private variable.
18608     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
18609 
18610     // Create a mappable component for the list item. List items in this clause
18611     // only need a component.
18612     MVLI.VarBaseDeclarations.push_back(D);
18613     MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
18614     MVLI.VarComponents.back().push_back(
18615         OMPClauseMappableExprCommon::MappableComponent(SimpleRefExpr, D));
18616   }
18617 
18618   if (MVLI.ProcessedVarList.empty())
18619     return nullptr;
18620 
18621   return OMPUseDevicePtrClause::Create(
18622       Context, Locs, MVLI.ProcessedVarList, PrivateCopies, Inits,
18623       MVLI.VarBaseDeclarations, MVLI.VarComponents);
18624 }
18625 
18626 OMPClause *Sema::ActOnOpenMPUseDeviceAddrClause(ArrayRef<Expr *> VarList,
18627                                                 const OMPVarListLocTy &Locs) {
18628   MappableVarListInfo MVLI(VarList);
18629 
18630   for (Expr *RefExpr : VarList) {
18631     assert(RefExpr && "NULL expr in OpenMP use_device_addr clause.");
18632     SourceLocation ELoc;
18633     SourceRange ERange;
18634     Expr *SimpleRefExpr = RefExpr;
18635     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
18636                               /*AllowArraySection=*/true);
18637     if (Res.second) {
18638       // It will be analyzed later.
18639       MVLI.ProcessedVarList.push_back(RefExpr);
18640     }
18641     ValueDecl *D = Res.first;
18642     if (!D)
18643       continue;
18644     auto *VD = dyn_cast<VarDecl>(D);
18645 
18646     // If required, build a capture to implement the privatization initialized
18647     // with the current list item value.
18648     DeclRefExpr *Ref = nullptr;
18649     if (!VD)
18650       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
18651     MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref);
18652 
18653     // We need to add a data sharing attribute for this variable to make sure it
18654     // is correctly captured. A variable that shows up in a use_device_addr has
18655     // similar properties of a first private variable.
18656     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
18657 
18658     // Create a mappable component for the list item. List items in this clause
18659     // only need a component.
18660     MVLI.VarBaseDeclarations.push_back(D);
18661     MVLI.VarComponents.emplace_back();
18662     Expr *Component = SimpleRefExpr;
18663     if (VD && (isa<OMPArraySectionExpr>(RefExpr->IgnoreParenImpCasts()) ||
18664                isa<ArraySubscriptExpr>(RefExpr->IgnoreParenImpCasts())))
18665       Component = DefaultFunctionArrayLvalueConversion(SimpleRefExpr).get();
18666     MVLI.VarComponents.back().push_back(
18667         OMPClauseMappableExprCommon::MappableComponent(Component, D));
18668   }
18669 
18670   if (MVLI.ProcessedVarList.empty())
18671     return nullptr;
18672 
18673   return OMPUseDeviceAddrClause::Create(Context, Locs, MVLI.ProcessedVarList,
18674                                         MVLI.VarBaseDeclarations,
18675                                         MVLI.VarComponents);
18676 }
18677 
18678 OMPClause *Sema::ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
18679                                               const OMPVarListLocTy &Locs) {
18680   MappableVarListInfo MVLI(VarList);
18681   for (Expr *RefExpr : VarList) {
18682     assert(RefExpr && "NULL expr in OpenMP is_device_ptr clause.");
18683     SourceLocation ELoc;
18684     SourceRange ERange;
18685     Expr *SimpleRefExpr = RefExpr;
18686     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
18687     if (Res.second) {
18688       // It will be analyzed later.
18689       MVLI.ProcessedVarList.push_back(RefExpr);
18690     }
18691     ValueDecl *D = Res.first;
18692     if (!D)
18693       continue;
18694 
18695     QualType Type = D->getType();
18696     // item should be a pointer or array or reference to pointer or array
18697     if (!Type.getNonReferenceType()->isPointerType() &&
18698         !Type.getNonReferenceType()->isArrayType()) {
18699       Diag(ELoc, diag::err_omp_argument_type_isdeviceptr)
18700           << 0 << RefExpr->getSourceRange();
18701       continue;
18702     }
18703 
18704     // Check if the declaration in the clause does not show up in any data
18705     // sharing attribute.
18706     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
18707     if (isOpenMPPrivate(DVar.CKind)) {
18708       Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
18709           << getOpenMPClauseName(DVar.CKind)
18710           << getOpenMPClauseName(OMPC_is_device_ptr)
18711           << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
18712       reportOriginalDsa(*this, DSAStack, D, DVar);
18713       continue;
18714     }
18715 
18716     const Expr *ConflictExpr;
18717     if (DSAStack->checkMappableExprComponentListsForDecl(
18718             D, /*CurrentRegionOnly=*/true,
18719             [&ConflictExpr](
18720                 OMPClauseMappableExprCommon::MappableExprComponentListRef R,
18721                 OpenMPClauseKind) -> bool {
18722               ConflictExpr = R.front().getAssociatedExpression();
18723               return true;
18724             })) {
18725       Diag(ELoc, diag::err_omp_map_shared_storage) << RefExpr->getSourceRange();
18726       Diag(ConflictExpr->getExprLoc(), diag::note_used_here)
18727           << ConflictExpr->getSourceRange();
18728       continue;
18729     }
18730 
18731     // Store the components in the stack so that they can be used to check
18732     // against other clauses later on.
18733     OMPClauseMappableExprCommon::MappableComponent MC(SimpleRefExpr, D);
18734     DSAStack->addMappableExpressionComponents(
18735         D, MC, /*WhereFoundClauseKind=*/OMPC_is_device_ptr);
18736 
18737     // Record the expression we've just processed.
18738     MVLI.ProcessedVarList.push_back(SimpleRefExpr);
18739 
18740     // Create a mappable component for the list item. List items in this clause
18741     // only need a component. We use a null declaration to signal fields in
18742     // 'this'.
18743     assert((isa<DeclRefExpr>(SimpleRefExpr) ||
18744             isa<CXXThisExpr>(cast<MemberExpr>(SimpleRefExpr)->getBase())) &&
18745            "Unexpected device pointer expression!");
18746     MVLI.VarBaseDeclarations.push_back(
18747         isa<DeclRefExpr>(SimpleRefExpr) ? D : nullptr);
18748     MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
18749     MVLI.VarComponents.back().push_back(MC);
18750   }
18751 
18752   if (MVLI.ProcessedVarList.empty())
18753     return nullptr;
18754 
18755   return OMPIsDevicePtrClause::Create(Context, Locs, MVLI.ProcessedVarList,
18756                                       MVLI.VarBaseDeclarations,
18757                                       MVLI.VarComponents);
18758 }
18759 
18760 OMPClause *Sema::ActOnOpenMPAllocateClause(
18761     Expr *Allocator, ArrayRef<Expr *> VarList, SourceLocation StartLoc,
18762     SourceLocation ColonLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
18763   if (Allocator) {
18764     // OpenMP [2.11.4 allocate Clause, Description]
18765     // allocator is an expression of omp_allocator_handle_t type.
18766     if (!findOMPAllocatorHandleT(*this, Allocator->getExprLoc(), DSAStack))
18767       return nullptr;
18768 
18769     ExprResult AllocatorRes = DefaultLvalueConversion(Allocator);
18770     if (AllocatorRes.isInvalid())
18771       return nullptr;
18772     AllocatorRes = PerformImplicitConversion(AllocatorRes.get(),
18773                                              DSAStack->getOMPAllocatorHandleT(),
18774                                              Sema::AA_Initializing,
18775                                              /*AllowExplicit=*/true);
18776     if (AllocatorRes.isInvalid())
18777       return nullptr;
18778     Allocator = AllocatorRes.get();
18779   } else {
18780     // OpenMP 5.0, 2.11.4 allocate Clause, Restrictions.
18781     // allocate clauses that appear on a target construct or on constructs in a
18782     // target region must specify an allocator expression unless a requires
18783     // directive with the dynamic_allocators clause is present in the same
18784     // compilation unit.
18785     if (LangOpts.OpenMPIsDevice &&
18786         !DSAStack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>())
18787       targetDiag(StartLoc, diag::err_expected_allocator_expression);
18788   }
18789   // Analyze and build list of variables.
18790   SmallVector<Expr *, 8> Vars;
18791   for (Expr *RefExpr : VarList) {
18792     assert(RefExpr && "NULL expr in OpenMP private clause.");
18793     SourceLocation ELoc;
18794     SourceRange ERange;
18795     Expr *SimpleRefExpr = RefExpr;
18796     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
18797     if (Res.second) {
18798       // It will be analyzed later.
18799       Vars.push_back(RefExpr);
18800     }
18801     ValueDecl *D = Res.first;
18802     if (!D)
18803       continue;
18804 
18805     auto *VD = dyn_cast<VarDecl>(D);
18806     DeclRefExpr *Ref = nullptr;
18807     if (!VD && !CurContext->isDependentContext())
18808       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
18809     Vars.push_back((VD || CurContext->isDependentContext())
18810                        ? RefExpr->IgnoreParens()
18811                        : Ref);
18812   }
18813 
18814   if (Vars.empty())
18815     return nullptr;
18816 
18817   if (Allocator)
18818     DSAStack->addInnerAllocatorExpr(Allocator);
18819   return OMPAllocateClause::Create(Context, StartLoc, LParenLoc, Allocator,
18820                                    ColonLoc, EndLoc, Vars);
18821 }
18822 
18823 OMPClause *Sema::ActOnOpenMPNontemporalClause(ArrayRef<Expr *> VarList,
18824                                               SourceLocation StartLoc,
18825                                               SourceLocation LParenLoc,
18826                                               SourceLocation EndLoc) {
18827   SmallVector<Expr *, 8> Vars;
18828   for (Expr *RefExpr : VarList) {
18829     assert(RefExpr && "NULL expr in OpenMP nontemporal clause.");
18830     SourceLocation ELoc;
18831     SourceRange ERange;
18832     Expr *SimpleRefExpr = RefExpr;
18833     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
18834     if (Res.second)
18835       // It will be analyzed later.
18836       Vars.push_back(RefExpr);
18837     ValueDecl *D = Res.first;
18838     if (!D)
18839       continue;
18840 
18841     // OpenMP 5.0, 2.9.3.1 simd Construct, Restrictions.
18842     // A list-item cannot appear in more than one nontemporal clause.
18843     if (const Expr *PrevRef =
18844             DSAStack->addUniqueNontemporal(D, SimpleRefExpr)) {
18845       Diag(ELoc, diag::err_omp_used_in_clause_twice)
18846           << 0 << getOpenMPClauseName(OMPC_nontemporal) << ERange;
18847       Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
18848           << getOpenMPClauseName(OMPC_nontemporal);
18849       continue;
18850     }
18851 
18852     Vars.push_back(RefExpr);
18853   }
18854 
18855   if (Vars.empty())
18856     return nullptr;
18857 
18858   return OMPNontemporalClause::Create(Context, StartLoc, LParenLoc, EndLoc,
18859                                       Vars);
18860 }
18861 
18862 OMPClause *Sema::ActOnOpenMPInclusiveClause(ArrayRef<Expr *> VarList,
18863                                             SourceLocation StartLoc,
18864                                             SourceLocation LParenLoc,
18865                                             SourceLocation EndLoc) {
18866   SmallVector<Expr *, 8> Vars;
18867   for (Expr *RefExpr : VarList) {
18868     assert(RefExpr && "NULL expr in OpenMP nontemporal clause.");
18869     SourceLocation ELoc;
18870     SourceRange ERange;
18871     Expr *SimpleRefExpr = RefExpr;
18872     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
18873                               /*AllowArraySection=*/true);
18874     if (Res.second)
18875       // It will be analyzed later.
18876       Vars.push_back(RefExpr);
18877     ValueDecl *D = Res.first;
18878     if (!D)
18879       continue;
18880 
18881     const DSAStackTy::DSAVarData DVar =
18882         DSAStack->getTopDSA(D, /*FromParent=*/true);
18883     // OpenMP 5.0, 2.9.6, scan Directive, Restrictions.
18884     // A list item that appears in the inclusive or exclusive clause must appear
18885     // in a reduction clause with the inscan modifier on the enclosing
18886     // worksharing-loop, worksharing-loop SIMD, or simd construct.
18887     if (DVar.CKind != OMPC_reduction ||
18888         DVar.Modifier != OMPC_REDUCTION_inscan)
18889       Diag(ELoc, diag::err_omp_inclusive_exclusive_not_reduction)
18890           << RefExpr->getSourceRange();
18891 
18892     if (DSAStack->getParentDirective() != OMPD_unknown)
18893       DSAStack->markDeclAsUsedInScanDirective(D);
18894     Vars.push_back(RefExpr);
18895   }
18896 
18897   if (Vars.empty())
18898     return nullptr;
18899 
18900   return OMPInclusiveClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
18901 }
18902 
18903 OMPClause *Sema::ActOnOpenMPExclusiveClause(ArrayRef<Expr *> VarList,
18904                                             SourceLocation StartLoc,
18905                                             SourceLocation LParenLoc,
18906                                             SourceLocation EndLoc) {
18907   SmallVector<Expr *, 8> Vars;
18908   for (Expr *RefExpr : VarList) {
18909     assert(RefExpr && "NULL expr in OpenMP nontemporal clause.");
18910     SourceLocation ELoc;
18911     SourceRange ERange;
18912     Expr *SimpleRefExpr = RefExpr;
18913     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
18914                               /*AllowArraySection=*/true);
18915     if (Res.second)
18916       // It will be analyzed later.
18917       Vars.push_back(RefExpr);
18918     ValueDecl *D = Res.first;
18919     if (!D)
18920       continue;
18921 
18922     OpenMPDirectiveKind ParentDirective = DSAStack->getParentDirective();
18923     DSAStackTy::DSAVarData DVar;
18924     if (ParentDirective != OMPD_unknown)
18925       DVar = DSAStack->getTopDSA(D, /*FromParent=*/true);
18926     // OpenMP 5.0, 2.9.6, scan Directive, Restrictions.
18927     // A list item that appears in the inclusive or exclusive clause must appear
18928     // in a reduction clause with the inscan modifier on the enclosing
18929     // worksharing-loop, worksharing-loop SIMD, or simd construct.
18930     if (ParentDirective == OMPD_unknown || DVar.CKind != OMPC_reduction ||
18931         DVar.Modifier != OMPC_REDUCTION_inscan) {
18932       Diag(ELoc, diag::err_omp_inclusive_exclusive_not_reduction)
18933           << RefExpr->getSourceRange();
18934     } else {
18935       DSAStack->markDeclAsUsedInScanDirective(D);
18936     }
18937     Vars.push_back(RefExpr);
18938   }
18939 
18940   if (Vars.empty())
18941     return nullptr;
18942 
18943   return OMPExclusiveClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
18944 }
18945 
18946 /// Tries to find omp_alloctrait_t type.
18947 static bool findOMPAlloctraitT(Sema &S, SourceLocation Loc, DSAStackTy *Stack) {
18948   QualType OMPAlloctraitT = Stack->getOMPAlloctraitT();
18949   if (!OMPAlloctraitT.isNull())
18950     return true;
18951   IdentifierInfo &II = S.PP.getIdentifierTable().get("omp_alloctrait_t");
18952   ParsedType PT = S.getTypeName(II, Loc, S.getCurScope());
18953   if (!PT.getAsOpaquePtr() || PT.get().isNull()) {
18954     S.Diag(Loc, diag::err_omp_implied_type_not_found) << "omp_alloctrait_t";
18955     return false;
18956   }
18957   Stack->setOMPAlloctraitT(PT.get());
18958   return true;
18959 }
18960 
18961 OMPClause *Sema::ActOnOpenMPUsesAllocatorClause(
18962     SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc,
18963     ArrayRef<UsesAllocatorsData> Data) {
18964   // OpenMP [2.12.5, target Construct]
18965   // allocator is an identifier of omp_allocator_handle_t type.
18966   if (!findOMPAllocatorHandleT(*this, StartLoc, DSAStack))
18967     return nullptr;
18968   // OpenMP [2.12.5, target Construct]
18969   // allocator-traits-array is an identifier of const omp_alloctrait_t * type.
18970   if (llvm::any_of(
18971           Data,
18972           [](const UsesAllocatorsData &D) { return D.AllocatorTraits; }) &&
18973       !findOMPAlloctraitT(*this, StartLoc, DSAStack))
18974     return nullptr;
18975   llvm::SmallSet<CanonicalDeclPtr<Decl>, 4> PredefinedAllocators;
18976   for (int I = 0; I < OMPAllocateDeclAttr::OMPUserDefinedMemAlloc; ++I) {
18977     auto AllocatorKind = static_cast<OMPAllocateDeclAttr::AllocatorTypeTy>(I);
18978     StringRef Allocator =
18979         OMPAllocateDeclAttr::ConvertAllocatorTypeTyToStr(AllocatorKind);
18980     DeclarationName AllocatorName = &Context.Idents.get(Allocator);
18981     PredefinedAllocators.insert(LookupSingleName(
18982         TUScope, AllocatorName, StartLoc, Sema::LookupAnyName));
18983   }
18984 
18985   SmallVector<OMPUsesAllocatorsClause::Data, 4> NewData;
18986   for (const UsesAllocatorsData &D : Data) {
18987     Expr *AllocatorExpr = nullptr;
18988     // Check allocator expression.
18989     if (D.Allocator->isTypeDependent()) {
18990       AllocatorExpr = D.Allocator;
18991     } else {
18992       // Traits were specified - need to assign new allocator to the specified
18993       // allocator, so it must be an lvalue.
18994       AllocatorExpr = D.Allocator->IgnoreParenImpCasts();
18995       auto *DRE = dyn_cast<DeclRefExpr>(AllocatorExpr);
18996       bool IsPredefinedAllocator = false;
18997       if (DRE)
18998         IsPredefinedAllocator = PredefinedAllocators.count(DRE->getDecl());
18999       if (!DRE ||
19000           !(Context.hasSameUnqualifiedType(
19001                 AllocatorExpr->getType(), DSAStack->getOMPAllocatorHandleT()) ||
19002             Context.typesAreCompatible(AllocatorExpr->getType(),
19003                                        DSAStack->getOMPAllocatorHandleT(),
19004                                        /*CompareUnqualified=*/true)) ||
19005           (!IsPredefinedAllocator &&
19006            (AllocatorExpr->getType().isConstant(Context) ||
19007             !AllocatorExpr->isLValue()))) {
19008         Diag(D.Allocator->getExprLoc(), diag::err_omp_var_expected)
19009             << "omp_allocator_handle_t" << (DRE ? 1 : 0)
19010             << AllocatorExpr->getType() << D.Allocator->getSourceRange();
19011         continue;
19012       }
19013       // OpenMP [2.12.5, target Construct]
19014       // Predefined allocators appearing in a uses_allocators clause cannot have
19015       // traits specified.
19016       if (IsPredefinedAllocator && D.AllocatorTraits) {
19017         Diag(D.AllocatorTraits->getExprLoc(),
19018              diag::err_omp_predefined_allocator_with_traits)
19019             << D.AllocatorTraits->getSourceRange();
19020         Diag(D.Allocator->getExprLoc(), diag::note_omp_predefined_allocator)
19021             << cast<NamedDecl>(DRE->getDecl())->getName()
19022             << D.Allocator->getSourceRange();
19023         continue;
19024       }
19025       // OpenMP [2.12.5, target Construct]
19026       // Non-predefined allocators appearing in a uses_allocators clause must
19027       // have traits specified.
19028       if (!IsPredefinedAllocator && !D.AllocatorTraits) {
19029         Diag(D.Allocator->getExprLoc(),
19030              diag::err_omp_nonpredefined_allocator_without_traits);
19031         continue;
19032       }
19033       // No allocator traits - just convert it to rvalue.
19034       if (!D.AllocatorTraits)
19035         AllocatorExpr = DefaultLvalueConversion(AllocatorExpr).get();
19036       DSAStack->addUsesAllocatorsDecl(
19037           DRE->getDecl(),
19038           IsPredefinedAllocator
19039               ? DSAStackTy::UsesAllocatorsDeclKind::PredefinedAllocator
19040               : DSAStackTy::UsesAllocatorsDeclKind::UserDefinedAllocator);
19041     }
19042     Expr *AllocatorTraitsExpr = nullptr;
19043     if (D.AllocatorTraits) {
19044       if (D.AllocatorTraits->isTypeDependent()) {
19045         AllocatorTraitsExpr = D.AllocatorTraits;
19046       } else {
19047         // OpenMP [2.12.5, target Construct]
19048         // Arrays that contain allocator traits that appear in a uses_allocators
19049         // clause must be constant arrays, have constant values and be defined
19050         // in the same scope as the construct in which the clause appears.
19051         AllocatorTraitsExpr = D.AllocatorTraits->IgnoreParenImpCasts();
19052         // Check that traits expr is a constant array.
19053         QualType TraitTy;
19054         if (const ArrayType *Ty =
19055                 AllocatorTraitsExpr->getType()->getAsArrayTypeUnsafe())
19056           if (const auto *ConstArrayTy = dyn_cast<ConstantArrayType>(Ty))
19057             TraitTy = ConstArrayTy->getElementType();
19058         if (TraitTy.isNull() ||
19059             !(Context.hasSameUnqualifiedType(TraitTy,
19060                                              DSAStack->getOMPAlloctraitT()) ||
19061               Context.typesAreCompatible(TraitTy, DSAStack->getOMPAlloctraitT(),
19062                                          /*CompareUnqualified=*/true))) {
19063           Diag(D.AllocatorTraits->getExprLoc(),
19064                diag::err_omp_expected_array_alloctraits)
19065               << AllocatorTraitsExpr->getType();
19066           continue;
19067         }
19068         // Do not map by default allocator traits if it is a standalone
19069         // variable.
19070         if (auto *DRE = dyn_cast<DeclRefExpr>(AllocatorTraitsExpr))
19071           DSAStack->addUsesAllocatorsDecl(
19072               DRE->getDecl(),
19073               DSAStackTy::UsesAllocatorsDeclKind::AllocatorTrait);
19074       }
19075     }
19076     OMPUsesAllocatorsClause::Data &NewD = NewData.emplace_back();
19077     NewD.Allocator = AllocatorExpr;
19078     NewD.AllocatorTraits = AllocatorTraitsExpr;
19079     NewD.LParenLoc = D.LParenLoc;
19080     NewD.RParenLoc = D.RParenLoc;
19081   }
19082   return OMPUsesAllocatorsClause::Create(Context, StartLoc, LParenLoc, EndLoc,
19083                                          NewData);
19084 }
19085 
19086 OMPClause *Sema::ActOnOpenMPAffinityClause(
19087     SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc,
19088     SourceLocation EndLoc, Expr *Modifier, ArrayRef<Expr *> Locators) {
19089   SmallVector<Expr *, 8> Vars;
19090   for (Expr *RefExpr : Locators) {
19091     assert(RefExpr && "NULL expr in OpenMP shared clause.");
19092     if (isa<DependentScopeDeclRefExpr>(RefExpr) || RefExpr->isTypeDependent()) {
19093       // It will be analyzed later.
19094       Vars.push_back(RefExpr);
19095       continue;
19096     }
19097 
19098     SourceLocation ELoc = RefExpr->getExprLoc();
19099     Expr *SimpleExpr = RefExpr->IgnoreParenImpCasts();
19100 
19101     if (!SimpleExpr->isLValue()) {
19102       Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
19103           << 1 << 0 << RefExpr->getSourceRange();
19104       continue;
19105     }
19106 
19107     ExprResult Res;
19108     {
19109       Sema::TentativeAnalysisScope Trap(*this);
19110       Res = CreateBuiltinUnaryOp(ELoc, UO_AddrOf, SimpleExpr);
19111     }
19112     if (!Res.isUsable() && !isa<OMPArraySectionExpr>(SimpleExpr) &&
19113         !isa<OMPArrayShapingExpr>(SimpleExpr)) {
19114       Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
19115           << 1 << 0 << RefExpr->getSourceRange();
19116       continue;
19117     }
19118     Vars.push_back(SimpleExpr);
19119   }
19120 
19121   return OMPAffinityClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
19122                                    EndLoc, Modifier, Vars);
19123 }
19124