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     llvm_unreachable("Unknown OpenMP directive");
4054   }
4055 }
4056 
4057 int Sema::getNumberOfConstructScopes(unsigned Level) const {
4058   return getOpenMPCaptureLevels(DSAStack->getDirective(Level));
4059 }
4060 
4061 int Sema::getOpenMPCaptureLevels(OpenMPDirectiveKind DKind) {
4062   SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
4063   getOpenMPCaptureRegions(CaptureRegions, DKind);
4064   return CaptureRegions.size();
4065 }
4066 
4067 static OMPCapturedExprDecl *buildCaptureDecl(Sema &S, IdentifierInfo *Id,
4068                                              Expr *CaptureExpr, bool WithInit,
4069                                              bool AsExpression) {
4070   assert(CaptureExpr);
4071   ASTContext &C = S.getASTContext();
4072   Expr *Init = AsExpression ? CaptureExpr : CaptureExpr->IgnoreImpCasts();
4073   QualType Ty = Init->getType();
4074   if (CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue()) {
4075     if (S.getLangOpts().CPlusPlus) {
4076       Ty = C.getLValueReferenceType(Ty);
4077     } else {
4078       Ty = C.getPointerType(Ty);
4079       ExprResult Res =
4080           S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_AddrOf, Init);
4081       if (!Res.isUsable())
4082         return nullptr;
4083       Init = Res.get();
4084     }
4085     WithInit = true;
4086   }
4087   auto *CED = OMPCapturedExprDecl::Create(C, S.CurContext, Id, Ty,
4088                                           CaptureExpr->getBeginLoc());
4089   if (!WithInit)
4090     CED->addAttr(OMPCaptureNoInitAttr::CreateImplicit(C));
4091   S.CurContext->addHiddenDecl(CED);
4092   S.AddInitializerToDecl(CED, Init, /*DirectInit=*/false);
4093   return CED;
4094 }
4095 
4096 static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr,
4097                                  bool WithInit) {
4098   OMPCapturedExprDecl *CD;
4099   if (VarDecl *VD = S.isOpenMPCapturedDecl(D))
4100     CD = cast<OMPCapturedExprDecl>(VD);
4101   else
4102     CD = buildCaptureDecl(S, D->getIdentifier(), CaptureExpr, WithInit,
4103                           /*AsExpression=*/false);
4104   return buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
4105                           CaptureExpr->getExprLoc());
4106 }
4107 
4108 static ExprResult buildCapture(Sema &S, Expr *CaptureExpr, DeclRefExpr *&Ref) {
4109   CaptureExpr = S.DefaultLvalueConversion(CaptureExpr).get();
4110   if (!Ref) {
4111     OMPCapturedExprDecl *CD = buildCaptureDecl(
4112         S, &S.getASTContext().Idents.get(".capture_expr."), CaptureExpr,
4113         /*WithInit=*/true, /*AsExpression=*/true);
4114     Ref = buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
4115                            CaptureExpr->getExprLoc());
4116   }
4117   ExprResult Res = Ref;
4118   if (!S.getLangOpts().CPlusPlus &&
4119       CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue() &&
4120       Ref->getType()->isPointerType()) {
4121     Res = S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_Deref, Ref);
4122     if (!Res.isUsable())
4123       return ExprError();
4124   }
4125   return S.DefaultLvalueConversion(Res.get());
4126 }
4127 
4128 namespace {
4129 // OpenMP directives parsed in this section are represented as a
4130 // CapturedStatement with an associated statement.  If a syntax error
4131 // is detected during the parsing of the associated statement, the
4132 // compiler must abort processing and close the CapturedStatement.
4133 //
4134 // Combined directives such as 'target parallel' have more than one
4135 // nested CapturedStatements.  This RAII ensures that we unwind out
4136 // of all the nested CapturedStatements when an error is found.
4137 class CaptureRegionUnwinderRAII {
4138 private:
4139   Sema &S;
4140   bool &ErrorFound;
4141   OpenMPDirectiveKind DKind = OMPD_unknown;
4142 
4143 public:
4144   CaptureRegionUnwinderRAII(Sema &S, bool &ErrorFound,
4145                             OpenMPDirectiveKind DKind)
4146       : S(S), ErrorFound(ErrorFound), DKind(DKind) {}
4147   ~CaptureRegionUnwinderRAII() {
4148     if (ErrorFound) {
4149       int ThisCaptureLevel = S.getOpenMPCaptureLevels(DKind);
4150       while (--ThisCaptureLevel >= 0)
4151         S.ActOnCapturedRegionError();
4152     }
4153   }
4154 };
4155 } // namespace
4156 
4157 void Sema::tryCaptureOpenMPLambdas(ValueDecl *V) {
4158   // Capture variables captured by reference in lambdas for target-based
4159   // directives.
4160   if (!CurContext->isDependentContext() &&
4161       (isOpenMPTargetExecutionDirective(DSAStack->getCurrentDirective()) ||
4162        isOpenMPTargetDataManagementDirective(
4163            DSAStack->getCurrentDirective()))) {
4164     QualType Type = V->getType();
4165     if (const auto *RD = Type.getCanonicalType()
4166                              .getNonReferenceType()
4167                              ->getAsCXXRecordDecl()) {
4168       bool SavedForceCaptureByReferenceInTargetExecutable =
4169           DSAStack->isForceCaptureByReferenceInTargetExecutable();
4170       DSAStack->setForceCaptureByReferenceInTargetExecutable(
4171           /*V=*/true);
4172       if (RD->isLambda()) {
4173         llvm::DenseMap<const VarDecl *, FieldDecl *> Captures;
4174         FieldDecl *ThisCapture;
4175         RD->getCaptureFields(Captures, ThisCapture);
4176         for (const LambdaCapture &LC : RD->captures()) {
4177           if (LC.getCaptureKind() == LCK_ByRef) {
4178             VarDecl *VD = LC.getCapturedVar();
4179             DeclContext *VDC = VD->getDeclContext();
4180             if (!VDC->Encloses(CurContext))
4181               continue;
4182             MarkVariableReferenced(LC.getLocation(), VD);
4183           } else if (LC.getCaptureKind() == LCK_This) {
4184             QualType ThisTy = getCurrentThisType();
4185             if (!ThisTy.isNull() &&
4186                 Context.typesAreCompatible(ThisTy, ThisCapture->getType()))
4187               CheckCXXThisCapture(LC.getLocation());
4188           }
4189         }
4190       }
4191       DSAStack->setForceCaptureByReferenceInTargetExecutable(
4192           SavedForceCaptureByReferenceInTargetExecutable);
4193     }
4194   }
4195 }
4196 
4197 static bool checkOrderedOrderSpecified(Sema &S,
4198                                        const ArrayRef<OMPClause *> Clauses) {
4199   const OMPOrderedClause *Ordered = nullptr;
4200   const OMPOrderClause *Order = nullptr;
4201 
4202   for (const OMPClause *Clause : Clauses) {
4203     if (Clause->getClauseKind() == OMPC_ordered)
4204       Ordered = cast<OMPOrderedClause>(Clause);
4205     else if (Clause->getClauseKind() == OMPC_order) {
4206       Order = cast<OMPOrderClause>(Clause);
4207       if (Order->getKind() != OMPC_ORDER_concurrent)
4208         Order = nullptr;
4209     }
4210     if (Ordered && Order)
4211       break;
4212   }
4213 
4214   if (Ordered && Order) {
4215     S.Diag(Order->getKindKwLoc(),
4216            diag::err_omp_simple_clause_incompatible_with_ordered)
4217         << getOpenMPClauseName(OMPC_order)
4218         << getOpenMPSimpleClauseTypeName(OMPC_order, OMPC_ORDER_concurrent)
4219         << SourceRange(Order->getBeginLoc(), Order->getEndLoc());
4220     S.Diag(Ordered->getBeginLoc(), diag::note_omp_ordered_param)
4221         << 0 << SourceRange(Ordered->getBeginLoc(), Ordered->getEndLoc());
4222     return true;
4223   }
4224   return false;
4225 }
4226 
4227 StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S,
4228                                       ArrayRef<OMPClause *> Clauses) {
4229   bool ErrorFound = false;
4230   CaptureRegionUnwinderRAII CaptureRegionUnwinder(
4231       *this, ErrorFound, DSAStack->getCurrentDirective());
4232   if (!S.isUsable()) {
4233     ErrorFound = true;
4234     return StmtError();
4235   }
4236 
4237   SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
4238   getOpenMPCaptureRegions(CaptureRegions, DSAStack->getCurrentDirective());
4239   OMPOrderedClause *OC = nullptr;
4240   OMPScheduleClause *SC = nullptr;
4241   SmallVector<const OMPLinearClause *, 4> LCs;
4242   SmallVector<const OMPClauseWithPreInit *, 4> PICs;
4243   // This is required for proper codegen.
4244   for (OMPClause *Clause : Clauses) {
4245     if (!LangOpts.OpenMPSimd &&
4246         isOpenMPTaskingDirective(DSAStack->getCurrentDirective()) &&
4247         Clause->getClauseKind() == OMPC_in_reduction) {
4248       // Capture taskgroup task_reduction descriptors inside the tasking regions
4249       // with the corresponding in_reduction items.
4250       auto *IRC = cast<OMPInReductionClause>(Clause);
4251       for (Expr *E : IRC->taskgroup_descriptors())
4252         if (E)
4253           MarkDeclarationsReferencedInExpr(E);
4254     }
4255     if (isOpenMPPrivate(Clause->getClauseKind()) ||
4256         Clause->getClauseKind() == OMPC_copyprivate ||
4257         (getLangOpts().OpenMPUseTLS &&
4258          getASTContext().getTargetInfo().isTLSSupported() &&
4259          Clause->getClauseKind() == OMPC_copyin)) {
4260       DSAStack->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin);
4261       // Mark all variables in private list clauses as used in inner region.
4262       for (Stmt *VarRef : Clause->children()) {
4263         if (auto *E = cast_or_null<Expr>(VarRef)) {
4264           MarkDeclarationsReferencedInExpr(E);
4265         }
4266       }
4267       DSAStack->setForceVarCapturing(/*V=*/false);
4268     } else if (CaptureRegions.size() > 1 ||
4269                CaptureRegions.back() != OMPD_unknown) {
4270       if (auto *C = OMPClauseWithPreInit::get(Clause))
4271         PICs.push_back(C);
4272       if (auto *C = OMPClauseWithPostUpdate::get(Clause)) {
4273         if (Expr *E = C->getPostUpdateExpr())
4274           MarkDeclarationsReferencedInExpr(E);
4275       }
4276     }
4277     if (Clause->getClauseKind() == OMPC_schedule)
4278       SC = cast<OMPScheduleClause>(Clause);
4279     else if (Clause->getClauseKind() == OMPC_ordered)
4280       OC = cast<OMPOrderedClause>(Clause);
4281     else if (Clause->getClauseKind() == OMPC_linear)
4282       LCs.push_back(cast<OMPLinearClause>(Clause));
4283   }
4284   // Capture allocator expressions if used.
4285   for (Expr *E : DSAStack->getInnerAllocators())
4286     MarkDeclarationsReferencedInExpr(E);
4287   // OpenMP, 2.7.1 Loop Construct, Restrictions
4288   // The nonmonotonic modifier cannot be specified if an ordered clause is
4289   // specified.
4290   if (SC &&
4291       (SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
4292        SC->getSecondScheduleModifier() ==
4293            OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
4294       OC) {
4295     Diag(SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic
4296              ? SC->getFirstScheduleModifierLoc()
4297              : SC->getSecondScheduleModifierLoc(),
4298          diag::err_omp_simple_clause_incompatible_with_ordered)
4299         << getOpenMPClauseName(OMPC_schedule)
4300         << getOpenMPSimpleClauseTypeName(OMPC_schedule,
4301                                          OMPC_SCHEDULE_MODIFIER_nonmonotonic)
4302         << SourceRange(OC->getBeginLoc(), OC->getEndLoc());
4303     ErrorFound = true;
4304   }
4305   // OpenMP 5.0, 2.9.2 Worksharing-Loop Construct, Restrictions.
4306   // If an order(concurrent) clause is present, an ordered clause may not appear
4307   // on the same directive.
4308   if (checkOrderedOrderSpecified(*this, Clauses))
4309     ErrorFound = true;
4310   if (!LCs.empty() && OC && OC->getNumForLoops()) {
4311     for (const OMPLinearClause *C : LCs) {
4312       Diag(C->getBeginLoc(), diag::err_omp_linear_ordered)
4313           << SourceRange(OC->getBeginLoc(), OC->getEndLoc());
4314     }
4315     ErrorFound = true;
4316   }
4317   if (isOpenMPWorksharingDirective(DSAStack->getCurrentDirective()) &&
4318       isOpenMPSimdDirective(DSAStack->getCurrentDirective()) && OC &&
4319       OC->getNumForLoops()) {
4320     Diag(OC->getBeginLoc(), diag::err_omp_ordered_simd)
4321         << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
4322     ErrorFound = true;
4323   }
4324   if (ErrorFound) {
4325     return StmtError();
4326   }
4327   StmtResult SR = S;
4328   unsigned CompletedRegions = 0;
4329   for (OpenMPDirectiveKind ThisCaptureRegion : llvm::reverse(CaptureRegions)) {
4330     // Mark all variables in private list clauses as used in inner region.
4331     // Required for proper codegen of combined directives.
4332     // TODO: add processing for other clauses.
4333     if (ThisCaptureRegion != OMPD_unknown) {
4334       for (const clang::OMPClauseWithPreInit *C : PICs) {
4335         OpenMPDirectiveKind CaptureRegion = C->getCaptureRegion();
4336         // Find the particular capture region for the clause if the
4337         // directive is a combined one with multiple capture regions.
4338         // If the directive is not a combined one, the capture region
4339         // associated with the clause is OMPD_unknown and is generated
4340         // only once.
4341         if (CaptureRegion == ThisCaptureRegion ||
4342             CaptureRegion == OMPD_unknown) {
4343           if (auto *DS = cast_or_null<DeclStmt>(C->getPreInitStmt())) {
4344             for (Decl *D : DS->decls())
4345               MarkVariableReferenced(D->getLocation(), cast<VarDecl>(D));
4346           }
4347         }
4348       }
4349     }
4350     if (ThisCaptureRegion == OMPD_target) {
4351       // Capture allocator traits in the target region. They are used implicitly
4352       // and, thus, are not captured by default.
4353       for (OMPClause *C : Clauses) {
4354         if (const auto *UAC = dyn_cast<OMPUsesAllocatorsClause>(C)) {
4355           for (unsigned I = 0, End = UAC->getNumberOfAllocators(); I < End;
4356                ++I) {
4357             OMPUsesAllocatorsClause::Data D = UAC->getAllocatorData(I);
4358             if (Expr *E = D.AllocatorTraits)
4359               MarkDeclarationsReferencedInExpr(E);
4360           }
4361           continue;
4362         }
4363       }
4364     }
4365     if (++CompletedRegions == CaptureRegions.size())
4366       DSAStack->setBodyComplete();
4367     SR = ActOnCapturedRegionEnd(SR.get());
4368   }
4369   return SR;
4370 }
4371 
4372 static bool checkCancelRegion(Sema &SemaRef, OpenMPDirectiveKind CurrentRegion,
4373                               OpenMPDirectiveKind CancelRegion,
4374                               SourceLocation StartLoc) {
4375   // CancelRegion is only needed for cancel and cancellation_point.
4376   if (CurrentRegion != OMPD_cancel && CurrentRegion != OMPD_cancellation_point)
4377     return false;
4378 
4379   if (CancelRegion == OMPD_parallel || CancelRegion == OMPD_for ||
4380       CancelRegion == OMPD_sections || CancelRegion == OMPD_taskgroup)
4381     return false;
4382 
4383   SemaRef.Diag(StartLoc, diag::err_omp_wrong_cancel_region)
4384       << getOpenMPDirectiveName(CancelRegion);
4385   return true;
4386 }
4387 
4388 static bool checkNestingOfRegions(Sema &SemaRef, const DSAStackTy *Stack,
4389                                   OpenMPDirectiveKind CurrentRegion,
4390                                   const DeclarationNameInfo &CurrentName,
4391                                   OpenMPDirectiveKind CancelRegion,
4392                                   SourceLocation StartLoc) {
4393   if (Stack->getCurScope()) {
4394     OpenMPDirectiveKind ParentRegion = Stack->getParentDirective();
4395     OpenMPDirectiveKind OffendingRegion = ParentRegion;
4396     bool NestingProhibited = false;
4397     bool CloseNesting = true;
4398     bool OrphanSeen = false;
4399     enum {
4400       NoRecommend,
4401       ShouldBeInParallelRegion,
4402       ShouldBeInOrderedRegion,
4403       ShouldBeInTargetRegion,
4404       ShouldBeInTeamsRegion,
4405       ShouldBeInLoopSimdRegion,
4406     } Recommend = NoRecommend;
4407     if (isOpenMPSimdDirective(ParentRegion) &&
4408         ((SemaRef.LangOpts.OpenMP <= 45 && CurrentRegion != OMPD_ordered) ||
4409          (SemaRef.LangOpts.OpenMP >= 50 && CurrentRegion != OMPD_ordered &&
4410           CurrentRegion != OMPD_simd && CurrentRegion != OMPD_atomic &&
4411           CurrentRegion != OMPD_scan))) {
4412       // OpenMP [2.16, Nesting of Regions]
4413       // OpenMP constructs may not be nested inside a simd region.
4414       // OpenMP [2.8.1,simd Construct, Restrictions]
4415       // An ordered construct with the simd clause is the only OpenMP
4416       // construct that can appear in the simd region.
4417       // Allowing a SIMD construct nested in another SIMD construct is an
4418       // extension. The OpenMP 4.5 spec does not allow it. Issue a warning
4419       // message.
4420       // OpenMP 5.0 [2.9.3.1, simd Construct, Restrictions]
4421       // The only OpenMP constructs that can be encountered during execution of
4422       // a simd region are the atomic construct, the loop construct, the simd
4423       // construct and the ordered construct with the simd clause.
4424       SemaRef.Diag(StartLoc, (CurrentRegion != OMPD_simd)
4425                                  ? diag::err_omp_prohibited_region_simd
4426                                  : diag::warn_omp_nesting_simd)
4427           << (SemaRef.LangOpts.OpenMP >= 50 ? 1 : 0);
4428       return CurrentRegion != OMPD_simd;
4429     }
4430     if (ParentRegion == OMPD_atomic) {
4431       // OpenMP [2.16, Nesting of Regions]
4432       // OpenMP constructs may not be nested inside an atomic region.
4433       SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic);
4434       return true;
4435     }
4436     if (CurrentRegion == OMPD_section) {
4437       // OpenMP [2.7.2, sections Construct, Restrictions]
4438       // Orphaned section directives are prohibited. That is, the section
4439       // directives must appear within the sections construct and must not be
4440       // encountered elsewhere in the sections region.
4441       if (ParentRegion != OMPD_sections &&
4442           ParentRegion != OMPD_parallel_sections) {
4443         SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive)
4444             << (ParentRegion != OMPD_unknown)
4445             << getOpenMPDirectiveName(ParentRegion);
4446         return true;
4447       }
4448       return false;
4449     }
4450     // Allow some constructs (except teams and cancellation constructs) to be
4451     // orphaned (they could be used in functions, called from OpenMP regions
4452     // with the required preconditions).
4453     if (ParentRegion == OMPD_unknown &&
4454         !isOpenMPNestingTeamsDirective(CurrentRegion) &&
4455         CurrentRegion != OMPD_cancellation_point &&
4456         CurrentRegion != OMPD_cancel && CurrentRegion != OMPD_scan)
4457       return false;
4458     if (CurrentRegion == OMPD_cancellation_point ||
4459         CurrentRegion == OMPD_cancel) {
4460       // OpenMP [2.16, Nesting of Regions]
4461       // A cancellation point construct for which construct-type-clause is
4462       // taskgroup must be nested inside a task construct. A cancellation
4463       // point construct for which construct-type-clause is not taskgroup must
4464       // be closely nested inside an OpenMP construct that matches the type
4465       // specified in construct-type-clause.
4466       // A cancel construct for which construct-type-clause is taskgroup must be
4467       // nested inside a task construct. A cancel construct for which
4468       // construct-type-clause is not taskgroup must be closely nested inside an
4469       // OpenMP construct that matches the type specified in
4470       // construct-type-clause.
4471       NestingProhibited =
4472           !((CancelRegion == OMPD_parallel &&
4473              (ParentRegion == OMPD_parallel ||
4474               ParentRegion == OMPD_target_parallel)) ||
4475             (CancelRegion == OMPD_for &&
4476              (ParentRegion == OMPD_for || ParentRegion == OMPD_parallel_for ||
4477               ParentRegion == OMPD_target_parallel_for ||
4478               ParentRegion == OMPD_distribute_parallel_for ||
4479               ParentRegion == OMPD_teams_distribute_parallel_for ||
4480               ParentRegion == OMPD_target_teams_distribute_parallel_for)) ||
4481             (CancelRegion == OMPD_taskgroup &&
4482              (ParentRegion == OMPD_task ||
4483               (SemaRef.getLangOpts().OpenMP >= 50 &&
4484                (ParentRegion == OMPD_taskloop ||
4485                 ParentRegion == OMPD_master_taskloop ||
4486                 ParentRegion == OMPD_parallel_master_taskloop)))) ||
4487             (CancelRegion == OMPD_sections &&
4488              (ParentRegion == OMPD_section || ParentRegion == OMPD_sections ||
4489               ParentRegion == OMPD_parallel_sections)));
4490       OrphanSeen = ParentRegion == OMPD_unknown;
4491     } else if (CurrentRegion == OMPD_master) {
4492       // OpenMP [2.16, Nesting of Regions]
4493       // A master region may not be closely nested inside a worksharing,
4494       // atomic, or explicit task region.
4495       NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
4496                           isOpenMPTaskingDirective(ParentRegion);
4497     } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) {
4498       // OpenMP [2.16, Nesting of Regions]
4499       // A critical region may not be nested (closely or otherwise) inside a
4500       // critical region with the same name. Note that this restriction is not
4501       // sufficient to prevent deadlock.
4502       SourceLocation PreviousCriticalLoc;
4503       bool DeadLock = Stack->hasDirective(
4504           [CurrentName, &PreviousCriticalLoc](OpenMPDirectiveKind K,
4505                                               const DeclarationNameInfo &DNI,
4506                                               SourceLocation Loc) {
4507             if (K == OMPD_critical && DNI.getName() == CurrentName.getName()) {
4508               PreviousCriticalLoc = Loc;
4509               return true;
4510             }
4511             return false;
4512           },
4513           false /* skip top directive */);
4514       if (DeadLock) {
4515         SemaRef.Diag(StartLoc,
4516                      diag::err_omp_prohibited_region_critical_same_name)
4517             << CurrentName.getName();
4518         if (PreviousCriticalLoc.isValid())
4519           SemaRef.Diag(PreviousCriticalLoc,
4520                        diag::note_omp_previous_critical_region);
4521         return true;
4522       }
4523     } else if (CurrentRegion == OMPD_barrier) {
4524       // OpenMP [2.16, Nesting of Regions]
4525       // A barrier region may not be closely nested inside a worksharing,
4526       // explicit task, critical, ordered, atomic, or master region.
4527       NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
4528                           isOpenMPTaskingDirective(ParentRegion) ||
4529                           ParentRegion == OMPD_master ||
4530                           ParentRegion == OMPD_parallel_master ||
4531                           ParentRegion == OMPD_critical ||
4532                           ParentRegion == OMPD_ordered;
4533     } else if (isOpenMPWorksharingDirective(CurrentRegion) &&
4534                !isOpenMPParallelDirective(CurrentRegion) &&
4535                !isOpenMPTeamsDirective(CurrentRegion)) {
4536       // OpenMP [2.16, Nesting of Regions]
4537       // A worksharing region may not be closely nested inside a worksharing,
4538       // explicit task, critical, ordered, atomic, or master region.
4539       NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
4540                           isOpenMPTaskingDirective(ParentRegion) ||
4541                           ParentRegion == OMPD_master ||
4542                           ParentRegion == OMPD_parallel_master ||
4543                           ParentRegion == OMPD_critical ||
4544                           ParentRegion == OMPD_ordered;
4545       Recommend = ShouldBeInParallelRegion;
4546     } else if (CurrentRegion == OMPD_ordered) {
4547       // OpenMP [2.16, Nesting of Regions]
4548       // An ordered region may not be closely nested inside a critical,
4549       // atomic, or explicit task region.
4550       // An ordered region must be closely nested inside a loop region (or
4551       // parallel loop region) with an ordered clause.
4552       // OpenMP [2.8.1,simd Construct, Restrictions]
4553       // An ordered construct with the simd clause is the only OpenMP construct
4554       // that can appear in the simd region.
4555       NestingProhibited = ParentRegion == OMPD_critical ||
4556                           isOpenMPTaskingDirective(ParentRegion) ||
4557                           !(isOpenMPSimdDirective(ParentRegion) ||
4558                             Stack->isParentOrderedRegion());
4559       Recommend = ShouldBeInOrderedRegion;
4560     } else if (isOpenMPNestingTeamsDirective(CurrentRegion)) {
4561       // OpenMP [2.16, Nesting of Regions]
4562       // If specified, a teams construct must be contained within a target
4563       // construct.
4564       NestingProhibited =
4565           (SemaRef.LangOpts.OpenMP <= 45 && ParentRegion != OMPD_target) ||
4566           (SemaRef.LangOpts.OpenMP >= 50 && ParentRegion != OMPD_unknown &&
4567            ParentRegion != OMPD_target);
4568       OrphanSeen = ParentRegion == OMPD_unknown;
4569       Recommend = ShouldBeInTargetRegion;
4570     } else if (CurrentRegion == OMPD_scan) {
4571       // OpenMP [2.16, Nesting of Regions]
4572       // If specified, a teams construct must be contained within a target
4573       // construct.
4574       NestingProhibited =
4575           SemaRef.LangOpts.OpenMP < 50 ||
4576           (ParentRegion != OMPD_simd && ParentRegion != OMPD_for &&
4577            ParentRegion != OMPD_for_simd && ParentRegion != OMPD_parallel_for &&
4578            ParentRegion != OMPD_parallel_for_simd);
4579       OrphanSeen = ParentRegion == OMPD_unknown;
4580       Recommend = ShouldBeInLoopSimdRegion;
4581     }
4582     if (!NestingProhibited &&
4583         !isOpenMPTargetExecutionDirective(CurrentRegion) &&
4584         !isOpenMPTargetDataManagementDirective(CurrentRegion) &&
4585         (ParentRegion == OMPD_teams || ParentRegion == OMPD_target_teams)) {
4586       // OpenMP [2.16, Nesting of Regions]
4587       // distribute, parallel, parallel sections, parallel workshare, and the
4588       // parallel loop and parallel loop SIMD constructs are the only OpenMP
4589       // constructs that can be closely nested in the teams region.
4590       NestingProhibited = !isOpenMPParallelDirective(CurrentRegion) &&
4591                           !isOpenMPDistributeDirective(CurrentRegion);
4592       Recommend = ShouldBeInParallelRegion;
4593     }
4594     if (!NestingProhibited &&
4595         isOpenMPNestingDistributeDirective(CurrentRegion)) {
4596       // OpenMP 4.5 [2.17 Nesting of Regions]
4597       // The region associated with the distribute construct must be strictly
4598       // nested inside a teams region
4599       NestingProhibited =
4600           (ParentRegion != OMPD_teams && ParentRegion != OMPD_target_teams);
4601       Recommend = ShouldBeInTeamsRegion;
4602     }
4603     if (!NestingProhibited &&
4604         (isOpenMPTargetExecutionDirective(CurrentRegion) ||
4605          isOpenMPTargetDataManagementDirective(CurrentRegion))) {
4606       // OpenMP 4.5 [2.17 Nesting of Regions]
4607       // If a target, target update, target data, target enter data, or
4608       // target exit data construct is encountered during execution of a
4609       // target region, the behavior is unspecified.
4610       NestingProhibited = Stack->hasDirective(
4611           [&OffendingRegion](OpenMPDirectiveKind K, const DeclarationNameInfo &,
4612                              SourceLocation) {
4613             if (isOpenMPTargetExecutionDirective(K)) {
4614               OffendingRegion = K;
4615               return true;
4616             }
4617             return false;
4618           },
4619           false /* don't skip top directive */);
4620       CloseNesting = false;
4621     }
4622     if (NestingProhibited) {
4623       if (OrphanSeen) {
4624         SemaRef.Diag(StartLoc, diag::err_omp_orphaned_device_directive)
4625             << getOpenMPDirectiveName(CurrentRegion) << Recommend;
4626       } else {
4627         SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region)
4628             << CloseNesting << getOpenMPDirectiveName(OffendingRegion)
4629             << Recommend << getOpenMPDirectiveName(CurrentRegion);
4630       }
4631       return true;
4632     }
4633   }
4634   return false;
4635 }
4636 
4637 struct Kind2Unsigned {
4638   using argument_type = OpenMPDirectiveKind;
4639   unsigned operator()(argument_type DK) { return unsigned(DK); }
4640 };
4641 static bool checkIfClauses(Sema &S, OpenMPDirectiveKind Kind,
4642                            ArrayRef<OMPClause *> Clauses,
4643                            ArrayRef<OpenMPDirectiveKind> AllowedNameModifiers) {
4644   bool ErrorFound = false;
4645   unsigned NamedModifiersNumber = 0;
4646   llvm::IndexedMap<const OMPIfClause *, Kind2Unsigned> FoundNameModifiers;
4647   FoundNameModifiers.resize(llvm::omp::Directive_enumSize + 1);
4648   SmallVector<SourceLocation, 4> NameModifierLoc;
4649   for (const OMPClause *C : Clauses) {
4650     if (const auto *IC = dyn_cast_or_null<OMPIfClause>(C)) {
4651       // At most one if clause without a directive-name-modifier can appear on
4652       // the directive.
4653       OpenMPDirectiveKind CurNM = IC->getNameModifier();
4654       if (FoundNameModifiers[CurNM]) {
4655         S.Diag(C->getBeginLoc(), diag::err_omp_more_one_clause)
4656             << getOpenMPDirectiveName(Kind) << getOpenMPClauseName(OMPC_if)
4657             << (CurNM != OMPD_unknown) << getOpenMPDirectiveName(CurNM);
4658         ErrorFound = true;
4659       } else if (CurNM != OMPD_unknown) {
4660         NameModifierLoc.push_back(IC->getNameModifierLoc());
4661         ++NamedModifiersNumber;
4662       }
4663       FoundNameModifiers[CurNM] = IC;
4664       if (CurNM == OMPD_unknown)
4665         continue;
4666       // Check if the specified name modifier is allowed for the current
4667       // directive.
4668       // At most one if clause with the particular directive-name-modifier can
4669       // appear on the directive.
4670       bool MatchFound = false;
4671       for (auto NM : AllowedNameModifiers) {
4672         if (CurNM == NM) {
4673           MatchFound = true;
4674           break;
4675         }
4676       }
4677       if (!MatchFound) {
4678         S.Diag(IC->getNameModifierLoc(),
4679                diag::err_omp_wrong_if_directive_name_modifier)
4680             << getOpenMPDirectiveName(CurNM) << getOpenMPDirectiveName(Kind);
4681         ErrorFound = true;
4682       }
4683     }
4684   }
4685   // If any if clause on the directive includes a directive-name-modifier then
4686   // all if clauses on the directive must include a directive-name-modifier.
4687   if (FoundNameModifiers[OMPD_unknown] && NamedModifiersNumber > 0) {
4688     if (NamedModifiersNumber == AllowedNameModifiers.size()) {
4689       S.Diag(FoundNameModifiers[OMPD_unknown]->getBeginLoc(),
4690              diag::err_omp_no_more_if_clause);
4691     } else {
4692       std::string Values;
4693       std::string Sep(", ");
4694       unsigned AllowedCnt = 0;
4695       unsigned TotalAllowedNum =
4696           AllowedNameModifiers.size() - NamedModifiersNumber;
4697       for (unsigned Cnt = 0, End = AllowedNameModifiers.size(); Cnt < End;
4698            ++Cnt) {
4699         OpenMPDirectiveKind NM = AllowedNameModifiers[Cnt];
4700         if (!FoundNameModifiers[NM]) {
4701           Values += "'";
4702           Values += getOpenMPDirectiveName(NM);
4703           Values += "'";
4704           if (AllowedCnt + 2 == TotalAllowedNum)
4705             Values += " or ";
4706           else if (AllowedCnt + 1 != TotalAllowedNum)
4707             Values += Sep;
4708           ++AllowedCnt;
4709         }
4710       }
4711       S.Diag(FoundNameModifiers[OMPD_unknown]->getCondition()->getBeginLoc(),
4712              diag::err_omp_unnamed_if_clause)
4713           << (TotalAllowedNum > 1) << Values;
4714     }
4715     for (SourceLocation Loc : NameModifierLoc) {
4716       S.Diag(Loc, diag::note_omp_previous_named_if_clause);
4717     }
4718     ErrorFound = true;
4719   }
4720   return ErrorFound;
4721 }
4722 
4723 static std::pair<ValueDecl *, bool> getPrivateItem(Sema &S, Expr *&RefExpr,
4724                                                    SourceLocation &ELoc,
4725                                                    SourceRange &ERange,
4726                                                    bool AllowArraySection) {
4727   if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() ||
4728       RefExpr->containsUnexpandedParameterPack())
4729     return std::make_pair(nullptr, true);
4730 
4731   // OpenMP [3.1, C/C++]
4732   //  A list item is a variable name.
4733   // OpenMP  [2.9.3.3, Restrictions, p.1]
4734   //  A variable that is part of another variable (as an array or
4735   //  structure element) cannot appear in a private clause.
4736   RefExpr = RefExpr->IgnoreParens();
4737   enum {
4738     NoArrayExpr = -1,
4739     ArraySubscript = 0,
4740     OMPArraySection = 1
4741   } IsArrayExpr = NoArrayExpr;
4742   if (AllowArraySection) {
4743     if (auto *ASE = dyn_cast_or_null<ArraySubscriptExpr>(RefExpr)) {
4744       Expr *Base = ASE->getBase()->IgnoreParenImpCasts();
4745       while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
4746         Base = TempASE->getBase()->IgnoreParenImpCasts();
4747       RefExpr = Base;
4748       IsArrayExpr = ArraySubscript;
4749     } else if (auto *OASE = dyn_cast_or_null<OMPArraySectionExpr>(RefExpr)) {
4750       Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
4751       while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
4752         Base = TempOASE->getBase()->IgnoreParenImpCasts();
4753       while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
4754         Base = TempASE->getBase()->IgnoreParenImpCasts();
4755       RefExpr = Base;
4756       IsArrayExpr = OMPArraySection;
4757     }
4758   }
4759   ELoc = RefExpr->getExprLoc();
4760   ERange = RefExpr->getSourceRange();
4761   RefExpr = RefExpr->IgnoreParenImpCasts();
4762   auto *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
4763   auto *ME = dyn_cast_or_null<MemberExpr>(RefExpr);
4764   if ((!DE || !isa<VarDecl>(DE->getDecl())) &&
4765       (S.getCurrentThisType().isNull() || !ME ||
4766        !isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()) ||
4767        !isa<FieldDecl>(ME->getMemberDecl()))) {
4768     if (IsArrayExpr != NoArrayExpr) {
4769       S.Diag(ELoc, diag::err_omp_expected_base_var_name) << IsArrayExpr
4770                                                          << ERange;
4771     } else {
4772       S.Diag(ELoc,
4773              AllowArraySection
4774                  ? diag::err_omp_expected_var_name_member_expr_or_array_item
4775                  : diag::err_omp_expected_var_name_member_expr)
4776           << (S.getCurrentThisType().isNull() ? 0 : 1) << ERange;
4777     }
4778     return std::make_pair(nullptr, false);
4779   }
4780   return std::make_pair(
4781       getCanonicalDecl(DE ? DE->getDecl() : ME->getMemberDecl()), false);
4782 }
4783 
4784 namespace {
4785 /// Checks if the allocator is used in uses_allocators clause to be allowed in
4786 /// target regions.
4787 class AllocatorChecker final : public ConstStmtVisitor<AllocatorChecker, bool> {
4788   DSAStackTy *S = nullptr;
4789 
4790 public:
4791   bool VisitDeclRefExpr(const DeclRefExpr *E) {
4792     return S->isUsesAllocatorsDecl(E->getDecl())
4793                .getValueOr(
4794                    DSAStackTy::UsesAllocatorsDeclKind::AllocatorTrait) ==
4795            DSAStackTy::UsesAllocatorsDeclKind::AllocatorTrait;
4796   }
4797   bool VisitStmt(const Stmt *S) {
4798     for (const Stmt *Child : S->children()) {
4799       if (Child && Visit(Child))
4800         return true;
4801     }
4802     return false;
4803   }
4804   explicit AllocatorChecker(DSAStackTy *S) : S(S) {}
4805 };
4806 } // namespace
4807 
4808 static void checkAllocateClauses(Sema &S, DSAStackTy *Stack,
4809                                  ArrayRef<OMPClause *> Clauses) {
4810   assert(!S.CurContext->isDependentContext() &&
4811          "Expected non-dependent context.");
4812   auto AllocateRange =
4813       llvm::make_filter_range(Clauses, OMPAllocateClause::classof);
4814   llvm::DenseMap<CanonicalDeclPtr<Decl>, CanonicalDeclPtr<VarDecl>>
4815       DeclToCopy;
4816   auto PrivateRange = llvm::make_filter_range(Clauses, [](const OMPClause *C) {
4817     return isOpenMPPrivate(C->getClauseKind());
4818   });
4819   for (OMPClause *Cl : PrivateRange) {
4820     MutableArrayRef<Expr *>::iterator I, It, Et;
4821     if (Cl->getClauseKind() == OMPC_private) {
4822       auto *PC = cast<OMPPrivateClause>(Cl);
4823       I = PC->private_copies().begin();
4824       It = PC->varlist_begin();
4825       Et = PC->varlist_end();
4826     } else if (Cl->getClauseKind() == OMPC_firstprivate) {
4827       auto *PC = cast<OMPFirstprivateClause>(Cl);
4828       I = PC->private_copies().begin();
4829       It = PC->varlist_begin();
4830       Et = PC->varlist_end();
4831     } else if (Cl->getClauseKind() == OMPC_lastprivate) {
4832       auto *PC = cast<OMPLastprivateClause>(Cl);
4833       I = PC->private_copies().begin();
4834       It = PC->varlist_begin();
4835       Et = PC->varlist_end();
4836     } else if (Cl->getClauseKind() == OMPC_linear) {
4837       auto *PC = cast<OMPLinearClause>(Cl);
4838       I = PC->privates().begin();
4839       It = PC->varlist_begin();
4840       Et = PC->varlist_end();
4841     } else if (Cl->getClauseKind() == OMPC_reduction) {
4842       auto *PC = cast<OMPReductionClause>(Cl);
4843       I = PC->privates().begin();
4844       It = PC->varlist_begin();
4845       Et = PC->varlist_end();
4846     } else if (Cl->getClauseKind() == OMPC_task_reduction) {
4847       auto *PC = cast<OMPTaskReductionClause>(Cl);
4848       I = PC->privates().begin();
4849       It = PC->varlist_begin();
4850       Et = PC->varlist_end();
4851     } else if (Cl->getClauseKind() == OMPC_in_reduction) {
4852       auto *PC = cast<OMPInReductionClause>(Cl);
4853       I = PC->privates().begin();
4854       It = PC->varlist_begin();
4855       Et = PC->varlist_end();
4856     } else {
4857       llvm_unreachable("Expected private clause.");
4858     }
4859     for (Expr *E : llvm::make_range(It, Et)) {
4860       if (!*I) {
4861         ++I;
4862         continue;
4863       }
4864       SourceLocation ELoc;
4865       SourceRange ERange;
4866       Expr *SimpleRefExpr = E;
4867       auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange,
4868                                 /*AllowArraySection=*/true);
4869       DeclToCopy.try_emplace(Res.first,
4870                              cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()));
4871       ++I;
4872     }
4873   }
4874   for (OMPClause *C : AllocateRange) {
4875     auto *AC = cast<OMPAllocateClause>(C);
4876     if (S.getLangOpts().OpenMP >= 50 &&
4877         !Stack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>() &&
4878         isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()) &&
4879         AC->getAllocator()) {
4880       Expr *Allocator = AC->getAllocator();
4881       // OpenMP, 2.12.5 target Construct
4882       // Memory allocators that do not appear in a uses_allocators clause cannot
4883       // appear as an allocator in an allocate clause or be used in the target
4884       // region unless a requires directive with the dynamic_allocators clause
4885       // is present in the same compilation unit.
4886       AllocatorChecker Checker(Stack);
4887       if (Checker.Visit(Allocator))
4888         S.Diag(Allocator->getExprLoc(),
4889                diag::err_omp_allocator_not_in_uses_allocators)
4890             << Allocator->getSourceRange();
4891     }
4892     OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind =
4893         getAllocatorKind(S, Stack, AC->getAllocator());
4894     // OpenMP, 2.11.4 allocate Clause, Restrictions.
4895     // For task, taskloop or target directives, allocation requests to memory
4896     // allocators with the trait access set to thread result in unspecified
4897     // behavior.
4898     if (AllocatorKind == OMPAllocateDeclAttr::OMPThreadMemAlloc &&
4899         (isOpenMPTaskingDirective(Stack->getCurrentDirective()) ||
4900          isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()))) {
4901       S.Diag(AC->getAllocator()->getExprLoc(),
4902              diag::warn_omp_allocate_thread_on_task_target_directive)
4903           << getOpenMPDirectiveName(Stack->getCurrentDirective());
4904     }
4905     for (Expr *E : AC->varlists()) {
4906       SourceLocation ELoc;
4907       SourceRange ERange;
4908       Expr *SimpleRefExpr = E;
4909       auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange);
4910       ValueDecl *VD = Res.first;
4911       DSAStackTy::DSAVarData Data = Stack->getTopDSA(VD, /*FromParent=*/false);
4912       if (!isOpenMPPrivate(Data.CKind)) {
4913         S.Diag(E->getExprLoc(),
4914                diag::err_omp_expected_private_copy_for_allocate);
4915         continue;
4916       }
4917       VarDecl *PrivateVD = DeclToCopy[VD];
4918       if (checkPreviousOMPAllocateAttribute(S, Stack, E, PrivateVD,
4919                                             AllocatorKind, AC->getAllocator()))
4920         continue;
4921       applyOMPAllocateAttribute(S, PrivateVD, AllocatorKind, AC->getAllocator(),
4922                                 E->getSourceRange());
4923     }
4924   }
4925 }
4926 
4927 StmtResult Sema::ActOnOpenMPExecutableDirective(
4928     OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
4929     OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
4930     Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
4931   StmtResult Res = StmtError();
4932   // First check CancelRegion which is then used in checkNestingOfRegions.
4933   if (checkCancelRegion(*this, Kind, CancelRegion, StartLoc) ||
4934       checkNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion,
4935                             StartLoc))
4936     return StmtError();
4937 
4938   llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit;
4939   VarsWithInheritedDSAType VarsWithInheritedDSA;
4940   bool ErrorFound = false;
4941   ClausesWithImplicit.append(Clauses.begin(), Clauses.end());
4942   if (AStmt && !CurContext->isDependentContext()) {
4943     assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
4944 
4945     // Check default data sharing attributes for referenced variables.
4946     DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt));
4947     int ThisCaptureLevel = getOpenMPCaptureLevels(Kind);
4948     Stmt *S = AStmt;
4949     while (--ThisCaptureLevel >= 0)
4950       S = cast<CapturedStmt>(S)->getCapturedStmt();
4951     DSAChecker.Visit(S);
4952     if (!isOpenMPTargetDataManagementDirective(Kind) &&
4953         !isOpenMPTaskingDirective(Kind)) {
4954       // Visit subcaptures to generate implicit clauses for captured vars.
4955       auto *CS = cast<CapturedStmt>(AStmt);
4956       SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
4957       getOpenMPCaptureRegions(CaptureRegions, Kind);
4958       // Ignore outer tasking regions for target directives.
4959       if (CaptureRegions.size() > 1 && CaptureRegions.front() == OMPD_task)
4960         CS = cast<CapturedStmt>(CS->getCapturedStmt());
4961       DSAChecker.visitSubCaptures(CS);
4962     }
4963     if (DSAChecker.isErrorFound())
4964       return StmtError();
4965     // Generate list of implicitly defined firstprivate variables.
4966     VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA();
4967 
4968     SmallVector<Expr *, 4> ImplicitFirstprivates(
4969         DSAChecker.getImplicitFirstprivate().begin(),
4970         DSAChecker.getImplicitFirstprivate().end());
4971     SmallVector<Expr *, 4> ImplicitMaps[OMPC_MAP_delete];
4972     for (unsigned I = 0; I < OMPC_MAP_delete; ++I) {
4973       ArrayRef<Expr *> ImplicitMap =
4974           DSAChecker.getImplicitMap(static_cast<OpenMPDefaultmapClauseKind>(I));
4975       ImplicitMaps[I].append(ImplicitMap.begin(), ImplicitMap.end());
4976     }
4977     // Mark taskgroup task_reduction descriptors as implicitly firstprivate.
4978     for (OMPClause *C : Clauses) {
4979       if (auto *IRC = dyn_cast<OMPInReductionClause>(C)) {
4980         for (Expr *E : IRC->taskgroup_descriptors())
4981           if (E)
4982             ImplicitFirstprivates.emplace_back(E);
4983       }
4984       // OpenMP 5.0, 2.10.1 task Construct
4985       // [detach clause]... The event-handle will be considered as if it was
4986       // specified on a firstprivate clause.
4987       if (auto *DC = dyn_cast<OMPDetachClause>(C))
4988         ImplicitFirstprivates.push_back(DC->getEventHandler());
4989     }
4990     if (!ImplicitFirstprivates.empty()) {
4991       if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause(
4992               ImplicitFirstprivates, SourceLocation(), SourceLocation(),
4993               SourceLocation())) {
4994         ClausesWithImplicit.push_back(Implicit);
4995         ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() !=
4996                      ImplicitFirstprivates.size();
4997       } else {
4998         ErrorFound = true;
4999       }
5000     }
5001     int ClauseKindCnt = -1;
5002     for (ArrayRef<Expr *> ImplicitMap : ImplicitMaps) {
5003       ++ClauseKindCnt;
5004       if (ImplicitMap.empty())
5005         continue;
5006       CXXScopeSpec MapperIdScopeSpec;
5007       DeclarationNameInfo MapperId;
5008       auto Kind = static_cast<OpenMPMapClauseKind>(ClauseKindCnt);
5009       if (OMPClause *Implicit = ActOnOpenMPMapClause(
5010               llvm::None, llvm::None, MapperIdScopeSpec, MapperId, Kind,
5011               /*IsMapTypeImplicit=*/true, SourceLocation(), SourceLocation(),
5012               ImplicitMap, OMPVarListLocTy())) {
5013         ClausesWithImplicit.emplace_back(Implicit);
5014         ErrorFound |=
5015             cast<OMPMapClause>(Implicit)->varlist_size() != ImplicitMap.size();
5016       } else {
5017         ErrorFound = true;
5018       }
5019     }
5020   }
5021 
5022   llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers;
5023   switch (Kind) {
5024   case OMPD_parallel:
5025     Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc,
5026                                        EndLoc);
5027     AllowedNameModifiers.push_back(OMPD_parallel);
5028     break;
5029   case OMPD_simd:
5030     Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
5031                                    VarsWithInheritedDSA);
5032     if (LangOpts.OpenMP >= 50)
5033       AllowedNameModifiers.push_back(OMPD_simd);
5034     break;
5035   case OMPD_for:
5036     Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
5037                                   VarsWithInheritedDSA);
5038     break;
5039   case OMPD_for_simd:
5040     Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
5041                                       EndLoc, VarsWithInheritedDSA);
5042     if (LangOpts.OpenMP >= 50)
5043       AllowedNameModifiers.push_back(OMPD_simd);
5044     break;
5045   case OMPD_sections:
5046     Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc,
5047                                        EndLoc);
5048     break;
5049   case OMPD_section:
5050     assert(ClausesWithImplicit.empty() &&
5051            "No clauses are allowed for 'omp section' directive");
5052     Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc);
5053     break;
5054   case OMPD_single:
5055     Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc,
5056                                      EndLoc);
5057     break;
5058   case OMPD_master:
5059     assert(ClausesWithImplicit.empty() &&
5060            "No clauses are allowed for 'omp master' directive");
5061     Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc);
5062     break;
5063   case OMPD_critical:
5064     Res = ActOnOpenMPCriticalDirective(DirName, ClausesWithImplicit, AStmt,
5065                                        StartLoc, EndLoc);
5066     break;
5067   case OMPD_parallel_for:
5068     Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc,
5069                                           EndLoc, VarsWithInheritedDSA);
5070     AllowedNameModifiers.push_back(OMPD_parallel);
5071     break;
5072   case OMPD_parallel_for_simd:
5073     Res = ActOnOpenMPParallelForSimdDirective(
5074         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
5075     AllowedNameModifiers.push_back(OMPD_parallel);
5076     if (LangOpts.OpenMP >= 50)
5077       AllowedNameModifiers.push_back(OMPD_simd);
5078     break;
5079   case OMPD_parallel_master:
5080     Res = ActOnOpenMPParallelMasterDirective(ClausesWithImplicit, AStmt,
5081                                                StartLoc, EndLoc);
5082     AllowedNameModifiers.push_back(OMPD_parallel);
5083     break;
5084   case OMPD_parallel_sections:
5085     Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt,
5086                                                StartLoc, EndLoc);
5087     AllowedNameModifiers.push_back(OMPD_parallel);
5088     break;
5089   case OMPD_task:
5090     Res =
5091         ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
5092     AllowedNameModifiers.push_back(OMPD_task);
5093     break;
5094   case OMPD_taskyield:
5095     assert(ClausesWithImplicit.empty() &&
5096            "No clauses are allowed for 'omp taskyield' directive");
5097     assert(AStmt == nullptr &&
5098            "No associated statement allowed for 'omp taskyield' directive");
5099     Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc);
5100     break;
5101   case OMPD_barrier:
5102     assert(ClausesWithImplicit.empty() &&
5103            "No clauses are allowed for 'omp barrier' directive");
5104     assert(AStmt == nullptr &&
5105            "No associated statement allowed for 'omp barrier' directive");
5106     Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc);
5107     break;
5108   case OMPD_taskwait:
5109     assert(ClausesWithImplicit.empty() &&
5110            "No clauses are allowed for 'omp taskwait' directive");
5111     assert(AStmt == nullptr &&
5112            "No associated statement allowed for 'omp taskwait' directive");
5113     Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc);
5114     break;
5115   case OMPD_taskgroup:
5116     Res = ActOnOpenMPTaskgroupDirective(ClausesWithImplicit, AStmt, StartLoc,
5117                                         EndLoc);
5118     break;
5119   case OMPD_flush:
5120     assert(AStmt == nullptr &&
5121            "No associated statement allowed for 'omp flush' directive");
5122     Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc);
5123     break;
5124   case OMPD_depobj:
5125     assert(AStmt == nullptr &&
5126            "No associated statement allowed for 'omp depobj' directive");
5127     Res = ActOnOpenMPDepobjDirective(ClausesWithImplicit, StartLoc, EndLoc);
5128     break;
5129   case OMPD_scan:
5130     assert(AStmt == nullptr &&
5131            "No associated statement allowed for 'omp scan' directive");
5132     Res = ActOnOpenMPScanDirective(ClausesWithImplicit, StartLoc, EndLoc);
5133     break;
5134   case OMPD_ordered:
5135     Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc,
5136                                       EndLoc);
5137     break;
5138   case OMPD_atomic:
5139     Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc,
5140                                      EndLoc);
5141     break;
5142   case OMPD_teams:
5143     Res =
5144         ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
5145     break;
5146   case OMPD_target:
5147     Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc,
5148                                      EndLoc);
5149     AllowedNameModifiers.push_back(OMPD_target);
5150     break;
5151   case OMPD_target_parallel:
5152     Res = ActOnOpenMPTargetParallelDirective(ClausesWithImplicit, AStmt,
5153                                              StartLoc, EndLoc);
5154     AllowedNameModifiers.push_back(OMPD_target);
5155     AllowedNameModifiers.push_back(OMPD_parallel);
5156     break;
5157   case OMPD_target_parallel_for:
5158     Res = ActOnOpenMPTargetParallelForDirective(
5159         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
5160     AllowedNameModifiers.push_back(OMPD_target);
5161     AllowedNameModifiers.push_back(OMPD_parallel);
5162     break;
5163   case OMPD_cancellation_point:
5164     assert(ClausesWithImplicit.empty() &&
5165            "No clauses are allowed for 'omp cancellation point' directive");
5166     assert(AStmt == nullptr && "No associated statement allowed for 'omp "
5167                                "cancellation point' directive");
5168     Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion);
5169     break;
5170   case OMPD_cancel:
5171     assert(AStmt == nullptr &&
5172            "No associated statement allowed for 'omp cancel' directive");
5173     Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc,
5174                                      CancelRegion);
5175     AllowedNameModifiers.push_back(OMPD_cancel);
5176     break;
5177   case OMPD_target_data:
5178     Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc,
5179                                          EndLoc);
5180     AllowedNameModifiers.push_back(OMPD_target_data);
5181     break;
5182   case OMPD_target_enter_data:
5183     Res = ActOnOpenMPTargetEnterDataDirective(ClausesWithImplicit, StartLoc,
5184                                               EndLoc, AStmt);
5185     AllowedNameModifiers.push_back(OMPD_target_enter_data);
5186     break;
5187   case OMPD_target_exit_data:
5188     Res = ActOnOpenMPTargetExitDataDirective(ClausesWithImplicit, StartLoc,
5189                                              EndLoc, AStmt);
5190     AllowedNameModifiers.push_back(OMPD_target_exit_data);
5191     break;
5192   case OMPD_taskloop:
5193     Res = ActOnOpenMPTaskLoopDirective(ClausesWithImplicit, AStmt, StartLoc,
5194                                        EndLoc, VarsWithInheritedDSA);
5195     AllowedNameModifiers.push_back(OMPD_taskloop);
5196     break;
5197   case OMPD_taskloop_simd:
5198     Res = ActOnOpenMPTaskLoopSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
5199                                            EndLoc, VarsWithInheritedDSA);
5200     AllowedNameModifiers.push_back(OMPD_taskloop);
5201     if (LangOpts.OpenMP >= 50)
5202       AllowedNameModifiers.push_back(OMPD_simd);
5203     break;
5204   case OMPD_master_taskloop:
5205     Res = ActOnOpenMPMasterTaskLoopDirective(
5206         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
5207     AllowedNameModifiers.push_back(OMPD_taskloop);
5208     break;
5209   case OMPD_master_taskloop_simd:
5210     Res = ActOnOpenMPMasterTaskLoopSimdDirective(
5211         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
5212     AllowedNameModifiers.push_back(OMPD_taskloop);
5213     if (LangOpts.OpenMP >= 50)
5214       AllowedNameModifiers.push_back(OMPD_simd);
5215     break;
5216   case OMPD_parallel_master_taskloop:
5217     Res = ActOnOpenMPParallelMasterTaskLoopDirective(
5218         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
5219     AllowedNameModifiers.push_back(OMPD_taskloop);
5220     AllowedNameModifiers.push_back(OMPD_parallel);
5221     break;
5222   case OMPD_parallel_master_taskloop_simd:
5223     Res = ActOnOpenMPParallelMasterTaskLoopSimdDirective(
5224         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
5225     AllowedNameModifiers.push_back(OMPD_taskloop);
5226     AllowedNameModifiers.push_back(OMPD_parallel);
5227     if (LangOpts.OpenMP >= 50)
5228       AllowedNameModifiers.push_back(OMPD_simd);
5229     break;
5230   case OMPD_distribute:
5231     Res = ActOnOpenMPDistributeDirective(ClausesWithImplicit, AStmt, StartLoc,
5232                                          EndLoc, VarsWithInheritedDSA);
5233     break;
5234   case OMPD_target_update:
5235     Res = ActOnOpenMPTargetUpdateDirective(ClausesWithImplicit, StartLoc,
5236                                            EndLoc, AStmt);
5237     AllowedNameModifiers.push_back(OMPD_target_update);
5238     break;
5239   case OMPD_distribute_parallel_for:
5240     Res = ActOnOpenMPDistributeParallelForDirective(
5241         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
5242     AllowedNameModifiers.push_back(OMPD_parallel);
5243     break;
5244   case OMPD_distribute_parallel_for_simd:
5245     Res = ActOnOpenMPDistributeParallelForSimdDirective(
5246         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
5247     AllowedNameModifiers.push_back(OMPD_parallel);
5248     if (LangOpts.OpenMP >= 50)
5249       AllowedNameModifiers.push_back(OMPD_simd);
5250     break;
5251   case OMPD_distribute_simd:
5252     Res = ActOnOpenMPDistributeSimdDirective(
5253         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
5254     if (LangOpts.OpenMP >= 50)
5255       AllowedNameModifiers.push_back(OMPD_simd);
5256     break;
5257   case OMPD_target_parallel_for_simd:
5258     Res = ActOnOpenMPTargetParallelForSimdDirective(
5259         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
5260     AllowedNameModifiers.push_back(OMPD_target);
5261     AllowedNameModifiers.push_back(OMPD_parallel);
5262     if (LangOpts.OpenMP >= 50)
5263       AllowedNameModifiers.push_back(OMPD_simd);
5264     break;
5265   case OMPD_target_simd:
5266     Res = ActOnOpenMPTargetSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
5267                                          EndLoc, VarsWithInheritedDSA);
5268     AllowedNameModifiers.push_back(OMPD_target);
5269     if (LangOpts.OpenMP >= 50)
5270       AllowedNameModifiers.push_back(OMPD_simd);
5271     break;
5272   case OMPD_teams_distribute:
5273     Res = ActOnOpenMPTeamsDistributeDirective(
5274         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
5275     break;
5276   case OMPD_teams_distribute_simd:
5277     Res = ActOnOpenMPTeamsDistributeSimdDirective(
5278         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
5279     if (LangOpts.OpenMP >= 50)
5280       AllowedNameModifiers.push_back(OMPD_simd);
5281     break;
5282   case OMPD_teams_distribute_parallel_for_simd:
5283     Res = ActOnOpenMPTeamsDistributeParallelForSimdDirective(
5284         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
5285     AllowedNameModifiers.push_back(OMPD_parallel);
5286     if (LangOpts.OpenMP >= 50)
5287       AllowedNameModifiers.push_back(OMPD_simd);
5288     break;
5289   case OMPD_teams_distribute_parallel_for:
5290     Res = ActOnOpenMPTeamsDistributeParallelForDirective(
5291         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
5292     AllowedNameModifiers.push_back(OMPD_parallel);
5293     break;
5294   case OMPD_target_teams:
5295     Res = ActOnOpenMPTargetTeamsDirective(ClausesWithImplicit, AStmt, StartLoc,
5296                                           EndLoc);
5297     AllowedNameModifiers.push_back(OMPD_target);
5298     break;
5299   case OMPD_target_teams_distribute:
5300     Res = ActOnOpenMPTargetTeamsDistributeDirective(
5301         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
5302     AllowedNameModifiers.push_back(OMPD_target);
5303     break;
5304   case OMPD_target_teams_distribute_parallel_for:
5305     Res = ActOnOpenMPTargetTeamsDistributeParallelForDirective(
5306         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
5307     AllowedNameModifiers.push_back(OMPD_target);
5308     AllowedNameModifiers.push_back(OMPD_parallel);
5309     break;
5310   case OMPD_target_teams_distribute_parallel_for_simd:
5311     Res = ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
5312         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
5313     AllowedNameModifiers.push_back(OMPD_target);
5314     AllowedNameModifiers.push_back(OMPD_parallel);
5315     if (LangOpts.OpenMP >= 50)
5316       AllowedNameModifiers.push_back(OMPD_simd);
5317     break;
5318   case OMPD_target_teams_distribute_simd:
5319     Res = ActOnOpenMPTargetTeamsDistributeSimdDirective(
5320         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
5321     AllowedNameModifiers.push_back(OMPD_target);
5322     if (LangOpts.OpenMP >= 50)
5323       AllowedNameModifiers.push_back(OMPD_simd);
5324     break;
5325   case OMPD_declare_target:
5326   case OMPD_end_declare_target:
5327   case OMPD_threadprivate:
5328   case OMPD_allocate:
5329   case OMPD_declare_reduction:
5330   case OMPD_declare_mapper:
5331   case OMPD_declare_simd:
5332   case OMPD_requires:
5333   case OMPD_declare_variant:
5334   case OMPD_begin_declare_variant:
5335   case OMPD_end_declare_variant:
5336     llvm_unreachable("OpenMP Directive is not allowed");
5337   case OMPD_unknown:
5338     llvm_unreachable("Unknown OpenMP directive");
5339   }
5340 
5341   ErrorFound = Res.isInvalid() || ErrorFound;
5342 
5343   // Check variables in the clauses if default(none) was specified.
5344   if (DSAStack->getDefaultDSA() == DSA_none) {
5345     DSAAttrChecker DSAChecker(DSAStack, *this, nullptr);
5346     for (OMPClause *C : Clauses) {
5347       switch (C->getClauseKind()) {
5348       case OMPC_num_threads:
5349       case OMPC_dist_schedule:
5350         // Do not analyse if no parent teams directive.
5351         if (isOpenMPTeamsDirective(Kind))
5352           break;
5353         continue;
5354       case OMPC_if:
5355         if (isOpenMPTeamsDirective(Kind) &&
5356             cast<OMPIfClause>(C)->getNameModifier() != OMPD_target)
5357           break;
5358         if (isOpenMPParallelDirective(Kind) &&
5359             isOpenMPTaskLoopDirective(Kind) &&
5360             cast<OMPIfClause>(C)->getNameModifier() != OMPD_parallel)
5361           break;
5362         continue;
5363       case OMPC_schedule:
5364       case OMPC_detach:
5365         break;
5366       case OMPC_grainsize:
5367       case OMPC_num_tasks:
5368       case OMPC_final:
5369       case OMPC_priority:
5370         // Do not analyze if no parent parallel directive.
5371         if (isOpenMPParallelDirective(Kind))
5372           break;
5373         continue;
5374       case OMPC_ordered:
5375       case OMPC_device:
5376       case OMPC_num_teams:
5377       case OMPC_thread_limit:
5378       case OMPC_hint:
5379       case OMPC_collapse:
5380       case OMPC_safelen:
5381       case OMPC_simdlen:
5382       case OMPC_default:
5383       case OMPC_proc_bind:
5384       case OMPC_private:
5385       case OMPC_firstprivate:
5386       case OMPC_lastprivate:
5387       case OMPC_shared:
5388       case OMPC_reduction:
5389       case OMPC_task_reduction:
5390       case OMPC_in_reduction:
5391       case OMPC_linear:
5392       case OMPC_aligned:
5393       case OMPC_copyin:
5394       case OMPC_copyprivate:
5395       case OMPC_nowait:
5396       case OMPC_untied:
5397       case OMPC_mergeable:
5398       case OMPC_allocate:
5399       case OMPC_read:
5400       case OMPC_write:
5401       case OMPC_update:
5402       case OMPC_capture:
5403       case OMPC_seq_cst:
5404       case OMPC_acq_rel:
5405       case OMPC_acquire:
5406       case OMPC_release:
5407       case OMPC_relaxed:
5408       case OMPC_depend:
5409       case OMPC_threads:
5410       case OMPC_simd:
5411       case OMPC_map:
5412       case OMPC_nogroup:
5413       case OMPC_defaultmap:
5414       case OMPC_to:
5415       case OMPC_from:
5416       case OMPC_use_device_ptr:
5417       case OMPC_use_device_addr:
5418       case OMPC_is_device_ptr:
5419       case OMPC_nontemporal:
5420       case OMPC_order:
5421       case OMPC_destroy:
5422       case OMPC_inclusive:
5423       case OMPC_exclusive:
5424       case OMPC_uses_allocators:
5425       case OMPC_affinity:
5426         continue;
5427       case OMPC_allocator:
5428       case OMPC_flush:
5429       case OMPC_depobj:
5430       case OMPC_threadprivate:
5431       case OMPC_uniform:
5432       case OMPC_unknown:
5433       case OMPC_unified_address:
5434       case OMPC_unified_shared_memory:
5435       case OMPC_reverse_offload:
5436       case OMPC_dynamic_allocators:
5437       case OMPC_atomic_default_mem_order:
5438       case OMPC_device_type:
5439       case OMPC_match:
5440         llvm_unreachable("Unexpected clause");
5441       }
5442       for (Stmt *CC : C->children()) {
5443         if (CC)
5444           DSAChecker.Visit(CC);
5445       }
5446     }
5447     for (const auto &P : DSAChecker.getVarsWithInheritedDSA())
5448       VarsWithInheritedDSA[P.getFirst()] = P.getSecond();
5449   }
5450   for (const auto &P : VarsWithInheritedDSA) {
5451     if (P.getFirst()->isImplicit() || isa<OMPCapturedExprDecl>(P.getFirst()))
5452       continue;
5453     ErrorFound = true;
5454     if (DSAStack->getDefaultDSA() == DSA_none) {
5455       Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable)
5456           << P.first << P.second->getSourceRange();
5457       Diag(DSAStack->getDefaultDSALocation(), diag::note_omp_default_dsa_none);
5458     } else if (getLangOpts().OpenMP >= 50) {
5459       Diag(P.second->getExprLoc(),
5460            diag::err_omp_defaultmap_no_attr_for_variable)
5461           << P.first << P.second->getSourceRange();
5462       Diag(DSAStack->getDefaultDSALocation(),
5463            diag::note_omp_defaultmap_attr_none);
5464     }
5465   }
5466 
5467   if (!AllowedNameModifiers.empty())
5468     ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) ||
5469                  ErrorFound;
5470 
5471   if (ErrorFound)
5472     return StmtError();
5473 
5474   if (!CurContext->isDependentContext() &&
5475       isOpenMPTargetExecutionDirective(Kind) &&
5476       !(DSAStack->hasRequiresDeclWithClause<OMPUnifiedSharedMemoryClause>() ||
5477         DSAStack->hasRequiresDeclWithClause<OMPUnifiedAddressClause>() ||
5478         DSAStack->hasRequiresDeclWithClause<OMPReverseOffloadClause>() ||
5479         DSAStack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>())) {
5480     // Register target to DSA Stack.
5481     DSAStack->addTargetDirLocation(StartLoc);
5482   }
5483 
5484   return Res;
5485 }
5486 
5487 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareSimdDirective(
5488     DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen,
5489     ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
5490     ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
5491     ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR) {
5492   assert(Aligneds.size() == Alignments.size());
5493   assert(Linears.size() == LinModifiers.size());
5494   assert(Linears.size() == Steps.size());
5495   if (!DG || DG.get().isNull())
5496     return DeclGroupPtrTy();
5497 
5498   const int SimdId = 0;
5499   if (!DG.get().isSingleDecl()) {
5500     Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd_variant)
5501         << SimdId;
5502     return DG;
5503   }
5504   Decl *ADecl = DG.get().getSingleDecl();
5505   if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
5506     ADecl = FTD->getTemplatedDecl();
5507 
5508   auto *FD = dyn_cast<FunctionDecl>(ADecl);
5509   if (!FD) {
5510     Diag(ADecl->getLocation(), diag::err_omp_function_expected) << SimdId;
5511     return DeclGroupPtrTy();
5512   }
5513 
5514   // OpenMP [2.8.2, declare simd construct, Description]
5515   // The parameter of the simdlen clause must be a constant positive integer
5516   // expression.
5517   ExprResult SL;
5518   if (Simdlen)
5519     SL = VerifyPositiveIntegerConstantInClause(Simdlen, OMPC_simdlen);
5520   // OpenMP [2.8.2, declare simd construct, Description]
5521   // The special this pointer can be used as if was one of the arguments to the
5522   // function in any of the linear, aligned, or uniform clauses.
5523   // The uniform clause declares one or more arguments to have an invariant
5524   // value for all concurrent invocations of the function in the execution of a
5525   // single SIMD loop.
5526   llvm::DenseMap<const Decl *, const Expr *> UniformedArgs;
5527   const Expr *UniformedLinearThis = nullptr;
5528   for (const Expr *E : Uniforms) {
5529     E = E->IgnoreParenImpCasts();
5530     if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
5531       if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
5532         if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
5533             FD->getParamDecl(PVD->getFunctionScopeIndex())
5534                     ->getCanonicalDecl() == PVD->getCanonicalDecl()) {
5535           UniformedArgs.try_emplace(PVD->getCanonicalDecl(), E);
5536           continue;
5537         }
5538     if (isa<CXXThisExpr>(E)) {
5539       UniformedLinearThis = E;
5540       continue;
5541     }
5542     Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
5543         << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
5544   }
5545   // OpenMP [2.8.2, declare simd construct, Description]
5546   // The aligned clause declares that the object to which each list item points
5547   // is aligned to the number of bytes expressed in the optional parameter of
5548   // the aligned clause.
5549   // The special this pointer can be used as if was one of the arguments to the
5550   // function in any of the linear, aligned, or uniform clauses.
5551   // The type of list items appearing in the aligned clause must be array,
5552   // pointer, reference to array, or reference to pointer.
5553   llvm::DenseMap<const Decl *, const Expr *> AlignedArgs;
5554   const Expr *AlignedThis = nullptr;
5555   for (const Expr *E : Aligneds) {
5556     E = E->IgnoreParenImpCasts();
5557     if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
5558       if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
5559         const VarDecl *CanonPVD = PVD->getCanonicalDecl();
5560         if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
5561             FD->getParamDecl(PVD->getFunctionScopeIndex())
5562                     ->getCanonicalDecl() == CanonPVD) {
5563           // OpenMP  [2.8.1, simd construct, Restrictions]
5564           // A list-item cannot appear in more than one aligned clause.
5565           if (AlignedArgs.count(CanonPVD) > 0) {
5566             Diag(E->getExprLoc(), diag::err_omp_used_in_clause_twice)
5567                 << 1 << getOpenMPClauseName(OMPC_aligned)
5568                 << E->getSourceRange();
5569             Diag(AlignedArgs[CanonPVD]->getExprLoc(),
5570                  diag::note_omp_explicit_dsa)
5571                 << getOpenMPClauseName(OMPC_aligned);
5572             continue;
5573           }
5574           AlignedArgs[CanonPVD] = E;
5575           QualType QTy = PVD->getType()
5576                              .getNonReferenceType()
5577                              .getUnqualifiedType()
5578                              .getCanonicalType();
5579           const Type *Ty = QTy.getTypePtrOrNull();
5580           if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
5581             Diag(E->getExprLoc(), diag::err_omp_aligned_expected_array_or_ptr)
5582                 << QTy << getLangOpts().CPlusPlus << E->getSourceRange();
5583             Diag(PVD->getLocation(), diag::note_previous_decl) << PVD;
5584           }
5585           continue;
5586         }
5587       }
5588     if (isa<CXXThisExpr>(E)) {
5589       if (AlignedThis) {
5590         Diag(E->getExprLoc(), diag::err_omp_used_in_clause_twice)
5591             << 2 << getOpenMPClauseName(OMPC_aligned) << E->getSourceRange();
5592         Diag(AlignedThis->getExprLoc(), diag::note_omp_explicit_dsa)
5593             << getOpenMPClauseName(OMPC_aligned);
5594       }
5595       AlignedThis = E;
5596       continue;
5597     }
5598     Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
5599         << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
5600   }
5601   // The optional parameter of the aligned clause, alignment, must be a constant
5602   // positive integer expression. If no optional parameter is specified,
5603   // implementation-defined default alignments for SIMD instructions on the
5604   // target platforms are assumed.
5605   SmallVector<const Expr *, 4> NewAligns;
5606   for (Expr *E : Alignments) {
5607     ExprResult Align;
5608     if (E)
5609       Align = VerifyPositiveIntegerConstantInClause(E, OMPC_aligned);
5610     NewAligns.push_back(Align.get());
5611   }
5612   // OpenMP [2.8.2, declare simd construct, Description]
5613   // The linear clause declares one or more list items to be private to a SIMD
5614   // lane and to have a linear relationship with respect to the iteration space
5615   // of a loop.
5616   // The special this pointer can be used as if was one of the arguments to the
5617   // function in any of the linear, aligned, or uniform clauses.
5618   // When a linear-step expression is specified in a linear clause it must be
5619   // either a constant integer expression or an integer-typed parameter that is
5620   // specified in a uniform clause on the directive.
5621   llvm::DenseMap<const Decl *, const Expr *> LinearArgs;
5622   const bool IsUniformedThis = UniformedLinearThis != nullptr;
5623   auto MI = LinModifiers.begin();
5624   for (const Expr *E : Linears) {
5625     auto LinKind = static_cast<OpenMPLinearClauseKind>(*MI);
5626     ++MI;
5627     E = E->IgnoreParenImpCasts();
5628     if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
5629       if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
5630         const VarDecl *CanonPVD = PVD->getCanonicalDecl();
5631         if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
5632             FD->getParamDecl(PVD->getFunctionScopeIndex())
5633                     ->getCanonicalDecl() == CanonPVD) {
5634           // OpenMP  [2.15.3.7, linear Clause, Restrictions]
5635           // A list-item cannot appear in more than one linear clause.
5636           if (LinearArgs.count(CanonPVD) > 0) {
5637             Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
5638                 << getOpenMPClauseName(OMPC_linear)
5639                 << getOpenMPClauseName(OMPC_linear) << E->getSourceRange();
5640             Diag(LinearArgs[CanonPVD]->getExprLoc(),
5641                  diag::note_omp_explicit_dsa)
5642                 << getOpenMPClauseName(OMPC_linear);
5643             continue;
5644           }
5645           // Each argument can appear in at most one uniform or linear clause.
5646           if (UniformedArgs.count(CanonPVD) > 0) {
5647             Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
5648                 << getOpenMPClauseName(OMPC_linear)
5649                 << getOpenMPClauseName(OMPC_uniform) << E->getSourceRange();
5650             Diag(UniformedArgs[CanonPVD]->getExprLoc(),
5651                  diag::note_omp_explicit_dsa)
5652                 << getOpenMPClauseName(OMPC_uniform);
5653             continue;
5654           }
5655           LinearArgs[CanonPVD] = E;
5656           if (E->isValueDependent() || E->isTypeDependent() ||
5657               E->isInstantiationDependent() ||
5658               E->containsUnexpandedParameterPack())
5659             continue;
5660           (void)CheckOpenMPLinearDecl(CanonPVD, E->getExprLoc(), LinKind,
5661                                       PVD->getOriginalType(),
5662                                       /*IsDeclareSimd=*/true);
5663           continue;
5664         }
5665       }
5666     if (isa<CXXThisExpr>(E)) {
5667       if (UniformedLinearThis) {
5668         Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
5669             << getOpenMPClauseName(OMPC_linear)
5670             << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform : OMPC_linear)
5671             << E->getSourceRange();
5672         Diag(UniformedLinearThis->getExprLoc(), diag::note_omp_explicit_dsa)
5673             << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform
5674                                                    : OMPC_linear);
5675         continue;
5676       }
5677       UniformedLinearThis = E;
5678       if (E->isValueDependent() || E->isTypeDependent() ||
5679           E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
5680         continue;
5681       (void)CheckOpenMPLinearDecl(/*D=*/nullptr, E->getExprLoc(), LinKind,
5682                                   E->getType(), /*IsDeclareSimd=*/true);
5683       continue;
5684     }
5685     Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
5686         << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
5687   }
5688   Expr *Step = nullptr;
5689   Expr *NewStep = nullptr;
5690   SmallVector<Expr *, 4> NewSteps;
5691   for (Expr *E : Steps) {
5692     // Skip the same step expression, it was checked already.
5693     if (Step == E || !E) {
5694       NewSteps.push_back(E ? NewStep : nullptr);
5695       continue;
5696     }
5697     Step = E;
5698     if (const auto *DRE = dyn_cast<DeclRefExpr>(Step))
5699       if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
5700         const VarDecl *CanonPVD = PVD->getCanonicalDecl();
5701         if (UniformedArgs.count(CanonPVD) == 0) {
5702           Diag(Step->getExprLoc(), diag::err_omp_expected_uniform_param)
5703               << Step->getSourceRange();
5704         } else if (E->isValueDependent() || E->isTypeDependent() ||
5705                    E->isInstantiationDependent() ||
5706                    E->containsUnexpandedParameterPack() ||
5707                    CanonPVD->getType()->hasIntegerRepresentation()) {
5708           NewSteps.push_back(Step);
5709         } else {
5710           Diag(Step->getExprLoc(), diag::err_omp_expected_int_param)
5711               << Step->getSourceRange();
5712         }
5713         continue;
5714       }
5715     NewStep = Step;
5716     if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
5717         !Step->isInstantiationDependent() &&
5718         !Step->containsUnexpandedParameterPack()) {
5719       NewStep = PerformOpenMPImplicitIntegerConversion(Step->getExprLoc(), Step)
5720                     .get();
5721       if (NewStep)
5722         NewStep = VerifyIntegerConstantExpression(NewStep).get();
5723     }
5724     NewSteps.push_back(NewStep);
5725   }
5726   auto *NewAttr = OMPDeclareSimdDeclAttr::CreateImplicit(
5727       Context, BS, SL.get(), const_cast<Expr **>(Uniforms.data()),
5728       Uniforms.size(), const_cast<Expr **>(Aligneds.data()), Aligneds.size(),
5729       const_cast<Expr **>(NewAligns.data()), NewAligns.size(),
5730       const_cast<Expr **>(Linears.data()), Linears.size(),
5731       const_cast<unsigned *>(LinModifiers.data()), LinModifiers.size(),
5732       NewSteps.data(), NewSteps.size(), SR);
5733   ADecl->addAttr(NewAttr);
5734   return DG;
5735 }
5736 
5737 static void setPrototype(Sema &S, FunctionDecl *FD, FunctionDecl *FDWithProto,
5738                          QualType NewType) {
5739   assert(NewType->isFunctionProtoType() &&
5740          "Expected function type with prototype.");
5741   assert(FD->getType()->isFunctionNoProtoType() &&
5742          "Expected function with type with no prototype.");
5743   assert(FDWithProto->getType()->isFunctionProtoType() &&
5744          "Expected function with prototype.");
5745   // Synthesize parameters with the same types.
5746   FD->setType(NewType);
5747   SmallVector<ParmVarDecl *, 16> Params;
5748   for (const ParmVarDecl *P : FDWithProto->parameters()) {
5749     auto *Param = ParmVarDecl::Create(S.getASTContext(), FD, SourceLocation(),
5750                                       SourceLocation(), nullptr, P->getType(),
5751                                       /*TInfo=*/nullptr, SC_None, nullptr);
5752     Param->setScopeInfo(0, Params.size());
5753     Param->setImplicit();
5754     Params.push_back(Param);
5755   }
5756 
5757   FD->setParams(Params);
5758 }
5759 
5760 Sema::OMPDeclareVariantScope::OMPDeclareVariantScope(OMPTraitInfo &TI)
5761     : TI(&TI), NameSuffix(TI.getMangledName()) {}
5762 
5763 FunctionDecl *
5764 Sema::ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(Scope *S,
5765                                                                 Declarator &D) {
5766   IdentifierInfo *BaseII = D.getIdentifier();
5767   LookupResult Lookup(*this, DeclarationName(BaseII), D.getIdentifierLoc(),
5768                       LookupOrdinaryName);
5769   LookupParsedName(Lookup, S, &D.getCXXScopeSpec());
5770 
5771   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
5772   QualType FType = TInfo->getType();
5773 
5774   bool IsConstexpr = D.getDeclSpec().getConstexprSpecifier() == CSK_constexpr;
5775   bool IsConsteval = D.getDeclSpec().getConstexprSpecifier() == CSK_consteval;
5776 
5777   FunctionDecl *BaseFD = nullptr;
5778   for (auto *Candidate : Lookup) {
5779     auto *UDecl = dyn_cast<FunctionDecl>(Candidate->getUnderlyingDecl());
5780     if (!UDecl)
5781       continue;
5782 
5783     // Don't specialize constexpr/consteval functions with
5784     // non-constexpr/consteval functions.
5785     if (UDecl->isConstexpr() && !IsConstexpr)
5786       continue;
5787     if (UDecl->isConsteval() && !IsConsteval)
5788       continue;
5789 
5790     QualType NewType = Context.mergeFunctionTypes(
5791         FType, UDecl->getType(), /* OfBlockPointer */ false,
5792         /* Unqualified */ false, /* AllowCXX */ true);
5793     if (NewType.isNull())
5794       continue;
5795 
5796     // Found a base!
5797     BaseFD = UDecl;
5798     break;
5799   }
5800   if (!BaseFD) {
5801     BaseFD = cast<FunctionDecl>(ActOnDeclarator(S, D));
5802     BaseFD->setImplicit(true);
5803   }
5804 
5805   OMPDeclareVariantScope &DVScope = OMPDeclareVariantScopes.back();
5806   std::string MangledName;
5807   MangledName += D.getIdentifier()->getName();
5808   MangledName += getOpenMPVariantManglingSeparatorStr();
5809   MangledName += DVScope.NameSuffix;
5810   IdentifierInfo &VariantII = Context.Idents.get(MangledName);
5811 
5812   VariantII.setMangledOpenMPVariantName(true);
5813   D.SetIdentifier(&VariantII, D.getBeginLoc());
5814   return BaseFD;
5815 }
5816 
5817 void Sema::ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(
5818     FunctionDecl *FD, FunctionDecl *BaseFD) {
5819   // Do not mark function as is used to prevent its emission if this is the
5820   // only place where it is used.
5821   EnterExpressionEvaluationContext Unevaluated(
5822       *this, Sema::ExpressionEvaluationContext::Unevaluated);
5823 
5824   Expr *VariantFuncRef = DeclRefExpr::Create(
5825       Context, NestedNameSpecifierLoc(), SourceLocation(), FD,
5826       /* RefersToEnclosingVariableOrCapture */ false,
5827       /* NameLoc */ FD->getLocation(), FD->getType(), ExprValueKind::VK_RValue);
5828 
5829   OMPDeclareVariantScope &DVScope = OMPDeclareVariantScopes.back();
5830   auto *OMPDeclareVariantA = OMPDeclareVariantAttr::CreateImplicit(
5831       Context, VariantFuncRef, DVScope.TI);
5832   BaseFD->addAttr(OMPDeclareVariantA);
5833 }
5834 
5835 ExprResult Sema::ActOnOpenMPCall(ExprResult Call, Scope *Scope,
5836                                  SourceLocation LParenLoc,
5837                                  MultiExprArg ArgExprs,
5838                                  SourceLocation RParenLoc, Expr *ExecConfig) {
5839   // The common case is a regular call we do not want to specialize at all. Try
5840   // to make that case fast by bailing early.
5841   CallExpr *CE = dyn_cast<CallExpr>(Call.get());
5842   if (!CE)
5843     return Call;
5844 
5845   FunctionDecl *CalleeFnDecl = CE->getDirectCallee();
5846   if (!CalleeFnDecl)
5847     return Call;
5848 
5849   if (!CalleeFnDecl->hasAttr<OMPDeclareVariantAttr>())
5850     return Call;
5851 
5852   ASTContext &Context = getASTContext();
5853   OMPContext OMPCtx(getLangOpts().OpenMPIsDevice,
5854                     Context.getTargetInfo().getTriple());
5855 
5856   SmallVector<Expr *, 4> Exprs;
5857   SmallVector<VariantMatchInfo, 4> VMIs;
5858   while (CalleeFnDecl) {
5859     for (OMPDeclareVariantAttr *A :
5860          CalleeFnDecl->specific_attrs<OMPDeclareVariantAttr>()) {
5861       Expr *VariantRef = A->getVariantFuncRef();
5862 
5863       VariantMatchInfo VMI;
5864       OMPTraitInfo &TI = A->getTraitInfo();
5865       TI.getAsVariantMatchInfo(Context, VMI);
5866       if (!isVariantApplicableInContext(VMI, OMPCtx, /* DeviceSetOnly */ false))
5867         continue;
5868 
5869       VMIs.push_back(VMI);
5870       Exprs.push_back(VariantRef);
5871     }
5872 
5873     CalleeFnDecl = CalleeFnDecl->getPreviousDecl();
5874   }
5875 
5876   ExprResult NewCall;
5877   do {
5878     int BestIdx = getBestVariantMatchForContext(VMIs, OMPCtx);
5879     if (BestIdx < 0)
5880       return Call;
5881     Expr *BestExpr = cast<DeclRefExpr>(Exprs[BestIdx]);
5882     Decl *BestDecl = cast<DeclRefExpr>(BestExpr)->getDecl();
5883 
5884     {
5885       // Try to build a (member) call expression for the current best applicable
5886       // variant expression. We allow this to fail in which case we continue
5887       // with the next best variant expression. The fail case is part of the
5888       // implementation defined behavior in the OpenMP standard when it talks
5889       // about what differences in the function prototypes: "Any differences
5890       // that the specific OpenMP context requires in the prototype of the
5891       // variant from the base function prototype are implementation defined."
5892       // This wording is there to allow the specialized variant to have a
5893       // different type than the base function. This is intended and OK but if
5894       // we cannot create a call the difference is not in the "implementation
5895       // defined range" we allow.
5896       Sema::TentativeAnalysisScope Trap(*this);
5897 
5898       if (auto *SpecializedMethod = dyn_cast<CXXMethodDecl>(BestDecl)) {
5899         auto *MemberCall = dyn_cast<CXXMemberCallExpr>(CE);
5900         BestExpr = MemberExpr::CreateImplicit(
5901             Context, MemberCall->getImplicitObjectArgument(),
5902             /* IsArrow */ false, SpecializedMethod, Context.BoundMemberTy,
5903             MemberCall->getValueKind(), MemberCall->getObjectKind());
5904       }
5905       NewCall = BuildCallExpr(Scope, BestExpr, LParenLoc, ArgExprs, RParenLoc,
5906                               ExecConfig);
5907       if (NewCall.isUsable())
5908         break;
5909     }
5910 
5911     VMIs.erase(VMIs.begin() + BestIdx);
5912     Exprs.erase(Exprs.begin() + BestIdx);
5913   } while (!VMIs.empty());
5914 
5915   if (!NewCall.isUsable())
5916     return Call;
5917   return PseudoObjectExpr::Create(Context, CE, {NewCall.get()}, 0);
5918 }
5919 
5920 Optional<std::pair<FunctionDecl *, Expr *>>
5921 Sema::checkOpenMPDeclareVariantFunction(Sema::DeclGroupPtrTy DG,
5922                                         Expr *VariantRef, OMPTraitInfo &TI,
5923                                         SourceRange SR) {
5924   if (!DG || DG.get().isNull())
5925     return None;
5926 
5927   const int VariantId = 1;
5928   // Must be applied only to single decl.
5929   if (!DG.get().isSingleDecl()) {
5930     Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd_variant)
5931         << VariantId << SR;
5932     return None;
5933   }
5934   Decl *ADecl = DG.get().getSingleDecl();
5935   if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
5936     ADecl = FTD->getTemplatedDecl();
5937 
5938   // Decl must be a function.
5939   auto *FD = dyn_cast<FunctionDecl>(ADecl);
5940   if (!FD) {
5941     Diag(ADecl->getLocation(), diag::err_omp_function_expected)
5942         << VariantId << SR;
5943     return None;
5944   }
5945 
5946   auto &&HasMultiVersionAttributes = [](const FunctionDecl *FD) {
5947     return FD->hasAttrs() &&
5948            (FD->hasAttr<CPUDispatchAttr>() || FD->hasAttr<CPUSpecificAttr>() ||
5949             FD->hasAttr<TargetAttr>());
5950   };
5951   // OpenMP is not compatible with CPU-specific attributes.
5952   if (HasMultiVersionAttributes(FD)) {
5953     Diag(FD->getLocation(), diag::err_omp_declare_variant_incompat_attributes)
5954         << SR;
5955     return None;
5956   }
5957 
5958   // Allow #pragma omp declare variant only if the function is not used.
5959   if (FD->isUsed(false))
5960     Diag(SR.getBegin(), diag::warn_omp_declare_variant_after_used)
5961         << FD->getLocation();
5962 
5963   // Check if the function was emitted already.
5964   const FunctionDecl *Definition;
5965   if (!FD->isThisDeclarationADefinition() && FD->isDefined(Definition) &&
5966       (LangOpts.EmitAllDecls || Context.DeclMustBeEmitted(Definition)))
5967     Diag(SR.getBegin(), diag::warn_omp_declare_variant_after_emitted)
5968         << FD->getLocation();
5969 
5970   // The VariantRef must point to function.
5971   if (!VariantRef) {
5972     Diag(SR.getBegin(), diag::err_omp_function_expected) << VariantId;
5973     return None;
5974   }
5975 
5976   auto ShouldDelayChecks = [](Expr *&E, bool) {
5977     return E && (E->isTypeDependent() || E->isValueDependent() ||
5978                  E->containsUnexpandedParameterPack() ||
5979                  E->isInstantiationDependent());
5980   };
5981   // Do not check templates, wait until instantiation.
5982   if (FD->isDependentContext() || ShouldDelayChecks(VariantRef, false) ||
5983       TI.anyScoreOrCondition(ShouldDelayChecks))
5984     return std::make_pair(FD, VariantRef);
5985 
5986   // Deal with non-constant score and user condition expressions.
5987   auto HandleNonConstantScoresAndConditions = [this](Expr *&E,
5988                                                      bool IsScore) -> bool {
5989     llvm::APSInt Result;
5990     if (!E || E->isIntegerConstantExpr(Result, Context))
5991       return false;
5992 
5993     if (IsScore) {
5994       // We warn on non-constant scores and pretend they were not present.
5995       Diag(E->getExprLoc(), diag::warn_omp_declare_variant_score_not_constant)
5996           << E;
5997       E = nullptr;
5998     } else {
5999       // We could replace a non-constant user condition with "false" but we
6000       // will soon need to handle these anyway for the dynamic version of
6001       // OpenMP context selectors.
6002       Diag(E->getExprLoc(),
6003            diag::err_omp_declare_variant_user_condition_not_constant)
6004           << E;
6005     }
6006     return true;
6007   };
6008   if (TI.anyScoreOrCondition(HandleNonConstantScoresAndConditions))
6009     return None;
6010 
6011   // Convert VariantRef expression to the type of the original function to
6012   // resolve possible conflicts.
6013   ExprResult VariantRefCast;
6014   if (LangOpts.CPlusPlus) {
6015     QualType FnPtrType;
6016     auto *Method = dyn_cast<CXXMethodDecl>(FD);
6017     if (Method && !Method->isStatic()) {
6018       const Type *ClassType =
6019           Context.getTypeDeclType(Method->getParent()).getTypePtr();
6020       FnPtrType = Context.getMemberPointerType(FD->getType(), ClassType);
6021       ExprResult ER;
6022       {
6023         // Build adrr_of unary op to correctly handle type checks for member
6024         // functions.
6025         Sema::TentativeAnalysisScope Trap(*this);
6026         ER = CreateBuiltinUnaryOp(VariantRef->getBeginLoc(), UO_AddrOf,
6027                                   VariantRef);
6028       }
6029       if (!ER.isUsable()) {
6030         Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected)
6031             << VariantId << VariantRef->getSourceRange();
6032         return None;
6033       }
6034       VariantRef = ER.get();
6035     } else {
6036       FnPtrType = Context.getPointerType(FD->getType());
6037     }
6038     ImplicitConversionSequence ICS =
6039         TryImplicitConversion(VariantRef, FnPtrType.getUnqualifiedType(),
6040                               /*SuppressUserConversions=*/false,
6041                               AllowedExplicit::None,
6042                               /*InOverloadResolution=*/false,
6043                               /*CStyle=*/false,
6044                               /*AllowObjCWritebackConversion=*/false);
6045     if (ICS.isFailure()) {
6046       Diag(VariantRef->getExprLoc(),
6047            diag::err_omp_declare_variant_incompat_types)
6048           << VariantRef->getType()
6049           << ((Method && !Method->isStatic()) ? FnPtrType : FD->getType())
6050           << VariantRef->getSourceRange();
6051       return None;
6052     }
6053     VariantRefCast = PerformImplicitConversion(
6054         VariantRef, FnPtrType.getUnqualifiedType(), AA_Converting);
6055     if (!VariantRefCast.isUsable())
6056       return None;
6057     // Drop previously built artificial addr_of unary op for member functions.
6058     if (Method && !Method->isStatic()) {
6059       Expr *PossibleAddrOfVariantRef = VariantRefCast.get();
6060       if (auto *UO = dyn_cast<UnaryOperator>(
6061               PossibleAddrOfVariantRef->IgnoreImplicit()))
6062         VariantRefCast = UO->getSubExpr();
6063     }
6064   } else {
6065     VariantRefCast = VariantRef;
6066   }
6067 
6068   ExprResult ER = CheckPlaceholderExpr(VariantRefCast.get());
6069   if (!ER.isUsable() ||
6070       !ER.get()->IgnoreParenImpCasts()->getType()->isFunctionType()) {
6071     Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected)
6072         << VariantId << VariantRef->getSourceRange();
6073     return None;
6074   }
6075 
6076   // The VariantRef must point to function.
6077   auto *DRE = dyn_cast<DeclRefExpr>(ER.get()->IgnoreParenImpCasts());
6078   if (!DRE) {
6079     Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected)
6080         << VariantId << VariantRef->getSourceRange();
6081     return None;
6082   }
6083   auto *NewFD = dyn_cast_or_null<FunctionDecl>(DRE->getDecl());
6084   if (!NewFD) {
6085     Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected)
6086         << VariantId << VariantRef->getSourceRange();
6087     return None;
6088   }
6089 
6090   // Check if function types are compatible in C.
6091   if (!LangOpts.CPlusPlus) {
6092     QualType NewType =
6093         Context.mergeFunctionTypes(FD->getType(), NewFD->getType());
6094     if (NewType.isNull()) {
6095       Diag(VariantRef->getExprLoc(),
6096            diag::err_omp_declare_variant_incompat_types)
6097           << NewFD->getType() << FD->getType() << VariantRef->getSourceRange();
6098       return None;
6099     }
6100     if (NewType->isFunctionProtoType()) {
6101       if (FD->getType()->isFunctionNoProtoType())
6102         setPrototype(*this, FD, NewFD, NewType);
6103       else if (NewFD->getType()->isFunctionNoProtoType())
6104         setPrototype(*this, NewFD, FD, NewType);
6105     }
6106   }
6107 
6108   // Check if variant function is not marked with declare variant directive.
6109   if (NewFD->hasAttrs() && NewFD->hasAttr<OMPDeclareVariantAttr>()) {
6110     Diag(VariantRef->getExprLoc(),
6111          diag::warn_omp_declare_variant_marked_as_declare_variant)
6112         << VariantRef->getSourceRange();
6113     SourceRange SR =
6114         NewFD->specific_attr_begin<OMPDeclareVariantAttr>()->getRange();
6115     Diag(SR.getBegin(), diag::note_omp_marked_declare_variant_here) << SR;
6116     return None;
6117   }
6118 
6119   enum DoesntSupport {
6120     VirtFuncs = 1,
6121     Constructors = 3,
6122     Destructors = 4,
6123     DeletedFuncs = 5,
6124     DefaultedFuncs = 6,
6125     ConstexprFuncs = 7,
6126     ConstevalFuncs = 8,
6127   };
6128   if (const auto *CXXFD = dyn_cast<CXXMethodDecl>(FD)) {
6129     if (CXXFD->isVirtual()) {
6130       Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
6131           << VirtFuncs;
6132       return None;
6133     }
6134 
6135     if (isa<CXXConstructorDecl>(FD)) {
6136       Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
6137           << Constructors;
6138       return None;
6139     }
6140 
6141     if (isa<CXXDestructorDecl>(FD)) {
6142       Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
6143           << Destructors;
6144       return None;
6145     }
6146   }
6147 
6148   if (FD->isDeleted()) {
6149     Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
6150         << DeletedFuncs;
6151     return None;
6152   }
6153 
6154   if (FD->isDefaulted()) {
6155     Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
6156         << DefaultedFuncs;
6157     return None;
6158   }
6159 
6160   if (FD->isConstexpr()) {
6161     Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
6162         << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
6163     return None;
6164   }
6165 
6166   // Check general compatibility.
6167   if (areMultiversionVariantFunctionsCompatible(
6168           FD, NewFD, PartialDiagnostic::NullDiagnostic(),
6169           PartialDiagnosticAt(SourceLocation(),
6170                               PartialDiagnostic::NullDiagnostic()),
6171           PartialDiagnosticAt(
6172               VariantRef->getExprLoc(),
6173               PDiag(diag::err_omp_declare_variant_doesnt_support)),
6174           PartialDiagnosticAt(VariantRef->getExprLoc(),
6175                               PDiag(diag::err_omp_declare_variant_diff)
6176                                   << FD->getLocation()),
6177           /*TemplatesSupported=*/true, /*ConstexprSupported=*/false,
6178           /*CLinkageMayDiffer=*/true))
6179     return None;
6180   return std::make_pair(FD, cast<Expr>(DRE));
6181 }
6182 
6183 void Sema::ActOnOpenMPDeclareVariantDirective(FunctionDecl *FD,
6184                                               Expr *VariantRef,
6185                                               OMPTraitInfo &TI,
6186                                               SourceRange SR) {
6187   auto *NewAttr =
6188       OMPDeclareVariantAttr::CreateImplicit(Context, VariantRef, &TI, SR);
6189   FD->addAttr(NewAttr);
6190 }
6191 
6192 StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
6193                                               Stmt *AStmt,
6194                                               SourceLocation StartLoc,
6195                                               SourceLocation EndLoc) {
6196   if (!AStmt)
6197     return StmtError();
6198 
6199   auto *CS = cast<CapturedStmt>(AStmt);
6200   // 1.2.2 OpenMP Language Terminology
6201   // Structured block - An executable statement with a single entry at the
6202   // top and a single exit at the bottom.
6203   // The point of exit cannot be a branch out of the structured block.
6204   // longjmp() and throw() must not violate the entry/exit criteria.
6205   CS->getCapturedDecl()->setNothrow();
6206 
6207   setFunctionHasBranchProtectedScope();
6208 
6209   return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
6210                                       DSAStack->getTaskgroupReductionRef(),
6211                                       DSAStack->isCancelRegion());
6212 }
6213 
6214 namespace {
6215 /// Iteration space of a single for loop.
6216 struct LoopIterationSpace final {
6217   /// True if the condition operator is the strict compare operator (<, > or
6218   /// !=).
6219   bool IsStrictCompare = false;
6220   /// Condition of the loop.
6221   Expr *PreCond = nullptr;
6222   /// This expression calculates the number of iterations in the loop.
6223   /// It is always possible to calculate it before starting the loop.
6224   Expr *NumIterations = nullptr;
6225   /// The loop counter variable.
6226   Expr *CounterVar = nullptr;
6227   /// Private loop counter variable.
6228   Expr *PrivateCounterVar = nullptr;
6229   /// This is initializer for the initial value of #CounterVar.
6230   Expr *CounterInit = nullptr;
6231   /// This is step for the #CounterVar used to generate its update:
6232   /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration.
6233   Expr *CounterStep = nullptr;
6234   /// Should step be subtracted?
6235   bool Subtract = false;
6236   /// Source range of the loop init.
6237   SourceRange InitSrcRange;
6238   /// Source range of the loop condition.
6239   SourceRange CondSrcRange;
6240   /// Source range of the loop increment.
6241   SourceRange IncSrcRange;
6242   /// Minimum value that can have the loop control variable. Used to support
6243   /// non-rectangular loops. Applied only for LCV with the non-iterator types,
6244   /// since only such variables can be used in non-loop invariant expressions.
6245   Expr *MinValue = nullptr;
6246   /// Maximum value that can have the loop control variable. Used to support
6247   /// non-rectangular loops. Applied only for LCV with the non-iterator type,
6248   /// since only such variables can be used in non-loop invariant expressions.
6249   Expr *MaxValue = nullptr;
6250   /// true, if the lower bound depends on the outer loop control var.
6251   bool IsNonRectangularLB = false;
6252   /// true, if the upper bound depends on the outer loop control var.
6253   bool IsNonRectangularUB = false;
6254   /// Index of the loop this loop depends on and forms non-rectangular loop
6255   /// nest.
6256   unsigned LoopDependentIdx = 0;
6257   /// Final condition for the non-rectangular loop nest support. It is used to
6258   /// check that the number of iterations for this particular counter must be
6259   /// finished.
6260   Expr *FinalCondition = nullptr;
6261 };
6262 
6263 /// Helper class for checking canonical form of the OpenMP loops and
6264 /// extracting iteration space of each loop in the loop nest, that will be used
6265 /// for IR generation.
6266 class OpenMPIterationSpaceChecker {
6267   /// Reference to Sema.
6268   Sema &SemaRef;
6269   /// Data-sharing stack.
6270   DSAStackTy &Stack;
6271   /// A location for diagnostics (when there is no some better location).
6272   SourceLocation DefaultLoc;
6273   /// A location for diagnostics (when increment is not compatible).
6274   SourceLocation ConditionLoc;
6275   /// A source location for referring to loop init later.
6276   SourceRange InitSrcRange;
6277   /// A source location for referring to condition later.
6278   SourceRange ConditionSrcRange;
6279   /// A source location for referring to increment later.
6280   SourceRange IncrementSrcRange;
6281   /// Loop variable.
6282   ValueDecl *LCDecl = nullptr;
6283   /// Reference to loop variable.
6284   Expr *LCRef = nullptr;
6285   /// Lower bound (initializer for the var).
6286   Expr *LB = nullptr;
6287   /// Upper bound.
6288   Expr *UB = nullptr;
6289   /// Loop step (increment).
6290   Expr *Step = nullptr;
6291   /// This flag is true when condition is one of:
6292   ///   Var <  UB
6293   ///   Var <= UB
6294   ///   UB  >  Var
6295   ///   UB  >= Var
6296   /// This will have no value when the condition is !=
6297   llvm::Optional<bool> TestIsLessOp;
6298   /// This flag is true when condition is strict ( < or > ).
6299   bool TestIsStrictOp = false;
6300   /// This flag is true when step is subtracted on each iteration.
6301   bool SubtractStep = false;
6302   /// The outer loop counter this loop depends on (if any).
6303   const ValueDecl *DepDecl = nullptr;
6304   /// Contains number of loop (starts from 1) on which loop counter init
6305   /// expression of this loop depends on.
6306   Optional<unsigned> InitDependOnLC;
6307   /// Contains number of loop (starts from 1) on which loop counter condition
6308   /// expression of this loop depends on.
6309   Optional<unsigned> CondDependOnLC;
6310   /// Checks if the provide statement depends on the loop counter.
6311   Optional<unsigned> doesDependOnLoopCounter(const Stmt *S, bool IsInitializer);
6312   /// Original condition required for checking of the exit condition for
6313   /// non-rectangular loop.
6314   Expr *Condition = nullptr;
6315 
6316 public:
6317   OpenMPIterationSpaceChecker(Sema &SemaRef, DSAStackTy &Stack,
6318                               SourceLocation DefaultLoc)
6319       : SemaRef(SemaRef), Stack(Stack), DefaultLoc(DefaultLoc),
6320         ConditionLoc(DefaultLoc) {}
6321   /// Check init-expr for canonical loop form and save loop counter
6322   /// variable - #Var and its initialization value - #LB.
6323   bool checkAndSetInit(Stmt *S, bool EmitDiags = true);
6324   /// Check test-expr for canonical form, save upper-bound (#UB), flags
6325   /// for less/greater and for strict/non-strict comparison.
6326   bool checkAndSetCond(Expr *S);
6327   /// Check incr-expr for canonical loop form and return true if it
6328   /// does not conform, otherwise save loop step (#Step).
6329   bool checkAndSetInc(Expr *S);
6330   /// Return the loop counter variable.
6331   ValueDecl *getLoopDecl() const { return LCDecl; }
6332   /// Return the reference expression to loop counter variable.
6333   Expr *getLoopDeclRefExpr() const { return LCRef; }
6334   /// Source range of the loop init.
6335   SourceRange getInitSrcRange() const { return InitSrcRange; }
6336   /// Source range of the loop condition.
6337   SourceRange getConditionSrcRange() const { return ConditionSrcRange; }
6338   /// Source range of the loop increment.
6339   SourceRange getIncrementSrcRange() const { return IncrementSrcRange; }
6340   /// True if the step should be subtracted.
6341   bool shouldSubtractStep() const { return SubtractStep; }
6342   /// True, if the compare operator is strict (<, > or !=).
6343   bool isStrictTestOp() const { return TestIsStrictOp; }
6344   /// Build the expression to calculate the number of iterations.
6345   Expr *buildNumIterations(
6346       Scope *S, ArrayRef<LoopIterationSpace> ResultIterSpaces, bool LimitedType,
6347       llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
6348   /// Build the precondition expression for the loops.
6349   Expr *
6350   buildPreCond(Scope *S, Expr *Cond,
6351                llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
6352   /// Build reference expression to the counter be used for codegen.
6353   DeclRefExpr *
6354   buildCounterVar(llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
6355                   DSAStackTy &DSA) const;
6356   /// Build reference expression to the private counter be used for
6357   /// codegen.
6358   Expr *buildPrivateCounterVar() const;
6359   /// Build initialization of the counter be used for codegen.
6360   Expr *buildCounterInit() const;
6361   /// Build step of the counter be used for codegen.
6362   Expr *buildCounterStep() const;
6363   /// Build loop data with counter value for depend clauses in ordered
6364   /// directives.
6365   Expr *
6366   buildOrderedLoopData(Scope *S, Expr *Counter,
6367                        llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
6368                        SourceLocation Loc, Expr *Inc = nullptr,
6369                        OverloadedOperatorKind OOK = OO_Amp);
6370   /// Builds the minimum value for the loop counter.
6371   std::pair<Expr *, Expr *> buildMinMaxValues(
6372       Scope *S, llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
6373   /// Builds final condition for the non-rectangular loops.
6374   Expr *buildFinalCondition(Scope *S) const;
6375   /// Return true if any expression is dependent.
6376   bool dependent() const;
6377   /// Returns true if the initializer forms non-rectangular loop.
6378   bool doesInitDependOnLC() const { return InitDependOnLC.hasValue(); }
6379   /// Returns true if the condition forms non-rectangular loop.
6380   bool doesCondDependOnLC() const { return CondDependOnLC.hasValue(); }
6381   /// Returns index of the loop we depend on (starting from 1), or 0 otherwise.
6382   unsigned getLoopDependentIdx() const {
6383     return InitDependOnLC.getValueOr(CondDependOnLC.getValueOr(0));
6384   }
6385 
6386 private:
6387   /// Check the right-hand side of an assignment in the increment
6388   /// expression.
6389   bool checkAndSetIncRHS(Expr *RHS);
6390   /// Helper to set loop counter variable and its initializer.
6391   bool setLCDeclAndLB(ValueDecl *NewLCDecl, Expr *NewDeclRefExpr, Expr *NewLB,
6392                       bool EmitDiags);
6393   /// Helper to set upper bound.
6394   bool setUB(Expr *NewUB, llvm::Optional<bool> LessOp, bool StrictOp,
6395              SourceRange SR, SourceLocation SL);
6396   /// Helper to set loop increment.
6397   bool setStep(Expr *NewStep, bool Subtract);
6398 };
6399 
6400 bool OpenMPIterationSpaceChecker::dependent() const {
6401   if (!LCDecl) {
6402     assert(!LB && !UB && !Step);
6403     return false;
6404   }
6405   return LCDecl->getType()->isDependentType() ||
6406          (LB && LB->isValueDependent()) || (UB && UB->isValueDependent()) ||
6407          (Step && Step->isValueDependent());
6408 }
6409 
6410 bool OpenMPIterationSpaceChecker::setLCDeclAndLB(ValueDecl *NewLCDecl,
6411                                                  Expr *NewLCRefExpr,
6412                                                  Expr *NewLB, bool EmitDiags) {
6413   // State consistency checking to ensure correct usage.
6414   assert(LCDecl == nullptr && LB == nullptr && LCRef == nullptr &&
6415          UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
6416   if (!NewLCDecl || !NewLB)
6417     return true;
6418   LCDecl = getCanonicalDecl(NewLCDecl);
6419   LCRef = NewLCRefExpr;
6420   if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB))
6421     if (const CXXConstructorDecl *Ctor = CE->getConstructor())
6422       if ((Ctor->isCopyOrMoveConstructor() ||
6423            Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
6424           CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
6425         NewLB = CE->getArg(0)->IgnoreParenImpCasts();
6426   LB = NewLB;
6427   if (EmitDiags)
6428     InitDependOnLC = doesDependOnLoopCounter(LB, /*IsInitializer=*/true);
6429   return false;
6430 }
6431 
6432 bool OpenMPIterationSpaceChecker::setUB(Expr *NewUB,
6433                                         llvm::Optional<bool> LessOp,
6434                                         bool StrictOp, SourceRange SR,
6435                                         SourceLocation SL) {
6436   // State consistency checking to ensure correct usage.
6437   assert(LCDecl != nullptr && LB != nullptr && UB == nullptr &&
6438          Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
6439   if (!NewUB)
6440     return true;
6441   UB = NewUB;
6442   if (LessOp)
6443     TestIsLessOp = LessOp;
6444   TestIsStrictOp = StrictOp;
6445   ConditionSrcRange = SR;
6446   ConditionLoc = SL;
6447   CondDependOnLC = doesDependOnLoopCounter(UB, /*IsInitializer=*/false);
6448   return false;
6449 }
6450 
6451 bool OpenMPIterationSpaceChecker::setStep(Expr *NewStep, bool Subtract) {
6452   // State consistency checking to ensure correct usage.
6453   assert(LCDecl != nullptr && LB != nullptr && Step == nullptr);
6454   if (!NewStep)
6455     return true;
6456   if (!NewStep->isValueDependent()) {
6457     // Check that the step is integer expression.
6458     SourceLocation StepLoc = NewStep->getBeginLoc();
6459     ExprResult Val = SemaRef.PerformOpenMPImplicitIntegerConversion(
6460         StepLoc, getExprAsWritten(NewStep));
6461     if (Val.isInvalid())
6462       return true;
6463     NewStep = Val.get();
6464 
6465     // OpenMP [2.6, Canonical Loop Form, Restrictions]
6466     //  If test-expr is of form var relational-op b and relational-op is < or
6467     //  <= then incr-expr must cause var to increase on each iteration of the
6468     //  loop. If test-expr is of form var relational-op b and relational-op is
6469     //  > or >= then incr-expr must cause var to decrease on each iteration of
6470     //  the loop.
6471     //  If test-expr is of form b relational-op var and relational-op is < or
6472     //  <= then incr-expr must cause var to decrease on each iteration of the
6473     //  loop. If test-expr is of form b relational-op var and relational-op is
6474     //  > or >= then incr-expr must cause var to increase on each iteration of
6475     //  the loop.
6476     llvm::APSInt Result;
6477     bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context);
6478     bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation();
6479     bool IsConstNeg =
6480         IsConstant && Result.isSigned() && (Subtract != Result.isNegative());
6481     bool IsConstPos =
6482         IsConstant && Result.isSigned() && (Subtract == Result.isNegative());
6483     bool IsConstZero = IsConstant && !Result.getBoolValue();
6484 
6485     // != with increment is treated as <; != with decrement is treated as >
6486     if (!TestIsLessOp.hasValue())
6487       TestIsLessOp = IsConstPos || (IsUnsigned && !Subtract);
6488     if (UB && (IsConstZero ||
6489                (TestIsLessOp.getValue() ?
6490                   (IsConstNeg || (IsUnsigned && Subtract)) :
6491                   (IsConstPos || (IsUnsigned && !Subtract))))) {
6492       SemaRef.Diag(NewStep->getExprLoc(),
6493                    diag::err_omp_loop_incr_not_compatible)
6494           << LCDecl << TestIsLessOp.getValue() << NewStep->getSourceRange();
6495       SemaRef.Diag(ConditionLoc,
6496                    diag::note_omp_loop_cond_requres_compatible_incr)
6497           << TestIsLessOp.getValue() << ConditionSrcRange;
6498       return true;
6499     }
6500     if (TestIsLessOp.getValue() == Subtract) {
6501       NewStep =
6502           SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus, NewStep)
6503               .get();
6504       Subtract = !Subtract;
6505     }
6506   }
6507 
6508   Step = NewStep;
6509   SubtractStep = Subtract;
6510   return false;
6511 }
6512 
6513 namespace {
6514 /// Checker for the non-rectangular loops. Checks if the initializer or
6515 /// condition expression references loop counter variable.
6516 class LoopCounterRefChecker final
6517     : public ConstStmtVisitor<LoopCounterRefChecker, bool> {
6518   Sema &SemaRef;
6519   DSAStackTy &Stack;
6520   const ValueDecl *CurLCDecl = nullptr;
6521   const ValueDecl *DepDecl = nullptr;
6522   const ValueDecl *PrevDepDecl = nullptr;
6523   bool IsInitializer = true;
6524   unsigned BaseLoopId = 0;
6525   bool checkDecl(const Expr *E, const ValueDecl *VD) {
6526     if (getCanonicalDecl(VD) == getCanonicalDecl(CurLCDecl)) {
6527       SemaRef.Diag(E->getExprLoc(), diag::err_omp_stmt_depends_on_loop_counter)
6528           << (IsInitializer ? 0 : 1);
6529       return false;
6530     }
6531     const auto &&Data = Stack.isLoopControlVariable(VD);
6532     // OpenMP, 2.9.1 Canonical Loop Form, Restrictions.
6533     // The type of the loop iterator on which we depend may not have a random
6534     // access iterator type.
6535     if (Data.first && VD->getType()->isRecordType()) {
6536       SmallString<128> Name;
6537       llvm::raw_svector_ostream OS(Name);
6538       VD->getNameForDiagnostic(OS, SemaRef.getPrintingPolicy(),
6539                                /*Qualified=*/true);
6540       SemaRef.Diag(E->getExprLoc(),
6541                    diag::err_omp_wrong_dependency_iterator_type)
6542           << OS.str();
6543       SemaRef.Diag(VD->getLocation(), diag::note_previous_decl) << VD;
6544       return false;
6545     }
6546     if (Data.first &&
6547         (DepDecl || (PrevDepDecl &&
6548                      getCanonicalDecl(VD) != getCanonicalDecl(PrevDepDecl)))) {
6549       if (!DepDecl && PrevDepDecl)
6550         DepDecl = PrevDepDecl;
6551       SmallString<128> Name;
6552       llvm::raw_svector_ostream OS(Name);
6553       DepDecl->getNameForDiagnostic(OS, SemaRef.getPrintingPolicy(),
6554                                     /*Qualified=*/true);
6555       SemaRef.Diag(E->getExprLoc(),
6556                    diag::err_omp_invariant_or_linear_dependency)
6557           << OS.str();
6558       return false;
6559     }
6560     if (Data.first) {
6561       DepDecl = VD;
6562       BaseLoopId = Data.first;
6563     }
6564     return Data.first;
6565   }
6566 
6567 public:
6568   bool VisitDeclRefExpr(const DeclRefExpr *E) {
6569     const ValueDecl *VD = E->getDecl();
6570     if (isa<VarDecl>(VD))
6571       return checkDecl(E, VD);
6572     return false;
6573   }
6574   bool VisitMemberExpr(const MemberExpr *E) {
6575     if (isa<CXXThisExpr>(E->getBase()->IgnoreParens())) {
6576       const ValueDecl *VD = E->getMemberDecl();
6577       if (isa<VarDecl>(VD) || isa<FieldDecl>(VD))
6578         return checkDecl(E, VD);
6579     }
6580     return false;
6581   }
6582   bool VisitStmt(const Stmt *S) {
6583     bool Res = false;
6584     for (const Stmt *Child : S->children())
6585       Res = (Child && Visit(Child)) || Res;
6586     return Res;
6587   }
6588   explicit LoopCounterRefChecker(Sema &SemaRef, DSAStackTy &Stack,
6589                                  const ValueDecl *CurLCDecl, bool IsInitializer,
6590                                  const ValueDecl *PrevDepDecl = nullptr)
6591       : SemaRef(SemaRef), Stack(Stack), CurLCDecl(CurLCDecl),
6592         PrevDepDecl(PrevDepDecl), IsInitializer(IsInitializer) {}
6593   unsigned getBaseLoopId() const {
6594     assert(CurLCDecl && "Expected loop dependency.");
6595     return BaseLoopId;
6596   }
6597   const ValueDecl *getDepDecl() const {
6598     assert(CurLCDecl && "Expected loop dependency.");
6599     return DepDecl;
6600   }
6601 };
6602 } // namespace
6603 
6604 Optional<unsigned>
6605 OpenMPIterationSpaceChecker::doesDependOnLoopCounter(const Stmt *S,
6606                                                      bool IsInitializer) {
6607   // Check for the non-rectangular loops.
6608   LoopCounterRefChecker LoopStmtChecker(SemaRef, Stack, LCDecl, IsInitializer,
6609                                         DepDecl);
6610   if (LoopStmtChecker.Visit(S)) {
6611     DepDecl = LoopStmtChecker.getDepDecl();
6612     return LoopStmtChecker.getBaseLoopId();
6613   }
6614   return llvm::None;
6615 }
6616 
6617 bool OpenMPIterationSpaceChecker::checkAndSetInit(Stmt *S, bool EmitDiags) {
6618   // Check init-expr for canonical loop form and save loop counter
6619   // variable - #Var and its initialization value - #LB.
6620   // OpenMP [2.6] Canonical loop form. init-expr may be one of the following:
6621   //   var = lb
6622   //   integer-type var = lb
6623   //   random-access-iterator-type var = lb
6624   //   pointer-type var = lb
6625   //
6626   if (!S) {
6627     if (EmitDiags) {
6628       SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init);
6629     }
6630     return true;
6631   }
6632   if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
6633     if (!ExprTemp->cleanupsHaveSideEffects())
6634       S = ExprTemp->getSubExpr();
6635 
6636   InitSrcRange = S->getSourceRange();
6637   if (Expr *E = dyn_cast<Expr>(S))
6638     S = E->IgnoreParens();
6639   if (auto *BO = dyn_cast<BinaryOperator>(S)) {
6640     if (BO->getOpcode() == BO_Assign) {
6641       Expr *LHS = BO->getLHS()->IgnoreParens();
6642       if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
6643         if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
6644           if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
6645             return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
6646                                   EmitDiags);
6647         return setLCDeclAndLB(DRE->getDecl(), DRE, BO->getRHS(), EmitDiags);
6648       }
6649       if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
6650         if (ME->isArrow() &&
6651             isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
6652           return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
6653                                 EmitDiags);
6654       }
6655     }
6656   } else if (auto *DS = dyn_cast<DeclStmt>(S)) {
6657     if (DS->isSingleDecl()) {
6658       if (auto *Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) {
6659         if (Var->hasInit() && !Var->getType()->isReferenceType()) {
6660           // Accept non-canonical init form here but emit ext. warning.
6661           if (Var->getInitStyle() != VarDecl::CInit && EmitDiags)
6662             SemaRef.Diag(S->getBeginLoc(),
6663                          diag::ext_omp_loop_not_canonical_init)
6664                 << S->getSourceRange();
6665           return setLCDeclAndLB(
6666               Var,
6667               buildDeclRefExpr(SemaRef, Var,
6668                                Var->getType().getNonReferenceType(),
6669                                DS->getBeginLoc()),
6670               Var->getInit(), EmitDiags);
6671         }
6672       }
6673     }
6674   } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
6675     if (CE->getOperator() == OO_Equal) {
6676       Expr *LHS = CE->getArg(0);
6677       if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
6678         if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
6679           if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
6680             return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
6681                                   EmitDiags);
6682         return setLCDeclAndLB(DRE->getDecl(), DRE, CE->getArg(1), EmitDiags);
6683       }
6684       if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
6685         if (ME->isArrow() &&
6686             isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
6687           return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
6688                                 EmitDiags);
6689       }
6690     }
6691   }
6692 
6693   if (dependent() || SemaRef.CurContext->isDependentContext())
6694     return false;
6695   if (EmitDiags) {
6696     SemaRef.Diag(S->getBeginLoc(), diag::err_omp_loop_not_canonical_init)
6697         << S->getSourceRange();
6698   }
6699   return true;
6700 }
6701 
6702 /// Ignore parenthesizes, implicit casts, copy constructor and return the
6703 /// variable (which may be the loop variable) if possible.
6704 static const ValueDecl *getInitLCDecl(const Expr *E) {
6705   if (!E)
6706     return nullptr;
6707   E = getExprAsWritten(E);
6708   if (const auto *CE = dyn_cast_or_null<CXXConstructExpr>(E))
6709     if (const CXXConstructorDecl *Ctor = CE->getConstructor())
6710       if ((Ctor->isCopyOrMoveConstructor() ||
6711            Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
6712           CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
6713         E = CE->getArg(0)->IgnoreParenImpCasts();
6714   if (const auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) {
6715     if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
6716       return getCanonicalDecl(VD);
6717   }
6718   if (const auto *ME = dyn_cast_or_null<MemberExpr>(E))
6719     if (ME->isArrow() && isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
6720       return getCanonicalDecl(ME->getMemberDecl());
6721   return nullptr;
6722 }
6723 
6724 bool OpenMPIterationSpaceChecker::checkAndSetCond(Expr *S) {
6725   // Check test-expr for canonical form, save upper-bound UB, flags for
6726   // less/greater and for strict/non-strict comparison.
6727   // OpenMP [2.9] Canonical loop form. Test-expr may be one of the following:
6728   //   var relational-op b
6729   //   b relational-op var
6730   //
6731   bool IneqCondIsCanonical = SemaRef.getLangOpts().OpenMP >= 50;
6732   if (!S) {
6733     SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond)
6734         << (IneqCondIsCanonical ? 1 : 0) << LCDecl;
6735     return true;
6736   }
6737   Condition = S;
6738   S = getExprAsWritten(S);
6739   SourceLocation CondLoc = S->getBeginLoc();
6740   if (auto *BO = dyn_cast<BinaryOperator>(S)) {
6741     if (BO->isRelationalOp()) {
6742       if (getInitLCDecl(BO->getLHS()) == LCDecl)
6743         return setUB(BO->getRHS(),
6744                      (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE),
6745                      (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
6746                      BO->getSourceRange(), BO->getOperatorLoc());
6747       if (getInitLCDecl(BO->getRHS()) == LCDecl)
6748         return setUB(BO->getLHS(),
6749                      (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE),
6750                      (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
6751                      BO->getSourceRange(), BO->getOperatorLoc());
6752     } else if (IneqCondIsCanonical && BO->getOpcode() == BO_NE)
6753       return setUB(
6754           getInitLCDecl(BO->getLHS()) == LCDecl ? BO->getRHS() : BO->getLHS(),
6755           /*LessOp=*/llvm::None,
6756           /*StrictOp=*/true, BO->getSourceRange(), BO->getOperatorLoc());
6757   } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
6758     if (CE->getNumArgs() == 2) {
6759       auto Op = CE->getOperator();
6760       switch (Op) {
6761       case OO_Greater:
6762       case OO_GreaterEqual:
6763       case OO_Less:
6764       case OO_LessEqual:
6765         if (getInitLCDecl(CE->getArg(0)) == LCDecl)
6766           return setUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual,
6767                        Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
6768                        CE->getOperatorLoc());
6769         if (getInitLCDecl(CE->getArg(1)) == LCDecl)
6770           return setUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual,
6771                        Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
6772                        CE->getOperatorLoc());
6773         break;
6774       case OO_ExclaimEqual:
6775         if (IneqCondIsCanonical)
6776           return setUB(getInitLCDecl(CE->getArg(0)) == LCDecl ? CE->getArg(1)
6777                                                               : CE->getArg(0),
6778                        /*LessOp=*/llvm::None,
6779                        /*StrictOp=*/true, CE->getSourceRange(),
6780                        CE->getOperatorLoc());
6781         break;
6782       default:
6783         break;
6784       }
6785     }
6786   }
6787   if (dependent() || SemaRef.CurContext->isDependentContext())
6788     return false;
6789   SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond)
6790       << (IneqCondIsCanonical ? 1 : 0) << S->getSourceRange() << LCDecl;
6791   return true;
6792 }
6793 
6794 bool OpenMPIterationSpaceChecker::checkAndSetIncRHS(Expr *RHS) {
6795   // RHS of canonical loop form increment can be:
6796   //   var + incr
6797   //   incr + var
6798   //   var - incr
6799   //
6800   RHS = RHS->IgnoreParenImpCasts();
6801   if (auto *BO = dyn_cast<BinaryOperator>(RHS)) {
6802     if (BO->isAdditiveOp()) {
6803       bool IsAdd = BO->getOpcode() == BO_Add;
6804       if (getInitLCDecl(BO->getLHS()) == LCDecl)
6805         return setStep(BO->getRHS(), !IsAdd);
6806       if (IsAdd && getInitLCDecl(BO->getRHS()) == LCDecl)
6807         return setStep(BO->getLHS(), /*Subtract=*/false);
6808     }
6809   } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(RHS)) {
6810     bool IsAdd = CE->getOperator() == OO_Plus;
6811     if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) {
6812       if (getInitLCDecl(CE->getArg(0)) == LCDecl)
6813         return setStep(CE->getArg(1), !IsAdd);
6814       if (IsAdd && getInitLCDecl(CE->getArg(1)) == LCDecl)
6815         return setStep(CE->getArg(0), /*Subtract=*/false);
6816     }
6817   }
6818   if (dependent() || SemaRef.CurContext->isDependentContext())
6819     return false;
6820   SemaRef.Diag(RHS->getBeginLoc(), diag::err_omp_loop_not_canonical_incr)
6821       << RHS->getSourceRange() << LCDecl;
6822   return true;
6823 }
6824 
6825 bool OpenMPIterationSpaceChecker::checkAndSetInc(Expr *S) {
6826   // Check incr-expr for canonical loop form and return true if it
6827   // does not conform.
6828   // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
6829   //   ++var
6830   //   var++
6831   //   --var
6832   //   var--
6833   //   var += incr
6834   //   var -= incr
6835   //   var = var + incr
6836   //   var = incr + var
6837   //   var = var - incr
6838   //
6839   if (!S) {
6840     SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << LCDecl;
6841     return true;
6842   }
6843   if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
6844     if (!ExprTemp->cleanupsHaveSideEffects())
6845       S = ExprTemp->getSubExpr();
6846 
6847   IncrementSrcRange = S->getSourceRange();
6848   S = S->IgnoreParens();
6849   if (auto *UO = dyn_cast<UnaryOperator>(S)) {
6850     if (UO->isIncrementDecrementOp() &&
6851         getInitLCDecl(UO->getSubExpr()) == LCDecl)
6852       return setStep(SemaRef
6853                          .ActOnIntegerConstant(UO->getBeginLoc(),
6854                                                (UO->isDecrementOp() ? -1 : 1))
6855                          .get(),
6856                      /*Subtract=*/false);
6857   } else if (auto *BO = dyn_cast<BinaryOperator>(S)) {
6858     switch (BO->getOpcode()) {
6859     case BO_AddAssign:
6860     case BO_SubAssign:
6861       if (getInitLCDecl(BO->getLHS()) == LCDecl)
6862         return setStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign);
6863       break;
6864     case BO_Assign:
6865       if (getInitLCDecl(BO->getLHS()) == LCDecl)
6866         return checkAndSetIncRHS(BO->getRHS());
6867       break;
6868     default:
6869       break;
6870     }
6871   } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
6872     switch (CE->getOperator()) {
6873     case OO_PlusPlus:
6874     case OO_MinusMinus:
6875       if (getInitLCDecl(CE->getArg(0)) == LCDecl)
6876         return setStep(SemaRef
6877                            .ActOnIntegerConstant(
6878                                CE->getBeginLoc(),
6879                                ((CE->getOperator() == OO_MinusMinus) ? -1 : 1))
6880                            .get(),
6881                        /*Subtract=*/false);
6882       break;
6883     case OO_PlusEqual:
6884     case OO_MinusEqual:
6885       if (getInitLCDecl(CE->getArg(0)) == LCDecl)
6886         return setStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual);
6887       break;
6888     case OO_Equal:
6889       if (getInitLCDecl(CE->getArg(0)) == LCDecl)
6890         return checkAndSetIncRHS(CE->getArg(1));
6891       break;
6892     default:
6893       break;
6894     }
6895   }
6896   if (dependent() || SemaRef.CurContext->isDependentContext())
6897     return false;
6898   SemaRef.Diag(S->getBeginLoc(), diag::err_omp_loop_not_canonical_incr)
6899       << S->getSourceRange() << LCDecl;
6900   return true;
6901 }
6902 
6903 static ExprResult
6904 tryBuildCapture(Sema &SemaRef, Expr *Capture,
6905                 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
6906   if (SemaRef.CurContext->isDependentContext() || Capture->containsErrors())
6907     return Capture;
6908   if (Capture->isEvaluatable(SemaRef.Context, Expr::SE_AllowSideEffects))
6909     return SemaRef.PerformImplicitConversion(
6910         Capture->IgnoreImpCasts(), Capture->getType(), Sema::AA_Converting,
6911         /*AllowExplicit=*/true);
6912   auto I = Captures.find(Capture);
6913   if (I != Captures.end())
6914     return buildCapture(SemaRef, Capture, I->second);
6915   DeclRefExpr *Ref = nullptr;
6916   ExprResult Res = buildCapture(SemaRef, Capture, Ref);
6917   Captures[Capture] = Ref;
6918   return Res;
6919 }
6920 
6921 /// Calculate number of iterations, transforming to unsigned, if number of
6922 /// iterations may be larger than the original type.
6923 static Expr *
6924 calculateNumIters(Sema &SemaRef, Scope *S, SourceLocation DefaultLoc,
6925                   Expr *Lower, Expr *Upper, Expr *Step, QualType LCTy,
6926                   bool TestIsStrictOp, bool RoundToStep,
6927                   llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
6928   ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures);
6929   if (!NewStep.isUsable())
6930     return nullptr;
6931   llvm::APSInt LRes, URes, SRes;
6932   bool IsLowerConst = Lower->isIntegerConstantExpr(LRes, SemaRef.Context);
6933   bool IsStepConst = Step->isIntegerConstantExpr(SRes, SemaRef.Context);
6934   bool NoNeedToConvert = IsLowerConst && !RoundToStep &&
6935                          ((!TestIsStrictOp && LRes.isNonNegative()) ||
6936                           (TestIsStrictOp && LRes.isStrictlyPositive()));
6937   bool NeedToReorganize = false;
6938   // Check if any subexpressions in Lower -Step [+ 1] lead to overflow.
6939   if (!NoNeedToConvert && IsLowerConst &&
6940       (TestIsStrictOp || (RoundToStep && IsStepConst))) {
6941     NoNeedToConvert = true;
6942     if (RoundToStep) {
6943       unsigned BW = LRes.getBitWidth() > SRes.getBitWidth()
6944                         ? LRes.getBitWidth()
6945                         : SRes.getBitWidth();
6946       LRes = LRes.extend(BW + 1);
6947       LRes.setIsSigned(true);
6948       SRes = SRes.extend(BW + 1);
6949       SRes.setIsSigned(true);
6950       LRes -= SRes;
6951       NoNeedToConvert = LRes.trunc(BW).extend(BW + 1) == LRes;
6952       LRes = LRes.trunc(BW);
6953     }
6954     if (TestIsStrictOp) {
6955       unsigned BW = LRes.getBitWidth();
6956       LRes = LRes.extend(BW + 1);
6957       LRes.setIsSigned(true);
6958       ++LRes;
6959       NoNeedToConvert =
6960           NoNeedToConvert && LRes.trunc(BW).extend(BW + 1) == LRes;
6961       // truncate to the original bitwidth.
6962       LRes = LRes.trunc(BW);
6963     }
6964     NeedToReorganize = NoNeedToConvert;
6965   }
6966   bool IsUpperConst = Upper->isIntegerConstantExpr(URes, SemaRef.Context);
6967   if (NoNeedToConvert && IsLowerConst && IsUpperConst &&
6968       (!RoundToStep || IsStepConst)) {
6969     unsigned BW = LRes.getBitWidth() > URes.getBitWidth() ? LRes.getBitWidth()
6970                                                           : URes.getBitWidth();
6971     LRes = LRes.extend(BW + 1);
6972     LRes.setIsSigned(true);
6973     URes = URes.extend(BW + 1);
6974     URes.setIsSigned(true);
6975     URes -= LRes;
6976     NoNeedToConvert = URes.trunc(BW).extend(BW + 1) == URes;
6977     NeedToReorganize = NoNeedToConvert;
6978   }
6979   // If the boundaries are not constant or (Lower - Step [+ 1]) is not constant
6980   // or less than zero (Upper - (Lower - Step [+ 1]) may overflow) - promote to
6981   // unsigned.
6982   if ((!NoNeedToConvert || (LRes.isNegative() && !IsUpperConst)) &&
6983       !LCTy->isDependentType() && LCTy->isIntegerType()) {
6984     QualType LowerTy = Lower->getType();
6985     QualType UpperTy = Upper->getType();
6986     uint64_t LowerSize = SemaRef.Context.getTypeSize(LowerTy);
6987     uint64_t UpperSize = SemaRef.Context.getTypeSize(UpperTy);
6988     if ((LowerSize <= UpperSize && UpperTy->hasSignedIntegerRepresentation()) ||
6989         (LowerSize > UpperSize && LowerTy->hasSignedIntegerRepresentation())) {
6990       QualType CastType = SemaRef.Context.getIntTypeForBitwidth(
6991           LowerSize > UpperSize ? LowerSize : UpperSize, /*Signed=*/0);
6992       Upper =
6993           SemaRef
6994               .PerformImplicitConversion(
6995                   SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Upper).get(),
6996                   CastType, Sema::AA_Converting)
6997               .get();
6998       Lower = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Lower).get();
6999       NewStep = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, NewStep.get());
7000     }
7001   }
7002   if (!Lower || !Upper || NewStep.isInvalid())
7003     return nullptr;
7004 
7005   ExprResult Diff;
7006   // If need to reorganize, then calculate the form as Upper - (Lower - Step [+
7007   // 1]).
7008   if (NeedToReorganize) {
7009     Diff = Lower;
7010 
7011     if (RoundToStep) {
7012       // Lower - Step
7013       Diff =
7014           SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Diff.get(), NewStep.get());
7015       if (!Diff.isUsable())
7016         return nullptr;
7017     }
7018 
7019     // Lower - Step [+ 1]
7020     if (TestIsStrictOp)
7021       Diff = SemaRef.BuildBinOp(
7022           S, DefaultLoc, BO_Add, Diff.get(),
7023           SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
7024     if (!Diff.isUsable())
7025       return nullptr;
7026 
7027     Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
7028     if (!Diff.isUsable())
7029       return nullptr;
7030 
7031     // Upper - (Lower - Step [+ 1]).
7032     Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Diff.get());
7033     if (!Diff.isUsable())
7034       return nullptr;
7035   } else {
7036     Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
7037 
7038     if (!Diff.isUsable() && LCTy->getAsCXXRecordDecl()) {
7039       // BuildBinOp already emitted error, this one is to point user to upper
7040       // and lower bound, and to tell what is passed to 'operator-'.
7041       SemaRef.Diag(Upper->getBeginLoc(), diag::err_omp_loop_diff_cxx)
7042           << Upper->getSourceRange() << Lower->getSourceRange();
7043       return nullptr;
7044     }
7045 
7046     if (!Diff.isUsable())
7047       return nullptr;
7048 
7049     // Upper - Lower [- 1]
7050     if (TestIsStrictOp)
7051       Diff = SemaRef.BuildBinOp(
7052           S, DefaultLoc, BO_Sub, Diff.get(),
7053           SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
7054     if (!Diff.isUsable())
7055       return nullptr;
7056 
7057     if (RoundToStep) {
7058       // Upper - Lower [- 1] + Step
7059       Diff =
7060           SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get());
7061       if (!Diff.isUsable())
7062         return nullptr;
7063     }
7064   }
7065 
7066   // Parentheses (for dumping/debugging purposes only).
7067   Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
7068   if (!Diff.isUsable())
7069     return nullptr;
7070 
7071   // (Upper - Lower [- 1] + Step) / Step or (Upper - Lower) / Step
7072   Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
7073   if (!Diff.isUsable())
7074     return nullptr;
7075 
7076   return Diff.get();
7077 }
7078 
7079 /// Build the expression to calculate the number of iterations.
7080 Expr *OpenMPIterationSpaceChecker::buildNumIterations(
7081     Scope *S, ArrayRef<LoopIterationSpace> ResultIterSpaces, bool LimitedType,
7082     llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
7083   QualType VarType = LCDecl->getType().getNonReferenceType();
7084   if (!VarType->isIntegerType() && !VarType->isPointerType() &&
7085       !SemaRef.getLangOpts().CPlusPlus)
7086     return nullptr;
7087   Expr *LBVal = LB;
7088   Expr *UBVal = UB;
7089   // LB = TestIsLessOp.getValue() ? min(LB(MinVal), LB(MaxVal)) :
7090   // max(LB(MinVal), LB(MaxVal))
7091   if (InitDependOnLC) {
7092     const LoopIterationSpace &IS =
7093         ResultIterSpaces[ResultIterSpaces.size() - 1 -
7094                          InitDependOnLC.getValueOr(
7095                              CondDependOnLC.getValueOr(0))];
7096     if (!IS.MinValue || !IS.MaxValue)
7097       return nullptr;
7098     // OuterVar = Min
7099     ExprResult MinValue =
7100         SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MinValue);
7101     if (!MinValue.isUsable())
7102       return nullptr;
7103 
7104     ExprResult LBMinVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign,
7105                                              IS.CounterVar, MinValue.get());
7106     if (!LBMinVal.isUsable())
7107       return nullptr;
7108     // OuterVar = Min, LBVal
7109     LBMinVal =
7110         SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, LBMinVal.get(), LBVal);
7111     if (!LBMinVal.isUsable())
7112       return nullptr;
7113     // (OuterVar = Min, LBVal)
7114     LBMinVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, LBMinVal.get());
7115     if (!LBMinVal.isUsable())
7116       return nullptr;
7117 
7118     // OuterVar = Max
7119     ExprResult MaxValue =
7120         SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MaxValue);
7121     if (!MaxValue.isUsable())
7122       return nullptr;
7123 
7124     ExprResult LBMaxVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign,
7125                                              IS.CounterVar, MaxValue.get());
7126     if (!LBMaxVal.isUsable())
7127       return nullptr;
7128     // OuterVar = Max, LBVal
7129     LBMaxVal =
7130         SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, LBMaxVal.get(), LBVal);
7131     if (!LBMaxVal.isUsable())
7132       return nullptr;
7133     // (OuterVar = Max, LBVal)
7134     LBMaxVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, LBMaxVal.get());
7135     if (!LBMaxVal.isUsable())
7136       return nullptr;
7137 
7138     Expr *LBMin = tryBuildCapture(SemaRef, LBMinVal.get(), Captures).get();
7139     Expr *LBMax = tryBuildCapture(SemaRef, LBMaxVal.get(), Captures).get();
7140     if (!LBMin || !LBMax)
7141       return nullptr;
7142     // LB(MinVal) < LB(MaxVal)
7143     ExprResult MinLessMaxRes =
7144         SemaRef.BuildBinOp(S, DefaultLoc, BO_LT, LBMin, LBMax);
7145     if (!MinLessMaxRes.isUsable())
7146       return nullptr;
7147     Expr *MinLessMax =
7148         tryBuildCapture(SemaRef, MinLessMaxRes.get(), Captures).get();
7149     if (!MinLessMax)
7150       return nullptr;
7151     if (TestIsLessOp.getValue()) {
7152       // LB(MinVal) < LB(MaxVal) ? LB(MinVal) : LB(MaxVal) - min(LB(MinVal),
7153       // LB(MaxVal))
7154       ExprResult MinLB = SemaRef.ActOnConditionalOp(DefaultLoc, DefaultLoc,
7155                                                     MinLessMax, LBMin, LBMax);
7156       if (!MinLB.isUsable())
7157         return nullptr;
7158       LBVal = MinLB.get();
7159     } else {
7160       // LB(MinVal) < LB(MaxVal) ? LB(MaxVal) : LB(MinVal) - max(LB(MinVal),
7161       // LB(MaxVal))
7162       ExprResult MaxLB = SemaRef.ActOnConditionalOp(DefaultLoc, DefaultLoc,
7163                                                     MinLessMax, LBMax, LBMin);
7164       if (!MaxLB.isUsable())
7165         return nullptr;
7166       LBVal = MaxLB.get();
7167     }
7168   }
7169   // UB = TestIsLessOp.getValue() ? max(UB(MinVal), UB(MaxVal)) :
7170   // min(UB(MinVal), UB(MaxVal))
7171   if (CondDependOnLC) {
7172     const LoopIterationSpace &IS =
7173         ResultIterSpaces[ResultIterSpaces.size() - 1 -
7174                          InitDependOnLC.getValueOr(
7175                              CondDependOnLC.getValueOr(0))];
7176     if (!IS.MinValue || !IS.MaxValue)
7177       return nullptr;
7178     // OuterVar = Min
7179     ExprResult MinValue =
7180         SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MinValue);
7181     if (!MinValue.isUsable())
7182       return nullptr;
7183 
7184     ExprResult UBMinVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign,
7185                                              IS.CounterVar, MinValue.get());
7186     if (!UBMinVal.isUsable())
7187       return nullptr;
7188     // OuterVar = Min, UBVal
7189     UBMinVal =
7190         SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, UBMinVal.get(), UBVal);
7191     if (!UBMinVal.isUsable())
7192       return nullptr;
7193     // (OuterVar = Min, UBVal)
7194     UBMinVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, UBMinVal.get());
7195     if (!UBMinVal.isUsable())
7196       return nullptr;
7197 
7198     // OuterVar = Max
7199     ExprResult MaxValue =
7200         SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MaxValue);
7201     if (!MaxValue.isUsable())
7202       return nullptr;
7203 
7204     ExprResult UBMaxVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign,
7205                                              IS.CounterVar, MaxValue.get());
7206     if (!UBMaxVal.isUsable())
7207       return nullptr;
7208     // OuterVar = Max, UBVal
7209     UBMaxVal =
7210         SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, UBMaxVal.get(), UBVal);
7211     if (!UBMaxVal.isUsable())
7212       return nullptr;
7213     // (OuterVar = Max, UBVal)
7214     UBMaxVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, UBMaxVal.get());
7215     if (!UBMaxVal.isUsable())
7216       return nullptr;
7217 
7218     Expr *UBMin = tryBuildCapture(SemaRef, UBMinVal.get(), Captures).get();
7219     Expr *UBMax = tryBuildCapture(SemaRef, UBMaxVal.get(), Captures).get();
7220     if (!UBMin || !UBMax)
7221       return nullptr;
7222     // UB(MinVal) > UB(MaxVal)
7223     ExprResult MinGreaterMaxRes =
7224         SemaRef.BuildBinOp(S, DefaultLoc, BO_GT, UBMin, UBMax);
7225     if (!MinGreaterMaxRes.isUsable())
7226       return nullptr;
7227     Expr *MinGreaterMax =
7228         tryBuildCapture(SemaRef, MinGreaterMaxRes.get(), Captures).get();
7229     if (!MinGreaterMax)
7230       return nullptr;
7231     if (TestIsLessOp.getValue()) {
7232       // UB(MinVal) > UB(MaxVal) ? UB(MinVal) : UB(MaxVal) - max(UB(MinVal),
7233       // UB(MaxVal))
7234       ExprResult MaxUB = SemaRef.ActOnConditionalOp(
7235           DefaultLoc, DefaultLoc, MinGreaterMax, UBMin, UBMax);
7236       if (!MaxUB.isUsable())
7237         return nullptr;
7238       UBVal = MaxUB.get();
7239     } else {
7240       // UB(MinVal) > UB(MaxVal) ? UB(MaxVal) : UB(MinVal) - min(UB(MinVal),
7241       // UB(MaxVal))
7242       ExprResult MinUB = SemaRef.ActOnConditionalOp(
7243           DefaultLoc, DefaultLoc, MinGreaterMax, UBMax, UBMin);
7244       if (!MinUB.isUsable())
7245         return nullptr;
7246       UBVal = MinUB.get();
7247     }
7248   }
7249   Expr *UBExpr = TestIsLessOp.getValue() ? UBVal : LBVal;
7250   Expr *LBExpr = TestIsLessOp.getValue() ? LBVal : UBVal;
7251   Expr *Upper = tryBuildCapture(SemaRef, UBExpr, Captures).get();
7252   Expr *Lower = tryBuildCapture(SemaRef, LBExpr, Captures).get();
7253   if (!Upper || !Lower)
7254     return nullptr;
7255 
7256   ExprResult Diff =
7257       calculateNumIters(SemaRef, S, DefaultLoc, Lower, Upper, Step, VarType,
7258                         TestIsStrictOp, /*RoundToStep=*/true, Captures);
7259   if (!Diff.isUsable())
7260     return nullptr;
7261 
7262   // OpenMP runtime requires 32-bit or 64-bit loop variables.
7263   QualType Type = Diff.get()->getType();
7264   ASTContext &C = SemaRef.Context;
7265   bool UseVarType = VarType->hasIntegerRepresentation() &&
7266                     C.getTypeSize(Type) > C.getTypeSize(VarType);
7267   if (!Type->isIntegerType() || UseVarType) {
7268     unsigned NewSize =
7269         UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type);
7270     bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation()
7271                                : Type->hasSignedIntegerRepresentation();
7272     Type = C.getIntTypeForBitwidth(NewSize, IsSigned);
7273     if (!SemaRef.Context.hasSameType(Diff.get()->getType(), Type)) {
7274       Diff = SemaRef.PerformImplicitConversion(
7275           Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true);
7276       if (!Diff.isUsable())
7277         return nullptr;
7278     }
7279   }
7280   if (LimitedType) {
7281     unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32;
7282     if (NewSize != C.getTypeSize(Type)) {
7283       if (NewSize < C.getTypeSize(Type)) {
7284         assert(NewSize == 64 && "incorrect loop var size");
7285         SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var)
7286             << InitSrcRange << ConditionSrcRange;
7287       }
7288       QualType NewType = C.getIntTypeForBitwidth(
7289           NewSize, Type->hasSignedIntegerRepresentation() ||
7290                        C.getTypeSize(Type) < NewSize);
7291       if (!SemaRef.Context.hasSameType(Diff.get()->getType(), NewType)) {
7292         Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType,
7293                                                  Sema::AA_Converting, true);
7294         if (!Diff.isUsable())
7295           return nullptr;
7296       }
7297     }
7298   }
7299 
7300   return Diff.get();
7301 }
7302 
7303 std::pair<Expr *, Expr *> OpenMPIterationSpaceChecker::buildMinMaxValues(
7304     Scope *S, llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
7305   // Do not build for iterators, they cannot be used in non-rectangular loop
7306   // nests.
7307   if (LCDecl->getType()->isRecordType())
7308     return std::make_pair(nullptr, nullptr);
7309   // If we subtract, the min is in the condition, otherwise the min is in the
7310   // init value.
7311   Expr *MinExpr = nullptr;
7312   Expr *MaxExpr = nullptr;
7313   Expr *LBExpr = TestIsLessOp.getValue() ? LB : UB;
7314   Expr *UBExpr = TestIsLessOp.getValue() ? UB : LB;
7315   bool LBNonRect = TestIsLessOp.getValue() ? InitDependOnLC.hasValue()
7316                                            : CondDependOnLC.hasValue();
7317   bool UBNonRect = TestIsLessOp.getValue() ? CondDependOnLC.hasValue()
7318                                            : InitDependOnLC.hasValue();
7319   Expr *Lower =
7320       LBNonRect ? LBExpr : tryBuildCapture(SemaRef, LBExpr, Captures).get();
7321   Expr *Upper =
7322       UBNonRect ? UBExpr : tryBuildCapture(SemaRef, UBExpr, Captures).get();
7323   if (!Upper || !Lower)
7324     return std::make_pair(nullptr, nullptr);
7325 
7326   if (TestIsLessOp.getValue())
7327     MinExpr = Lower;
7328   else
7329     MaxExpr = Upper;
7330 
7331   // Build minimum/maximum value based on number of iterations.
7332   QualType VarType = LCDecl->getType().getNonReferenceType();
7333 
7334   ExprResult Diff =
7335       calculateNumIters(SemaRef, S, DefaultLoc, Lower, Upper, Step, VarType,
7336                         TestIsStrictOp, /*RoundToStep=*/false, Captures);
7337   if (!Diff.isUsable())
7338     return std::make_pair(nullptr, nullptr);
7339 
7340   // ((Upper - Lower [- 1]) / Step) * Step
7341   // Parentheses (for dumping/debugging purposes only).
7342   Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
7343   if (!Diff.isUsable())
7344     return std::make_pair(nullptr, nullptr);
7345 
7346   ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures);
7347   if (!NewStep.isUsable())
7348     return std::make_pair(nullptr, nullptr);
7349   Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Mul, Diff.get(), NewStep.get());
7350   if (!Diff.isUsable())
7351     return std::make_pair(nullptr, nullptr);
7352 
7353   // Parentheses (for dumping/debugging purposes only).
7354   Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
7355   if (!Diff.isUsable())
7356     return std::make_pair(nullptr, nullptr);
7357 
7358   // Convert to the ptrdiff_t, if original type is pointer.
7359   if (VarType->isAnyPointerType() &&
7360       !SemaRef.Context.hasSameType(
7361           Diff.get()->getType(),
7362           SemaRef.Context.getUnsignedPointerDiffType())) {
7363     Diff = SemaRef.PerformImplicitConversion(
7364         Diff.get(), SemaRef.Context.getUnsignedPointerDiffType(),
7365         Sema::AA_Converting, /*AllowExplicit=*/true);
7366   }
7367   if (!Diff.isUsable())
7368     return std::make_pair(nullptr, nullptr);
7369 
7370   if (TestIsLessOp.getValue()) {
7371     // MinExpr = Lower;
7372     // MaxExpr = Lower + (((Upper - Lower [- 1]) / Step) * Step)
7373     Diff = SemaRef.BuildBinOp(
7374         S, DefaultLoc, BO_Add,
7375         SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Lower).get(),
7376         Diff.get());
7377     if (!Diff.isUsable())
7378       return std::make_pair(nullptr, nullptr);
7379   } else {
7380     // MaxExpr = Upper;
7381     // MinExpr = Upper - (((Upper - Lower [- 1]) / Step) * Step)
7382     Diff = SemaRef.BuildBinOp(
7383         S, DefaultLoc, BO_Sub,
7384         SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Upper).get(),
7385         Diff.get());
7386     if (!Diff.isUsable())
7387       return std::make_pair(nullptr, nullptr);
7388   }
7389 
7390   // Convert to the original type.
7391   if (SemaRef.Context.hasSameType(Diff.get()->getType(), VarType))
7392     Diff = SemaRef.PerformImplicitConversion(Diff.get(), VarType,
7393                                              Sema::AA_Converting,
7394                                              /*AllowExplicit=*/true);
7395   if (!Diff.isUsable())
7396     return std::make_pair(nullptr, nullptr);
7397 
7398   Diff = SemaRef.ActOnFinishFullExpr(Diff.get(), /*DiscardedValue=*/false);
7399   if (!Diff.isUsable())
7400     return std::make_pair(nullptr, nullptr);
7401 
7402   if (TestIsLessOp.getValue())
7403     MaxExpr = Diff.get();
7404   else
7405     MinExpr = Diff.get();
7406 
7407   return std::make_pair(MinExpr, MaxExpr);
7408 }
7409 
7410 Expr *OpenMPIterationSpaceChecker::buildFinalCondition(Scope *S) const {
7411   if (InitDependOnLC || CondDependOnLC)
7412     return Condition;
7413   return nullptr;
7414 }
7415 
7416 Expr *OpenMPIterationSpaceChecker::buildPreCond(
7417     Scope *S, Expr *Cond,
7418     llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
7419   // Do not build a precondition when the condition/initialization is dependent
7420   // to prevent pessimistic early loop exit.
7421   // TODO: this can be improved by calculating min/max values but not sure that
7422   // it will be very effective.
7423   if (CondDependOnLC || InitDependOnLC)
7424     return SemaRef.PerformImplicitConversion(
7425         SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get(),
7426         SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
7427         /*AllowExplicit=*/true).get();
7428 
7429   // Try to build LB <op> UB, where <op> is <, >, <=, or >=.
7430   Sema::TentativeAnalysisScope Trap(SemaRef);
7431 
7432   ExprResult NewLB = tryBuildCapture(SemaRef, LB, Captures);
7433   ExprResult NewUB = tryBuildCapture(SemaRef, UB, Captures);
7434   if (!NewLB.isUsable() || !NewUB.isUsable())
7435     return nullptr;
7436 
7437   ExprResult CondExpr =
7438       SemaRef.BuildBinOp(S, DefaultLoc,
7439                          TestIsLessOp.getValue() ?
7440                            (TestIsStrictOp ? BO_LT : BO_LE) :
7441                            (TestIsStrictOp ? BO_GT : BO_GE),
7442                          NewLB.get(), NewUB.get());
7443   if (CondExpr.isUsable()) {
7444     if (!SemaRef.Context.hasSameUnqualifiedType(CondExpr.get()->getType(),
7445                                                 SemaRef.Context.BoolTy))
7446       CondExpr = SemaRef.PerformImplicitConversion(
7447           CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
7448           /*AllowExplicit=*/true);
7449   }
7450 
7451   // Otherwise use original loop condition and evaluate it in runtime.
7452   return CondExpr.isUsable() ? CondExpr.get() : Cond;
7453 }
7454 
7455 /// Build reference expression to the counter be used for codegen.
7456 DeclRefExpr *OpenMPIterationSpaceChecker::buildCounterVar(
7457     llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
7458     DSAStackTy &DSA) const {
7459   auto *VD = dyn_cast<VarDecl>(LCDecl);
7460   if (!VD) {
7461     VD = SemaRef.isOpenMPCapturedDecl(LCDecl);
7462     DeclRefExpr *Ref = buildDeclRefExpr(
7463         SemaRef, VD, VD->getType().getNonReferenceType(), DefaultLoc);
7464     const DSAStackTy::DSAVarData Data =
7465         DSA.getTopDSA(LCDecl, /*FromParent=*/false);
7466     // If the loop control decl is explicitly marked as private, do not mark it
7467     // as captured again.
7468     if (!isOpenMPPrivate(Data.CKind) || !Data.RefExpr)
7469       Captures.insert(std::make_pair(LCRef, Ref));
7470     return Ref;
7471   }
7472   return cast<DeclRefExpr>(LCRef);
7473 }
7474 
7475 Expr *OpenMPIterationSpaceChecker::buildPrivateCounterVar() const {
7476   if (LCDecl && !LCDecl->isInvalidDecl()) {
7477     QualType Type = LCDecl->getType().getNonReferenceType();
7478     VarDecl *PrivateVar = buildVarDecl(
7479         SemaRef, DefaultLoc, Type, LCDecl->getName(),
7480         LCDecl->hasAttrs() ? &LCDecl->getAttrs() : nullptr,
7481         isa<VarDecl>(LCDecl)
7482             ? buildDeclRefExpr(SemaRef, cast<VarDecl>(LCDecl), Type, DefaultLoc)
7483             : nullptr);
7484     if (PrivateVar->isInvalidDecl())
7485       return nullptr;
7486     return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc);
7487   }
7488   return nullptr;
7489 }
7490 
7491 /// Build initialization of the counter to be used for codegen.
7492 Expr *OpenMPIterationSpaceChecker::buildCounterInit() const { return LB; }
7493 
7494 /// Build step of the counter be used for codegen.
7495 Expr *OpenMPIterationSpaceChecker::buildCounterStep() const { return Step; }
7496 
7497 Expr *OpenMPIterationSpaceChecker::buildOrderedLoopData(
7498     Scope *S, Expr *Counter,
7499     llvm::MapVector<const Expr *, DeclRefExpr *> &Captures, SourceLocation Loc,
7500     Expr *Inc, OverloadedOperatorKind OOK) {
7501   Expr *Cnt = SemaRef.DefaultLvalueConversion(Counter).get();
7502   if (!Cnt)
7503     return nullptr;
7504   if (Inc) {
7505     assert((OOK == OO_Plus || OOK == OO_Minus) &&
7506            "Expected only + or - operations for depend clauses.");
7507     BinaryOperatorKind BOK = (OOK == OO_Plus) ? BO_Add : BO_Sub;
7508     Cnt = SemaRef.BuildBinOp(S, Loc, BOK, Cnt, Inc).get();
7509     if (!Cnt)
7510       return nullptr;
7511   }
7512   QualType VarType = LCDecl->getType().getNonReferenceType();
7513   if (!VarType->isIntegerType() && !VarType->isPointerType() &&
7514       !SemaRef.getLangOpts().CPlusPlus)
7515     return nullptr;
7516   // Upper - Lower
7517   Expr *Upper = TestIsLessOp.getValue()
7518                     ? Cnt
7519                     : tryBuildCapture(SemaRef, LB, Captures).get();
7520   Expr *Lower = TestIsLessOp.getValue()
7521                     ? tryBuildCapture(SemaRef, LB, Captures).get()
7522                     : Cnt;
7523   if (!Upper || !Lower)
7524     return nullptr;
7525 
7526   ExprResult Diff = calculateNumIters(SemaRef, S, DefaultLoc, Lower, Upper,
7527                                       Step, VarType, /*TestIsStrictOp=*/false,
7528                                       /*RoundToStep=*/false, Captures);
7529   if (!Diff.isUsable())
7530     return nullptr;
7531 
7532   return Diff.get();
7533 }
7534 } // namespace
7535 
7536 void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) {
7537   assert(getLangOpts().OpenMP && "OpenMP is not active.");
7538   assert(Init && "Expected loop in canonical form.");
7539   unsigned AssociatedLoops = DSAStack->getAssociatedLoops();
7540   if (AssociatedLoops > 0 &&
7541       isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
7542     DSAStack->loopStart();
7543     OpenMPIterationSpaceChecker ISC(*this, *DSAStack, ForLoc);
7544     if (!ISC.checkAndSetInit(Init, /*EmitDiags=*/false)) {
7545       if (ValueDecl *D = ISC.getLoopDecl()) {
7546         auto *VD = dyn_cast<VarDecl>(D);
7547         DeclRefExpr *PrivateRef = nullptr;
7548         if (!VD) {
7549           if (VarDecl *Private = isOpenMPCapturedDecl(D)) {
7550             VD = Private;
7551           } else {
7552             PrivateRef = buildCapture(*this, D, ISC.getLoopDeclRefExpr(),
7553                                       /*WithInit=*/false);
7554             VD = cast<VarDecl>(PrivateRef->getDecl());
7555           }
7556         }
7557         DSAStack->addLoopControlVariable(D, VD);
7558         const Decl *LD = DSAStack->getPossiblyLoopCunter();
7559         if (LD != D->getCanonicalDecl()) {
7560           DSAStack->resetPossibleLoopCounter();
7561           if (auto *Var = dyn_cast_or_null<VarDecl>(LD))
7562             MarkDeclarationsReferencedInExpr(
7563                 buildDeclRefExpr(*this, const_cast<VarDecl *>(Var),
7564                                  Var->getType().getNonLValueExprType(Context),
7565                                  ForLoc, /*RefersToCapture=*/true));
7566         }
7567         OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
7568         // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables
7569         // Referenced in a Construct, C/C++]. The loop iteration variable in the
7570         // associated for-loop of a simd construct with just one associated
7571         // for-loop may be listed in a linear clause with a constant-linear-step
7572         // that is the increment of the associated for-loop. The loop iteration
7573         // variable(s) in the associated for-loop(s) of a for or parallel for
7574         // construct may be listed in a private or lastprivate clause.
7575         DSAStackTy::DSAVarData DVar =
7576             DSAStack->getTopDSA(D, /*FromParent=*/false);
7577         // If LoopVarRefExpr is nullptr it means the corresponding loop variable
7578         // is declared in the loop and it is predetermined as a private.
7579         Expr *LoopDeclRefExpr = ISC.getLoopDeclRefExpr();
7580         OpenMPClauseKind PredeterminedCKind =
7581             isOpenMPSimdDirective(DKind)
7582                 ? (DSAStack->hasMutipleLoops() ? OMPC_lastprivate : OMPC_linear)
7583                 : OMPC_private;
7584         if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
7585               DVar.CKind != PredeterminedCKind && DVar.RefExpr &&
7586               (LangOpts.OpenMP <= 45 || (DVar.CKind != OMPC_lastprivate &&
7587                                          DVar.CKind != OMPC_private))) ||
7588              ((isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop ||
7589                DKind == OMPD_master_taskloop ||
7590                DKind == OMPD_parallel_master_taskloop ||
7591                isOpenMPDistributeDirective(DKind)) &&
7592               !isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
7593               DVar.CKind != OMPC_private && DVar.CKind != OMPC_lastprivate)) &&
7594             (DVar.CKind != OMPC_private || DVar.RefExpr)) {
7595           Diag(Init->getBeginLoc(), diag::err_omp_loop_var_dsa)
7596               << getOpenMPClauseName(DVar.CKind)
7597               << getOpenMPDirectiveName(DKind)
7598               << getOpenMPClauseName(PredeterminedCKind);
7599           if (DVar.RefExpr == nullptr)
7600             DVar.CKind = PredeterminedCKind;
7601           reportOriginalDsa(*this, DSAStack, D, DVar,
7602                             /*IsLoopIterVar=*/true);
7603         } else if (LoopDeclRefExpr) {
7604           // Make the loop iteration variable private (for worksharing
7605           // constructs), linear (for simd directives with the only one
7606           // associated loop) or lastprivate (for simd directives with several
7607           // collapsed or ordered loops).
7608           if (DVar.CKind == OMPC_unknown)
7609             DSAStack->addDSA(D, LoopDeclRefExpr, PredeterminedCKind,
7610                              PrivateRef);
7611         }
7612       }
7613     }
7614     DSAStack->setAssociatedLoops(AssociatedLoops - 1);
7615   }
7616 }
7617 
7618 /// Called on a for stmt to check and extract its iteration space
7619 /// for further processing (such as collapsing).
7620 static bool checkOpenMPIterationSpace(
7621     OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA,
7622     unsigned CurrentNestedLoopCount, unsigned NestedLoopCount,
7623     unsigned TotalNestedLoopCount, Expr *CollapseLoopCountExpr,
7624     Expr *OrderedLoopCountExpr,
7625     Sema::VarsWithInheritedDSAType &VarsWithImplicitDSA,
7626     llvm::MutableArrayRef<LoopIterationSpace> ResultIterSpaces,
7627     llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
7628   // OpenMP [2.9.1, Canonical Loop Form]
7629   //   for (init-expr; test-expr; incr-expr) structured-block
7630   //   for (range-decl: range-expr) structured-block
7631   auto *For = dyn_cast_or_null<ForStmt>(S);
7632   auto *CXXFor = dyn_cast_or_null<CXXForRangeStmt>(S);
7633   // Ranged for is supported only in OpenMP 5.0.
7634   if (!For && (SemaRef.LangOpts.OpenMP <= 45 || !CXXFor)) {
7635     SemaRef.Diag(S->getBeginLoc(), diag::err_omp_not_for)
7636         << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr)
7637         << getOpenMPDirectiveName(DKind) << TotalNestedLoopCount
7638         << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount;
7639     if (TotalNestedLoopCount > 1) {
7640       if (CollapseLoopCountExpr && OrderedLoopCountExpr)
7641         SemaRef.Diag(DSA.getConstructLoc(),
7642                      diag::note_omp_collapse_ordered_expr)
7643             << 2 << CollapseLoopCountExpr->getSourceRange()
7644             << OrderedLoopCountExpr->getSourceRange();
7645       else if (CollapseLoopCountExpr)
7646         SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
7647                      diag::note_omp_collapse_ordered_expr)
7648             << 0 << CollapseLoopCountExpr->getSourceRange();
7649       else
7650         SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
7651                      diag::note_omp_collapse_ordered_expr)
7652             << 1 << OrderedLoopCountExpr->getSourceRange();
7653     }
7654     return true;
7655   }
7656   assert(((For && For->getBody()) || (CXXFor && CXXFor->getBody())) &&
7657          "No loop body.");
7658 
7659   OpenMPIterationSpaceChecker ISC(SemaRef, DSA,
7660                                   For ? For->getForLoc() : CXXFor->getForLoc());
7661 
7662   // Check init.
7663   Stmt *Init = For ? For->getInit() : CXXFor->getBeginStmt();
7664   if (ISC.checkAndSetInit(Init))
7665     return true;
7666 
7667   bool HasErrors = false;
7668 
7669   // Check loop variable's type.
7670   if (ValueDecl *LCDecl = ISC.getLoopDecl()) {
7671     // OpenMP [2.6, Canonical Loop Form]
7672     // Var is one of the following:
7673     //   A variable of signed or unsigned integer type.
7674     //   For C++, a variable of a random access iterator type.
7675     //   For C, a variable of a pointer type.
7676     QualType VarType = LCDecl->getType().getNonReferenceType();
7677     if (!VarType->isDependentType() && !VarType->isIntegerType() &&
7678         !VarType->isPointerType() &&
7679         !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) {
7680       SemaRef.Diag(Init->getBeginLoc(), diag::err_omp_loop_variable_type)
7681           << SemaRef.getLangOpts().CPlusPlus;
7682       HasErrors = true;
7683     }
7684 
7685     // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in
7686     // a Construct
7687     // The loop iteration variable(s) in the associated for-loop(s) of a for or
7688     // parallel for construct is (are) private.
7689     // The loop iteration variable in the associated for-loop of a simd
7690     // construct with just one associated for-loop is linear with a
7691     // constant-linear-step that is the increment of the associated for-loop.
7692     // Exclude loop var from the list of variables with implicitly defined data
7693     // sharing attributes.
7694     VarsWithImplicitDSA.erase(LCDecl);
7695 
7696     assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars");
7697 
7698     // Check test-expr.
7699     HasErrors |= ISC.checkAndSetCond(For ? For->getCond() : CXXFor->getCond());
7700 
7701     // Check incr-expr.
7702     HasErrors |= ISC.checkAndSetInc(For ? For->getInc() : CXXFor->getInc());
7703   }
7704 
7705   if (ISC.dependent() || SemaRef.CurContext->isDependentContext() || HasErrors)
7706     return HasErrors;
7707 
7708   // Build the loop's iteration space representation.
7709   ResultIterSpaces[CurrentNestedLoopCount].PreCond = ISC.buildPreCond(
7710       DSA.getCurScope(), For ? For->getCond() : CXXFor->getCond(), Captures);
7711   ResultIterSpaces[CurrentNestedLoopCount].NumIterations =
7712       ISC.buildNumIterations(DSA.getCurScope(), ResultIterSpaces,
7713                              (isOpenMPWorksharingDirective(DKind) ||
7714                               isOpenMPTaskLoopDirective(DKind) ||
7715                               isOpenMPDistributeDirective(DKind)),
7716                              Captures);
7717   ResultIterSpaces[CurrentNestedLoopCount].CounterVar =
7718       ISC.buildCounterVar(Captures, DSA);
7719   ResultIterSpaces[CurrentNestedLoopCount].PrivateCounterVar =
7720       ISC.buildPrivateCounterVar();
7721   ResultIterSpaces[CurrentNestedLoopCount].CounterInit = ISC.buildCounterInit();
7722   ResultIterSpaces[CurrentNestedLoopCount].CounterStep = ISC.buildCounterStep();
7723   ResultIterSpaces[CurrentNestedLoopCount].InitSrcRange = ISC.getInitSrcRange();
7724   ResultIterSpaces[CurrentNestedLoopCount].CondSrcRange =
7725       ISC.getConditionSrcRange();
7726   ResultIterSpaces[CurrentNestedLoopCount].IncSrcRange =
7727       ISC.getIncrementSrcRange();
7728   ResultIterSpaces[CurrentNestedLoopCount].Subtract = ISC.shouldSubtractStep();
7729   ResultIterSpaces[CurrentNestedLoopCount].IsStrictCompare =
7730       ISC.isStrictTestOp();
7731   std::tie(ResultIterSpaces[CurrentNestedLoopCount].MinValue,
7732            ResultIterSpaces[CurrentNestedLoopCount].MaxValue) =
7733       ISC.buildMinMaxValues(DSA.getCurScope(), Captures);
7734   ResultIterSpaces[CurrentNestedLoopCount].FinalCondition =
7735       ISC.buildFinalCondition(DSA.getCurScope());
7736   ResultIterSpaces[CurrentNestedLoopCount].IsNonRectangularLB =
7737       ISC.doesInitDependOnLC();
7738   ResultIterSpaces[CurrentNestedLoopCount].IsNonRectangularUB =
7739       ISC.doesCondDependOnLC();
7740   ResultIterSpaces[CurrentNestedLoopCount].LoopDependentIdx =
7741       ISC.getLoopDependentIdx();
7742 
7743   HasErrors |=
7744       (ResultIterSpaces[CurrentNestedLoopCount].PreCond == nullptr ||
7745        ResultIterSpaces[CurrentNestedLoopCount].NumIterations == nullptr ||
7746        ResultIterSpaces[CurrentNestedLoopCount].CounterVar == nullptr ||
7747        ResultIterSpaces[CurrentNestedLoopCount].PrivateCounterVar == nullptr ||
7748        ResultIterSpaces[CurrentNestedLoopCount].CounterInit == nullptr ||
7749        ResultIterSpaces[CurrentNestedLoopCount].CounterStep == nullptr);
7750   if (!HasErrors && DSA.isOrderedRegion()) {
7751     if (DSA.getOrderedRegionParam().second->getNumForLoops()) {
7752       if (CurrentNestedLoopCount <
7753           DSA.getOrderedRegionParam().second->getLoopNumIterations().size()) {
7754         DSA.getOrderedRegionParam().second->setLoopNumIterations(
7755             CurrentNestedLoopCount,
7756             ResultIterSpaces[CurrentNestedLoopCount].NumIterations);
7757         DSA.getOrderedRegionParam().second->setLoopCounter(
7758             CurrentNestedLoopCount,
7759             ResultIterSpaces[CurrentNestedLoopCount].CounterVar);
7760       }
7761     }
7762     for (auto &Pair : DSA.getDoacrossDependClauses()) {
7763       if (CurrentNestedLoopCount >= Pair.first->getNumLoops()) {
7764         // Erroneous case - clause has some problems.
7765         continue;
7766       }
7767       if (Pair.first->getDependencyKind() == OMPC_DEPEND_sink &&
7768           Pair.second.size() <= CurrentNestedLoopCount) {
7769         // Erroneous case - clause has some problems.
7770         Pair.first->setLoopData(CurrentNestedLoopCount, nullptr);
7771         continue;
7772       }
7773       Expr *CntValue;
7774       if (Pair.first->getDependencyKind() == OMPC_DEPEND_source)
7775         CntValue = ISC.buildOrderedLoopData(
7776             DSA.getCurScope(),
7777             ResultIterSpaces[CurrentNestedLoopCount].CounterVar, Captures,
7778             Pair.first->getDependencyLoc());
7779       else
7780         CntValue = ISC.buildOrderedLoopData(
7781             DSA.getCurScope(),
7782             ResultIterSpaces[CurrentNestedLoopCount].CounterVar, Captures,
7783             Pair.first->getDependencyLoc(),
7784             Pair.second[CurrentNestedLoopCount].first,
7785             Pair.second[CurrentNestedLoopCount].second);
7786       Pair.first->setLoopData(CurrentNestedLoopCount, CntValue);
7787     }
7788   }
7789 
7790   return HasErrors;
7791 }
7792 
7793 /// Build 'VarRef = Start.
7794 static ExprResult
7795 buildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
7796                  ExprResult Start, bool IsNonRectangularLB,
7797                  llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
7798   // Build 'VarRef = Start.
7799   ExprResult NewStart = IsNonRectangularLB
7800                             ? Start.get()
7801                             : tryBuildCapture(SemaRef, Start.get(), Captures);
7802   if (!NewStart.isUsable())
7803     return ExprError();
7804   if (!SemaRef.Context.hasSameType(NewStart.get()->getType(),
7805                                    VarRef.get()->getType())) {
7806     NewStart = SemaRef.PerformImplicitConversion(
7807         NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting,
7808         /*AllowExplicit=*/true);
7809     if (!NewStart.isUsable())
7810       return ExprError();
7811   }
7812 
7813   ExprResult Init =
7814       SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
7815   return Init;
7816 }
7817 
7818 /// Build 'VarRef = Start + Iter * Step'.
7819 static ExprResult buildCounterUpdate(
7820     Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
7821     ExprResult Start, ExprResult Iter, ExprResult Step, bool Subtract,
7822     bool IsNonRectangularLB,
7823     llvm::MapVector<const Expr *, DeclRefExpr *> *Captures = nullptr) {
7824   // Add parentheses (for debugging purposes only).
7825   Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get());
7826   if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() ||
7827       !Step.isUsable())
7828     return ExprError();
7829 
7830   ExprResult NewStep = Step;
7831   if (Captures)
7832     NewStep = tryBuildCapture(SemaRef, Step.get(), *Captures);
7833   if (NewStep.isInvalid())
7834     return ExprError();
7835   ExprResult Update =
7836       SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get());
7837   if (!Update.isUsable())
7838     return ExprError();
7839 
7840   // Try to build 'VarRef = Start, VarRef (+|-)= Iter * Step' or
7841   // 'VarRef = Start (+|-) Iter * Step'.
7842   if (!Start.isUsable())
7843     return ExprError();
7844   ExprResult NewStart = SemaRef.ActOnParenExpr(Loc, Loc, Start.get());
7845   if (!NewStart.isUsable())
7846     return ExprError();
7847   if (Captures && !IsNonRectangularLB)
7848     NewStart = tryBuildCapture(SemaRef, Start.get(), *Captures);
7849   if (NewStart.isInvalid())
7850     return ExprError();
7851 
7852   // First attempt: try to build 'VarRef = Start, VarRef += Iter * Step'.
7853   ExprResult SavedUpdate = Update;
7854   ExprResult UpdateVal;
7855   if (VarRef.get()->getType()->isOverloadableType() ||
7856       NewStart.get()->getType()->isOverloadableType() ||
7857       Update.get()->getType()->isOverloadableType()) {
7858     Sema::TentativeAnalysisScope Trap(SemaRef);
7859 
7860     Update =
7861         SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
7862     if (Update.isUsable()) {
7863       UpdateVal =
7864           SemaRef.BuildBinOp(S, Loc, Subtract ? BO_SubAssign : BO_AddAssign,
7865                              VarRef.get(), SavedUpdate.get());
7866       if (UpdateVal.isUsable()) {
7867         Update = SemaRef.CreateBuiltinBinOp(Loc, BO_Comma, Update.get(),
7868                                             UpdateVal.get());
7869       }
7870     }
7871   }
7872 
7873   // Second attempt: try to build 'VarRef = Start (+|-) Iter * Step'.
7874   if (!Update.isUsable() || !UpdateVal.isUsable()) {
7875     Update = SemaRef.BuildBinOp(S, Loc, Subtract ? BO_Sub : BO_Add,
7876                                 NewStart.get(), SavedUpdate.get());
7877     if (!Update.isUsable())
7878       return ExprError();
7879 
7880     if (!SemaRef.Context.hasSameType(Update.get()->getType(),
7881                                      VarRef.get()->getType())) {
7882       Update = SemaRef.PerformImplicitConversion(
7883           Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true);
7884       if (!Update.isUsable())
7885         return ExprError();
7886     }
7887 
7888     Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get());
7889   }
7890   return Update;
7891 }
7892 
7893 /// Convert integer expression \a E to make it have at least \a Bits
7894 /// bits.
7895 static ExprResult widenIterationCount(unsigned Bits, Expr *E, Sema &SemaRef) {
7896   if (E == nullptr)
7897     return ExprError();
7898   ASTContext &C = SemaRef.Context;
7899   QualType OldType = E->getType();
7900   unsigned HasBits = C.getTypeSize(OldType);
7901   if (HasBits >= Bits)
7902     return ExprResult(E);
7903   // OK to convert to signed, because new type has more bits than old.
7904   QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true);
7905   return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting,
7906                                            true);
7907 }
7908 
7909 /// Check if the given expression \a E is a constant integer that fits
7910 /// into \a Bits bits.
7911 static bool fitsInto(unsigned Bits, bool Signed, const Expr *E, Sema &SemaRef) {
7912   if (E == nullptr)
7913     return false;
7914   llvm::APSInt Result;
7915   if (E->isIntegerConstantExpr(Result, SemaRef.Context))
7916     return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits);
7917   return false;
7918 }
7919 
7920 /// Build preinits statement for the given declarations.
7921 static Stmt *buildPreInits(ASTContext &Context,
7922                            MutableArrayRef<Decl *> PreInits) {
7923   if (!PreInits.empty()) {
7924     return new (Context) DeclStmt(
7925         DeclGroupRef::Create(Context, PreInits.begin(), PreInits.size()),
7926         SourceLocation(), SourceLocation());
7927   }
7928   return nullptr;
7929 }
7930 
7931 /// Build preinits statement for the given declarations.
7932 static Stmt *
7933 buildPreInits(ASTContext &Context,
7934               const llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
7935   if (!Captures.empty()) {
7936     SmallVector<Decl *, 16> PreInits;
7937     for (const auto &Pair : Captures)
7938       PreInits.push_back(Pair.second->getDecl());
7939     return buildPreInits(Context, PreInits);
7940   }
7941   return nullptr;
7942 }
7943 
7944 /// Build postupdate expression for the given list of postupdates expressions.
7945 static Expr *buildPostUpdate(Sema &S, ArrayRef<Expr *> PostUpdates) {
7946   Expr *PostUpdate = nullptr;
7947   if (!PostUpdates.empty()) {
7948     for (Expr *E : PostUpdates) {
7949       Expr *ConvE = S.BuildCStyleCastExpr(
7950                          E->getExprLoc(),
7951                          S.Context.getTrivialTypeSourceInfo(S.Context.VoidTy),
7952                          E->getExprLoc(), E)
7953                         .get();
7954       PostUpdate = PostUpdate
7955                        ? S.CreateBuiltinBinOp(ConvE->getExprLoc(), BO_Comma,
7956                                               PostUpdate, ConvE)
7957                              .get()
7958                        : ConvE;
7959     }
7960   }
7961   return PostUpdate;
7962 }
7963 
7964 /// Called on a for stmt to check itself and nested loops (if any).
7965 /// \return Returns 0 if one of the collapsed stmts is not canonical for loop,
7966 /// number of collapsed loops otherwise.
7967 static unsigned
7968 checkOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr,
7969                 Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef,
7970                 DSAStackTy &DSA,
7971                 Sema::VarsWithInheritedDSAType &VarsWithImplicitDSA,
7972                 OMPLoopDirective::HelperExprs &Built) {
7973   unsigned NestedLoopCount = 1;
7974   if (CollapseLoopCountExpr) {
7975     // Found 'collapse' clause - calculate collapse number.
7976     Expr::EvalResult Result;
7977     if (!CollapseLoopCountExpr->isValueDependent() &&
7978         CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext())) {
7979       NestedLoopCount = Result.Val.getInt().getLimitedValue();
7980     } else {
7981       Built.clear(/*Size=*/1);
7982       return 1;
7983     }
7984   }
7985   unsigned OrderedLoopCount = 1;
7986   if (OrderedLoopCountExpr) {
7987     // Found 'ordered' clause - calculate collapse number.
7988     Expr::EvalResult EVResult;
7989     if (!OrderedLoopCountExpr->isValueDependent() &&
7990         OrderedLoopCountExpr->EvaluateAsInt(EVResult,
7991                                             SemaRef.getASTContext())) {
7992       llvm::APSInt Result = EVResult.Val.getInt();
7993       if (Result.getLimitedValue() < NestedLoopCount) {
7994         SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
7995                      diag::err_omp_wrong_ordered_loop_count)
7996             << OrderedLoopCountExpr->getSourceRange();
7997         SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
7998                      diag::note_collapse_loop_count)
7999             << CollapseLoopCountExpr->getSourceRange();
8000       }
8001       OrderedLoopCount = Result.getLimitedValue();
8002     } else {
8003       Built.clear(/*Size=*/1);
8004       return 1;
8005     }
8006   }
8007   // This is helper routine for loop directives (e.g., 'for', 'simd',
8008   // 'for simd', etc.).
8009   llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
8010   SmallVector<LoopIterationSpace, 4> IterSpaces(
8011       std::max(OrderedLoopCount, NestedLoopCount));
8012   Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true);
8013   for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
8014     if (checkOpenMPIterationSpace(
8015             DKind, CurStmt, SemaRef, DSA, Cnt, NestedLoopCount,
8016             std::max(OrderedLoopCount, NestedLoopCount), CollapseLoopCountExpr,
8017             OrderedLoopCountExpr, VarsWithImplicitDSA, IterSpaces, Captures))
8018       return 0;
8019     // Move on to the next nested for loop, or to the loop body.
8020     // OpenMP [2.8.1, simd construct, Restrictions]
8021     // All loops associated with the construct must be perfectly nested; that
8022     // is, there must be no intervening code nor any OpenMP directive between
8023     // any two loops.
8024     if (auto *For = dyn_cast<ForStmt>(CurStmt)) {
8025       CurStmt = For->getBody();
8026     } else {
8027       assert(isa<CXXForRangeStmt>(CurStmt) &&
8028              "Expected canonical for or range-based for loops.");
8029       CurStmt = cast<CXXForRangeStmt>(CurStmt)->getBody();
8030     }
8031     CurStmt = OMPLoopDirective::tryToFindNextInnerLoop(
8032         CurStmt, SemaRef.LangOpts.OpenMP >= 50);
8033   }
8034   for (unsigned Cnt = NestedLoopCount; Cnt < OrderedLoopCount; ++Cnt) {
8035     if (checkOpenMPIterationSpace(
8036             DKind, CurStmt, SemaRef, DSA, Cnt, NestedLoopCount,
8037             std::max(OrderedLoopCount, NestedLoopCount), CollapseLoopCountExpr,
8038             OrderedLoopCountExpr, VarsWithImplicitDSA, IterSpaces, Captures))
8039       return 0;
8040     if (Cnt > 0 && IterSpaces[Cnt].CounterVar) {
8041       // Handle initialization of captured loop iterator variables.
8042       auto *DRE = cast<DeclRefExpr>(IterSpaces[Cnt].CounterVar);
8043       if (isa<OMPCapturedExprDecl>(DRE->getDecl())) {
8044         Captures[DRE] = DRE;
8045       }
8046     }
8047     // Move on to the next nested for loop, or to the loop body.
8048     // OpenMP [2.8.1, simd construct, Restrictions]
8049     // All loops associated with the construct must be perfectly nested; that
8050     // is, there must be no intervening code nor any OpenMP directive between
8051     // any two loops.
8052     if (auto *For = dyn_cast<ForStmt>(CurStmt)) {
8053       CurStmt = For->getBody();
8054     } else {
8055       assert(isa<CXXForRangeStmt>(CurStmt) &&
8056              "Expected canonical for or range-based for loops.");
8057       CurStmt = cast<CXXForRangeStmt>(CurStmt)->getBody();
8058     }
8059     CurStmt = OMPLoopDirective::tryToFindNextInnerLoop(
8060         CurStmt, SemaRef.LangOpts.OpenMP >= 50);
8061   }
8062 
8063   Built.clear(/* size */ NestedLoopCount);
8064 
8065   if (SemaRef.CurContext->isDependentContext())
8066     return NestedLoopCount;
8067 
8068   // An example of what is generated for the following code:
8069   //
8070   //   #pragma omp simd collapse(2) ordered(2)
8071   //   for (i = 0; i < NI; ++i)
8072   //     for (k = 0; k < NK; ++k)
8073   //       for (j = J0; j < NJ; j+=2) {
8074   //         <loop body>
8075   //       }
8076   //
8077   // We generate the code below.
8078   // Note: the loop body may be outlined in CodeGen.
8079   // Note: some counters may be C++ classes, operator- is used to find number of
8080   // iterations and operator+= to calculate counter value.
8081   // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32
8082   // or i64 is currently supported).
8083   //
8084   //   #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2))
8085   //   for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) {
8086   //     .local.i = IV / ((NJ - J0 - 1 + 2) / 2);
8087   //     .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2;
8088   //     // similar updates for vars in clauses (e.g. 'linear')
8089   //     <loop body (using local i and j)>
8090   //   }
8091   //   i = NI; // assign final values of counters
8092   //   j = NJ;
8093   //
8094 
8095   // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are
8096   // the iteration counts of the collapsed for loops.
8097   // Precondition tests if there is at least one iteration (all conditions are
8098   // true).
8099   auto PreCond = ExprResult(IterSpaces[0].PreCond);
8100   Expr *N0 = IterSpaces[0].NumIterations;
8101   ExprResult LastIteration32 =
8102       widenIterationCount(/*Bits=*/32,
8103                           SemaRef
8104                               .PerformImplicitConversion(
8105                                   N0->IgnoreImpCasts(), N0->getType(),
8106                                   Sema::AA_Converting, /*AllowExplicit=*/true)
8107                               .get(),
8108                           SemaRef);
8109   ExprResult LastIteration64 = widenIterationCount(
8110       /*Bits=*/64,
8111       SemaRef
8112           .PerformImplicitConversion(N0->IgnoreImpCasts(), N0->getType(),
8113                                      Sema::AA_Converting,
8114                                      /*AllowExplicit=*/true)
8115           .get(),
8116       SemaRef);
8117 
8118   if (!LastIteration32.isUsable() || !LastIteration64.isUsable())
8119     return NestedLoopCount;
8120 
8121   ASTContext &C = SemaRef.Context;
8122   bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32;
8123 
8124   Scope *CurScope = DSA.getCurScope();
8125   for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) {
8126     if (PreCond.isUsable()) {
8127       PreCond =
8128           SemaRef.BuildBinOp(CurScope, PreCond.get()->getExprLoc(), BO_LAnd,
8129                              PreCond.get(), IterSpaces[Cnt].PreCond);
8130     }
8131     Expr *N = IterSpaces[Cnt].NumIterations;
8132     SourceLocation Loc = N->getExprLoc();
8133     AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32;
8134     if (LastIteration32.isUsable())
8135       LastIteration32 = SemaRef.BuildBinOp(
8136           CurScope, Loc, BO_Mul, LastIteration32.get(),
8137           SemaRef
8138               .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
8139                                          Sema::AA_Converting,
8140                                          /*AllowExplicit=*/true)
8141               .get());
8142     if (LastIteration64.isUsable())
8143       LastIteration64 = SemaRef.BuildBinOp(
8144           CurScope, Loc, BO_Mul, LastIteration64.get(),
8145           SemaRef
8146               .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
8147                                          Sema::AA_Converting,
8148                                          /*AllowExplicit=*/true)
8149               .get());
8150   }
8151 
8152   // Choose either the 32-bit or 64-bit version.
8153   ExprResult LastIteration = LastIteration64;
8154   if (SemaRef.getLangOpts().OpenMPOptimisticCollapse ||
8155       (LastIteration32.isUsable() &&
8156        C.getTypeSize(LastIteration32.get()->getType()) == 32 &&
8157        (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 ||
8158         fitsInto(
8159             /*Bits=*/32,
8160             LastIteration32.get()->getType()->hasSignedIntegerRepresentation(),
8161             LastIteration64.get(), SemaRef))))
8162     LastIteration = LastIteration32;
8163   QualType VType = LastIteration.get()->getType();
8164   QualType RealVType = VType;
8165   QualType StrideVType = VType;
8166   if (isOpenMPTaskLoopDirective(DKind)) {
8167     VType =
8168         SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
8169     StrideVType =
8170         SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
8171   }
8172 
8173   if (!LastIteration.isUsable())
8174     return 0;
8175 
8176   // Save the number of iterations.
8177   ExprResult NumIterations = LastIteration;
8178   {
8179     LastIteration = SemaRef.BuildBinOp(
8180         CurScope, LastIteration.get()->getExprLoc(), BO_Sub,
8181         LastIteration.get(),
8182         SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
8183     if (!LastIteration.isUsable())
8184       return 0;
8185   }
8186 
8187   // Calculate the last iteration number beforehand instead of doing this on
8188   // each iteration. Do not do this if the number of iterations may be kfold-ed.
8189   llvm::APSInt Result;
8190   bool IsConstant =
8191       LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context);
8192   ExprResult CalcLastIteration;
8193   if (!IsConstant) {
8194     ExprResult SaveRef =
8195         tryBuildCapture(SemaRef, LastIteration.get(), Captures);
8196     LastIteration = SaveRef;
8197 
8198     // Prepare SaveRef + 1.
8199     NumIterations = SemaRef.BuildBinOp(
8200         CurScope, SaveRef.get()->getExprLoc(), BO_Add, SaveRef.get(),
8201         SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
8202     if (!NumIterations.isUsable())
8203       return 0;
8204   }
8205 
8206   SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin();
8207 
8208   // Build variables passed into runtime, necessary for worksharing directives.
8209   ExprResult LB, UB, IL, ST, EUB, CombLB, CombUB, PrevLB, PrevUB, CombEUB;
8210   if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
8211       isOpenMPDistributeDirective(DKind)) {
8212     // Lower bound variable, initialized with zero.
8213     VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb");
8214     LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc);
8215     SemaRef.AddInitializerToDecl(LBDecl,
8216                                  SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
8217                                  /*DirectInit*/ false);
8218 
8219     // Upper bound variable, initialized with last iteration number.
8220     VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub");
8221     UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc);
8222     SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(),
8223                                  /*DirectInit*/ false);
8224 
8225     // A 32-bit variable-flag where runtime returns 1 for the last iteration.
8226     // This will be used to implement clause 'lastprivate'.
8227     QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true);
8228     VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last");
8229     IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc);
8230     SemaRef.AddInitializerToDecl(ILDecl,
8231                                  SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
8232                                  /*DirectInit*/ false);
8233 
8234     // Stride variable returned by runtime (we initialize it to 1 by default).
8235     VarDecl *STDecl =
8236         buildVarDecl(SemaRef, InitLoc, StrideVType, ".omp.stride");
8237     ST = buildDeclRefExpr(SemaRef, STDecl, StrideVType, InitLoc);
8238     SemaRef.AddInitializerToDecl(STDecl,
8239                                  SemaRef.ActOnIntegerConstant(InitLoc, 1).get(),
8240                                  /*DirectInit*/ false);
8241 
8242     // Build expression: UB = min(UB, LastIteration)
8243     // It is necessary for CodeGen of directives with static scheduling.
8244     ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT,
8245                                                 UB.get(), LastIteration.get());
8246     ExprResult CondOp = SemaRef.ActOnConditionalOp(
8247         LastIteration.get()->getExprLoc(), InitLoc, IsUBGreater.get(),
8248         LastIteration.get(), UB.get());
8249     EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(),
8250                              CondOp.get());
8251     EUB = SemaRef.ActOnFinishFullExpr(EUB.get(), /*DiscardedValue*/ false);
8252 
8253     // If we have a combined directive that combines 'distribute', 'for' or
8254     // 'simd' we need to be able to access the bounds of the schedule of the
8255     // enclosing region. E.g. in 'distribute parallel for' the bounds obtained
8256     // by scheduling 'distribute' have to be passed to the schedule of 'for'.
8257     if (isOpenMPLoopBoundSharingDirective(DKind)) {
8258       // Lower bound variable, initialized with zero.
8259       VarDecl *CombLBDecl =
8260           buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.lb");
8261       CombLB = buildDeclRefExpr(SemaRef, CombLBDecl, VType, InitLoc);
8262       SemaRef.AddInitializerToDecl(
8263           CombLBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
8264           /*DirectInit*/ false);
8265 
8266       // Upper bound variable, initialized with last iteration number.
8267       VarDecl *CombUBDecl =
8268           buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.ub");
8269       CombUB = buildDeclRefExpr(SemaRef, CombUBDecl, VType, InitLoc);
8270       SemaRef.AddInitializerToDecl(CombUBDecl, LastIteration.get(),
8271                                    /*DirectInit*/ false);
8272 
8273       ExprResult CombIsUBGreater = SemaRef.BuildBinOp(
8274           CurScope, InitLoc, BO_GT, CombUB.get(), LastIteration.get());
8275       ExprResult CombCondOp =
8276           SemaRef.ActOnConditionalOp(InitLoc, InitLoc, CombIsUBGreater.get(),
8277                                      LastIteration.get(), CombUB.get());
8278       CombEUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, CombUB.get(),
8279                                    CombCondOp.get());
8280       CombEUB =
8281           SemaRef.ActOnFinishFullExpr(CombEUB.get(), /*DiscardedValue*/ false);
8282 
8283       const CapturedDecl *CD = cast<CapturedStmt>(AStmt)->getCapturedDecl();
8284       // We expect to have at least 2 more parameters than the 'parallel'
8285       // directive does - the lower and upper bounds of the previous schedule.
8286       assert(CD->getNumParams() >= 4 &&
8287              "Unexpected number of parameters in loop combined directive");
8288 
8289       // Set the proper type for the bounds given what we learned from the
8290       // enclosed loops.
8291       ImplicitParamDecl *PrevLBDecl = CD->getParam(/*PrevLB=*/2);
8292       ImplicitParamDecl *PrevUBDecl = CD->getParam(/*PrevUB=*/3);
8293 
8294       // Previous lower and upper bounds are obtained from the region
8295       // parameters.
8296       PrevLB =
8297           buildDeclRefExpr(SemaRef, PrevLBDecl, PrevLBDecl->getType(), InitLoc);
8298       PrevUB =
8299           buildDeclRefExpr(SemaRef, PrevUBDecl, PrevUBDecl->getType(), InitLoc);
8300     }
8301   }
8302 
8303   // Build the iteration variable and its initialization before loop.
8304   ExprResult IV;
8305   ExprResult Init, CombInit;
8306   {
8307     VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, RealVType, ".omp.iv");
8308     IV = buildDeclRefExpr(SemaRef, IVDecl, RealVType, InitLoc);
8309     Expr *RHS =
8310         (isOpenMPWorksharingDirective(DKind) ||
8311          isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
8312             ? LB.get()
8313             : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
8314     Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS);
8315     Init = SemaRef.ActOnFinishFullExpr(Init.get(), /*DiscardedValue*/ false);
8316 
8317     if (isOpenMPLoopBoundSharingDirective(DKind)) {
8318       Expr *CombRHS =
8319           (isOpenMPWorksharingDirective(DKind) ||
8320            isOpenMPTaskLoopDirective(DKind) ||
8321            isOpenMPDistributeDirective(DKind))
8322               ? CombLB.get()
8323               : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
8324       CombInit =
8325           SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), CombRHS);
8326       CombInit =
8327           SemaRef.ActOnFinishFullExpr(CombInit.get(), /*DiscardedValue*/ false);
8328     }
8329   }
8330 
8331   bool UseStrictCompare =
8332       RealVType->hasUnsignedIntegerRepresentation() &&
8333       llvm::all_of(IterSpaces, [](const LoopIterationSpace &LIS) {
8334         return LIS.IsStrictCompare;
8335       });
8336   // Loop condition (IV < NumIterations) or (IV <= UB or IV < UB + 1 (for
8337   // unsigned IV)) for worksharing loops.
8338   SourceLocation CondLoc = AStmt->getBeginLoc();
8339   Expr *BoundUB = UB.get();
8340   if (UseStrictCompare) {
8341     BoundUB =
8342         SemaRef
8343             .BuildBinOp(CurScope, CondLoc, BO_Add, BoundUB,
8344                         SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
8345             .get();
8346     BoundUB =
8347         SemaRef.ActOnFinishFullExpr(BoundUB, /*DiscardedValue*/ false).get();
8348   }
8349   ExprResult Cond =
8350       (isOpenMPWorksharingDirective(DKind) ||
8351        isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
8352           ? SemaRef.BuildBinOp(CurScope, CondLoc,
8353                                UseStrictCompare ? BO_LT : BO_LE, IV.get(),
8354                                BoundUB)
8355           : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
8356                                NumIterations.get());
8357   ExprResult CombDistCond;
8358   if (isOpenMPLoopBoundSharingDirective(DKind)) {
8359     CombDistCond = SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
8360                                       NumIterations.get());
8361   }
8362 
8363   ExprResult CombCond;
8364   if (isOpenMPLoopBoundSharingDirective(DKind)) {
8365     Expr *BoundCombUB = CombUB.get();
8366     if (UseStrictCompare) {
8367       BoundCombUB =
8368           SemaRef
8369               .BuildBinOp(
8370                   CurScope, CondLoc, BO_Add, BoundCombUB,
8371                   SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
8372               .get();
8373       BoundCombUB =
8374           SemaRef.ActOnFinishFullExpr(BoundCombUB, /*DiscardedValue*/ false)
8375               .get();
8376     }
8377     CombCond =
8378         SemaRef.BuildBinOp(CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE,
8379                            IV.get(), BoundCombUB);
8380   }
8381   // Loop increment (IV = IV + 1)
8382   SourceLocation IncLoc = AStmt->getBeginLoc();
8383   ExprResult Inc =
8384       SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(),
8385                          SemaRef.ActOnIntegerConstant(IncLoc, 1).get());
8386   if (!Inc.isUsable())
8387     return 0;
8388   Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get());
8389   Inc = SemaRef.ActOnFinishFullExpr(Inc.get(), /*DiscardedValue*/ false);
8390   if (!Inc.isUsable())
8391     return 0;
8392 
8393   // Increments for worksharing loops (LB = LB + ST; UB = UB + ST).
8394   // Used for directives with static scheduling.
8395   // In combined construct, add combined version that use CombLB and CombUB
8396   // base variables for the update
8397   ExprResult NextLB, NextUB, CombNextLB, CombNextUB;
8398   if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
8399       isOpenMPDistributeDirective(DKind)) {
8400     // LB + ST
8401     NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get());
8402     if (!NextLB.isUsable())
8403       return 0;
8404     // LB = LB + ST
8405     NextLB =
8406         SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get());
8407     NextLB =
8408         SemaRef.ActOnFinishFullExpr(NextLB.get(), /*DiscardedValue*/ false);
8409     if (!NextLB.isUsable())
8410       return 0;
8411     // UB + ST
8412     NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get());
8413     if (!NextUB.isUsable())
8414       return 0;
8415     // UB = UB + ST
8416     NextUB =
8417         SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get());
8418     NextUB =
8419         SemaRef.ActOnFinishFullExpr(NextUB.get(), /*DiscardedValue*/ false);
8420     if (!NextUB.isUsable())
8421       return 0;
8422     if (isOpenMPLoopBoundSharingDirective(DKind)) {
8423       CombNextLB =
8424           SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombLB.get(), ST.get());
8425       if (!NextLB.isUsable())
8426         return 0;
8427       // LB = LB + ST
8428       CombNextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombLB.get(),
8429                                       CombNextLB.get());
8430       CombNextLB = SemaRef.ActOnFinishFullExpr(CombNextLB.get(),
8431                                                /*DiscardedValue*/ false);
8432       if (!CombNextLB.isUsable())
8433         return 0;
8434       // UB + ST
8435       CombNextUB =
8436           SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombUB.get(), ST.get());
8437       if (!CombNextUB.isUsable())
8438         return 0;
8439       // UB = UB + ST
8440       CombNextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombUB.get(),
8441                                       CombNextUB.get());
8442       CombNextUB = SemaRef.ActOnFinishFullExpr(CombNextUB.get(),
8443                                                /*DiscardedValue*/ false);
8444       if (!CombNextUB.isUsable())
8445         return 0;
8446     }
8447   }
8448 
8449   // Create increment expression for distribute loop when combined in a same
8450   // directive with for as IV = IV + ST; ensure upper bound expression based
8451   // on PrevUB instead of NumIterations - used to implement 'for' when found
8452   // in combination with 'distribute', like in 'distribute parallel for'
8453   SourceLocation DistIncLoc = AStmt->getBeginLoc();
8454   ExprResult DistCond, DistInc, PrevEUB, ParForInDistCond;
8455   if (isOpenMPLoopBoundSharingDirective(DKind)) {
8456     DistCond = SemaRef.BuildBinOp(
8457         CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE, IV.get(), BoundUB);
8458     assert(DistCond.isUsable() && "distribute cond expr was not built");
8459 
8460     DistInc =
8461         SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Add, IV.get(), ST.get());
8462     assert(DistInc.isUsable() && "distribute inc expr was not built");
8463     DistInc = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, IV.get(),
8464                                  DistInc.get());
8465     DistInc =
8466         SemaRef.ActOnFinishFullExpr(DistInc.get(), /*DiscardedValue*/ false);
8467     assert(DistInc.isUsable() && "distribute inc expr was not built");
8468 
8469     // Build expression: UB = min(UB, prevUB) for #for in composite or combined
8470     // construct
8471     SourceLocation DistEUBLoc = AStmt->getBeginLoc();
8472     ExprResult IsUBGreater =
8473         SemaRef.BuildBinOp(CurScope, DistEUBLoc, BO_GT, UB.get(), PrevUB.get());
8474     ExprResult CondOp = SemaRef.ActOnConditionalOp(
8475         DistEUBLoc, DistEUBLoc, IsUBGreater.get(), PrevUB.get(), UB.get());
8476     PrevEUB = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, UB.get(),
8477                                  CondOp.get());
8478     PrevEUB =
8479         SemaRef.ActOnFinishFullExpr(PrevEUB.get(), /*DiscardedValue*/ false);
8480 
8481     // Build IV <= PrevUB or IV < PrevUB + 1 for unsigned IV to be used in
8482     // parallel for is in combination with a distribute directive with
8483     // schedule(static, 1)
8484     Expr *BoundPrevUB = PrevUB.get();
8485     if (UseStrictCompare) {
8486       BoundPrevUB =
8487           SemaRef
8488               .BuildBinOp(
8489                   CurScope, CondLoc, BO_Add, BoundPrevUB,
8490                   SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
8491               .get();
8492       BoundPrevUB =
8493           SemaRef.ActOnFinishFullExpr(BoundPrevUB, /*DiscardedValue*/ false)
8494               .get();
8495     }
8496     ParForInDistCond =
8497         SemaRef.BuildBinOp(CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE,
8498                            IV.get(), BoundPrevUB);
8499   }
8500 
8501   // Build updates and final values of the loop counters.
8502   bool HasErrors = false;
8503   Built.Counters.resize(NestedLoopCount);
8504   Built.Inits.resize(NestedLoopCount);
8505   Built.Updates.resize(NestedLoopCount);
8506   Built.Finals.resize(NestedLoopCount);
8507   Built.DependentCounters.resize(NestedLoopCount);
8508   Built.DependentInits.resize(NestedLoopCount);
8509   Built.FinalsConditions.resize(NestedLoopCount);
8510   {
8511     // We implement the following algorithm for obtaining the
8512     // original loop iteration variable values based on the
8513     // value of the collapsed loop iteration variable IV.
8514     //
8515     // Let n+1 be the number of collapsed loops in the nest.
8516     // Iteration variables (I0, I1, .... In)
8517     // Iteration counts (N0, N1, ... Nn)
8518     //
8519     // Acc = IV;
8520     //
8521     // To compute Ik for loop k, 0 <= k <= n, generate:
8522     //    Prod = N(k+1) * N(k+2) * ... * Nn;
8523     //    Ik = Acc / Prod;
8524     //    Acc -= Ik * Prod;
8525     //
8526     ExprResult Acc = IV;
8527     for (unsigned int Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
8528       LoopIterationSpace &IS = IterSpaces[Cnt];
8529       SourceLocation UpdLoc = IS.IncSrcRange.getBegin();
8530       ExprResult Iter;
8531 
8532       // Compute prod
8533       ExprResult Prod =
8534           SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
8535       for (unsigned int K = Cnt+1; K < NestedLoopCount; ++K)
8536         Prod = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Prod.get(),
8537                                   IterSpaces[K].NumIterations);
8538 
8539       // Iter = Acc / Prod
8540       // If there is at least one more inner loop to avoid
8541       // multiplication by 1.
8542       if (Cnt + 1 < NestedLoopCount)
8543         Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div,
8544                                   Acc.get(), Prod.get());
8545       else
8546         Iter = Acc;
8547       if (!Iter.isUsable()) {
8548         HasErrors = true;
8549         break;
8550       }
8551 
8552       // Update Acc:
8553       // Acc -= Iter * Prod
8554       // Check if there is at least one more inner loop to avoid
8555       // multiplication by 1.
8556       if (Cnt + 1 < NestedLoopCount)
8557         Prod = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul,
8558                                   Iter.get(), Prod.get());
8559       else
8560         Prod = Iter;
8561       Acc = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Sub,
8562                                Acc.get(), Prod.get());
8563 
8564       // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step
8565       auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl());
8566       DeclRefExpr *CounterVar = buildDeclRefExpr(
8567           SemaRef, VD, IS.CounterVar->getType(), IS.CounterVar->getExprLoc(),
8568           /*RefersToCapture=*/true);
8569       ExprResult Init =
8570           buildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar,
8571                            IS.CounterInit, IS.IsNonRectangularLB, Captures);
8572       if (!Init.isUsable()) {
8573         HasErrors = true;
8574         break;
8575       }
8576       ExprResult Update = buildCounterUpdate(
8577           SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, Iter,
8578           IS.CounterStep, IS.Subtract, IS.IsNonRectangularLB, &Captures);
8579       if (!Update.isUsable()) {
8580         HasErrors = true;
8581         break;
8582       }
8583 
8584       // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step
8585       ExprResult Final =
8586           buildCounterUpdate(SemaRef, CurScope, UpdLoc, CounterVar,
8587                              IS.CounterInit, IS.NumIterations, IS.CounterStep,
8588                              IS.Subtract, IS.IsNonRectangularLB, &Captures);
8589       if (!Final.isUsable()) {
8590         HasErrors = true;
8591         break;
8592       }
8593 
8594       if (!Update.isUsable() || !Final.isUsable()) {
8595         HasErrors = true;
8596         break;
8597       }
8598       // Save results
8599       Built.Counters[Cnt] = IS.CounterVar;
8600       Built.PrivateCounters[Cnt] = IS.PrivateCounterVar;
8601       Built.Inits[Cnt] = Init.get();
8602       Built.Updates[Cnt] = Update.get();
8603       Built.Finals[Cnt] = Final.get();
8604       Built.DependentCounters[Cnt] = nullptr;
8605       Built.DependentInits[Cnt] = nullptr;
8606       Built.FinalsConditions[Cnt] = nullptr;
8607       if (IS.IsNonRectangularLB || IS.IsNonRectangularUB) {
8608         Built.DependentCounters[Cnt] =
8609             Built.Counters[NestedLoopCount - 1 - IS.LoopDependentIdx];
8610         Built.DependentInits[Cnt] =
8611             Built.Inits[NestedLoopCount - 1 - IS.LoopDependentIdx];
8612         Built.FinalsConditions[Cnt] = IS.FinalCondition;
8613       }
8614     }
8615   }
8616 
8617   if (HasErrors)
8618     return 0;
8619 
8620   // Save results
8621   Built.IterationVarRef = IV.get();
8622   Built.LastIteration = LastIteration.get();
8623   Built.NumIterations = NumIterations.get();
8624   Built.CalcLastIteration = SemaRef
8625                                 .ActOnFinishFullExpr(CalcLastIteration.get(),
8626                                                      /*DiscardedValue=*/false)
8627                                 .get();
8628   Built.PreCond = PreCond.get();
8629   Built.PreInits = buildPreInits(C, Captures);
8630   Built.Cond = Cond.get();
8631   Built.Init = Init.get();
8632   Built.Inc = Inc.get();
8633   Built.LB = LB.get();
8634   Built.UB = UB.get();
8635   Built.IL = IL.get();
8636   Built.ST = ST.get();
8637   Built.EUB = EUB.get();
8638   Built.NLB = NextLB.get();
8639   Built.NUB = NextUB.get();
8640   Built.PrevLB = PrevLB.get();
8641   Built.PrevUB = PrevUB.get();
8642   Built.DistInc = DistInc.get();
8643   Built.PrevEUB = PrevEUB.get();
8644   Built.DistCombinedFields.LB = CombLB.get();
8645   Built.DistCombinedFields.UB = CombUB.get();
8646   Built.DistCombinedFields.EUB = CombEUB.get();
8647   Built.DistCombinedFields.Init = CombInit.get();
8648   Built.DistCombinedFields.Cond = CombCond.get();
8649   Built.DistCombinedFields.NLB = CombNextLB.get();
8650   Built.DistCombinedFields.NUB = CombNextUB.get();
8651   Built.DistCombinedFields.DistCond = CombDistCond.get();
8652   Built.DistCombinedFields.ParForInDistCond = ParForInDistCond.get();
8653 
8654   return NestedLoopCount;
8655 }
8656 
8657 static Expr *getCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) {
8658   auto CollapseClauses =
8659       OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses);
8660   if (CollapseClauses.begin() != CollapseClauses.end())
8661     return (*CollapseClauses.begin())->getNumForLoops();
8662   return nullptr;
8663 }
8664 
8665 static Expr *getOrderedNumberExpr(ArrayRef<OMPClause *> Clauses) {
8666   auto OrderedClauses =
8667       OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses);
8668   if (OrderedClauses.begin() != OrderedClauses.end())
8669     return (*OrderedClauses.begin())->getNumForLoops();
8670   return nullptr;
8671 }
8672 
8673 static bool checkSimdlenSafelenSpecified(Sema &S,
8674                                          const ArrayRef<OMPClause *> Clauses) {
8675   const OMPSafelenClause *Safelen = nullptr;
8676   const OMPSimdlenClause *Simdlen = nullptr;
8677 
8678   for (const OMPClause *Clause : Clauses) {
8679     if (Clause->getClauseKind() == OMPC_safelen)
8680       Safelen = cast<OMPSafelenClause>(Clause);
8681     else if (Clause->getClauseKind() == OMPC_simdlen)
8682       Simdlen = cast<OMPSimdlenClause>(Clause);
8683     if (Safelen && Simdlen)
8684       break;
8685   }
8686 
8687   if (Simdlen && Safelen) {
8688     const Expr *SimdlenLength = Simdlen->getSimdlen();
8689     const Expr *SafelenLength = Safelen->getSafelen();
8690     if (SimdlenLength->isValueDependent() || SimdlenLength->isTypeDependent() ||
8691         SimdlenLength->isInstantiationDependent() ||
8692         SimdlenLength->containsUnexpandedParameterPack())
8693       return false;
8694     if (SafelenLength->isValueDependent() || SafelenLength->isTypeDependent() ||
8695         SafelenLength->isInstantiationDependent() ||
8696         SafelenLength->containsUnexpandedParameterPack())
8697       return false;
8698     Expr::EvalResult SimdlenResult, SafelenResult;
8699     SimdlenLength->EvaluateAsInt(SimdlenResult, S.Context);
8700     SafelenLength->EvaluateAsInt(SafelenResult, S.Context);
8701     llvm::APSInt SimdlenRes = SimdlenResult.Val.getInt();
8702     llvm::APSInt SafelenRes = SafelenResult.Val.getInt();
8703     // OpenMP 4.5 [2.8.1, simd Construct, Restrictions]
8704     // If both simdlen and safelen clauses are specified, the value of the
8705     // simdlen parameter must be less than or equal to the value of the safelen
8706     // parameter.
8707     if (SimdlenRes > SafelenRes) {
8708       S.Diag(SimdlenLength->getExprLoc(),
8709              diag::err_omp_wrong_simdlen_safelen_values)
8710           << SimdlenLength->getSourceRange() << SafelenLength->getSourceRange();
8711       return true;
8712     }
8713   }
8714   return false;
8715 }
8716 
8717 StmtResult
8718 Sema::ActOnOpenMPSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
8719                                SourceLocation StartLoc, SourceLocation EndLoc,
8720                                VarsWithInheritedDSAType &VarsWithImplicitDSA) {
8721   if (!AStmt)
8722     return StmtError();
8723 
8724   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
8725   OMPLoopDirective::HelperExprs B;
8726   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
8727   // define the nested loops number.
8728   unsigned NestedLoopCount = checkOpenMPLoop(
8729       OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
8730       AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
8731   if (NestedLoopCount == 0)
8732     return StmtError();
8733 
8734   assert((CurContext->isDependentContext() || B.builtAll()) &&
8735          "omp simd loop exprs were not built");
8736 
8737   if (!CurContext->isDependentContext()) {
8738     // Finalize the clauses that need pre-built expressions for CodeGen.
8739     for (OMPClause *C : Clauses) {
8740       if (auto *LC = dyn_cast<OMPLinearClause>(C))
8741         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
8742                                      B.NumIterations, *this, CurScope,
8743                                      DSAStack))
8744           return StmtError();
8745     }
8746   }
8747 
8748   if (checkSimdlenSafelenSpecified(*this, Clauses))
8749     return StmtError();
8750 
8751   setFunctionHasBranchProtectedScope();
8752   return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
8753                                   Clauses, AStmt, B);
8754 }
8755 
8756 StmtResult
8757 Sema::ActOnOpenMPForDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
8758                               SourceLocation StartLoc, SourceLocation EndLoc,
8759                               VarsWithInheritedDSAType &VarsWithImplicitDSA) {
8760   if (!AStmt)
8761     return StmtError();
8762 
8763   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
8764   OMPLoopDirective::HelperExprs B;
8765   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
8766   // define the nested loops number.
8767   unsigned NestedLoopCount = checkOpenMPLoop(
8768       OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
8769       AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
8770   if (NestedLoopCount == 0)
8771     return StmtError();
8772 
8773   assert((CurContext->isDependentContext() || B.builtAll()) &&
8774          "omp for loop exprs were not built");
8775 
8776   if (!CurContext->isDependentContext()) {
8777     // Finalize the clauses that need pre-built expressions for CodeGen.
8778     for (OMPClause *C : Clauses) {
8779       if (auto *LC = dyn_cast<OMPLinearClause>(C))
8780         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
8781                                      B.NumIterations, *this, CurScope,
8782                                      DSAStack))
8783           return StmtError();
8784     }
8785   }
8786 
8787   setFunctionHasBranchProtectedScope();
8788   return OMPForDirective::Create(
8789       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
8790       DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion());
8791 }
8792 
8793 StmtResult Sema::ActOnOpenMPForSimdDirective(
8794     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8795     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
8796   if (!AStmt)
8797     return StmtError();
8798 
8799   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
8800   OMPLoopDirective::HelperExprs B;
8801   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
8802   // define the nested loops number.
8803   unsigned NestedLoopCount =
8804       checkOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses),
8805                       getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
8806                       VarsWithImplicitDSA, B);
8807   if (NestedLoopCount == 0)
8808     return StmtError();
8809 
8810   assert((CurContext->isDependentContext() || B.builtAll()) &&
8811          "omp for simd loop exprs were not built");
8812 
8813   if (!CurContext->isDependentContext()) {
8814     // Finalize the clauses that need pre-built expressions for CodeGen.
8815     for (OMPClause *C : Clauses) {
8816       if (auto *LC = dyn_cast<OMPLinearClause>(C))
8817         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
8818                                      B.NumIterations, *this, CurScope,
8819                                      DSAStack))
8820           return StmtError();
8821     }
8822   }
8823 
8824   if (checkSimdlenSafelenSpecified(*this, Clauses))
8825     return StmtError();
8826 
8827   setFunctionHasBranchProtectedScope();
8828   return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
8829                                      Clauses, AStmt, B);
8830 }
8831 
8832 StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
8833                                               Stmt *AStmt,
8834                                               SourceLocation StartLoc,
8835                                               SourceLocation EndLoc) {
8836   if (!AStmt)
8837     return StmtError();
8838 
8839   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
8840   auto BaseStmt = AStmt;
8841   while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
8842     BaseStmt = CS->getCapturedStmt();
8843   if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
8844     auto S = C->children();
8845     if (S.begin() == S.end())
8846       return StmtError();
8847     // All associated statements must be '#pragma omp section' except for
8848     // the first one.
8849     for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
8850       if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
8851         if (SectionStmt)
8852           Diag(SectionStmt->getBeginLoc(),
8853                diag::err_omp_sections_substmt_not_section);
8854         return StmtError();
8855       }
8856       cast<OMPSectionDirective>(SectionStmt)
8857           ->setHasCancel(DSAStack->isCancelRegion());
8858     }
8859   } else {
8860     Diag(AStmt->getBeginLoc(), diag::err_omp_sections_not_compound_stmt);
8861     return StmtError();
8862   }
8863 
8864   setFunctionHasBranchProtectedScope();
8865 
8866   return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
8867                                       DSAStack->getTaskgroupReductionRef(),
8868                                       DSAStack->isCancelRegion());
8869 }
8870 
8871 StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt,
8872                                              SourceLocation StartLoc,
8873                                              SourceLocation EndLoc) {
8874   if (!AStmt)
8875     return StmtError();
8876 
8877   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
8878 
8879   setFunctionHasBranchProtectedScope();
8880   DSAStack->setParentCancelRegion(DSAStack->isCancelRegion());
8881 
8882   return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt,
8883                                      DSAStack->isCancelRegion());
8884 }
8885 
8886 StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
8887                                             Stmt *AStmt,
8888                                             SourceLocation StartLoc,
8889                                             SourceLocation EndLoc) {
8890   if (!AStmt)
8891     return StmtError();
8892 
8893   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
8894 
8895   setFunctionHasBranchProtectedScope();
8896 
8897   // OpenMP [2.7.3, single Construct, Restrictions]
8898   // The copyprivate clause must not be used with the nowait clause.
8899   const OMPClause *Nowait = nullptr;
8900   const OMPClause *Copyprivate = nullptr;
8901   for (const OMPClause *Clause : Clauses) {
8902     if (Clause->getClauseKind() == OMPC_nowait)
8903       Nowait = Clause;
8904     else if (Clause->getClauseKind() == OMPC_copyprivate)
8905       Copyprivate = Clause;
8906     if (Copyprivate && Nowait) {
8907       Diag(Copyprivate->getBeginLoc(),
8908            diag::err_omp_single_copyprivate_with_nowait);
8909       Diag(Nowait->getBeginLoc(), diag::note_omp_nowait_clause_here);
8910       return StmtError();
8911     }
8912   }
8913 
8914   return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
8915 }
8916 
8917 StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt,
8918                                             SourceLocation StartLoc,
8919                                             SourceLocation EndLoc) {
8920   if (!AStmt)
8921     return StmtError();
8922 
8923   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
8924 
8925   setFunctionHasBranchProtectedScope();
8926 
8927   return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt);
8928 }
8929 
8930 StmtResult Sema::ActOnOpenMPCriticalDirective(
8931     const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses,
8932     Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
8933   if (!AStmt)
8934     return StmtError();
8935 
8936   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
8937 
8938   bool ErrorFound = false;
8939   llvm::APSInt Hint;
8940   SourceLocation HintLoc;
8941   bool DependentHint = false;
8942   for (const OMPClause *C : Clauses) {
8943     if (C->getClauseKind() == OMPC_hint) {
8944       if (!DirName.getName()) {
8945         Diag(C->getBeginLoc(), diag::err_omp_hint_clause_no_name);
8946         ErrorFound = true;
8947       }
8948       Expr *E = cast<OMPHintClause>(C)->getHint();
8949       if (E->isTypeDependent() || E->isValueDependent() ||
8950           E->isInstantiationDependent()) {
8951         DependentHint = true;
8952       } else {
8953         Hint = E->EvaluateKnownConstInt(Context);
8954         HintLoc = C->getBeginLoc();
8955       }
8956     }
8957   }
8958   if (ErrorFound)
8959     return StmtError();
8960   const auto Pair = DSAStack->getCriticalWithHint(DirName);
8961   if (Pair.first && DirName.getName() && !DependentHint) {
8962     if (llvm::APSInt::compareValues(Hint, Pair.second) != 0) {
8963       Diag(StartLoc, diag::err_omp_critical_with_hint);
8964       if (HintLoc.isValid())
8965         Diag(HintLoc, diag::note_omp_critical_hint_here)
8966             << 0 << Hint.toString(/*Radix=*/10, /*Signed=*/false);
8967       else
8968         Diag(StartLoc, diag::note_omp_critical_no_hint) << 0;
8969       if (const auto *C = Pair.first->getSingleClause<OMPHintClause>()) {
8970         Diag(C->getBeginLoc(), diag::note_omp_critical_hint_here)
8971             << 1
8972             << C->getHint()->EvaluateKnownConstInt(Context).toString(
8973                    /*Radix=*/10, /*Signed=*/false);
8974       } else {
8975         Diag(Pair.first->getBeginLoc(), diag::note_omp_critical_no_hint) << 1;
8976       }
8977     }
8978   }
8979 
8980   setFunctionHasBranchProtectedScope();
8981 
8982   auto *Dir = OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc,
8983                                            Clauses, AStmt);
8984   if (!Pair.first && DirName.getName() && !DependentHint)
8985     DSAStack->addCriticalWithHint(Dir, Hint);
8986   return Dir;
8987 }
8988 
8989 StmtResult Sema::ActOnOpenMPParallelForDirective(
8990     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8991     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
8992   if (!AStmt)
8993     return StmtError();
8994 
8995   auto *CS = cast<CapturedStmt>(AStmt);
8996   // 1.2.2 OpenMP Language Terminology
8997   // Structured block - An executable statement with a single entry at the
8998   // top and a single exit at the bottom.
8999   // The point of exit cannot be a branch out of the structured block.
9000   // longjmp() and throw() must not violate the entry/exit criteria.
9001   CS->getCapturedDecl()->setNothrow();
9002 
9003   OMPLoopDirective::HelperExprs B;
9004   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
9005   // define the nested loops number.
9006   unsigned NestedLoopCount =
9007       checkOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses),
9008                       getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
9009                       VarsWithImplicitDSA, B);
9010   if (NestedLoopCount == 0)
9011     return StmtError();
9012 
9013   assert((CurContext->isDependentContext() || B.builtAll()) &&
9014          "omp parallel for loop exprs were not built");
9015 
9016   if (!CurContext->isDependentContext()) {
9017     // Finalize the clauses that need pre-built expressions for CodeGen.
9018     for (OMPClause *C : Clauses) {
9019       if (auto *LC = dyn_cast<OMPLinearClause>(C))
9020         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
9021                                      B.NumIterations, *this, CurScope,
9022                                      DSAStack))
9023           return StmtError();
9024     }
9025   }
9026 
9027   setFunctionHasBranchProtectedScope();
9028   return OMPParallelForDirective::Create(
9029       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
9030       DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion());
9031 }
9032 
9033 StmtResult Sema::ActOnOpenMPParallelForSimdDirective(
9034     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
9035     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
9036   if (!AStmt)
9037     return StmtError();
9038 
9039   auto *CS = cast<CapturedStmt>(AStmt);
9040   // 1.2.2 OpenMP Language Terminology
9041   // Structured block - An executable statement with a single entry at the
9042   // top and a single exit at the bottom.
9043   // The point of exit cannot be a branch out of the structured block.
9044   // longjmp() and throw() must not violate the entry/exit criteria.
9045   CS->getCapturedDecl()->setNothrow();
9046 
9047   OMPLoopDirective::HelperExprs B;
9048   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
9049   // define the nested loops number.
9050   unsigned NestedLoopCount =
9051       checkOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses),
9052                       getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
9053                       VarsWithImplicitDSA, B);
9054   if (NestedLoopCount == 0)
9055     return StmtError();
9056 
9057   if (!CurContext->isDependentContext()) {
9058     // Finalize the clauses that need pre-built expressions for CodeGen.
9059     for (OMPClause *C : Clauses) {
9060       if (auto *LC = dyn_cast<OMPLinearClause>(C))
9061         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
9062                                      B.NumIterations, *this, CurScope,
9063                                      DSAStack))
9064           return StmtError();
9065     }
9066   }
9067 
9068   if (checkSimdlenSafelenSpecified(*this, Clauses))
9069     return StmtError();
9070 
9071   setFunctionHasBranchProtectedScope();
9072   return OMPParallelForSimdDirective::Create(
9073       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
9074 }
9075 
9076 StmtResult
9077 Sema::ActOnOpenMPParallelMasterDirective(ArrayRef<OMPClause *> Clauses,
9078                                          Stmt *AStmt, SourceLocation StartLoc,
9079                                          SourceLocation EndLoc) {
9080   if (!AStmt)
9081     return StmtError();
9082 
9083   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
9084   auto *CS = cast<CapturedStmt>(AStmt);
9085   // 1.2.2 OpenMP Language Terminology
9086   // Structured block - An executable statement with a single entry at the
9087   // top and a single exit at the bottom.
9088   // The point of exit cannot be a branch out of the structured block.
9089   // longjmp() and throw() must not violate the entry/exit criteria.
9090   CS->getCapturedDecl()->setNothrow();
9091 
9092   setFunctionHasBranchProtectedScope();
9093 
9094   return OMPParallelMasterDirective::Create(
9095       Context, StartLoc, EndLoc, Clauses, AStmt,
9096       DSAStack->getTaskgroupReductionRef());
9097 }
9098 
9099 StmtResult
9100 Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
9101                                            Stmt *AStmt, SourceLocation StartLoc,
9102                                            SourceLocation EndLoc) {
9103   if (!AStmt)
9104     return StmtError();
9105 
9106   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
9107   auto BaseStmt = AStmt;
9108   while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
9109     BaseStmt = CS->getCapturedStmt();
9110   if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
9111     auto S = C->children();
9112     if (S.begin() == S.end())
9113       return StmtError();
9114     // All associated statements must be '#pragma omp section' except for
9115     // the first one.
9116     for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
9117       if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
9118         if (SectionStmt)
9119           Diag(SectionStmt->getBeginLoc(),
9120                diag::err_omp_parallel_sections_substmt_not_section);
9121         return StmtError();
9122       }
9123       cast<OMPSectionDirective>(SectionStmt)
9124           ->setHasCancel(DSAStack->isCancelRegion());
9125     }
9126   } else {
9127     Diag(AStmt->getBeginLoc(),
9128          diag::err_omp_parallel_sections_not_compound_stmt);
9129     return StmtError();
9130   }
9131 
9132   setFunctionHasBranchProtectedScope();
9133 
9134   return OMPParallelSectionsDirective::Create(
9135       Context, StartLoc, EndLoc, Clauses, AStmt,
9136       DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion());
9137 }
9138 
9139 /// detach and mergeable clauses are mutially exclusive, check for it.
9140 static bool checkDetachMergeableClauses(Sema &S,
9141                                         ArrayRef<OMPClause *> Clauses) {
9142   const OMPClause *PrevClause = nullptr;
9143   bool ErrorFound = false;
9144   for (const OMPClause *C : Clauses) {
9145     if (C->getClauseKind() == OMPC_detach ||
9146         C->getClauseKind() == OMPC_mergeable) {
9147       if (!PrevClause) {
9148         PrevClause = C;
9149       } else if (PrevClause->getClauseKind() != C->getClauseKind()) {
9150         S.Diag(C->getBeginLoc(), diag::err_omp_clauses_mutually_exclusive)
9151             << getOpenMPClauseName(C->getClauseKind())
9152             << getOpenMPClauseName(PrevClause->getClauseKind());
9153         S.Diag(PrevClause->getBeginLoc(), diag::note_omp_previous_clause)
9154             << getOpenMPClauseName(PrevClause->getClauseKind());
9155         ErrorFound = true;
9156       }
9157     }
9158   }
9159   return ErrorFound;
9160 }
9161 
9162 StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
9163                                           Stmt *AStmt, SourceLocation StartLoc,
9164                                           SourceLocation EndLoc) {
9165   if (!AStmt)
9166     return StmtError();
9167 
9168   // OpenMP 5.0, 2.10.1 task Construct
9169   // If a detach clause appears on the directive, then a mergeable clause cannot
9170   // appear on the same directive.
9171   if (checkDetachMergeableClauses(*this, Clauses))
9172     return StmtError();
9173 
9174   auto *CS = cast<CapturedStmt>(AStmt);
9175   // 1.2.2 OpenMP Language Terminology
9176   // Structured block - An executable statement with a single entry at the
9177   // top and a single exit at the bottom.
9178   // The point of exit cannot be a branch out of the structured block.
9179   // longjmp() and throw() must not violate the entry/exit criteria.
9180   CS->getCapturedDecl()->setNothrow();
9181 
9182   setFunctionHasBranchProtectedScope();
9183 
9184   return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
9185                                   DSAStack->isCancelRegion());
9186 }
9187 
9188 StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
9189                                                SourceLocation EndLoc) {
9190   return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc);
9191 }
9192 
9193 StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
9194                                              SourceLocation EndLoc) {
9195   return OMPBarrierDirective::Create(Context, StartLoc, EndLoc);
9196 }
9197 
9198 StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
9199                                               SourceLocation EndLoc) {
9200   return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc);
9201 }
9202 
9203 StmtResult Sema::ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses,
9204                                                Stmt *AStmt,
9205                                                SourceLocation StartLoc,
9206                                                SourceLocation EndLoc) {
9207   if (!AStmt)
9208     return StmtError();
9209 
9210   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
9211 
9212   setFunctionHasBranchProtectedScope();
9213 
9214   return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, Clauses,
9215                                        AStmt,
9216                                        DSAStack->getTaskgroupReductionRef());
9217 }
9218 
9219 StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
9220                                            SourceLocation StartLoc,
9221                                            SourceLocation EndLoc) {
9222   OMPFlushClause *FC = nullptr;
9223   OMPClause *OrderClause = nullptr;
9224   for (OMPClause *C : Clauses) {
9225     if (C->getClauseKind() == OMPC_flush)
9226       FC = cast<OMPFlushClause>(C);
9227     else
9228       OrderClause = C;
9229   }
9230   OpenMPClauseKind MemOrderKind = OMPC_unknown;
9231   SourceLocation MemOrderLoc;
9232   for (const OMPClause *C : Clauses) {
9233     if (C->getClauseKind() == OMPC_acq_rel ||
9234         C->getClauseKind() == OMPC_acquire ||
9235         C->getClauseKind() == OMPC_release) {
9236       if (MemOrderKind != OMPC_unknown) {
9237         Diag(C->getBeginLoc(), diag::err_omp_several_mem_order_clauses)
9238             << getOpenMPDirectiveName(OMPD_flush) << 1
9239             << SourceRange(C->getBeginLoc(), C->getEndLoc());
9240         Diag(MemOrderLoc, diag::note_omp_previous_mem_order_clause)
9241             << getOpenMPClauseName(MemOrderKind);
9242       } else {
9243         MemOrderKind = C->getClauseKind();
9244         MemOrderLoc = C->getBeginLoc();
9245       }
9246     }
9247   }
9248   if (FC && OrderClause) {
9249     Diag(FC->getLParenLoc(), diag::err_omp_flush_order_clause_and_list)
9250         << getOpenMPClauseName(OrderClause->getClauseKind());
9251     Diag(OrderClause->getBeginLoc(), diag::note_omp_flush_order_clause_here)
9252         << getOpenMPClauseName(OrderClause->getClauseKind());
9253     return StmtError();
9254   }
9255   return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses);
9256 }
9257 
9258 StmtResult Sema::ActOnOpenMPDepobjDirective(ArrayRef<OMPClause *> Clauses,
9259                                             SourceLocation StartLoc,
9260                                             SourceLocation EndLoc) {
9261   if (Clauses.empty()) {
9262     Diag(StartLoc, diag::err_omp_depobj_expected);
9263     return StmtError();
9264   } else if (Clauses[0]->getClauseKind() != OMPC_depobj) {
9265     Diag(Clauses[0]->getBeginLoc(), diag::err_omp_depobj_expected);
9266     return StmtError();
9267   }
9268   // Only depobj expression and another single clause is allowed.
9269   if (Clauses.size() > 2) {
9270     Diag(Clauses[2]->getBeginLoc(),
9271          diag::err_omp_depobj_single_clause_expected);
9272     return StmtError();
9273   } else if (Clauses.size() < 1) {
9274     Diag(Clauses[0]->getEndLoc(), diag::err_omp_depobj_single_clause_expected);
9275     return StmtError();
9276   }
9277   return OMPDepobjDirective::Create(Context, StartLoc, EndLoc, Clauses);
9278 }
9279 
9280 StmtResult Sema::ActOnOpenMPScanDirective(ArrayRef<OMPClause *> Clauses,
9281                                           SourceLocation StartLoc,
9282                                           SourceLocation EndLoc) {
9283   // Check that exactly one clause is specified.
9284   if (Clauses.size() != 1) {
9285     Diag(Clauses.empty() ? EndLoc : Clauses[1]->getBeginLoc(),
9286          diag::err_omp_scan_single_clause_expected);
9287     return StmtError();
9288   }
9289   // Check that scan directive is used in the scopeof the OpenMP loop body.
9290   if (Scope *S = DSAStack->getCurScope()) {
9291     Scope *ParentS = S->getParent();
9292     if (!ParentS || ParentS->getParent() != ParentS->getBreakParent() ||
9293         !ParentS->getBreakParent()->isOpenMPLoopScope())
9294       return StmtError(Diag(StartLoc, diag::err_omp_orphaned_device_directive)
9295                        << getOpenMPDirectiveName(OMPD_scan) << 5);
9296   }
9297   // Check that only one instance of scan directives is used in the same outer
9298   // region.
9299   if (DSAStack->doesParentHasScanDirective()) {
9300     Diag(StartLoc, diag::err_omp_several_directives_in_region) << "scan";
9301     Diag(DSAStack->getParentScanDirectiveLoc(),
9302          diag::note_omp_previous_directive)
9303         << "scan";
9304     return StmtError();
9305   }
9306   DSAStack->setParentHasScanDirective(StartLoc);
9307   return OMPScanDirective::Create(Context, StartLoc, EndLoc, Clauses);
9308 }
9309 
9310 StmtResult Sema::ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
9311                                              Stmt *AStmt,
9312                                              SourceLocation StartLoc,
9313                                              SourceLocation EndLoc) {
9314   const OMPClause *DependFound = nullptr;
9315   const OMPClause *DependSourceClause = nullptr;
9316   const OMPClause *DependSinkClause = nullptr;
9317   bool ErrorFound = false;
9318   const OMPThreadsClause *TC = nullptr;
9319   const OMPSIMDClause *SC = nullptr;
9320   for (const OMPClause *C : Clauses) {
9321     if (auto *DC = dyn_cast<OMPDependClause>(C)) {
9322       DependFound = C;
9323       if (DC->getDependencyKind() == OMPC_DEPEND_source) {
9324         if (DependSourceClause) {
9325           Diag(C->getBeginLoc(), diag::err_omp_more_one_clause)
9326               << getOpenMPDirectiveName(OMPD_ordered)
9327               << getOpenMPClauseName(OMPC_depend) << 2;
9328           ErrorFound = true;
9329         } else {
9330           DependSourceClause = C;
9331         }
9332         if (DependSinkClause) {
9333           Diag(C->getBeginLoc(), diag::err_omp_depend_sink_source_not_allowed)
9334               << 0;
9335           ErrorFound = true;
9336         }
9337       } else if (DC->getDependencyKind() == OMPC_DEPEND_sink) {
9338         if (DependSourceClause) {
9339           Diag(C->getBeginLoc(), diag::err_omp_depend_sink_source_not_allowed)
9340               << 1;
9341           ErrorFound = true;
9342         }
9343         DependSinkClause = C;
9344       }
9345     } else if (C->getClauseKind() == OMPC_threads) {
9346       TC = cast<OMPThreadsClause>(C);
9347     } else if (C->getClauseKind() == OMPC_simd) {
9348       SC = cast<OMPSIMDClause>(C);
9349     }
9350   }
9351   if (!ErrorFound && !SC &&
9352       isOpenMPSimdDirective(DSAStack->getParentDirective())) {
9353     // OpenMP [2.8.1,simd Construct, Restrictions]
9354     // An ordered construct with the simd clause is the only OpenMP construct
9355     // that can appear in the simd region.
9356     Diag(StartLoc, diag::err_omp_prohibited_region_simd)
9357         << (LangOpts.OpenMP >= 50 ? 1 : 0);
9358     ErrorFound = true;
9359   } else if (DependFound && (TC || SC)) {
9360     Diag(DependFound->getBeginLoc(), diag::err_omp_depend_clause_thread_simd)
9361         << getOpenMPClauseName(TC ? TC->getClauseKind() : SC->getClauseKind());
9362     ErrorFound = true;
9363   } else if (DependFound && !DSAStack->getParentOrderedRegionParam().first) {
9364     Diag(DependFound->getBeginLoc(),
9365          diag::err_omp_ordered_directive_without_param);
9366     ErrorFound = true;
9367   } else if (TC || Clauses.empty()) {
9368     if (const Expr *Param = DSAStack->getParentOrderedRegionParam().first) {
9369       SourceLocation ErrLoc = TC ? TC->getBeginLoc() : StartLoc;
9370       Diag(ErrLoc, diag::err_omp_ordered_directive_with_param)
9371           << (TC != nullptr);
9372       Diag(Param->getBeginLoc(), diag::note_omp_ordered_param) << 1;
9373       ErrorFound = true;
9374     }
9375   }
9376   if ((!AStmt && !DependFound) || ErrorFound)
9377     return StmtError();
9378 
9379   // OpenMP 5.0, 2.17.9, ordered Construct, Restrictions.
9380   // During execution of an iteration of a worksharing-loop or a loop nest
9381   // within a worksharing-loop, simd, or worksharing-loop SIMD region, a thread
9382   // must not execute more than one ordered region corresponding to an ordered
9383   // construct without a depend clause.
9384   if (!DependFound) {
9385     if (DSAStack->doesParentHasOrderedDirective()) {
9386       Diag(StartLoc, diag::err_omp_several_directives_in_region) << "ordered";
9387       Diag(DSAStack->getParentOrderedDirectiveLoc(),
9388            diag::note_omp_previous_directive)
9389           << "ordered";
9390       return StmtError();
9391     }
9392     DSAStack->setParentHasOrderedDirective(StartLoc);
9393   }
9394 
9395   if (AStmt) {
9396     assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
9397 
9398     setFunctionHasBranchProtectedScope();
9399   }
9400 
9401   return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
9402 }
9403 
9404 namespace {
9405 /// Helper class for checking expression in 'omp atomic [update]'
9406 /// construct.
9407 class OpenMPAtomicUpdateChecker {
9408   /// Error results for atomic update expressions.
9409   enum ExprAnalysisErrorCode {
9410     /// A statement is not an expression statement.
9411     NotAnExpression,
9412     /// Expression is not builtin binary or unary operation.
9413     NotABinaryOrUnaryExpression,
9414     /// Unary operation is not post-/pre- increment/decrement operation.
9415     NotAnUnaryIncDecExpression,
9416     /// An expression is not of scalar type.
9417     NotAScalarType,
9418     /// A binary operation is not an assignment operation.
9419     NotAnAssignmentOp,
9420     /// RHS part of the binary operation is not a binary expression.
9421     NotABinaryExpression,
9422     /// RHS part is not additive/multiplicative/shift/biwise binary
9423     /// expression.
9424     NotABinaryOperator,
9425     /// RHS binary operation does not have reference to the updated LHS
9426     /// part.
9427     NotAnUpdateExpression,
9428     /// No errors is found.
9429     NoError
9430   };
9431   /// Reference to Sema.
9432   Sema &SemaRef;
9433   /// A location for note diagnostics (when error is found).
9434   SourceLocation NoteLoc;
9435   /// 'x' lvalue part of the source atomic expression.
9436   Expr *X;
9437   /// 'expr' rvalue part of the source atomic expression.
9438   Expr *E;
9439   /// Helper expression of the form
9440   /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
9441   /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
9442   Expr *UpdateExpr;
9443   /// Is 'x' a LHS in a RHS part of full update expression. It is
9444   /// important for non-associative operations.
9445   bool IsXLHSInRHSPart;
9446   BinaryOperatorKind Op;
9447   SourceLocation OpLoc;
9448   /// true if the source expression is a postfix unary operation, false
9449   /// if it is a prefix unary operation.
9450   bool IsPostfixUpdate;
9451 
9452 public:
9453   OpenMPAtomicUpdateChecker(Sema &SemaRef)
9454       : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr),
9455         IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {}
9456   /// Check specified statement that it is suitable for 'atomic update'
9457   /// constructs and extract 'x', 'expr' and Operation from the original
9458   /// expression. If DiagId and NoteId == 0, then only check is performed
9459   /// without error notification.
9460   /// \param DiagId Diagnostic which should be emitted if error is found.
9461   /// \param NoteId Diagnostic note for the main error message.
9462   /// \return true if statement is not an update expression, false otherwise.
9463   bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0);
9464   /// Return the 'x' lvalue part of the source atomic expression.
9465   Expr *getX() const { return X; }
9466   /// Return the 'expr' rvalue part of the source atomic expression.
9467   Expr *getExpr() const { return E; }
9468   /// Return the update expression used in calculation of the updated
9469   /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
9470   /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
9471   Expr *getUpdateExpr() const { return UpdateExpr; }
9472   /// Return true if 'x' is LHS in RHS part of full update expression,
9473   /// false otherwise.
9474   bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; }
9475 
9476   /// true if the source expression is a postfix unary operation, false
9477   /// if it is a prefix unary operation.
9478   bool isPostfixUpdate() const { return IsPostfixUpdate; }
9479 
9480 private:
9481   bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0,
9482                             unsigned NoteId = 0);
9483 };
9484 } // namespace
9485 
9486 bool OpenMPAtomicUpdateChecker::checkBinaryOperation(
9487     BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) {
9488   ExprAnalysisErrorCode ErrorFound = NoError;
9489   SourceLocation ErrorLoc, NoteLoc;
9490   SourceRange ErrorRange, NoteRange;
9491   // Allowed constructs are:
9492   //  x = x binop expr;
9493   //  x = expr binop x;
9494   if (AtomicBinOp->getOpcode() == BO_Assign) {
9495     X = AtomicBinOp->getLHS();
9496     if (const auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>(
9497             AtomicBinOp->getRHS()->IgnoreParenImpCasts())) {
9498       if (AtomicInnerBinOp->isMultiplicativeOp() ||
9499           AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() ||
9500           AtomicInnerBinOp->isBitwiseOp()) {
9501         Op = AtomicInnerBinOp->getOpcode();
9502         OpLoc = AtomicInnerBinOp->getOperatorLoc();
9503         Expr *LHS = AtomicInnerBinOp->getLHS();
9504         Expr *RHS = AtomicInnerBinOp->getRHS();
9505         llvm::FoldingSetNodeID XId, LHSId, RHSId;
9506         X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(),
9507                                           /*Canonical=*/true);
9508         LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(),
9509                                             /*Canonical=*/true);
9510         RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(),
9511                                             /*Canonical=*/true);
9512         if (XId == LHSId) {
9513           E = RHS;
9514           IsXLHSInRHSPart = true;
9515         } else if (XId == RHSId) {
9516           E = LHS;
9517           IsXLHSInRHSPart = false;
9518         } else {
9519           ErrorLoc = AtomicInnerBinOp->getExprLoc();
9520           ErrorRange = AtomicInnerBinOp->getSourceRange();
9521           NoteLoc = X->getExprLoc();
9522           NoteRange = X->getSourceRange();
9523           ErrorFound = NotAnUpdateExpression;
9524         }
9525       } else {
9526         ErrorLoc = AtomicInnerBinOp->getExprLoc();
9527         ErrorRange = AtomicInnerBinOp->getSourceRange();
9528         NoteLoc = AtomicInnerBinOp->getOperatorLoc();
9529         NoteRange = SourceRange(NoteLoc, NoteLoc);
9530         ErrorFound = NotABinaryOperator;
9531       }
9532     } else {
9533       NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc();
9534       NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange();
9535       ErrorFound = NotABinaryExpression;
9536     }
9537   } else {
9538     ErrorLoc = AtomicBinOp->getExprLoc();
9539     ErrorRange = AtomicBinOp->getSourceRange();
9540     NoteLoc = AtomicBinOp->getOperatorLoc();
9541     NoteRange = SourceRange(NoteLoc, NoteLoc);
9542     ErrorFound = NotAnAssignmentOp;
9543   }
9544   if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
9545     SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
9546     SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
9547     return true;
9548   }
9549   if (SemaRef.CurContext->isDependentContext())
9550     E = X = UpdateExpr = nullptr;
9551   return ErrorFound != NoError;
9552 }
9553 
9554 bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId,
9555                                                unsigned NoteId) {
9556   ExprAnalysisErrorCode ErrorFound = NoError;
9557   SourceLocation ErrorLoc, NoteLoc;
9558   SourceRange ErrorRange, NoteRange;
9559   // Allowed constructs are:
9560   //  x++;
9561   //  x--;
9562   //  ++x;
9563   //  --x;
9564   //  x binop= expr;
9565   //  x = x binop expr;
9566   //  x = expr binop x;
9567   if (auto *AtomicBody = dyn_cast<Expr>(S)) {
9568     AtomicBody = AtomicBody->IgnoreParenImpCasts();
9569     if (AtomicBody->getType()->isScalarType() ||
9570         AtomicBody->isInstantiationDependent()) {
9571       if (const auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>(
9572               AtomicBody->IgnoreParenImpCasts())) {
9573         // Check for Compound Assignment Operation
9574         Op = BinaryOperator::getOpForCompoundAssignment(
9575             AtomicCompAssignOp->getOpcode());
9576         OpLoc = AtomicCompAssignOp->getOperatorLoc();
9577         E = AtomicCompAssignOp->getRHS();
9578         X = AtomicCompAssignOp->getLHS()->IgnoreParens();
9579         IsXLHSInRHSPart = true;
9580       } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>(
9581                      AtomicBody->IgnoreParenImpCasts())) {
9582         // Check for Binary Operation
9583         if (checkBinaryOperation(AtomicBinOp, DiagId, NoteId))
9584           return true;
9585       } else if (const auto *AtomicUnaryOp = dyn_cast<UnaryOperator>(
9586                      AtomicBody->IgnoreParenImpCasts())) {
9587         // Check for Unary Operation
9588         if (AtomicUnaryOp->isIncrementDecrementOp()) {
9589           IsPostfixUpdate = AtomicUnaryOp->isPostfix();
9590           Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub;
9591           OpLoc = AtomicUnaryOp->getOperatorLoc();
9592           X = AtomicUnaryOp->getSubExpr()->IgnoreParens();
9593           E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get();
9594           IsXLHSInRHSPart = true;
9595         } else {
9596           ErrorFound = NotAnUnaryIncDecExpression;
9597           ErrorLoc = AtomicUnaryOp->getExprLoc();
9598           ErrorRange = AtomicUnaryOp->getSourceRange();
9599           NoteLoc = AtomicUnaryOp->getOperatorLoc();
9600           NoteRange = SourceRange(NoteLoc, NoteLoc);
9601         }
9602       } else if (!AtomicBody->isInstantiationDependent()) {
9603         ErrorFound = NotABinaryOrUnaryExpression;
9604         NoteLoc = ErrorLoc = AtomicBody->getExprLoc();
9605         NoteRange = ErrorRange = AtomicBody->getSourceRange();
9606       }
9607     } else {
9608       ErrorFound = NotAScalarType;
9609       NoteLoc = ErrorLoc = AtomicBody->getBeginLoc();
9610       NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
9611     }
9612   } else {
9613     ErrorFound = NotAnExpression;
9614     NoteLoc = ErrorLoc = S->getBeginLoc();
9615     NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
9616   }
9617   if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
9618     SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
9619     SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
9620     return true;
9621   }
9622   if (SemaRef.CurContext->isDependentContext())
9623     E = X = UpdateExpr = nullptr;
9624   if (ErrorFound == NoError && E && X) {
9625     // Build an update expression of form 'OpaqueValueExpr(x) binop
9626     // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop
9627     // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression.
9628     auto *OVEX = new (SemaRef.getASTContext())
9629         OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue);
9630     auto *OVEExpr = new (SemaRef.getASTContext())
9631         OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue);
9632     ExprResult Update =
9633         SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr,
9634                                    IsXLHSInRHSPart ? OVEExpr : OVEX);
9635     if (Update.isInvalid())
9636       return true;
9637     Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(),
9638                                                Sema::AA_Casting);
9639     if (Update.isInvalid())
9640       return true;
9641     UpdateExpr = Update.get();
9642   }
9643   return ErrorFound != NoError;
9644 }
9645 
9646 StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
9647                                             Stmt *AStmt,
9648                                             SourceLocation StartLoc,
9649                                             SourceLocation EndLoc) {
9650   // Register location of the first atomic directive.
9651   DSAStack->addAtomicDirectiveLoc(StartLoc);
9652   if (!AStmt)
9653     return StmtError();
9654 
9655   auto *CS = cast<CapturedStmt>(AStmt);
9656   // 1.2.2 OpenMP Language Terminology
9657   // Structured block - An executable statement with a single entry at the
9658   // top and a single exit at the bottom.
9659   // The point of exit cannot be a branch out of the structured block.
9660   // longjmp() and throw() must not violate the entry/exit criteria.
9661   OpenMPClauseKind AtomicKind = OMPC_unknown;
9662   SourceLocation AtomicKindLoc;
9663   OpenMPClauseKind MemOrderKind = OMPC_unknown;
9664   SourceLocation MemOrderLoc;
9665   for (const OMPClause *C : Clauses) {
9666     if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write ||
9667         C->getClauseKind() == OMPC_update ||
9668         C->getClauseKind() == OMPC_capture) {
9669       if (AtomicKind != OMPC_unknown) {
9670         Diag(C->getBeginLoc(), diag::err_omp_atomic_several_clauses)
9671             << SourceRange(C->getBeginLoc(), C->getEndLoc());
9672         Diag(AtomicKindLoc, diag::note_omp_previous_mem_order_clause)
9673             << getOpenMPClauseName(AtomicKind);
9674       } else {
9675         AtomicKind = C->getClauseKind();
9676         AtomicKindLoc = C->getBeginLoc();
9677       }
9678     }
9679     if (C->getClauseKind() == OMPC_seq_cst ||
9680         C->getClauseKind() == OMPC_acq_rel ||
9681         C->getClauseKind() == OMPC_acquire ||
9682         C->getClauseKind() == OMPC_release ||
9683         C->getClauseKind() == OMPC_relaxed) {
9684       if (MemOrderKind != OMPC_unknown) {
9685         Diag(C->getBeginLoc(), diag::err_omp_several_mem_order_clauses)
9686             << getOpenMPDirectiveName(OMPD_atomic) << 0
9687             << SourceRange(C->getBeginLoc(), C->getEndLoc());
9688         Diag(MemOrderLoc, diag::note_omp_previous_mem_order_clause)
9689             << getOpenMPClauseName(MemOrderKind);
9690       } else {
9691         MemOrderKind = C->getClauseKind();
9692         MemOrderLoc = C->getBeginLoc();
9693       }
9694     }
9695   }
9696   // OpenMP 5.0, 2.17.7 atomic Construct, Restrictions
9697   // If atomic-clause is read then memory-order-clause must not be acq_rel or
9698   // release.
9699   // If atomic-clause is write then memory-order-clause must not be acq_rel or
9700   // acquire.
9701   // If atomic-clause is update or not present then memory-order-clause must not
9702   // be acq_rel or acquire.
9703   if ((AtomicKind == OMPC_read &&
9704        (MemOrderKind == OMPC_acq_rel || MemOrderKind == OMPC_release)) ||
9705       ((AtomicKind == OMPC_write || AtomicKind == OMPC_update ||
9706         AtomicKind == OMPC_unknown) &&
9707        (MemOrderKind == OMPC_acq_rel || MemOrderKind == OMPC_acquire))) {
9708     SourceLocation Loc = AtomicKindLoc;
9709     if (AtomicKind == OMPC_unknown)
9710       Loc = StartLoc;
9711     Diag(Loc, diag::err_omp_atomic_incompatible_mem_order_clause)
9712         << getOpenMPClauseName(AtomicKind)
9713         << (AtomicKind == OMPC_unknown ? 1 : 0)
9714         << getOpenMPClauseName(MemOrderKind);
9715     Diag(MemOrderLoc, diag::note_omp_previous_mem_order_clause)
9716         << getOpenMPClauseName(MemOrderKind);
9717   }
9718 
9719   Stmt *Body = CS->getCapturedStmt();
9720   if (auto *EWC = dyn_cast<ExprWithCleanups>(Body))
9721     Body = EWC->getSubExpr();
9722 
9723   Expr *X = nullptr;
9724   Expr *V = nullptr;
9725   Expr *E = nullptr;
9726   Expr *UE = nullptr;
9727   bool IsXLHSInRHSPart = false;
9728   bool IsPostfixUpdate = false;
9729   // OpenMP [2.12.6, atomic Construct]
9730   // In the next expressions:
9731   // * x and v (as applicable) are both l-value expressions with scalar type.
9732   // * During the execution of an atomic region, multiple syntactic
9733   // occurrences of x must designate the same storage location.
9734   // * Neither of v and expr (as applicable) may access the storage location
9735   // designated by x.
9736   // * Neither of x and expr (as applicable) may access the storage location
9737   // designated by v.
9738   // * expr is an expression with scalar type.
9739   // * binop is one of +, *, -, /, &, ^, |, <<, or >>.
9740   // * binop, binop=, ++, and -- are not overloaded operators.
9741   // * The expression x binop expr must be numerically equivalent to x binop
9742   // (expr). This requirement is satisfied if the operators in expr have
9743   // precedence greater than binop, or by using parentheses around expr or
9744   // subexpressions of expr.
9745   // * The expression expr binop x must be numerically equivalent to (expr)
9746   // binop x. This requirement is satisfied if the operators in expr have
9747   // precedence equal to or greater than binop, or by using parentheses around
9748   // expr or subexpressions of expr.
9749   // * For forms that allow multiple occurrences of x, the number of times
9750   // that x is evaluated is unspecified.
9751   if (AtomicKind == OMPC_read) {
9752     enum {
9753       NotAnExpression,
9754       NotAnAssignmentOp,
9755       NotAScalarType,
9756       NotAnLValue,
9757       NoError
9758     } ErrorFound = NoError;
9759     SourceLocation ErrorLoc, NoteLoc;
9760     SourceRange ErrorRange, NoteRange;
9761     // If clause is read:
9762     //  v = x;
9763     if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
9764       const auto *AtomicBinOp =
9765           dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
9766       if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
9767         X = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
9768         V = AtomicBinOp->getLHS()->IgnoreParenImpCasts();
9769         if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
9770             (V->isInstantiationDependent() || V->getType()->isScalarType())) {
9771           if (!X->isLValue() || !V->isLValue()) {
9772             const Expr *NotLValueExpr = X->isLValue() ? V : X;
9773             ErrorFound = NotAnLValue;
9774             ErrorLoc = AtomicBinOp->getExprLoc();
9775             ErrorRange = AtomicBinOp->getSourceRange();
9776             NoteLoc = NotLValueExpr->getExprLoc();
9777             NoteRange = NotLValueExpr->getSourceRange();
9778           }
9779         } else if (!X->isInstantiationDependent() ||
9780                    !V->isInstantiationDependent()) {
9781           const Expr *NotScalarExpr =
9782               (X->isInstantiationDependent() || X->getType()->isScalarType())
9783                   ? V
9784                   : X;
9785           ErrorFound = NotAScalarType;
9786           ErrorLoc = AtomicBinOp->getExprLoc();
9787           ErrorRange = AtomicBinOp->getSourceRange();
9788           NoteLoc = NotScalarExpr->getExprLoc();
9789           NoteRange = NotScalarExpr->getSourceRange();
9790         }
9791       } else if (!AtomicBody->isInstantiationDependent()) {
9792         ErrorFound = NotAnAssignmentOp;
9793         ErrorLoc = AtomicBody->getExprLoc();
9794         ErrorRange = AtomicBody->getSourceRange();
9795         NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
9796                               : AtomicBody->getExprLoc();
9797         NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
9798                                 : AtomicBody->getSourceRange();
9799       }
9800     } else {
9801       ErrorFound = NotAnExpression;
9802       NoteLoc = ErrorLoc = Body->getBeginLoc();
9803       NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
9804     }
9805     if (ErrorFound != NoError) {
9806       Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement)
9807           << ErrorRange;
9808       Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
9809                                                       << NoteRange;
9810       return StmtError();
9811     }
9812     if (CurContext->isDependentContext())
9813       V = X = nullptr;
9814   } else if (AtomicKind == OMPC_write) {
9815     enum {
9816       NotAnExpression,
9817       NotAnAssignmentOp,
9818       NotAScalarType,
9819       NotAnLValue,
9820       NoError
9821     } ErrorFound = NoError;
9822     SourceLocation ErrorLoc, NoteLoc;
9823     SourceRange ErrorRange, NoteRange;
9824     // If clause is write:
9825     //  x = expr;
9826     if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
9827       const auto *AtomicBinOp =
9828           dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
9829       if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
9830         X = AtomicBinOp->getLHS();
9831         E = AtomicBinOp->getRHS();
9832         if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
9833             (E->isInstantiationDependent() || E->getType()->isScalarType())) {
9834           if (!X->isLValue()) {
9835             ErrorFound = NotAnLValue;
9836             ErrorLoc = AtomicBinOp->getExprLoc();
9837             ErrorRange = AtomicBinOp->getSourceRange();
9838             NoteLoc = X->getExprLoc();
9839             NoteRange = X->getSourceRange();
9840           }
9841         } else if (!X->isInstantiationDependent() ||
9842                    !E->isInstantiationDependent()) {
9843           const Expr *NotScalarExpr =
9844               (X->isInstantiationDependent() || X->getType()->isScalarType())
9845                   ? E
9846                   : X;
9847           ErrorFound = NotAScalarType;
9848           ErrorLoc = AtomicBinOp->getExprLoc();
9849           ErrorRange = AtomicBinOp->getSourceRange();
9850           NoteLoc = NotScalarExpr->getExprLoc();
9851           NoteRange = NotScalarExpr->getSourceRange();
9852         }
9853       } else if (!AtomicBody->isInstantiationDependent()) {
9854         ErrorFound = NotAnAssignmentOp;
9855         ErrorLoc = AtomicBody->getExprLoc();
9856         ErrorRange = AtomicBody->getSourceRange();
9857         NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
9858                               : AtomicBody->getExprLoc();
9859         NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
9860                                 : AtomicBody->getSourceRange();
9861       }
9862     } else {
9863       ErrorFound = NotAnExpression;
9864       NoteLoc = ErrorLoc = Body->getBeginLoc();
9865       NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
9866     }
9867     if (ErrorFound != NoError) {
9868       Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement)
9869           << ErrorRange;
9870       Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
9871                                                       << NoteRange;
9872       return StmtError();
9873     }
9874     if (CurContext->isDependentContext())
9875       E = X = nullptr;
9876   } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) {
9877     // If clause is update:
9878     //  x++;
9879     //  x--;
9880     //  ++x;
9881     //  --x;
9882     //  x binop= expr;
9883     //  x = x binop expr;
9884     //  x = expr binop x;
9885     OpenMPAtomicUpdateChecker Checker(*this);
9886     if (Checker.checkStatement(
9887             Body, (AtomicKind == OMPC_update)
9888                       ? diag::err_omp_atomic_update_not_expression_statement
9889                       : diag::err_omp_atomic_not_expression_statement,
9890             diag::note_omp_atomic_update))
9891       return StmtError();
9892     if (!CurContext->isDependentContext()) {
9893       E = Checker.getExpr();
9894       X = Checker.getX();
9895       UE = Checker.getUpdateExpr();
9896       IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
9897     }
9898   } else if (AtomicKind == OMPC_capture) {
9899     enum {
9900       NotAnAssignmentOp,
9901       NotACompoundStatement,
9902       NotTwoSubstatements,
9903       NotASpecificExpression,
9904       NoError
9905     } ErrorFound = NoError;
9906     SourceLocation ErrorLoc, NoteLoc;
9907     SourceRange ErrorRange, NoteRange;
9908     if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
9909       // If clause is a capture:
9910       //  v = x++;
9911       //  v = x--;
9912       //  v = ++x;
9913       //  v = --x;
9914       //  v = x binop= expr;
9915       //  v = x = x binop expr;
9916       //  v = x = expr binop x;
9917       const auto *AtomicBinOp =
9918           dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
9919       if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
9920         V = AtomicBinOp->getLHS();
9921         Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
9922         OpenMPAtomicUpdateChecker Checker(*this);
9923         if (Checker.checkStatement(
9924                 Body, diag::err_omp_atomic_capture_not_expression_statement,
9925                 diag::note_omp_atomic_update))
9926           return StmtError();
9927         E = Checker.getExpr();
9928         X = Checker.getX();
9929         UE = Checker.getUpdateExpr();
9930         IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
9931         IsPostfixUpdate = Checker.isPostfixUpdate();
9932       } else if (!AtomicBody->isInstantiationDependent()) {
9933         ErrorLoc = AtomicBody->getExprLoc();
9934         ErrorRange = AtomicBody->getSourceRange();
9935         NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
9936                               : AtomicBody->getExprLoc();
9937         NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
9938                                 : AtomicBody->getSourceRange();
9939         ErrorFound = NotAnAssignmentOp;
9940       }
9941       if (ErrorFound != NoError) {
9942         Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement)
9943             << ErrorRange;
9944         Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
9945         return StmtError();
9946       }
9947       if (CurContext->isDependentContext())
9948         UE = V = E = X = nullptr;
9949     } else {
9950       // If clause is a capture:
9951       //  { v = x; x = expr; }
9952       //  { v = x; x++; }
9953       //  { v = x; x--; }
9954       //  { v = x; ++x; }
9955       //  { v = x; --x; }
9956       //  { v = x; x binop= expr; }
9957       //  { v = x; x = x binop expr; }
9958       //  { v = x; x = expr binop x; }
9959       //  { x++; v = x; }
9960       //  { x--; v = x; }
9961       //  { ++x; v = x; }
9962       //  { --x; v = x; }
9963       //  { x binop= expr; v = x; }
9964       //  { x = x binop expr; v = x; }
9965       //  { x = expr binop x; v = x; }
9966       if (auto *CS = dyn_cast<CompoundStmt>(Body)) {
9967         // Check that this is { expr1; expr2; }
9968         if (CS->size() == 2) {
9969           Stmt *First = CS->body_front();
9970           Stmt *Second = CS->body_back();
9971           if (auto *EWC = dyn_cast<ExprWithCleanups>(First))
9972             First = EWC->getSubExpr()->IgnoreParenImpCasts();
9973           if (auto *EWC = dyn_cast<ExprWithCleanups>(Second))
9974             Second = EWC->getSubExpr()->IgnoreParenImpCasts();
9975           // Need to find what subexpression is 'v' and what is 'x'.
9976           OpenMPAtomicUpdateChecker Checker(*this);
9977           bool IsUpdateExprFound = !Checker.checkStatement(Second);
9978           BinaryOperator *BinOp = nullptr;
9979           if (IsUpdateExprFound) {
9980             BinOp = dyn_cast<BinaryOperator>(First);
9981             IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
9982           }
9983           if (IsUpdateExprFound && !CurContext->isDependentContext()) {
9984             //  { v = x; x++; }
9985             //  { v = x; x--; }
9986             //  { v = x; ++x; }
9987             //  { v = x; --x; }
9988             //  { v = x; x binop= expr; }
9989             //  { v = x; x = x binop expr; }
9990             //  { v = x; x = expr binop x; }
9991             // Check that the first expression has form v = x.
9992             Expr *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
9993             llvm::FoldingSetNodeID XId, PossibleXId;
9994             Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
9995             PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
9996             IsUpdateExprFound = XId == PossibleXId;
9997             if (IsUpdateExprFound) {
9998               V = BinOp->getLHS();
9999               X = Checker.getX();
10000               E = Checker.getExpr();
10001               UE = Checker.getUpdateExpr();
10002               IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
10003               IsPostfixUpdate = true;
10004             }
10005           }
10006           if (!IsUpdateExprFound) {
10007             IsUpdateExprFound = !Checker.checkStatement(First);
10008             BinOp = nullptr;
10009             if (IsUpdateExprFound) {
10010               BinOp = dyn_cast<BinaryOperator>(Second);
10011               IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
10012             }
10013             if (IsUpdateExprFound && !CurContext->isDependentContext()) {
10014               //  { x++; v = x; }
10015               //  { x--; v = x; }
10016               //  { ++x; v = x; }
10017               //  { --x; v = x; }
10018               //  { x binop= expr; v = x; }
10019               //  { x = x binop expr; v = x; }
10020               //  { x = expr binop x; v = x; }
10021               // Check that the second expression has form v = x.
10022               Expr *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
10023               llvm::FoldingSetNodeID XId, PossibleXId;
10024               Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
10025               PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
10026               IsUpdateExprFound = XId == PossibleXId;
10027               if (IsUpdateExprFound) {
10028                 V = BinOp->getLHS();
10029                 X = Checker.getX();
10030                 E = Checker.getExpr();
10031                 UE = Checker.getUpdateExpr();
10032                 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
10033                 IsPostfixUpdate = false;
10034               }
10035             }
10036           }
10037           if (!IsUpdateExprFound) {
10038             //  { v = x; x = expr; }
10039             auto *FirstExpr = dyn_cast<Expr>(First);
10040             auto *SecondExpr = dyn_cast<Expr>(Second);
10041             if (!FirstExpr || !SecondExpr ||
10042                 !(FirstExpr->isInstantiationDependent() ||
10043                   SecondExpr->isInstantiationDependent())) {
10044               auto *FirstBinOp = dyn_cast<BinaryOperator>(First);
10045               if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) {
10046                 ErrorFound = NotAnAssignmentOp;
10047                 NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc()
10048                                                 : First->getBeginLoc();
10049                 NoteRange = ErrorRange = FirstBinOp
10050                                              ? FirstBinOp->getSourceRange()
10051                                              : SourceRange(ErrorLoc, ErrorLoc);
10052               } else {
10053                 auto *SecondBinOp = dyn_cast<BinaryOperator>(Second);
10054                 if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) {
10055                   ErrorFound = NotAnAssignmentOp;
10056                   NoteLoc = ErrorLoc = SecondBinOp
10057                                            ? SecondBinOp->getOperatorLoc()
10058                                            : Second->getBeginLoc();
10059                   NoteRange = ErrorRange =
10060                       SecondBinOp ? SecondBinOp->getSourceRange()
10061                                   : SourceRange(ErrorLoc, ErrorLoc);
10062                 } else {
10063                   Expr *PossibleXRHSInFirst =
10064                       FirstBinOp->getRHS()->IgnoreParenImpCasts();
10065                   Expr *PossibleXLHSInSecond =
10066                       SecondBinOp->getLHS()->IgnoreParenImpCasts();
10067                   llvm::FoldingSetNodeID X1Id, X2Id;
10068                   PossibleXRHSInFirst->Profile(X1Id, Context,
10069                                                /*Canonical=*/true);
10070                   PossibleXLHSInSecond->Profile(X2Id, Context,
10071                                                 /*Canonical=*/true);
10072                   IsUpdateExprFound = X1Id == X2Id;
10073                   if (IsUpdateExprFound) {
10074                     V = FirstBinOp->getLHS();
10075                     X = SecondBinOp->getLHS();
10076                     E = SecondBinOp->getRHS();
10077                     UE = nullptr;
10078                     IsXLHSInRHSPart = false;
10079                     IsPostfixUpdate = true;
10080                   } else {
10081                     ErrorFound = NotASpecificExpression;
10082                     ErrorLoc = FirstBinOp->getExprLoc();
10083                     ErrorRange = FirstBinOp->getSourceRange();
10084                     NoteLoc = SecondBinOp->getLHS()->getExprLoc();
10085                     NoteRange = SecondBinOp->getRHS()->getSourceRange();
10086                   }
10087                 }
10088               }
10089             }
10090           }
10091         } else {
10092           NoteLoc = ErrorLoc = Body->getBeginLoc();
10093           NoteRange = ErrorRange =
10094               SourceRange(Body->getBeginLoc(), Body->getBeginLoc());
10095           ErrorFound = NotTwoSubstatements;
10096         }
10097       } else {
10098         NoteLoc = ErrorLoc = Body->getBeginLoc();
10099         NoteRange = ErrorRange =
10100             SourceRange(Body->getBeginLoc(), Body->getBeginLoc());
10101         ErrorFound = NotACompoundStatement;
10102       }
10103       if (ErrorFound != NoError) {
10104         Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement)
10105             << ErrorRange;
10106         Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
10107         return StmtError();
10108       }
10109       if (CurContext->isDependentContext())
10110         UE = V = E = X = nullptr;
10111     }
10112   }
10113 
10114   setFunctionHasBranchProtectedScope();
10115 
10116   return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
10117                                     X, V, E, UE, IsXLHSInRHSPart,
10118                                     IsPostfixUpdate);
10119 }
10120 
10121 StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
10122                                             Stmt *AStmt,
10123                                             SourceLocation StartLoc,
10124                                             SourceLocation EndLoc) {
10125   if (!AStmt)
10126     return StmtError();
10127 
10128   auto *CS = cast<CapturedStmt>(AStmt);
10129   // 1.2.2 OpenMP Language Terminology
10130   // Structured block - An executable statement with a single entry at the
10131   // top and a single exit at the bottom.
10132   // The point of exit cannot be a branch out of the structured block.
10133   // longjmp() and throw() must not violate the entry/exit criteria.
10134   CS->getCapturedDecl()->setNothrow();
10135   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target);
10136        ThisCaptureLevel > 1; --ThisCaptureLevel) {
10137     CS = cast<CapturedStmt>(CS->getCapturedStmt());
10138     // 1.2.2 OpenMP Language Terminology
10139     // Structured block - An executable statement with a single entry at the
10140     // top and a single exit at the bottom.
10141     // The point of exit cannot be a branch out of the structured block.
10142     // longjmp() and throw() must not violate the entry/exit criteria.
10143     CS->getCapturedDecl()->setNothrow();
10144   }
10145 
10146   // OpenMP [2.16, Nesting of Regions]
10147   // If specified, a teams construct must be contained within a target
10148   // construct. That target construct must contain no statements or directives
10149   // outside of the teams construct.
10150   if (DSAStack->hasInnerTeamsRegion()) {
10151     const Stmt *S = CS->IgnoreContainers(/*IgnoreCaptured=*/true);
10152     bool OMPTeamsFound = true;
10153     if (const auto *CS = dyn_cast<CompoundStmt>(S)) {
10154       auto I = CS->body_begin();
10155       while (I != CS->body_end()) {
10156         const auto *OED = dyn_cast<OMPExecutableDirective>(*I);
10157         if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind()) ||
10158             OMPTeamsFound) {
10159 
10160           OMPTeamsFound = false;
10161           break;
10162         }
10163         ++I;
10164       }
10165       assert(I != CS->body_end() && "Not found statement");
10166       S = *I;
10167     } else {
10168       const auto *OED = dyn_cast<OMPExecutableDirective>(S);
10169       OMPTeamsFound = OED && isOpenMPTeamsDirective(OED->getDirectiveKind());
10170     }
10171     if (!OMPTeamsFound) {
10172       Diag(StartLoc, diag::err_omp_target_contains_not_only_teams);
10173       Diag(DSAStack->getInnerTeamsRegionLoc(),
10174            diag::note_omp_nested_teams_construct_here);
10175       Diag(S->getBeginLoc(), diag::note_omp_nested_statement_here)
10176           << isa<OMPExecutableDirective>(S);
10177       return StmtError();
10178     }
10179   }
10180 
10181   setFunctionHasBranchProtectedScope();
10182 
10183   return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
10184 }
10185 
10186 StmtResult
10187 Sema::ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
10188                                          Stmt *AStmt, SourceLocation StartLoc,
10189                                          SourceLocation EndLoc) {
10190   if (!AStmt)
10191     return StmtError();
10192 
10193   auto *CS = cast<CapturedStmt>(AStmt);
10194   // 1.2.2 OpenMP Language Terminology
10195   // Structured block - An executable statement with a single entry at the
10196   // top and a single exit at the bottom.
10197   // The point of exit cannot be a branch out of the structured block.
10198   // longjmp() and throw() must not violate the entry/exit criteria.
10199   CS->getCapturedDecl()->setNothrow();
10200   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel);
10201        ThisCaptureLevel > 1; --ThisCaptureLevel) {
10202     CS = cast<CapturedStmt>(CS->getCapturedStmt());
10203     // 1.2.2 OpenMP Language Terminology
10204     // Structured block - An executable statement with a single entry at the
10205     // top and a single exit at the bottom.
10206     // The point of exit cannot be a branch out of the structured block.
10207     // longjmp() and throw() must not violate the entry/exit criteria.
10208     CS->getCapturedDecl()->setNothrow();
10209   }
10210 
10211   setFunctionHasBranchProtectedScope();
10212 
10213   return OMPTargetParallelDirective::Create(
10214       Context, StartLoc, EndLoc, Clauses, AStmt,
10215       DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion());
10216 }
10217 
10218 StmtResult Sema::ActOnOpenMPTargetParallelForDirective(
10219     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10220     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
10221   if (!AStmt)
10222     return StmtError();
10223 
10224   auto *CS = cast<CapturedStmt>(AStmt);
10225   // 1.2.2 OpenMP Language Terminology
10226   // Structured block - An executable statement with a single entry at the
10227   // top and a single exit at the bottom.
10228   // The point of exit cannot be a branch out of the structured block.
10229   // longjmp() and throw() must not violate the entry/exit criteria.
10230   CS->getCapturedDecl()->setNothrow();
10231   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
10232        ThisCaptureLevel > 1; --ThisCaptureLevel) {
10233     CS = cast<CapturedStmt>(CS->getCapturedStmt());
10234     // 1.2.2 OpenMP Language Terminology
10235     // Structured block - An executable statement with a single entry at the
10236     // top and a single exit at the bottom.
10237     // The point of exit cannot be a branch out of the structured block.
10238     // longjmp() and throw() must not violate the entry/exit criteria.
10239     CS->getCapturedDecl()->setNothrow();
10240   }
10241 
10242   OMPLoopDirective::HelperExprs B;
10243   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
10244   // define the nested loops number.
10245   unsigned NestedLoopCount =
10246       checkOpenMPLoop(OMPD_target_parallel_for, getCollapseNumberExpr(Clauses),
10247                       getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
10248                       VarsWithImplicitDSA, B);
10249   if (NestedLoopCount == 0)
10250     return StmtError();
10251 
10252   assert((CurContext->isDependentContext() || B.builtAll()) &&
10253          "omp target parallel for loop exprs were not built");
10254 
10255   if (!CurContext->isDependentContext()) {
10256     // Finalize the clauses that need pre-built expressions for CodeGen.
10257     for (OMPClause *C : Clauses) {
10258       if (auto *LC = dyn_cast<OMPLinearClause>(C))
10259         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
10260                                      B.NumIterations, *this, CurScope,
10261                                      DSAStack))
10262           return StmtError();
10263     }
10264   }
10265 
10266   setFunctionHasBranchProtectedScope();
10267   return OMPTargetParallelForDirective::Create(
10268       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
10269       DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion());
10270 }
10271 
10272 /// Check for existence of a map clause in the list of clauses.
10273 static bool hasClauses(ArrayRef<OMPClause *> Clauses,
10274                        const OpenMPClauseKind K) {
10275   return llvm::any_of(
10276       Clauses, [K](const OMPClause *C) { return C->getClauseKind() == K; });
10277 }
10278 
10279 template <typename... Params>
10280 static bool hasClauses(ArrayRef<OMPClause *> Clauses, const OpenMPClauseKind K,
10281                        const Params... ClauseTypes) {
10282   return hasClauses(Clauses, K) || hasClauses(Clauses, ClauseTypes...);
10283 }
10284 
10285 StmtResult Sema::ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
10286                                                 Stmt *AStmt,
10287                                                 SourceLocation StartLoc,
10288                                                 SourceLocation EndLoc) {
10289   if (!AStmt)
10290     return StmtError();
10291 
10292   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
10293 
10294   // OpenMP [2.12.2, target data Construct, Restrictions]
10295   // At least one map, use_device_addr or use_device_ptr clause must appear on
10296   // the directive.
10297   if (!hasClauses(Clauses, OMPC_map, OMPC_use_device_ptr) &&
10298       (LangOpts.OpenMP < 50 || !hasClauses(Clauses, OMPC_use_device_addr))) {
10299     StringRef Expected;
10300     if (LangOpts.OpenMP < 50)
10301       Expected = "'map' or 'use_device_ptr'";
10302     else
10303       Expected = "'map', 'use_device_ptr', or 'use_device_addr'";
10304     Diag(StartLoc, diag::err_omp_no_clause_for_directive)
10305         << Expected << getOpenMPDirectiveName(OMPD_target_data);
10306     return StmtError();
10307   }
10308 
10309   setFunctionHasBranchProtectedScope();
10310 
10311   return OMPTargetDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
10312                                         AStmt);
10313 }
10314 
10315 StmtResult
10316 Sema::ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
10317                                           SourceLocation StartLoc,
10318                                           SourceLocation EndLoc, Stmt *AStmt) {
10319   if (!AStmt)
10320     return StmtError();
10321 
10322   auto *CS = cast<CapturedStmt>(AStmt);
10323   // 1.2.2 OpenMP Language Terminology
10324   // Structured block - An executable statement with a single entry at the
10325   // top and a single exit at the bottom.
10326   // The point of exit cannot be a branch out of the structured block.
10327   // longjmp() and throw() must not violate the entry/exit criteria.
10328   CS->getCapturedDecl()->setNothrow();
10329   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_enter_data);
10330        ThisCaptureLevel > 1; --ThisCaptureLevel) {
10331     CS = cast<CapturedStmt>(CS->getCapturedStmt());
10332     // 1.2.2 OpenMP Language Terminology
10333     // Structured block - An executable statement with a single entry at the
10334     // top and a single exit at the bottom.
10335     // The point of exit cannot be a branch out of the structured block.
10336     // longjmp() and throw() must not violate the entry/exit criteria.
10337     CS->getCapturedDecl()->setNothrow();
10338   }
10339 
10340   // OpenMP [2.10.2, Restrictions, p. 99]
10341   // At least one map clause must appear on the directive.
10342   if (!hasClauses(Clauses, OMPC_map)) {
10343     Diag(StartLoc, diag::err_omp_no_clause_for_directive)
10344         << "'map'" << getOpenMPDirectiveName(OMPD_target_enter_data);
10345     return StmtError();
10346   }
10347 
10348   return OMPTargetEnterDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
10349                                              AStmt);
10350 }
10351 
10352 StmtResult
10353 Sema::ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
10354                                          SourceLocation StartLoc,
10355                                          SourceLocation EndLoc, Stmt *AStmt) {
10356   if (!AStmt)
10357     return StmtError();
10358 
10359   auto *CS = cast<CapturedStmt>(AStmt);
10360   // 1.2.2 OpenMP Language Terminology
10361   // Structured block - An executable statement with a single entry at the
10362   // top and a single exit at the bottom.
10363   // The point of exit cannot be a branch out of the structured block.
10364   // longjmp() and throw() must not violate the entry/exit criteria.
10365   CS->getCapturedDecl()->setNothrow();
10366   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_exit_data);
10367        ThisCaptureLevel > 1; --ThisCaptureLevel) {
10368     CS = cast<CapturedStmt>(CS->getCapturedStmt());
10369     // 1.2.2 OpenMP Language Terminology
10370     // Structured block - An executable statement with a single entry at the
10371     // top and a single exit at the bottom.
10372     // The point of exit cannot be a branch out of the structured block.
10373     // longjmp() and throw() must not violate the entry/exit criteria.
10374     CS->getCapturedDecl()->setNothrow();
10375   }
10376 
10377   // OpenMP [2.10.3, Restrictions, p. 102]
10378   // At least one map clause must appear on the directive.
10379   if (!hasClauses(Clauses, OMPC_map)) {
10380     Diag(StartLoc, diag::err_omp_no_clause_for_directive)
10381         << "'map'" << getOpenMPDirectiveName(OMPD_target_exit_data);
10382     return StmtError();
10383   }
10384 
10385   return OMPTargetExitDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
10386                                             AStmt);
10387 }
10388 
10389 StmtResult Sema::ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
10390                                                   SourceLocation StartLoc,
10391                                                   SourceLocation EndLoc,
10392                                                   Stmt *AStmt) {
10393   if (!AStmt)
10394     return StmtError();
10395 
10396   auto *CS = cast<CapturedStmt>(AStmt);
10397   // 1.2.2 OpenMP Language Terminology
10398   // Structured block - An executable statement with a single entry at the
10399   // top and a single exit at the bottom.
10400   // The point of exit cannot be a branch out of the structured block.
10401   // longjmp() and throw() must not violate the entry/exit criteria.
10402   CS->getCapturedDecl()->setNothrow();
10403   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_update);
10404        ThisCaptureLevel > 1; --ThisCaptureLevel) {
10405     CS = cast<CapturedStmt>(CS->getCapturedStmt());
10406     // 1.2.2 OpenMP Language Terminology
10407     // Structured block - An executable statement with a single entry at the
10408     // top and a single exit at the bottom.
10409     // The point of exit cannot be a branch out of the structured block.
10410     // longjmp() and throw() must not violate the entry/exit criteria.
10411     CS->getCapturedDecl()->setNothrow();
10412   }
10413 
10414   if (!hasClauses(Clauses, OMPC_to, OMPC_from)) {
10415     Diag(StartLoc, diag::err_omp_at_least_one_motion_clause_required);
10416     return StmtError();
10417   }
10418   return OMPTargetUpdateDirective::Create(Context, StartLoc, EndLoc, Clauses,
10419                                           AStmt);
10420 }
10421 
10422 StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
10423                                            Stmt *AStmt, SourceLocation StartLoc,
10424                                            SourceLocation EndLoc) {
10425   if (!AStmt)
10426     return StmtError();
10427 
10428   auto *CS = cast<CapturedStmt>(AStmt);
10429   // 1.2.2 OpenMP Language Terminology
10430   // Structured block - An executable statement with a single entry at the
10431   // top and a single exit at the bottom.
10432   // The point of exit cannot be a branch out of the structured block.
10433   // longjmp() and throw() must not violate the entry/exit criteria.
10434   CS->getCapturedDecl()->setNothrow();
10435 
10436   setFunctionHasBranchProtectedScope();
10437 
10438   DSAStack->setParentTeamsRegionLoc(StartLoc);
10439 
10440   return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
10441 }
10442 
10443 StmtResult
10444 Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
10445                                             SourceLocation EndLoc,
10446                                             OpenMPDirectiveKind CancelRegion) {
10447   if (DSAStack->isParentNowaitRegion()) {
10448     Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0;
10449     return StmtError();
10450   }
10451   if (DSAStack->isParentOrderedRegion()) {
10452     Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0;
10453     return StmtError();
10454   }
10455   return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc,
10456                                                CancelRegion);
10457 }
10458 
10459 StmtResult Sema::ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
10460                                             SourceLocation StartLoc,
10461                                             SourceLocation EndLoc,
10462                                             OpenMPDirectiveKind CancelRegion) {
10463   if (DSAStack->isParentNowaitRegion()) {
10464     Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1;
10465     return StmtError();
10466   }
10467   if (DSAStack->isParentOrderedRegion()) {
10468     Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1;
10469     return StmtError();
10470   }
10471   DSAStack->setParentCancelRegion(/*Cancel=*/true);
10472   return OMPCancelDirective::Create(Context, StartLoc, EndLoc, Clauses,
10473                                     CancelRegion);
10474 }
10475 
10476 static bool checkGrainsizeNumTasksClauses(Sema &S,
10477                                           ArrayRef<OMPClause *> Clauses) {
10478   const OMPClause *PrevClause = nullptr;
10479   bool ErrorFound = false;
10480   for (const OMPClause *C : Clauses) {
10481     if (C->getClauseKind() == OMPC_grainsize ||
10482         C->getClauseKind() == OMPC_num_tasks) {
10483       if (!PrevClause)
10484         PrevClause = C;
10485       else if (PrevClause->getClauseKind() != C->getClauseKind()) {
10486         S.Diag(C->getBeginLoc(), diag::err_omp_clauses_mutually_exclusive)
10487             << getOpenMPClauseName(C->getClauseKind())
10488             << getOpenMPClauseName(PrevClause->getClauseKind());
10489         S.Diag(PrevClause->getBeginLoc(), diag::note_omp_previous_clause)
10490             << getOpenMPClauseName(PrevClause->getClauseKind());
10491         ErrorFound = true;
10492       }
10493     }
10494   }
10495   return ErrorFound;
10496 }
10497 
10498 static bool checkReductionClauseWithNogroup(Sema &S,
10499                                             ArrayRef<OMPClause *> Clauses) {
10500   const OMPClause *ReductionClause = nullptr;
10501   const OMPClause *NogroupClause = nullptr;
10502   for (const OMPClause *C : Clauses) {
10503     if (C->getClauseKind() == OMPC_reduction) {
10504       ReductionClause = C;
10505       if (NogroupClause)
10506         break;
10507       continue;
10508     }
10509     if (C->getClauseKind() == OMPC_nogroup) {
10510       NogroupClause = C;
10511       if (ReductionClause)
10512         break;
10513       continue;
10514     }
10515   }
10516   if (ReductionClause && NogroupClause) {
10517     S.Diag(ReductionClause->getBeginLoc(), diag::err_omp_reduction_with_nogroup)
10518         << SourceRange(NogroupClause->getBeginLoc(),
10519                        NogroupClause->getEndLoc());
10520     return true;
10521   }
10522   return false;
10523 }
10524 
10525 StmtResult Sema::ActOnOpenMPTaskLoopDirective(
10526     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10527     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
10528   if (!AStmt)
10529     return StmtError();
10530 
10531   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
10532   OMPLoopDirective::HelperExprs B;
10533   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
10534   // define the nested loops number.
10535   unsigned NestedLoopCount =
10536       checkOpenMPLoop(OMPD_taskloop, getCollapseNumberExpr(Clauses),
10537                       /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
10538                       VarsWithImplicitDSA, B);
10539   if (NestedLoopCount == 0)
10540     return StmtError();
10541 
10542   assert((CurContext->isDependentContext() || B.builtAll()) &&
10543          "omp for loop exprs were not built");
10544 
10545   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
10546   // The grainsize clause and num_tasks clause are mutually exclusive and may
10547   // not appear on the same taskloop directive.
10548   if (checkGrainsizeNumTasksClauses(*this, Clauses))
10549     return StmtError();
10550   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
10551   // If a reduction clause is present on the taskloop directive, the nogroup
10552   // clause must not be specified.
10553   if (checkReductionClauseWithNogroup(*this, Clauses))
10554     return StmtError();
10555 
10556   setFunctionHasBranchProtectedScope();
10557   return OMPTaskLoopDirective::Create(Context, StartLoc, EndLoc,
10558                                       NestedLoopCount, Clauses, AStmt, B,
10559                                       DSAStack->isCancelRegion());
10560 }
10561 
10562 StmtResult Sema::ActOnOpenMPTaskLoopSimdDirective(
10563     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10564     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
10565   if (!AStmt)
10566     return StmtError();
10567 
10568   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
10569   OMPLoopDirective::HelperExprs B;
10570   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
10571   // define the nested loops number.
10572   unsigned NestedLoopCount =
10573       checkOpenMPLoop(OMPD_taskloop_simd, getCollapseNumberExpr(Clauses),
10574                       /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
10575                       VarsWithImplicitDSA, B);
10576   if (NestedLoopCount == 0)
10577     return StmtError();
10578 
10579   assert((CurContext->isDependentContext() || B.builtAll()) &&
10580          "omp for loop exprs were not built");
10581 
10582   if (!CurContext->isDependentContext()) {
10583     // Finalize the clauses that need pre-built expressions for CodeGen.
10584     for (OMPClause *C : Clauses) {
10585       if (auto *LC = dyn_cast<OMPLinearClause>(C))
10586         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
10587                                      B.NumIterations, *this, CurScope,
10588                                      DSAStack))
10589           return StmtError();
10590     }
10591   }
10592 
10593   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
10594   // The grainsize clause and num_tasks clause are mutually exclusive and may
10595   // not appear on the same taskloop directive.
10596   if (checkGrainsizeNumTasksClauses(*this, Clauses))
10597     return StmtError();
10598   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
10599   // If a reduction clause is present on the taskloop directive, the nogroup
10600   // clause must not be specified.
10601   if (checkReductionClauseWithNogroup(*this, Clauses))
10602     return StmtError();
10603   if (checkSimdlenSafelenSpecified(*this, Clauses))
10604     return StmtError();
10605 
10606   setFunctionHasBranchProtectedScope();
10607   return OMPTaskLoopSimdDirective::Create(Context, StartLoc, EndLoc,
10608                                           NestedLoopCount, Clauses, AStmt, B);
10609 }
10610 
10611 StmtResult Sema::ActOnOpenMPMasterTaskLoopDirective(
10612     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10613     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
10614   if (!AStmt)
10615     return StmtError();
10616 
10617   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
10618   OMPLoopDirective::HelperExprs B;
10619   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
10620   // define the nested loops number.
10621   unsigned NestedLoopCount =
10622       checkOpenMPLoop(OMPD_master_taskloop, getCollapseNumberExpr(Clauses),
10623                       /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
10624                       VarsWithImplicitDSA, B);
10625   if (NestedLoopCount == 0)
10626     return StmtError();
10627 
10628   assert((CurContext->isDependentContext() || B.builtAll()) &&
10629          "omp for loop exprs were not built");
10630 
10631   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
10632   // The grainsize clause and num_tasks clause are mutually exclusive and may
10633   // not appear on the same taskloop directive.
10634   if (checkGrainsizeNumTasksClauses(*this, Clauses))
10635     return StmtError();
10636   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
10637   // If a reduction clause is present on the taskloop directive, the nogroup
10638   // clause must not be specified.
10639   if (checkReductionClauseWithNogroup(*this, Clauses))
10640     return StmtError();
10641 
10642   setFunctionHasBranchProtectedScope();
10643   return OMPMasterTaskLoopDirective::Create(Context, StartLoc, EndLoc,
10644                                             NestedLoopCount, Clauses, AStmt, B,
10645                                             DSAStack->isCancelRegion());
10646 }
10647 
10648 StmtResult Sema::ActOnOpenMPMasterTaskLoopSimdDirective(
10649     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10650     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
10651   if (!AStmt)
10652     return StmtError();
10653 
10654   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
10655   OMPLoopDirective::HelperExprs B;
10656   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
10657   // define the nested loops number.
10658   unsigned NestedLoopCount =
10659       checkOpenMPLoop(OMPD_master_taskloop_simd, getCollapseNumberExpr(Clauses),
10660                       /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
10661                       VarsWithImplicitDSA, B);
10662   if (NestedLoopCount == 0)
10663     return StmtError();
10664 
10665   assert((CurContext->isDependentContext() || B.builtAll()) &&
10666          "omp for loop exprs were not built");
10667 
10668   if (!CurContext->isDependentContext()) {
10669     // Finalize the clauses that need pre-built expressions for CodeGen.
10670     for (OMPClause *C : Clauses) {
10671       if (auto *LC = dyn_cast<OMPLinearClause>(C))
10672         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
10673                                      B.NumIterations, *this, CurScope,
10674                                      DSAStack))
10675           return StmtError();
10676     }
10677   }
10678 
10679   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
10680   // The grainsize clause and num_tasks clause are mutually exclusive and may
10681   // not appear on the same taskloop directive.
10682   if (checkGrainsizeNumTasksClauses(*this, Clauses))
10683     return StmtError();
10684   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
10685   // If a reduction clause is present on the taskloop directive, the nogroup
10686   // clause must not be specified.
10687   if (checkReductionClauseWithNogroup(*this, Clauses))
10688     return StmtError();
10689   if (checkSimdlenSafelenSpecified(*this, Clauses))
10690     return StmtError();
10691 
10692   setFunctionHasBranchProtectedScope();
10693   return OMPMasterTaskLoopSimdDirective::Create(
10694       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
10695 }
10696 
10697 StmtResult Sema::ActOnOpenMPParallelMasterTaskLoopDirective(
10698     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10699     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
10700   if (!AStmt)
10701     return StmtError();
10702 
10703   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
10704   auto *CS = cast<CapturedStmt>(AStmt);
10705   // 1.2.2 OpenMP Language Terminology
10706   // Structured block - An executable statement with a single entry at the
10707   // top and a single exit at the bottom.
10708   // The point of exit cannot be a branch out of the structured block.
10709   // longjmp() and throw() must not violate the entry/exit criteria.
10710   CS->getCapturedDecl()->setNothrow();
10711   for (int ThisCaptureLevel =
10712            getOpenMPCaptureLevels(OMPD_parallel_master_taskloop);
10713        ThisCaptureLevel > 1; --ThisCaptureLevel) {
10714     CS = cast<CapturedStmt>(CS->getCapturedStmt());
10715     // 1.2.2 OpenMP Language Terminology
10716     // Structured block - An executable statement with a single entry at the
10717     // top and a single exit at the bottom.
10718     // The point of exit cannot be a branch out of the structured block.
10719     // longjmp() and throw() must not violate the entry/exit criteria.
10720     CS->getCapturedDecl()->setNothrow();
10721   }
10722 
10723   OMPLoopDirective::HelperExprs B;
10724   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
10725   // define the nested loops number.
10726   unsigned NestedLoopCount = checkOpenMPLoop(
10727       OMPD_parallel_master_taskloop, getCollapseNumberExpr(Clauses),
10728       /*OrderedLoopCountExpr=*/nullptr, CS, *this, *DSAStack,
10729       VarsWithImplicitDSA, B);
10730   if (NestedLoopCount == 0)
10731     return StmtError();
10732 
10733   assert((CurContext->isDependentContext() || B.builtAll()) &&
10734          "omp for loop exprs were not built");
10735 
10736   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
10737   // The grainsize clause and num_tasks clause are mutually exclusive and may
10738   // not appear on the same taskloop directive.
10739   if (checkGrainsizeNumTasksClauses(*this, Clauses))
10740     return StmtError();
10741   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
10742   // If a reduction clause is present on the taskloop directive, the nogroup
10743   // clause must not be specified.
10744   if (checkReductionClauseWithNogroup(*this, Clauses))
10745     return StmtError();
10746 
10747   setFunctionHasBranchProtectedScope();
10748   return OMPParallelMasterTaskLoopDirective::Create(
10749       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
10750       DSAStack->isCancelRegion());
10751 }
10752 
10753 StmtResult Sema::ActOnOpenMPParallelMasterTaskLoopSimdDirective(
10754     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10755     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
10756   if (!AStmt)
10757     return StmtError();
10758 
10759   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
10760   auto *CS = cast<CapturedStmt>(AStmt);
10761   // 1.2.2 OpenMP Language Terminology
10762   // Structured block - An executable statement with a single entry at the
10763   // top and a single exit at the bottom.
10764   // The point of exit cannot be a branch out of the structured block.
10765   // longjmp() and throw() must not violate the entry/exit criteria.
10766   CS->getCapturedDecl()->setNothrow();
10767   for (int ThisCaptureLevel =
10768            getOpenMPCaptureLevels(OMPD_parallel_master_taskloop_simd);
10769        ThisCaptureLevel > 1; --ThisCaptureLevel) {
10770     CS = cast<CapturedStmt>(CS->getCapturedStmt());
10771     // 1.2.2 OpenMP Language Terminology
10772     // Structured block - An executable statement with a single entry at the
10773     // top and a single exit at the bottom.
10774     // The point of exit cannot be a branch out of the structured block.
10775     // longjmp() and throw() must not violate the entry/exit criteria.
10776     CS->getCapturedDecl()->setNothrow();
10777   }
10778 
10779   OMPLoopDirective::HelperExprs B;
10780   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
10781   // define the nested loops number.
10782   unsigned NestedLoopCount = checkOpenMPLoop(
10783       OMPD_parallel_master_taskloop_simd, getCollapseNumberExpr(Clauses),
10784       /*OrderedLoopCountExpr=*/nullptr, CS, *this, *DSAStack,
10785       VarsWithImplicitDSA, B);
10786   if (NestedLoopCount == 0)
10787     return StmtError();
10788 
10789   assert((CurContext->isDependentContext() || B.builtAll()) &&
10790          "omp for loop exprs were not built");
10791 
10792   if (!CurContext->isDependentContext()) {
10793     // Finalize the clauses that need pre-built expressions for CodeGen.
10794     for (OMPClause *C : Clauses) {
10795       if (auto *LC = dyn_cast<OMPLinearClause>(C))
10796         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
10797                                      B.NumIterations, *this, CurScope,
10798                                      DSAStack))
10799           return StmtError();
10800     }
10801   }
10802 
10803   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
10804   // The grainsize clause and num_tasks clause are mutually exclusive and may
10805   // not appear on the same taskloop directive.
10806   if (checkGrainsizeNumTasksClauses(*this, Clauses))
10807     return StmtError();
10808   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
10809   // If a reduction clause is present on the taskloop directive, the nogroup
10810   // clause must not be specified.
10811   if (checkReductionClauseWithNogroup(*this, Clauses))
10812     return StmtError();
10813   if (checkSimdlenSafelenSpecified(*this, Clauses))
10814     return StmtError();
10815 
10816   setFunctionHasBranchProtectedScope();
10817   return OMPParallelMasterTaskLoopSimdDirective::Create(
10818       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
10819 }
10820 
10821 StmtResult Sema::ActOnOpenMPDistributeDirective(
10822     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10823     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
10824   if (!AStmt)
10825     return StmtError();
10826 
10827   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
10828   OMPLoopDirective::HelperExprs B;
10829   // In presence of clause 'collapse' with number of loops, it will
10830   // define the nested loops number.
10831   unsigned NestedLoopCount =
10832       checkOpenMPLoop(OMPD_distribute, getCollapseNumberExpr(Clauses),
10833                       nullptr /*ordered not a clause on distribute*/, AStmt,
10834                       *this, *DSAStack, VarsWithImplicitDSA, B);
10835   if (NestedLoopCount == 0)
10836     return StmtError();
10837 
10838   assert((CurContext->isDependentContext() || B.builtAll()) &&
10839          "omp for loop exprs were not built");
10840 
10841   setFunctionHasBranchProtectedScope();
10842   return OMPDistributeDirective::Create(Context, StartLoc, EndLoc,
10843                                         NestedLoopCount, Clauses, AStmt, B);
10844 }
10845 
10846 StmtResult Sema::ActOnOpenMPDistributeParallelForDirective(
10847     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10848     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
10849   if (!AStmt)
10850     return StmtError();
10851 
10852   auto *CS = cast<CapturedStmt>(AStmt);
10853   // 1.2.2 OpenMP Language Terminology
10854   // Structured block - An executable statement with a single entry at the
10855   // top and a single exit at the bottom.
10856   // The point of exit cannot be a branch out of the structured block.
10857   // longjmp() and throw() must not violate the entry/exit criteria.
10858   CS->getCapturedDecl()->setNothrow();
10859   for (int ThisCaptureLevel =
10860            getOpenMPCaptureLevels(OMPD_distribute_parallel_for);
10861        ThisCaptureLevel > 1; --ThisCaptureLevel) {
10862     CS = cast<CapturedStmt>(CS->getCapturedStmt());
10863     // 1.2.2 OpenMP Language Terminology
10864     // Structured block - An executable statement with a single entry at the
10865     // top and a single exit at the bottom.
10866     // The point of exit cannot be a branch out of the structured block.
10867     // longjmp() and throw() must not violate the entry/exit criteria.
10868     CS->getCapturedDecl()->setNothrow();
10869   }
10870 
10871   OMPLoopDirective::HelperExprs B;
10872   // In presence of clause 'collapse' with number of loops, it will
10873   // define the nested loops number.
10874   unsigned NestedLoopCount = checkOpenMPLoop(
10875       OMPD_distribute_parallel_for, getCollapseNumberExpr(Clauses),
10876       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
10877       VarsWithImplicitDSA, B);
10878   if (NestedLoopCount == 0)
10879     return StmtError();
10880 
10881   assert((CurContext->isDependentContext() || B.builtAll()) &&
10882          "omp for loop exprs were not built");
10883 
10884   setFunctionHasBranchProtectedScope();
10885   return OMPDistributeParallelForDirective::Create(
10886       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
10887       DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion());
10888 }
10889 
10890 StmtResult Sema::ActOnOpenMPDistributeParallelForSimdDirective(
10891     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10892     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
10893   if (!AStmt)
10894     return StmtError();
10895 
10896   auto *CS = cast<CapturedStmt>(AStmt);
10897   // 1.2.2 OpenMP Language Terminology
10898   // Structured block - An executable statement with a single entry at the
10899   // top and a single exit at the bottom.
10900   // The point of exit cannot be a branch out of the structured block.
10901   // longjmp() and throw() must not violate the entry/exit criteria.
10902   CS->getCapturedDecl()->setNothrow();
10903   for (int ThisCaptureLevel =
10904            getOpenMPCaptureLevels(OMPD_distribute_parallel_for_simd);
10905        ThisCaptureLevel > 1; --ThisCaptureLevel) {
10906     CS = cast<CapturedStmt>(CS->getCapturedStmt());
10907     // 1.2.2 OpenMP Language Terminology
10908     // Structured block - An executable statement with a single entry at the
10909     // top and a single exit at the bottom.
10910     // The point of exit cannot be a branch out of the structured block.
10911     // longjmp() and throw() must not violate the entry/exit criteria.
10912     CS->getCapturedDecl()->setNothrow();
10913   }
10914 
10915   OMPLoopDirective::HelperExprs B;
10916   // In presence of clause 'collapse' with number of loops, it will
10917   // define the nested loops number.
10918   unsigned NestedLoopCount = checkOpenMPLoop(
10919       OMPD_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
10920       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
10921       VarsWithImplicitDSA, B);
10922   if (NestedLoopCount == 0)
10923     return StmtError();
10924 
10925   assert((CurContext->isDependentContext() || B.builtAll()) &&
10926          "omp for loop exprs were not built");
10927 
10928   if (!CurContext->isDependentContext()) {
10929     // Finalize the clauses that need pre-built expressions for CodeGen.
10930     for (OMPClause *C : Clauses) {
10931       if (auto *LC = dyn_cast<OMPLinearClause>(C))
10932         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
10933                                      B.NumIterations, *this, CurScope,
10934                                      DSAStack))
10935           return StmtError();
10936     }
10937   }
10938 
10939   if (checkSimdlenSafelenSpecified(*this, Clauses))
10940     return StmtError();
10941 
10942   setFunctionHasBranchProtectedScope();
10943   return OMPDistributeParallelForSimdDirective::Create(
10944       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
10945 }
10946 
10947 StmtResult Sema::ActOnOpenMPDistributeSimdDirective(
10948     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10949     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
10950   if (!AStmt)
10951     return StmtError();
10952 
10953   auto *CS = cast<CapturedStmt>(AStmt);
10954   // 1.2.2 OpenMP Language Terminology
10955   // Structured block - An executable statement with a single entry at the
10956   // top and a single exit at the bottom.
10957   // The point of exit cannot be a branch out of the structured block.
10958   // longjmp() and throw() must not violate the entry/exit criteria.
10959   CS->getCapturedDecl()->setNothrow();
10960   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_distribute_simd);
10961        ThisCaptureLevel > 1; --ThisCaptureLevel) {
10962     CS = cast<CapturedStmt>(CS->getCapturedStmt());
10963     // 1.2.2 OpenMP Language Terminology
10964     // Structured block - An executable statement with a single entry at the
10965     // top and a single exit at the bottom.
10966     // The point of exit cannot be a branch out of the structured block.
10967     // longjmp() and throw() must not violate the entry/exit criteria.
10968     CS->getCapturedDecl()->setNothrow();
10969   }
10970 
10971   OMPLoopDirective::HelperExprs B;
10972   // In presence of clause 'collapse' with number of loops, it will
10973   // define the nested loops number.
10974   unsigned NestedLoopCount =
10975       checkOpenMPLoop(OMPD_distribute_simd, getCollapseNumberExpr(Clauses),
10976                       nullptr /*ordered not a clause on distribute*/, CS, *this,
10977                       *DSAStack, VarsWithImplicitDSA, B);
10978   if (NestedLoopCount == 0)
10979     return StmtError();
10980 
10981   assert((CurContext->isDependentContext() || B.builtAll()) &&
10982          "omp for loop exprs were not built");
10983 
10984   if (!CurContext->isDependentContext()) {
10985     // Finalize the clauses that need pre-built expressions for CodeGen.
10986     for (OMPClause *C : Clauses) {
10987       if (auto *LC = dyn_cast<OMPLinearClause>(C))
10988         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
10989                                      B.NumIterations, *this, CurScope,
10990                                      DSAStack))
10991           return StmtError();
10992     }
10993   }
10994 
10995   if (checkSimdlenSafelenSpecified(*this, Clauses))
10996     return StmtError();
10997 
10998   setFunctionHasBranchProtectedScope();
10999   return OMPDistributeSimdDirective::Create(Context, StartLoc, EndLoc,
11000                                             NestedLoopCount, Clauses, AStmt, B);
11001 }
11002 
11003 StmtResult Sema::ActOnOpenMPTargetParallelForSimdDirective(
11004     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11005     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
11006   if (!AStmt)
11007     return StmtError();
11008 
11009   auto *CS = cast<CapturedStmt>(AStmt);
11010   // 1.2.2 OpenMP Language Terminology
11011   // Structured block - An executable statement with a single entry at the
11012   // top and a single exit at the bottom.
11013   // The point of exit cannot be a branch out of the structured block.
11014   // longjmp() and throw() must not violate the entry/exit criteria.
11015   CS->getCapturedDecl()->setNothrow();
11016   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
11017        ThisCaptureLevel > 1; --ThisCaptureLevel) {
11018     CS = cast<CapturedStmt>(CS->getCapturedStmt());
11019     // 1.2.2 OpenMP Language Terminology
11020     // Structured block - An executable statement with a single entry at the
11021     // top and a single exit at the bottom.
11022     // The point of exit cannot be a branch out of the structured block.
11023     // longjmp() and throw() must not violate the entry/exit criteria.
11024     CS->getCapturedDecl()->setNothrow();
11025   }
11026 
11027   OMPLoopDirective::HelperExprs B;
11028   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
11029   // define the nested loops number.
11030   unsigned NestedLoopCount = checkOpenMPLoop(
11031       OMPD_target_parallel_for_simd, getCollapseNumberExpr(Clauses),
11032       getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
11033       VarsWithImplicitDSA, B);
11034   if (NestedLoopCount == 0)
11035     return StmtError();
11036 
11037   assert((CurContext->isDependentContext() || B.builtAll()) &&
11038          "omp target parallel for simd loop exprs were not built");
11039 
11040   if (!CurContext->isDependentContext()) {
11041     // Finalize the clauses that need pre-built expressions for CodeGen.
11042     for (OMPClause *C : Clauses) {
11043       if (auto *LC = dyn_cast<OMPLinearClause>(C))
11044         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
11045                                      B.NumIterations, *this, CurScope,
11046                                      DSAStack))
11047           return StmtError();
11048     }
11049   }
11050   if (checkSimdlenSafelenSpecified(*this, Clauses))
11051     return StmtError();
11052 
11053   setFunctionHasBranchProtectedScope();
11054   return OMPTargetParallelForSimdDirective::Create(
11055       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
11056 }
11057 
11058 StmtResult Sema::ActOnOpenMPTargetSimdDirective(
11059     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11060     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
11061   if (!AStmt)
11062     return StmtError();
11063 
11064   auto *CS = cast<CapturedStmt>(AStmt);
11065   // 1.2.2 OpenMP Language Terminology
11066   // Structured block - An executable statement with a single entry at the
11067   // top and a single exit at the bottom.
11068   // The point of exit cannot be a branch out of the structured block.
11069   // longjmp() and throw() must not violate the entry/exit criteria.
11070   CS->getCapturedDecl()->setNothrow();
11071   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_simd);
11072        ThisCaptureLevel > 1; --ThisCaptureLevel) {
11073     CS = cast<CapturedStmt>(CS->getCapturedStmt());
11074     // 1.2.2 OpenMP Language Terminology
11075     // Structured block - An executable statement with a single entry at the
11076     // top and a single exit at the bottom.
11077     // The point of exit cannot be a branch out of the structured block.
11078     // longjmp() and throw() must not violate the entry/exit criteria.
11079     CS->getCapturedDecl()->setNothrow();
11080   }
11081 
11082   OMPLoopDirective::HelperExprs B;
11083   // In presence of clause 'collapse' with number of loops, it will define the
11084   // nested loops number.
11085   unsigned NestedLoopCount =
11086       checkOpenMPLoop(OMPD_target_simd, getCollapseNumberExpr(Clauses),
11087                       getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
11088                       VarsWithImplicitDSA, B);
11089   if (NestedLoopCount == 0)
11090     return StmtError();
11091 
11092   assert((CurContext->isDependentContext() || B.builtAll()) &&
11093          "omp target simd loop exprs were not built");
11094 
11095   if (!CurContext->isDependentContext()) {
11096     // Finalize the clauses that need pre-built expressions for CodeGen.
11097     for (OMPClause *C : Clauses) {
11098       if (auto *LC = dyn_cast<OMPLinearClause>(C))
11099         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
11100                                      B.NumIterations, *this, CurScope,
11101                                      DSAStack))
11102           return StmtError();
11103     }
11104   }
11105 
11106   if (checkSimdlenSafelenSpecified(*this, Clauses))
11107     return StmtError();
11108 
11109   setFunctionHasBranchProtectedScope();
11110   return OMPTargetSimdDirective::Create(Context, StartLoc, EndLoc,
11111                                         NestedLoopCount, Clauses, AStmt, B);
11112 }
11113 
11114 StmtResult Sema::ActOnOpenMPTeamsDistributeDirective(
11115     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11116     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
11117   if (!AStmt)
11118     return StmtError();
11119 
11120   auto *CS = cast<CapturedStmt>(AStmt);
11121   // 1.2.2 OpenMP Language Terminology
11122   // Structured block - An executable statement with a single entry at the
11123   // top and a single exit at the bottom.
11124   // The point of exit cannot be a branch out of the structured block.
11125   // longjmp() and throw() must not violate the entry/exit criteria.
11126   CS->getCapturedDecl()->setNothrow();
11127   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_teams_distribute);
11128        ThisCaptureLevel > 1; --ThisCaptureLevel) {
11129     CS = cast<CapturedStmt>(CS->getCapturedStmt());
11130     // 1.2.2 OpenMP Language Terminology
11131     // Structured block - An executable statement with a single entry at the
11132     // top and a single exit at the bottom.
11133     // The point of exit cannot be a branch out of the structured block.
11134     // longjmp() and throw() must not violate the entry/exit criteria.
11135     CS->getCapturedDecl()->setNothrow();
11136   }
11137 
11138   OMPLoopDirective::HelperExprs B;
11139   // In presence of clause 'collapse' with number of loops, it will
11140   // define the nested loops number.
11141   unsigned NestedLoopCount =
11142       checkOpenMPLoop(OMPD_teams_distribute, getCollapseNumberExpr(Clauses),
11143                       nullptr /*ordered not a clause on distribute*/, CS, *this,
11144                       *DSAStack, VarsWithImplicitDSA, B);
11145   if (NestedLoopCount == 0)
11146     return StmtError();
11147 
11148   assert((CurContext->isDependentContext() || B.builtAll()) &&
11149          "omp teams distribute loop exprs were not built");
11150 
11151   setFunctionHasBranchProtectedScope();
11152 
11153   DSAStack->setParentTeamsRegionLoc(StartLoc);
11154 
11155   return OMPTeamsDistributeDirective::Create(
11156       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
11157 }
11158 
11159 StmtResult Sema::ActOnOpenMPTeamsDistributeSimdDirective(
11160     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11161     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
11162   if (!AStmt)
11163     return StmtError();
11164 
11165   auto *CS = cast<CapturedStmt>(AStmt);
11166   // 1.2.2 OpenMP Language Terminology
11167   // Structured block - An executable statement with a single entry at the
11168   // top and a single exit at the bottom.
11169   // The point of exit cannot be a branch out of the structured block.
11170   // longjmp() and throw() must not violate the entry/exit criteria.
11171   CS->getCapturedDecl()->setNothrow();
11172   for (int ThisCaptureLevel =
11173            getOpenMPCaptureLevels(OMPD_teams_distribute_simd);
11174        ThisCaptureLevel > 1; --ThisCaptureLevel) {
11175     CS = cast<CapturedStmt>(CS->getCapturedStmt());
11176     // 1.2.2 OpenMP Language Terminology
11177     // Structured block - An executable statement with a single entry at the
11178     // top and a single exit at the bottom.
11179     // The point of exit cannot be a branch out of the structured block.
11180     // longjmp() and throw() must not violate the entry/exit criteria.
11181     CS->getCapturedDecl()->setNothrow();
11182   }
11183 
11184   OMPLoopDirective::HelperExprs B;
11185   // In presence of clause 'collapse' with number of loops, it will
11186   // define the nested loops number.
11187   unsigned NestedLoopCount = checkOpenMPLoop(
11188       OMPD_teams_distribute_simd, getCollapseNumberExpr(Clauses),
11189       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
11190       VarsWithImplicitDSA, B);
11191 
11192   if (NestedLoopCount == 0)
11193     return StmtError();
11194 
11195   assert((CurContext->isDependentContext() || B.builtAll()) &&
11196          "omp teams distribute simd loop exprs were not built");
11197 
11198   if (!CurContext->isDependentContext()) {
11199     // Finalize the clauses that need pre-built expressions for CodeGen.
11200     for (OMPClause *C : Clauses) {
11201       if (auto *LC = dyn_cast<OMPLinearClause>(C))
11202         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
11203                                      B.NumIterations, *this, CurScope,
11204                                      DSAStack))
11205           return StmtError();
11206     }
11207   }
11208 
11209   if (checkSimdlenSafelenSpecified(*this, Clauses))
11210     return StmtError();
11211 
11212   setFunctionHasBranchProtectedScope();
11213 
11214   DSAStack->setParentTeamsRegionLoc(StartLoc);
11215 
11216   return OMPTeamsDistributeSimdDirective::Create(
11217       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
11218 }
11219 
11220 StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForSimdDirective(
11221     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11222     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
11223   if (!AStmt)
11224     return StmtError();
11225 
11226   auto *CS = cast<CapturedStmt>(AStmt);
11227   // 1.2.2 OpenMP Language Terminology
11228   // Structured block - An executable statement with a single entry at the
11229   // top and a single exit at the bottom.
11230   // The point of exit cannot be a branch out of the structured block.
11231   // longjmp() and throw() must not violate the entry/exit criteria.
11232   CS->getCapturedDecl()->setNothrow();
11233 
11234   for (int ThisCaptureLevel =
11235            getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for_simd);
11236        ThisCaptureLevel > 1; --ThisCaptureLevel) {
11237     CS = cast<CapturedStmt>(CS->getCapturedStmt());
11238     // 1.2.2 OpenMP Language Terminology
11239     // Structured block - An executable statement with a single entry at the
11240     // top and a single exit at the bottom.
11241     // The point of exit cannot be a branch out of the structured block.
11242     // longjmp() and throw() must not violate the entry/exit criteria.
11243     CS->getCapturedDecl()->setNothrow();
11244   }
11245 
11246   OMPLoopDirective::HelperExprs B;
11247   // In presence of clause 'collapse' with number of loops, it will
11248   // define the nested loops number.
11249   unsigned NestedLoopCount = checkOpenMPLoop(
11250       OMPD_teams_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
11251       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
11252       VarsWithImplicitDSA, B);
11253 
11254   if (NestedLoopCount == 0)
11255     return StmtError();
11256 
11257   assert((CurContext->isDependentContext() || B.builtAll()) &&
11258          "omp for loop exprs were not built");
11259 
11260   if (!CurContext->isDependentContext()) {
11261     // Finalize the clauses that need pre-built expressions for CodeGen.
11262     for (OMPClause *C : Clauses) {
11263       if (auto *LC = dyn_cast<OMPLinearClause>(C))
11264         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
11265                                      B.NumIterations, *this, CurScope,
11266                                      DSAStack))
11267           return StmtError();
11268     }
11269   }
11270 
11271   if (checkSimdlenSafelenSpecified(*this, Clauses))
11272     return StmtError();
11273 
11274   setFunctionHasBranchProtectedScope();
11275 
11276   DSAStack->setParentTeamsRegionLoc(StartLoc);
11277 
11278   return OMPTeamsDistributeParallelForSimdDirective::Create(
11279       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
11280 }
11281 
11282 StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForDirective(
11283     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11284     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
11285   if (!AStmt)
11286     return StmtError();
11287 
11288   auto *CS = cast<CapturedStmt>(AStmt);
11289   // 1.2.2 OpenMP Language Terminology
11290   // Structured block - An executable statement with a single entry at the
11291   // top and a single exit at the bottom.
11292   // The point of exit cannot be a branch out of the structured block.
11293   // longjmp() and throw() must not violate the entry/exit criteria.
11294   CS->getCapturedDecl()->setNothrow();
11295 
11296   for (int ThisCaptureLevel =
11297            getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for);
11298        ThisCaptureLevel > 1; --ThisCaptureLevel) {
11299     CS = cast<CapturedStmt>(CS->getCapturedStmt());
11300     // 1.2.2 OpenMP Language Terminology
11301     // Structured block - An executable statement with a single entry at the
11302     // top and a single exit at the bottom.
11303     // The point of exit cannot be a branch out of the structured block.
11304     // longjmp() and throw() must not violate the entry/exit criteria.
11305     CS->getCapturedDecl()->setNothrow();
11306   }
11307 
11308   OMPLoopDirective::HelperExprs B;
11309   // In presence of clause 'collapse' with number of loops, it will
11310   // define the nested loops number.
11311   unsigned NestedLoopCount = checkOpenMPLoop(
11312       OMPD_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
11313       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
11314       VarsWithImplicitDSA, B);
11315 
11316   if (NestedLoopCount == 0)
11317     return StmtError();
11318 
11319   assert((CurContext->isDependentContext() || B.builtAll()) &&
11320          "omp for loop exprs were not built");
11321 
11322   setFunctionHasBranchProtectedScope();
11323 
11324   DSAStack->setParentTeamsRegionLoc(StartLoc);
11325 
11326   return OMPTeamsDistributeParallelForDirective::Create(
11327       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
11328       DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion());
11329 }
11330 
11331 StmtResult Sema::ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses,
11332                                                  Stmt *AStmt,
11333                                                  SourceLocation StartLoc,
11334                                                  SourceLocation EndLoc) {
11335   if (!AStmt)
11336     return StmtError();
11337 
11338   auto *CS = cast<CapturedStmt>(AStmt);
11339   // 1.2.2 OpenMP Language Terminology
11340   // Structured block - An executable statement with a single entry at the
11341   // top and a single exit at the bottom.
11342   // The point of exit cannot be a branch out of the structured block.
11343   // longjmp() and throw() must not violate the entry/exit criteria.
11344   CS->getCapturedDecl()->setNothrow();
11345 
11346   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_teams);
11347        ThisCaptureLevel > 1; --ThisCaptureLevel) {
11348     CS = cast<CapturedStmt>(CS->getCapturedStmt());
11349     // 1.2.2 OpenMP Language Terminology
11350     // Structured block - An executable statement with a single entry at the
11351     // top and a single exit at the bottom.
11352     // The point of exit cannot be a branch out of the structured block.
11353     // longjmp() and throw() must not violate the entry/exit criteria.
11354     CS->getCapturedDecl()->setNothrow();
11355   }
11356   setFunctionHasBranchProtectedScope();
11357 
11358   return OMPTargetTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses,
11359                                          AStmt);
11360 }
11361 
11362 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeDirective(
11363     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11364     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
11365   if (!AStmt)
11366     return StmtError();
11367 
11368   auto *CS = cast<CapturedStmt>(AStmt);
11369   // 1.2.2 OpenMP Language Terminology
11370   // Structured block - An executable statement with a single entry at the
11371   // top and a single exit at the bottom.
11372   // The point of exit cannot be a branch out of the structured block.
11373   // longjmp() and throw() must not violate the entry/exit criteria.
11374   CS->getCapturedDecl()->setNothrow();
11375   for (int ThisCaptureLevel =
11376            getOpenMPCaptureLevels(OMPD_target_teams_distribute);
11377        ThisCaptureLevel > 1; --ThisCaptureLevel) {
11378     CS = cast<CapturedStmt>(CS->getCapturedStmt());
11379     // 1.2.2 OpenMP Language Terminology
11380     // Structured block - An executable statement with a single entry at the
11381     // top and a single exit at the bottom.
11382     // The point of exit cannot be a branch out of the structured block.
11383     // longjmp() and throw() must not violate the entry/exit criteria.
11384     CS->getCapturedDecl()->setNothrow();
11385   }
11386 
11387   OMPLoopDirective::HelperExprs B;
11388   // In presence of clause 'collapse' with number of loops, it will
11389   // define the nested loops number.
11390   unsigned NestedLoopCount = checkOpenMPLoop(
11391       OMPD_target_teams_distribute, getCollapseNumberExpr(Clauses),
11392       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
11393       VarsWithImplicitDSA, B);
11394   if (NestedLoopCount == 0)
11395     return StmtError();
11396 
11397   assert((CurContext->isDependentContext() || B.builtAll()) &&
11398          "omp target teams distribute loop exprs were not built");
11399 
11400   setFunctionHasBranchProtectedScope();
11401   return OMPTargetTeamsDistributeDirective::Create(
11402       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
11403 }
11404 
11405 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForDirective(
11406     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11407     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
11408   if (!AStmt)
11409     return StmtError();
11410 
11411   auto *CS = cast<CapturedStmt>(AStmt);
11412   // 1.2.2 OpenMP Language Terminology
11413   // Structured block - An executable statement with a single entry at the
11414   // top and a single exit at the bottom.
11415   // The point of exit cannot be a branch out of the structured block.
11416   // longjmp() and throw() must not violate the entry/exit criteria.
11417   CS->getCapturedDecl()->setNothrow();
11418   for (int ThisCaptureLevel =
11419            getOpenMPCaptureLevels(OMPD_target_teams_distribute_parallel_for);
11420        ThisCaptureLevel > 1; --ThisCaptureLevel) {
11421     CS = cast<CapturedStmt>(CS->getCapturedStmt());
11422     // 1.2.2 OpenMP Language Terminology
11423     // Structured block - An executable statement with a single entry at the
11424     // top and a single exit at the bottom.
11425     // The point of exit cannot be a branch out of the structured block.
11426     // longjmp() and throw() must not violate the entry/exit criteria.
11427     CS->getCapturedDecl()->setNothrow();
11428   }
11429 
11430   OMPLoopDirective::HelperExprs B;
11431   // In presence of clause 'collapse' with number of loops, it will
11432   // define the nested loops number.
11433   unsigned NestedLoopCount = checkOpenMPLoop(
11434       OMPD_target_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
11435       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
11436       VarsWithImplicitDSA, B);
11437   if (NestedLoopCount == 0)
11438     return StmtError();
11439 
11440   assert((CurContext->isDependentContext() || B.builtAll()) &&
11441          "omp target teams distribute parallel for loop exprs were not built");
11442 
11443   if (!CurContext->isDependentContext()) {
11444     // Finalize the clauses that need pre-built expressions for CodeGen.
11445     for (OMPClause *C : Clauses) {
11446       if (auto *LC = dyn_cast<OMPLinearClause>(C))
11447         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
11448                                      B.NumIterations, *this, CurScope,
11449                                      DSAStack))
11450           return StmtError();
11451     }
11452   }
11453 
11454   setFunctionHasBranchProtectedScope();
11455   return OMPTargetTeamsDistributeParallelForDirective::Create(
11456       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
11457       DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion());
11458 }
11459 
11460 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
11461     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11462     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
11463   if (!AStmt)
11464     return StmtError();
11465 
11466   auto *CS = cast<CapturedStmt>(AStmt);
11467   // 1.2.2 OpenMP Language Terminology
11468   // Structured block - An executable statement with a single entry at the
11469   // top and a single exit at the bottom.
11470   // The point of exit cannot be a branch out of the structured block.
11471   // longjmp() and throw() must not violate the entry/exit criteria.
11472   CS->getCapturedDecl()->setNothrow();
11473   for (int ThisCaptureLevel = getOpenMPCaptureLevels(
11474            OMPD_target_teams_distribute_parallel_for_simd);
11475        ThisCaptureLevel > 1; --ThisCaptureLevel) {
11476     CS = cast<CapturedStmt>(CS->getCapturedStmt());
11477     // 1.2.2 OpenMP Language Terminology
11478     // Structured block - An executable statement with a single entry at the
11479     // top and a single exit at the bottom.
11480     // The point of exit cannot be a branch out of the structured block.
11481     // longjmp() and throw() must not violate the entry/exit criteria.
11482     CS->getCapturedDecl()->setNothrow();
11483   }
11484 
11485   OMPLoopDirective::HelperExprs B;
11486   // In presence of clause 'collapse' with number of loops, it will
11487   // define the nested loops number.
11488   unsigned NestedLoopCount =
11489       checkOpenMPLoop(OMPD_target_teams_distribute_parallel_for_simd,
11490                       getCollapseNumberExpr(Clauses),
11491                       nullptr /*ordered not a clause on distribute*/, CS, *this,
11492                       *DSAStack, VarsWithImplicitDSA, B);
11493   if (NestedLoopCount == 0)
11494     return StmtError();
11495 
11496   assert((CurContext->isDependentContext() || B.builtAll()) &&
11497          "omp target teams distribute parallel for simd loop exprs were not "
11498          "built");
11499 
11500   if (!CurContext->isDependentContext()) {
11501     // Finalize the clauses that need pre-built expressions for CodeGen.
11502     for (OMPClause *C : Clauses) {
11503       if (auto *LC = dyn_cast<OMPLinearClause>(C))
11504         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
11505                                      B.NumIterations, *this, CurScope,
11506                                      DSAStack))
11507           return StmtError();
11508     }
11509   }
11510 
11511   if (checkSimdlenSafelenSpecified(*this, Clauses))
11512     return StmtError();
11513 
11514   setFunctionHasBranchProtectedScope();
11515   return OMPTargetTeamsDistributeParallelForSimdDirective::Create(
11516       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
11517 }
11518 
11519 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeSimdDirective(
11520     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11521     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
11522   if (!AStmt)
11523     return StmtError();
11524 
11525   auto *CS = cast<CapturedStmt>(AStmt);
11526   // 1.2.2 OpenMP Language Terminology
11527   // Structured block - An executable statement with a single entry at the
11528   // top and a single exit at the bottom.
11529   // The point of exit cannot be a branch out of the structured block.
11530   // longjmp() and throw() must not violate the entry/exit criteria.
11531   CS->getCapturedDecl()->setNothrow();
11532   for (int ThisCaptureLevel =
11533            getOpenMPCaptureLevels(OMPD_target_teams_distribute_simd);
11534        ThisCaptureLevel > 1; --ThisCaptureLevel) {
11535     CS = cast<CapturedStmt>(CS->getCapturedStmt());
11536     // 1.2.2 OpenMP Language Terminology
11537     // Structured block - An executable statement with a single entry at the
11538     // top and a single exit at the bottom.
11539     // The point of exit cannot be a branch out of the structured block.
11540     // longjmp() and throw() must not violate the entry/exit criteria.
11541     CS->getCapturedDecl()->setNothrow();
11542   }
11543 
11544   OMPLoopDirective::HelperExprs B;
11545   // In presence of clause 'collapse' with number of loops, it will
11546   // define the nested loops number.
11547   unsigned NestedLoopCount = checkOpenMPLoop(
11548       OMPD_target_teams_distribute_simd, getCollapseNumberExpr(Clauses),
11549       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
11550       VarsWithImplicitDSA, B);
11551   if (NestedLoopCount == 0)
11552     return StmtError();
11553 
11554   assert((CurContext->isDependentContext() || B.builtAll()) &&
11555          "omp target teams distribute simd loop exprs were not built");
11556 
11557   if (!CurContext->isDependentContext()) {
11558     // Finalize the clauses that need pre-built expressions for CodeGen.
11559     for (OMPClause *C : Clauses) {
11560       if (auto *LC = dyn_cast<OMPLinearClause>(C))
11561         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
11562                                      B.NumIterations, *this, CurScope,
11563                                      DSAStack))
11564           return StmtError();
11565     }
11566   }
11567 
11568   if (checkSimdlenSafelenSpecified(*this, Clauses))
11569     return StmtError();
11570 
11571   setFunctionHasBranchProtectedScope();
11572   return OMPTargetTeamsDistributeSimdDirective::Create(
11573       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
11574 }
11575 
11576 OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
11577                                              SourceLocation StartLoc,
11578                                              SourceLocation LParenLoc,
11579                                              SourceLocation EndLoc) {
11580   OMPClause *Res = nullptr;
11581   switch (Kind) {
11582   case OMPC_final:
11583     Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc);
11584     break;
11585   case OMPC_num_threads:
11586     Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc);
11587     break;
11588   case OMPC_safelen:
11589     Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
11590     break;
11591   case OMPC_simdlen:
11592     Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc);
11593     break;
11594   case OMPC_allocator:
11595     Res = ActOnOpenMPAllocatorClause(Expr, StartLoc, LParenLoc, EndLoc);
11596     break;
11597   case OMPC_collapse:
11598     Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc);
11599     break;
11600   case OMPC_ordered:
11601     Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr);
11602     break;
11603   case OMPC_num_teams:
11604     Res = ActOnOpenMPNumTeamsClause(Expr, StartLoc, LParenLoc, EndLoc);
11605     break;
11606   case OMPC_thread_limit:
11607     Res = ActOnOpenMPThreadLimitClause(Expr, StartLoc, LParenLoc, EndLoc);
11608     break;
11609   case OMPC_priority:
11610     Res = ActOnOpenMPPriorityClause(Expr, StartLoc, LParenLoc, EndLoc);
11611     break;
11612   case OMPC_grainsize:
11613     Res = ActOnOpenMPGrainsizeClause(Expr, StartLoc, LParenLoc, EndLoc);
11614     break;
11615   case OMPC_num_tasks:
11616     Res = ActOnOpenMPNumTasksClause(Expr, StartLoc, LParenLoc, EndLoc);
11617     break;
11618   case OMPC_hint:
11619     Res = ActOnOpenMPHintClause(Expr, StartLoc, LParenLoc, EndLoc);
11620     break;
11621   case OMPC_depobj:
11622     Res = ActOnOpenMPDepobjClause(Expr, StartLoc, LParenLoc, EndLoc);
11623     break;
11624   case OMPC_detach:
11625     Res = ActOnOpenMPDetachClause(Expr, StartLoc, LParenLoc, EndLoc);
11626     break;
11627   case OMPC_device:
11628   case OMPC_if:
11629   case OMPC_default:
11630   case OMPC_proc_bind:
11631   case OMPC_schedule:
11632   case OMPC_private:
11633   case OMPC_firstprivate:
11634   case OMPC_lastprivate:
11635   case OMPC_shared:
11636   case OMPC_reduction:
11637   case OMPC_task_reduction:
11638   case OMPC_in_reduction:
11639   case OMPC_linear:
11640   case OMPC_aligned:
11641   case OMPC_copyin:
11642   case OMPC_copyprivate:
11643   case OMPC_nowait:
11644   case OMPC_untied:
11645   case OMPC_mergeable:
11646   case OMPC_threadprivate:
11647   case OMPC_allocate:
11648   case OMPC_flush:
11649   case OMPC_read:
11650   case OMPC_write:
11651   case OMPC_update:
11652   case OMPC_capture:
11653   case OMPC_seq_cst:
11654   case OMPC_acq_rel:
11655   case OMPC_acquire:
11656   case OMPC_release:
11657   case OMPC_relaxed:
11658   case OMPC_depend:
11659   case OMPC_threads:
11660   case OMPC_simd:
11661   case OMPC_map:
11662   case OMPC_nogroup:
11663   case OMPC_dist_schedule:
11664   case OMPC_defaultmap:
11665   case OMPC_unknown:
11666   case OMPC_uniform:
11667   case OMPC_to:
11668   case OMPC_from:
11669   case OMPC_use_device_ptr:
11670   case OMPC_use_device_addr:
11671   case OMPC_is_device_ptr:
11672   case OMPC_unified_address:
11673   case OMPC_unified_shared_memory:
11674   case OMPC_reverse_offload:
11675   case OMPC_dynamic_allocators:
11676   case OMPC_atomic_default_mem_order:
11677   case OMPC_device_type:
11678   case OMPC_match:
11679   case OMPC_nontemporal:
11680   case OMPC_order:
11681   case OMPC_destroy:
11682   case OMPC_inclusive:
11683   case OMPC_exclusive:
11684   case OMPC_uses_allocators:
11685   case OMPC_affinity:
11686     llvm_unreachable("Clause is not allowed.");
11687   }
11688   return Res;
11689 }
11690 
11691 // An OpenMP directive such as 'target parallel' has two captured regions:
11692 // for the 'target' and 'parallel' respectively.  This function returns
11693 // the region in which to capture expressions associated with a clause.
11694 // A return value of OMPD_unknown signifies that the expression should not
11695 // be captured.
11696 static OpenMPDirectiveKind getOpenMPCaptureRegionForClause(
11697     OpenMPDirectiveKind DKind, OpenMPClauseKind CKind, unsigned OpenMPVersion,
11698     OpenMPDirectiveKind NameModifier = OMPD_unknown) {
11699   OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
11700   switch (CKind) {
11701   case OMPC_if:
11702     switch (DKind) {
11703     case OMPD_target_parallel_for_simd:
11704       if (OpenMPVersion >= 50 &&
11705           (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)) {
11706         CaptureRegion = OMPD_parallel;
11707         break;
11708       }
11709       LLVM_FALLTHROUGH;
11710     case OMPD_target_parallel:
11711     case OMPD_target_parallel_for:
11712       // If this clause applies to the nested 'parallel' region, capture within
11713       // the 'target' region, otherwise do not capture.
11714       if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
11715         CaptureRegion = OMPD_target;
11716       break;
11717     case OMPD_target_teams_distribute_parallel_for_simd:
11718       if (OpenMPVersion >= 50 &&
11719           (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)) {
11720         CaptureRegion = OMPD_parallel;
11721         break;
11722       }
11723       LLVM_FALLTHROUGH;
11724     case OMPD_target_teams_distribute_parallel_for:
11725       // If this clause applies to the nested 'parallel' region, capture within
11726       // the 'teams' region, otherwise do not capture.
11727       if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
11728         CaptureRegion = OMPD_teams;
11729       break;
11730     case OMPD_teams_distribute_parallel_for_simd:
11731       if (OpenMPVersion >= 50 &&
11732           (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)) {
11733         CaptureRegion = OMPD_parallel;
11734         break;
11735       }
11736       LLVM_FALLTHROUGH;
11737     case OMPD_teams_distribute_parallel_for:
11738       CaptureRegion = OMPD_teams;
11739       break;
11740     case OMPD_target_update:
11741     case OMPD_target_enter_data:
11742     case OMPD_target_exit_data:
11743       CaptureRegion = OMPD_task;
11744       break;
11745     case OMPD_parallel_master_taskloop:
11746       if (NameModifier == OMPD_unknown || NameModifier == OMPD_taskloop)
11747         CaptureRegion = OMPD_parallel;
11748       break;
11749     case OMPD_parallel_master_taskloop_simd:
11750       if ((OpenMPVersion <= 45 && NameModifier == OMPD_unknown) ||
11751           NameModifier == OMPD_taskloop) {
11752         CaptureRegion = OMPD_parallel;
11753         break;
11754       }
11755       if (OpenMPVersion <= 45)
11756         break;
11757       if (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)
11758         CaptureRegion = OMPD_taskloop;
11759       break;
11760     case OMPD_parallel_for_simd:
11761       if (OpenMPVersion <= 45)
11762         break;
11763       if (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)
11764         CaptureRegion = OMPD_parallel;
11765       break;
11766     case OMPD_taskloop_simd:
11767     case OMPD_master_taskloop_simd:
11768       if (OpenMPVersion <= 45)
11769         break;
11770       if (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)
11771         CaptureRegion = OMPD_taskloop;
11772       break;
11773     case OMPD_distribute_parallel_for_simd:
11774       if (OpenMPVersion <= 45)
11775         break;
11776       if (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)
11777         CaptureRegion = OMPD_parallel;
11778       break;
11779     case OMPD_target_simd:
11780       if (OpenMPVersion >= 50 &&
11781           (NameModifier == OMPD_unknown || NameModifier == OMPD_simd))
11782         CaptureRegion = OMPD_target;
11783       break;
11784     case OMPD_teams_distribute_simd:
11785     case OMPD_target_teams_distribute_simd:
11786       if (OpenMPVersion >= 50 &&
11787           (NameModifier == OMPD_unknown || NameModifier == OMPD_simd))
11788         CaptureRegion = OMPD_teams;
11789       break;
11790     case OMPD_cancel:
11791     case OMPD_parallel:
11792     case OMPD_parallel_master:
11793     case OMPD_parallel_sections:
11794     case OMPD_parallel_for:
11795     case OMPD_target:
11796     case OMPD_target_teams:
11797     case OMPD_target_teams_distribute:
11798     case OMPD_distribute_parallel_for:
11799     case OMPD_task:
11800     case OMPD_taskloop:
11801     case OMPD_master_taskloop:
11802     case OMPD_target_data:
11803     case OMPD_simd:
11804     case OMPD_for_simd:
11805     case OMPD_distribute_simd:
11806       // Do not capture if-clause expressions.
11807       break;
11808     case OMPD_threadprivate:
11809     case OMPD_allocate:
11810     case OMPD_taskyield:
11811     case OMPD_barrier:
11812     case OMPD_taskwait:
11813     case OMPD_cancellation_point:
11814     case OMPD_flush:
11815     case OMPD_depobj:
11816     case OMPD_scan:
11817     case OMPD_declare_reduction:
11818     case OMPD_declare_mapper:
11819     case OMPD_declare_simd:
11820     case OMPD_declare_variant:
11821     case OMPD_begin_declare_variant:
11822     case OMPD_end_declare_variant:
11823     case OMPD_declare_target:
11824     case OMPD_end_declare_target:
11825     case OMPD_teams:
11826     case OMPD_for:
11827     case OMPD_sections:
11828     case OMPD_section:
11829     case OMPD_single:
11830     case OMPD_master:
11831     case OMPD_critical:
11832     case OMPD_taskgroup:
11833     case OMPD_distribute:
11834     case OMPD_ordered:
11835     case OMPD_atomic:
11836     case OMPD_teams_distribute:
11837     case OMPD_requires:
11838       llvm_unreachable("Unexpected OpenMP directive with if-clause");
11839     case OMPD_unknown:
11840       llvm_unreachable("Unknown OpenMP directive");
11841     }
11842     break;
11843   case OMPC_num_threads:
11844     switch (DKind) {
11845     case OMPD_target_parallel:
11846     case OMPD_target_parallel_for:
11847     case OMPD_target_parallel_for_simd:
11848       CaptureRegion = OMPD_target;
11849       break;
11850     case OMPD_teams_distribute_parallel_for:
11851     case OMPD_teams_distribute_parallel_for_simd:
11852     case OMPD_target_teams_distribute_parallel_for:
11853     case OMPD_target_teams_distribute_parallel_for_simd:
11854       CaptureRegion = OMPD_teams;
11855       break;
11856     case OMPD_parallel:
11857     case OMPD_parallel_master:
11858     case OMPD_parallel_sections:
11859     case OMPD_parallel_for:
11860     case OMPD_parallel_for_simd:
11861     case OMPD_distribute_parallel_for:
11862     case OMPD_distribute_parallel_for_simd:
11863     case OMPD_parallel_master_taskloop:
11864     case OMPD_parallel_master_taskloop_simd:
11865       // Do not capture num_threads-clause expressions.
11866       break;
11867     case OMPD_target_data:
11868     case OMPD_target_enter_data:
11869     case OMPD_target_exit_data:
11870     case OMPD_target_update:
11871     case OMPD_target:
11872     case OMPD_target_simd:
11873     case OMPD_target_teams:
11874     case OMPD_target_teams_distribute:
11875     case OMPD_target_teams_distribute_simd:
11876     case OMPD_cancel:
11877     case OMPD_task:
11878     case OMPD_taskloop:
11879     case OMPD_taskloop_simd:
11880     case OMPD_master_taskloop:
11881     case OMPD_master_taskloop_simd:
11882     case OMPD_threadprivate:
11883     case OMPD_allocate:
11884     case OMPD_taskyield:
11885     case OMPD_barrier:
11886     case OMPD_taskwait:
11887     case OMPD_cancellation_point:
11888     case OMPD_flush:
11889     case OMPD_depobj:
11890     case OMPD_scan:
11891     case OMPD_declare_reduction:
11892     case OMPD_declare_mapper:
11893     case OMPD_declare_simd:
11894     case OMPD_declare_variant:
11895     case OMPD_begin_declare_variant:
11896     case OMPD_end_declare_variant:
11897     case OMPD_declare_target:
11898     case OMPD_end_declare_target:
11899     case OMPD_teams:
11900     case OMPD_simd:
11901     case OMPD_for:
11902     case OMPD_for_simd:
11903     case OMPD_sections:
11904     case OMPD_section:
11905     case OMPD_single:
11906     case OMPD_master:
11907     case OMPD_critical:
11908     case OMPD_taskgroup:
11909     case OMPD_distribute:
11910     case OMPD_ordered:
11911     case OMPD_atomic:
11912     case OMPD_distribute_simd:
11913     case OMPD_teams_distribute:
11914     case OMPD_teams_distribute_simd:
11915     case OMPD_requires:
11916       llvm_unreachable("Unexpected OpenMP directive with num_threads-clause");
11917     case OMPD_unknown:
11918       llvm_unreachable("Unknown OpenMP directive");
11919     }
11920     break;
11921   case OMPC_num_teams:
11922     switch (DKind) {
11923     case OMPD_target_teams:
11924     case OMPD_target_teams_distribute:
11925     case OMPD_target_teams_distribute_simd:
11926     case OMPD_target_teams_distribute_parallel_for:
11927     case OMPD_target_teams_distribute_parallel_for_simd:
11928       CaptureRegion = OMPD_target;
11929       break;
11930     case OMPD_teams_distribute_parallel_for:
11931     case OMPD_teams_distribute_parallel_for_simd:
11932     case OMPD_teams:
11933     case OMPD_teams_distribute:
11934     case OMPD_teams_distribute_simd:
11935       // Do not capture num_teams-clause expressions.
11936       break;
11937     case OMPD_distribute_parallel_for:
11938     case OMPD_distribute_parallel_for_simd:
11939     case OMPD_task:
11940     case OMPD_taskloop:
11941     case OMPD_taskloop_simd:
11942     case OMPD_master_taskloop:
11943     case OMPD_master_taskloop_simd:
11944     case OMPD_parallel_master_taskloop:
11945     case OMPD_parallel_master_taskloop_simd:
11946     case OMPD_target_data:
11947     case OMPD_target_enter_data:
11948     case OMPD_target_exit_data:
11949     case OMPD_target_update:
11950     case OMPD_cancel:
11951     case OMPD_parallel:
11952     case OMPD_parallel_master:
11953     case OMPD_parallel_sections:
11954     case OMPD_parallel_for:
11955     case OMPD_parallel_for_simd:
11956     case OMPD_target:
11957     case OMPD_target_simd:
11958     case OMPD_target_parallel:
11959     case OMPD_target_parallel_for:
11960     case OMPD_target_parallel_for_simd:
11961     case OMPD_threadprivate:
11962     case OMPD_allocate:
11963     case OMPD_taskyield:
11964     case OMPD_barrier:
11965     case OMPD_taskwait:
11966     case OMPD_cancellation_point:
11967     case OMPD_flush:
11968     case OMPD_depobj:
11969     case OMPD_scan:
11970     case OMPD_declare_reduction:
11971     case OMPD_declare_mapper:
11972     case OMPD_declare_simd:
11973     case OMPD_declare_variant:
11974     case OMPD_begin_declare_variant:
11975     case OMPD_end_declare_variant:
11976     case OMPD_declare_target:
11977     case OMPD_end_declare_target:
11978     case OMPD_simd:
11979     case OMPD_for:
11980     case OMPD_for_simd:
11981     case OMPD_sections:
11982     case OMPD_section:
11983     case OMPD_single:
11984     case OMPD_master:
11985     case OMPD_critical:
11986     case OMPD_taskgroup:
11987     case OMPD_distribute:
11988     case OMPD_ordered:
11989     case OMPD_atomic:
11990     case OMPD_distribute_simd:
11991     case OMPD_requires:
11992       llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
11993     case OMPD_unknown:
11994       llvm_unreachable("Unknown OpenMP directive");
11995     }
11996     break;
11997   case OMPC_thread_limit:
11998     switch (DKind) {
11999     case OMPD_target_teams:
12000     case OMPD_target_teams_distribute:
12001     case OMPD_target_teams_distribute_simd:
12002     case OMPD_target_teams_distribute_parallel_for:
12003     case OMPD_target_teams_distribute_parallel_for_simd:
12004       CaptureRegion = OMPD_target;
12005       break;
12006     case OMPD_teams_distribute_parallel_for:
12007     case OMPD_teams_distribute_parallel_for_simd:
12008     case OMPD_teams:
12009     case OMPD_teams_distribute:
12010     case OMPD_teams_distribute_simd:
12011       // Do not capture thread_limit-clause expressions.
12012       break;
12013     case OMPD_distribute_parallel_for:
12014     case OMPD_distribute_parallel_for_simd:
12015     case OMPD_task:
12016     case OMPD_taskloop:
12017     case OMPD_taskloop_simd:
12018     case OMPD_master_taskloop:
12019     case OMPD_master_taskloop_simd:
12020     case OMPD_parallel_master_taskloop:
12021     case OMPD_parallel_master_taskloop_simd:
12022     case OMPD_target_data:
12023     case OMPD_target_enter_data:
12024     case OMPD_target_exit_data:
12025     case OMPD_target_update:
12026     case OMPD_cancel:
12027     case OMPD_parallel:
12028     case OMPD_parallel_master:
12029     case OMPD_parallel_sections:
12030     case OMPD_parallel_for:
12031     case OMPD_parallel_for_simd:
12032     case OMPD_target:
12033     case OMPD_target_simd:
12034     case OMPD_target_parallel:
12035     case OMPD_target_parallel_for:
12036     case OMPD_target_parallel_for_simd:
12037     case OMPD_threadprivate:
12038     case OMPD_allocate:
12039     case OMPD_taskyield:
12040     case OMPD_barrier:
12041     case OMPD_taskwait:
12042     case OMPD_cancellation_point:
12043     case OMPD_flush:
12044     case OMPD_depobj:
12045     case OMPD_scan:
12046     case OMPD_declare_reduction:
12047     case OMPD_declare_mapper:
12048     case OMPD_declare_simd:
12049     case OMPD_declare_variant:
12050     case OMPD_begin_declare_variant:
12051     case OMPD_end_declare_variant:
12052     case OMPD_declare_target:
12053     case OMPD_end_declare_target:
12054     case OMPD_simd:
12055     case OMPD_for:
12056     case OMPD_for_simd:
12057     case OMPD_sections:
12058     case OMPD_section:
12059     case OMPD_single:
12060     case OMPD_master:
12061     case OMPD_critical:
12062     case OMPD_taskgroup:
12063     case OMPD_distribute:
12064     case OMPD_ordered:
12065     case OMPD_atomic:
12066     case OMPD_distribute_simd:
12067     case OMPD_requires:
12068       llvm_unreachable("Unexpected OpenMP directive with thread_limit-clause");
12069     case OMPD_unknown:
12070       llvm_unreachable("Unknown OpenMP directive");
12071     }
12072     break;
12073   case OMPC_schedule:
12074     switch (DKind) {
12075     case OMPD_parallel_for:
12076     case OMPD_parallel_for_simd:
12077     case OMPD_distribute_parallel_for:
12078     case OMPD_distribute_parallel_for_simd:
12079     case OMPD_teams_distribute_parallel_for:
12080     case OMPD_teams_distribute_parallel_for_simd:
12081     case OMPD_target_parallel_for:
12082     case OMPD_target_parallel_for_simd:
12083     case OMPD_target_teams_distribute_parallel_for:
12084     case OMPD_target_teams_distribute_parallel_for_simd:
12085       CaptureRegion = OMPD_parallel;
12086       break;
12087     case OMPD_for:
12088     case OMPD_for_simd:
12089       // Do not capture schedule-clause expressions.
12090       break;
12091     case OMPD_task:
12092     case OMPD_taskloop:
12093     case OMPD_taskloop_simd:
12094     case OMPD_master_taskloop:
12095     case OMPD_master_taskloop_simd:
12096     case OMPD_parallel_master_taskloop:
12097     case OMPD_parallel_master_taskloop_simd:
12098     case OMPD_target_data:
12099     case OMPD_target_enter_data:
12100     case OMPD_target_exit_data:
12101     case OMPD_target_update:
12102     case OMPD_teams:
12103     case OMPD_teams_distribute:
12104     case OMPD_teams_distribute_simd:
12105     case OMPD_target_teams_distribute:
12106     case OMPD_target_teams_distribute_simd:
12107     case OMPD_target:
12108     case OMPD_target_simd:
12109     case OMPD_target_parallel:
12110     case OMPD_cancel:
12111     case OMPD_parallel:
12112     case OMPD_parallel_master:
12113     case OMPD_parallel_sections:
12114     case OMPD_threadprivate:
12115     case OMPD_allocate:
12116     case OMPD_taskyield:
12117     case OMPD_barrier:
12118     case OMPD_taskwait:
12119     case OMPD_cancellation_point:
12120     case OMPD_flush:
12121     case OMPD_depobj:
12122     case OMPD_scan:
12123     case OMPD_declare_reduction:
12124     case OMPD_declare_mapper:
12125     case OMPD_declare_simd:
12126     case OMPD_declare_variant:
12127     case OMPD_begin_declare_variant:
12128     case OMPD_end_declare_variant:
12129     case OMPD_declare_target:
12130     case OMPD_end_declare_target:
12131     case OMPD_simd:
12132     case OMPD_sections:
12133     case OMPD_section:
12134     case OMPD_single:
12135     case OMPD_master:
12136     case OMPD_critical:
12137     case OMPD_taskgroup:
12138     case OMPD_distribute:
12139     case OMPD_ordered:
12140     case OMPD_atomic:
12141     case OMPD_distribute_simd:
12142     case OMPD_target_teams:
12143     case OMPD_requires:
12144       llvm_unreachable("Unexpected OpenMP directive with schedule clause");
12145     case OMPD_unknown:
12146       llvm_unreachable("Unknown OpenMP directive");
12147     }
12148     break;
12149   case OMPC_dist_schedule:
12150     switch (DKind) {
12151     case OMPD_teams_distribute_parallel_for:
12152     case OMPD_teams_distribute_parallel_for_simd:
12153     case OMPD_teams_distribute:
12154     case OMPD_teams_distribute_simd:
12155     case OMPD_target_teams_distribute_parallel_for:
12156     case OMPD_target_teams_distribute_parallel_for_simd:
12157     case OMPD_target_teams_distribute:
12158     case OMPD_target_teams_distribute_simd:
12159       CaptureRegion = OMPD_teams;
12160       break;
12161     case OMPD_distribute_parallel_for:
12162     case OMPD_distribute_parallel_for_simd:
12163     case OMPD_distribute:
12164     case OMPD_distribute_simd:
12165       // Do not capture thread_limit-clause expressions.
12166       break;
12167     case OMPD_parallel_for:
12168     case OMPD_parallel_for_simd:
12169     case OMPD_target_parallel_for_simd:
12170     case OMPD_target_parallel_for:
12171     case OMPD_task:
12172     case OMPD_taskloop:
12173     case OMPD_taskloop_simd:
12174     case OMPD_master_taskloop:
12175     case OMPD_master_taskloop_simd:
12176     case OMPD_parallel_master_taskloop:
12177     case OMPD_parallel_master_taskloop_simd:
12178     case OMPD_target_data:
12179     case OMPD_target_enter_data:
12180     case OMPD_target_exit_data:
12181     case OMPD_target_update:
12182     case OMPD_teams:
12183     case OMPD_target:
12184     case OMPD_target_simd:
12185     case OMPD_target_parallel:
12186     case OMPD_cancel:
12187     case OMPD_parallel:
12188     case OMPD_parallel_master:
12189     case OMPD_parallel_sections:
12190     case OMPD_threadprivate:
12191     case OMPD_allocate:
12192     case OMPD_taskyield:
12193     case OMPD_barrier:
12194     case OMPD_taskwait:
12195     case OMPD_cancellation_point:
12196     case OMPD_flush:
12197     case OMPD_depobj:
12198     case OMPD_scan:
12199     case OMPD_declare_reduction:
12200     case OMPD_declare_mapper:
12201     case OMPD_declare_simd:
12202     case OMPD_declare_variant:
12203     case OMPD_begin_declare_variant:
12204     case OMPD_end_declare_variant:
12205     case OMPD_declare_target:
12206     case OMPD_end_declare_target:
12207     case OMPD_simd:
12208     case OMPD_for:
12209     case OMPD_for_simd:
12210     case OMPD_sections:
12211     case OMPD_section:
12212     case OMPD_single:
12213     case OMPD_master:
12214     case OMPD_critical:
12215     case OMPD_taskgroup:
12216     case OMPD_ordered:
12217     case OMPD_atomic:
12218     case OMPD_target_teams:
12219     case OMPD_requires:
12220       llvm_unreachable("Unexpected OpenMP directive with schedule clause");
12221     case OMPD_unknown:
12222       llvm_unreachable("Unknown OpenMP directive");
12223     }
12224     break;
12225   case OMPC_device:
12226     switch (DKind) {
12227     case OMPD_target_update:
12228     case OMPD_target_enter_data:
12229     case OMPD_target_exit_data:
12230     case OMPD_target:
12231     case OMPD_target_simd:
12232     case OMPD_target_teams:
12233     case OMPD_target_parallel:
12234     case OMPD_target_teams_distribute:
12235     case OMPD_target_teams_distribute_simd:
12236     case OMPD_target_parallel_for:
12237     case OMPD_target_parallel_for_simd:
12238     case OMPD_target_teams_distribute_parallel_for:
12239     case OMPD_target_teams_distribute_parallel_for_simd:
12240       CaptureRegion = OMPD_task;
12241       break;
12242     case OMPD_target_data:
12243       // Do not capture device-clause expressions.
12244       break;
12245     case OMPD_teams_distribute_parallel_for:
12246     case OMPD_teams_distribute_parallel_for_simd:
12247     case OMPD_teams:
12248     case OMPD_teams_distribute:
12249     case OMPD_teams_distribute_simd:
12250     case OMPD_distribute_parallel_for:
12251     case OMPD_distribute_parallel_for_simd:
12252     case OMPD_task:
12253     case OMPD_taskloop:
12254     case OMPD_taskloop_simd:
12255     case OMPD_master_taskloop:
12256     case OMPD_master_taskloop_simd:
12257     case OMPD_parallel_master_taskloop:
12258     case OMPD_parallel_master_taskloop_simd:
12259     case OMPD_cancel:
12260     case OMPD_parallel:
12261     case OMPD_parallel_master:
12262     case OMPD_parallel_sections:
12263     case OMPD_parallel_for:
12264     case OMPD_parallel_for_simd:
12265     case OMPD_threadprivate:
12266     case OMPD_allocate:
12267     case OMPD_taskyield:
12268     case OMPD_barrier:
12269     case OMPD_taskwait:
12270     case OMPD_cancellation_point:
12271     case OMPD_flush:
12272     case OMPD_depobj:
12273     case OMPD_scan:
12274     case OMPD_declare_reduction:
12275     case OMPD_declare_mapper:
12276     case OMPD_declare_simd:
12277     case OMPD_declare_variant:
12278     case OMPD_begin_declare_variant:
12279     case OMPD_end_declare_variant:
12280     case OMPD_declare_target:
12281     case OMPD_end_declare_target:
12282     case OMPD_simd:
12283     case OMPD_for:
12284     case OMPD_for_simd:
12285     case OMPD_sections:
12286     case OMPD_section:
12287     case OMPD_single:
12288     case OMPD_master:
12289     case OMPD_critical:
12290     case OMPD_taskgroup:
12291     case OMPD_distribute:
12292     case OMPD_ordered:
12293     case OMPD_atomic:
12294     case OMPD_distribute_simd:
12295     case OMPD_requires:
12296       llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
12297     case OMPD_unknown:
12298       llvm_unreachable("Unknown OpenMP directive");
12299     }
12300     break;
12301   case OMPC_grainsize:
12302   case OMPC_num_tasks:
12303   case OMPC_final:
12304   case OMPC_priority:
12305     switch (DKind) {
12306     case OMPD_task:
12307     case OMPD_taskloop:
12308     case OMPD_taskloop_simd:
12309     case OMPD_master_taskloop:
12310     case OMPD_master_taskloop_simd:
12311       break;
12312     case OMPD_parallel_master_taskloop:
12313     case OMPD_parallel_master_taskloop_simd:
12314       CaptureRegion = OMPD_parallel;
12315       break;
12316     case OMPD_target_update:
12317     case OMPD_target_enter_data:
12318     case OMPD_target_exit_data:
12319     case OMPD_target:
12320     case OMPD_target_simd:
12321     case OMPD_target_teams:
12322     case OMPD_target_parallel:
12323     case OMPD_target_teams_distribute:
12324     case OMPD_target_teams_distribute_simd:
12325     case OMPD_target_parallel_for:
12326     case OMPD_target_parallel_for_simd:
12327     case OMPD_target_teams_distribute_parallel_for:
12328     case OMPD_target_teams_distribute_parallel_for_simd:
12329     case OMPD_target_data:
12330     case OMPD_teams_distribute_parallel_for:
12331     case OMPD_teams_distribute_parallel_for_simd:
12332     case OMPD_teams:
12333     case OMPD_teams_distribute:
12334     case OMPD_teams_distribute_simd:
12335     case OMPD_distribute_parallel_for:
12336     case OMPD_distribute_parallel_for_simd:
12337     case OMPD_cancel:
12338     case OMPD_parallel:
12339     case OMPD_parallel_master:
12340     case OMPD_parallel_sections:
12341     case OMPD_parallel_for:
12342     case OMPD_parallel_for_simd:
12343     case OMPD_threadprivate:
12344     case OMPD_allocate:
12345     case OMPD_taskyield:
12346     case OMPD_barrier:
12347     case OMPD_taskwait:
12348     case OMPD_cancellation_point:
12349     case OMPD_flush:
12350     case OMPD_depobj:
12351     case OMPD_scan:
12352     case OMPD_declare_reduction:
12353     case OMPD_declare_mapper:
12354     case OMPD_declare_simd:
12355     case OMPD_declare_variant:
12356     case OMPD_begin_declare_variant:
12357     case OMPD_end_declare_variant:
12358     case OMPD_declare_target:
12359     case OMPD_end_declare_target:
12360     case OMPD_simd:
12361     case OMPD_for:
12362     case OMPD_for_simd:
12363     case OMPD_sections:
12364     case OMPD_section:
12365     case OMPD_single:
12366     case OMPD_master:
12367     case OMPD_critical:
12368     case OMPD_taskgroup:
12369     case OMPD_distribute:
12370     case OMPD_ordered:
12371     case OMPD_atomic:
12372     case OMPD_distribute_simd:
12373     case OMPD_requires:
12374       llvm_unreachable("Unexpected OpenMP directive with grainsize-clause");
12375     case OMPD_unknown:
12376       llvm_unreachable("Unknown OpenMP directive");
12377     }
12378     break;
12379   case OMPC_firstprivate:
12380   case OMPC_lastprivate:
12381   case OMPC_reduction:
12382   case OMPC_task_reduction:
12383   case OMPC_in_reduction:
12384   case OMPC_linear:
12385   case OMPC_default:
12386   case OMPC_proc_bind:
12387   case OMPC_safelen:
12388   case OMPC_simdlen:
12389   case OMPC_allocator:
12390   case OMPC_collapse:
12391   case OMPC_private:
12392   case OMPC_shared:
12393   case OMPC_aligned:
12394   case OMPC_copyin:
12395   case OMPC_copyprivate:
12396   case OMPC_ordered:
12397   case OMPC_nowait:
12398   case OMPC_untied:
12399   case OMPC_mergeable:
12400   case OMPC_threadprivate:
12401   case OMPC_allocate:
12402   case OMPC_flush:
12403   case OMPC_depobj:
12404   case OMPC_read:
12405   case OMPC_write:
12406   case OMPC_update:
12407   case OMPC_capture:
12408   case OMPC_seq_cst:
12409   case OMPC_acq_rel:
12410   case OMPC_acquire:
12411   case OMPC_release:
12412   case OMPC_relaxed:
12413   case OMPC_depend:
12414   case OMPC_threads:
12415   case OMPC_simd:
12416   case OMPC_map:
12417   case OMPC_nogroup:
12418   case OMPC_hint:
12419   case OMPC_defaultmap:
12420   case OMPC_unknown:
12421   case OMPC_uniform:
12422   case OMPC_to:
12423   case OMPC_from:
12424   case OMPC_use_device_ptr:
12425   case OMPC_use_device_addr:
12426   case OMPC_is_device_ptr:
12427   case OMPC_unified_address:
12428   case OMPC_unified_shared_memory:
12429   case OMPC_reverse_offload:
12430   case OMPC_dynamic_allocators:
12431   case OMPC_atomic_default_mem_order:
12432   case OMPC_device_type:
12433   case OMPC_match:
12434   case OMPC_nontemporal:
12435   case OMPC_order:
12436   case OMPC_destroy:
12437   case OMPC_detach:
12438   case OMPC_inclusive:
12439   case OMPC_exclusive:
12440   case OMPC_uses_allocators:
12441   case OMPC_affinity:
12442     llvm_unreachable("Unexpected OpenMP clause.");
12443   }
12444   return CaptureRegion;
12445 }
12446 
12447 OMPClause *Sema::ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
12448                                      Expr *Condition, SourceLocation StartLoc,
12449                                      SourceLocation LParenLoc,
12450                                      SourceLocation NameModifierLoc,
12451                                      SourceLocation ColonLoc,
12452                                      SourceLocation EndLoc) {
12453   Expr *ValExpr = Condition;
12454   Stmt *HelperValStmt = nullptr;
12455   OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
12456   if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
12457       !Condition->isInstantiationDependent() &&
12458       !Condition->containsUnexpandedParameterPack()) {
12459     ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
12460     if (Val.isInvalid())
12461       return nullptr;
12462 
12463     ValExpr = Val.get();
12464 
12465     OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
12466     CaptureRegion = getOpenMPCaptureRegionForClause(
12467         DKind, OMPC_if, LangOpts.OpenMP, NameModifier);
12468     if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
12469       ValExpr = MakeFullExpr(ValExpr).get();
12470       llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
12471       ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
12472       HelperValStmt = buildPreInits(Context, Captures);
12473     }
12474   }
12475 
12476   return new (Context)
12477       OMPIfClause(NameModifier, ValExpr, HelperValStmt, CaptureRegion, StartLoc,
12478                   LParenLoc, NameModifierLoc, ColonLoc, EndLoc);
12479 }
12480 
12481 OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition,
12482                                         SourceLocation StartLoc,
12483                                         SourceLocation LParenLoc,
12484                                         SourceLocation EndLoc) {
12485   Expr *ValExpr = Condition;
12486   Stmt *HelperValStmt = nullptr;
12487   OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
12488   if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
12489       !Condition->isInstantiationDependent() &&
12490       !Condition->containsUnexpandedParameterPack()) {
12491     ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
12492     if (Val.isInvalid())
12493       return nullptr;
12494 
12495     ValExpr = MakeFullExpr(Val.get()).get();
12496 
12497     OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
12498     CaptureRegion =
12499         getOpenMPCaptureRegionForClause(DKind, OMPC_final, LangOpts.OpenMP);
12500     if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
12501       ValExpr = MakeFullExpr(ValExpr).get();
12502       llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
12503       ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
12504       HelperValStmt = buildPreInits(Context, Captures);
12505     }
12506   }
12507 
12508   return new (Context) OMPFinalClause(ValExpr, HelperValStmt, CaptureRegion,
12509                                       StartLoc, LParenLoc, EndLoc);
12510 }
12511 
12512 ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc,
12513                                                         Expr *Op) {
12514   if (!Op)
12515     return ExprError();
12516 
12517   class IntConvertDiagnoser : public ICEConvertDiagnoser {
12518   public:
12519     IntConvertDiagnoser()
12520         : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {}
12521     SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
12522                                          QualType T) override {
12523       return S.Diag(Loc, diag::err_omp_not_integral) << T;
12524     }
12525     SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
12526                                              QualType T) override {
12527       return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
12528     }
12529     SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
12530                                                QualType T,
12531                                                QualType ConvTy) override {
12532       return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
12533     }
12534     SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
12535                                            QualType ConvTy) override {
12536       return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
12537              << ConvTy->isEnumeralType() << ConvTy;
12538     }
12539     SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
12540                                             QualType T) override {
12541       return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
12542     }
12543     SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
12544                                         QualType ConvTy) override {
12545       return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
12546              << ConvTy->isEnumeralType() << ConvTy;
12547     }
12548     SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType,
12549                                              QualType) override {
12550       llvm_unreachable("conversion functions are permitted");
12551     }
12552   } ConvertDiagnoser;
12553   return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
12554 }
12555 
12556 static bool
12557 isNonNegativeIntegerValue(Expr *&ValExpr, Sema &SemaRef, OpenMPClauseKind CKind,
12558                           bool StrictlyPositive, bool BuildCapture = false,
12559                           OpenMPDirectiveKind DKind = OMPD_unknown,
12560                           OpenMPDirectiveKind *CaptureRegion = nullptr,
12561                           Stmt **HelperValStmt = nullptr) {
12562   if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() &&
12563       !ValExpr->isInstantiationDependent()) {
12564     SourceLocation Loc = ValExpr->getExprLoc();
12565     ExprResult Value =
12566         SemaRef.PerformOpenMPImplicitIntegerConversion(Loc, ValExpr);
12567     if (Value.isInvalid())
12568       return false;
12569 
12570     ValExpr = Value.get();
12571     // The expression must evaluate to a non-negative integer value.
12572     llvm::APSInt Result;
12573     if (ValExpr->isIntegerConstantExpr(Result, SemaRef.Context) &&
12574         Result.isSigned() &&
12575         !((!StrictlyPositive && Result.isNonNegative()) ||
12576           (StrictlyPositive && Result.isStrictlyPositive()))) {
12577       SemaRef.Diag(Loc, diag::err_omp_negative_expression_in_clause)
12578           << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
12579           << ValExpr->getSourceRange();
12580       return false;
12581     }
12582     if (!BuildCapture)
12583       return true;
12584     *CaptureRegion =
12585         getOpenMPCaptureRegionForClause(DKind, CKind, SemaRef.LangOpts.OpenMP);
12586     if (*CaptureRegion != OMPD_unknown &&
12587         !SemaRef.CurContext->isDependentContext()) {
12588       ValExpr = SemaRef.MakeFullExpr(ValExpr).get();
12589       llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
12590       ValExpr = tryBuildCapture(SemaRef, ValExpr, Captures).get();
12591       *HelperValStmt = buildPreInits(SemaRef.Context, Captures);
12592     }
12593   }
12594   return true;
12595 }
12596 
12597 OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
12598                                              SourceLocation StartLoc,
12599                                              SourceLocation LParenLoc,
12600                                              SourceLocation EndLoc) {
12601   Expr *ValExpr = NumThreads;
12602   Stmt *HelperValStmt = nullptr;
12603 
12604   // OpenMP [2.5, Restrictions]
12605   //  The num_threads expression must evaluate to a positive integer value.
12606   if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_threads,
12607                                  /*StrictlyPositive=*/true))
12608     return nullptr;
12609 
12610   OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
12611   OpenMPDirectiveKind CaptureRegion =
12612       getOpenMPCaptureRegionForClause(DKind, OMPC_num_threads, LangOpts.OpenMP);
12613   if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
12614     ValExpr = MakeFullExpr(ValExpr).get();
12615     llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
12616     ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
12617     HelperValStmt = buildPreInits(Context, Captures);
12618   }
12619 
12620   return new (Context) OMPNumThreadsClause(
12621       ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
12622 }
12623 
12624 ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
12625                                                        OpenMPClauseKind CKind,
12626                                                        bool StrictlyPositive) {
12627   if (!E)
12628     return ExprError();
12629   if (E->isValueDependent() || E->isTypeDependent() ||
12630       E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
12631     return E;
12632   llvm::APSInt Result;
12633   ExprResult ICE = VerifyIntegerConstantExpression(E, &Result);
12634   if (ICE.isInvalid())
12635     return ExprError();
12636   if ((StrictlyPositive && !Result.isStrictlyPositive()) ||
12637       (!StrictlyPositive && !Result.isNonNegative())) {
12638     Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
12639         << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
12640         << E->getSourceRange();
12641     return ExprError();
12642   }
12643   if (CKind == OMPC_aligned && !Result.isPowerOf2()) {
12644     Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two)
12645         << E->getSourceRange();
12646     return ExprError();
12647   }
12648   if (CKind == OMPC_collapse && DSAStack->getAssociatedLoops() == 1)
12649     DSAStack->setAssociatedLoops(Result.getExtValue());
12650   else if (CKind == OMPC_ordered)
12651     DSAStack->setAssociatedLoops(Result.getExtValue());
12652   return ICE;
12653 }
12654 
12655 OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
12656                                           SourceLocation LParenLoc,
12657                                           SourceLocation EndLoc) {
12658   // OpenMP [2.8.1, simd construct, Description]
12659   // The parameter of the safelen clause must be a constant
12660   // positive integer expression.
12661   ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen);
12662   if (Safelen.isInvalid())
12663     return nullptr;
12664   return new (Context)
12665       OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc);
12666 }
12667 
12668 OMPClause *Sema::ActOnOpenMPSimdlenClause(Expr *Len, SourceLocation StartLoc,
12669                                           SourceLocation LParenLoc,
12670                                           SourceLocation EndLoc) {
12671   // OpenMP [2.8.1, simd construct, Description]
12672   // The parameter of the simdlen clause must be a constant
12673   // positive integer expression.
12674   ExprResult Simdlen = VerifyPositiveIntegerConstantInClause(Len, OMPC_simdlen);
12675   if (Simdlen.isInvalid())
12676     return nullptr;
12677   return new (Context)
12678       OMPSimdlenClause(Simdlen.get(), StartLoc, LParenLoc, EndLoc);
12679 }
12680 
12681 /// Tries to find omp_allocator_handle_t type.
12682 static bool findOMPAllocatorHandleT(Sema &S, SourceLocation Loc,
12683                                     DSAStackTy *Stack) {
12684   QualType OMPAllocatorHandleT = Stack->getOMPAllocatorHandleT();
12685   if (!OMPAllocatorHandleT.isNull())
12686     return true;
12687   // Build the predefined allocator expressions.
12688   bool ErrorFound = false;
12689   for (int I = 0; I < OMPAllocateDeclAttr::OMPUserDefinedMemAlloc; ++I) {
12690     auto AllocatorKind = static_cast<OMPAllocateDeclAttr::AllocatorTypeTy>(I);
12691     StringRef Allocator =
12692         OMPAllocateDeclAttr::ConvertAllocatorTypeTyToStr(AllocatorKind);
12693     DeclarationName AllocatorName = &S.getASTContext().Idents.get(Allocator);
12694     auto *VD = dyn_cast_or_null<ValueDecl>(
12695         S.LookupSingleName(S.TUScope, AllocatorName, Loc, Sema::LookupAnyName));
12696     if (!VD) {
12697       ErrorFound = true;
12698       break;
12699     }
12700     QualType AllocatorType =
12701         VD->getType().getNonLValueExprType(S.getASTContext());
12702     ExprResult Res = S.BuildDeclRefExpr(VD, AllocatorType, VK_LValue, Loc);
12703     if (!Res.isUsable()) {
12704       ErrorFound = true;
12705       break;
12706     }
12707     if (OMPAllocatorHandleT.isNull())
12708       OMPAllocatorHandleT = AllocatorType;
12709     if (!S.getASTContext().hasSameType(OMPAllocatorHandleT, AllocatorType)) {
12710       ErrorFound = true;
12711       break;
12712     }
12713     Stack->setAllocator(AllocatorKind, Res.get());
12714   }
12715   if (ErrorFound) {
12716     S.Diag(Loc, diag::err_omp_implied_type_not_found)
12717         << "omp_allocator_handle_t";
12718     return false;
12719   }
12720   OMPAllocatorHandleT.addConst();
12721   Stack->setOMPAllocatorHandleT(OMPAllocatorHandleT);
12722   return true;
12723 }
12724 
12725 OMPClause *Sema::ActOnOpenMPAllocatorClause(Expr *A, SourceLocation StartLoc,
12726                                             SourceLocation LParenLoc,
12727                                             SourceLocation EndLoc) {
12728   // OpenMP [2.11.3, allocate Directive, Description]
12729   // allocator is an expression of omp_allocator_handle_t type.
12730   if (!findOMPAllocatorHandleT(*this, A->getExprLoc(), DSAStack))
12731     return nullptr;
12732 
12733   ExprResult Allocator = DefaultLvalueConversion(A);
12734   if (Allocator.isInvalid())
12735     return nullptr;
12736   Allocator = PerformImplicitConversion(Allocator.get(),
12737                                         DSAStack->getOMPAllocatorHandleT(),
12738                                         Sema::AA_Initializing,
12739                                         /*AllowExplicit=*/true);
12740   if (Allocator.isInvalid())
12741     return nullptr;
12742   return new (Context)
12743       OMPAllocatorClause(Allocator.get(), StartLoc, LParenLoc, EndLoc);
12744 }
12745 
12746 OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops,
12747                                            SourceLocation StartLoc,
12748                                            SourceLocation LParenLoc,
12749                                            SourceLocation EndLoc) {
12750   // OpenMP [2.7.1, loop construct, Description]
12751   // OpenMP [2.8.1, simd construct, Description]
12752   // OpenMP [2.9.6, distribute construct, Description]
12753   // The parameter of the collapse clause must be a constant
12754   // positive integer expression.
12755   ExprResult NumForLoopsResult =
12756       VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse);
12757   if (NumForLoopsResult.isInvalid())
12758     return nullptr;
12759   return new (Context)
12760       OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc);
12761 }
12762 
12763 OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc,
12764                                           SourceLocation EndLoc,
12765                                           SourceLocation LParenLoc,
12766                                           Expr *NumForLoops) {
12767   // OpenMP [2.7.1, loop construct, Description]
12768   // OpenMP [2.8.1, simd construct, Description]
12769   // OpenMP [2.9.6, distribute construct, Description]
12770   // The parameter of the ordered clause must be a constant
12771   // positive integer expression if any.
12772   if (NumForLoops && LParenLoc.isValid()) {
12773     ExprResult NumForLoopsResult =
12774         VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_ordered);
12775     if (NumForLoopsResult.isInvalid())
12776       return nullptr;
12777     NumForLoops = NumForLoopsResult.get();
12778   } else {
12779     NumForLoops = nullptr;
12780   }
12781   auto *Clause = OMPOrderedClause::Create(
12782       Context, NumForLoops, NumForLoops ? DSAStack->getAssociatedLoops() : 0,
12783       StartLoc, LParenLoc, EndLoc);
12784   DSAStack->setOrderedRegion(/*IsOrdered=*/true, NumForLoops, Clause);
12785   return Clause;
12786 }
12787 
12788 OMPClause *Sema::ActOnOpenMPSimpleClause(
12789     OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc,
12790     SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
12791   OMPClause *Res = nullptr;
12792   switch (Kind) {
12793   case OMPC_default:
12794     Res = ActOnOpenMPDefaultClause(static_cast<DefaultKind>(Argument),
12795                                    ArgumentLoc, StartLoc, LParenLoc, EndLoc);
12796     break;
12797   case OMPC_proc_bind:
12798     Res = ActOnOpenMPProcBindClause(static_cast<ProcBindKind>(Argument),
12799                                     ArgumentLoc, StartLoc, LParenLoc, EndLoc);
12800     break;
12801   case OMPC_atomic_default_mem_order:
12802     Res = ActOnOpenMPAtomicDefaultMemOrderClause(
12803         static_cast<OpenMPAtomicDefaultMemOrderClauseKind>(Argument),
12804         ArgumentLoc, StartLoc, LParenLoc, EndLoc);
12805     break;
12806   case OMPC_order:
12807     Res = ActOnOpenMPOrderClause(static_cast<OpenMPOrderClauseKind>(Argument),
12808                                  ArgumentLoc, StartLoc, LParenLoc, EndLoc);
12809     break;
12810   case OMPC_update:
12811     Res = ActOnOpenMPUpdateClause(static_cast<OpenMPDependClauseKind>(Argument),
12812                                   ArgumentLoc, StartLoc, LParenLoc, EndLoc);
12813     break;
12814   case OMPC_if:
12815   case OMPC_final:
12816   case OMPC_num_threads:
12817   case OMPC_safelen:
12818   case OMPC_simdlen:
12819   case OMPC_allocator:
12820   case OMPC_collapse:
12821   case OMPC_schedule:
12822   case OMPC_private:
12823   case OMPC_firstprivate:
12824   case OMPC_lastprivate:
12825   case OMPC_shared:
12826   case OMPC_reduction:
12827   case OMPC_task_reduction:
12828   case OMPC_in_reduction:
12829   case OMPC_linear:
12830   case OMPC_aligned:
12831   case OMPC_copyin:
12832   case OMPC_copyprivate:
12833   case OMPC_ordered:
12834   case OMPC_nowait:
12835   case OMPC_untied:
12836   case OMPC_mergeable:
12837   case OMPC_threadprivate:
12838   case OMPC_allocate:
12839   case OMPC_flush:
12840   case OMPC_depobj:
12841   case OMPC_read:
12842   case OMPC_write:
12843   case OMPC_capture:
12844   case OMPC_seq_cst:
12845   case OMPC_acq_rel:
12846   case OMPC_acquire:
12847   case OMPC_release:
12848   case OMPC_relaxed:
12849   case OMPC_depend:
12850   case OMPC_device:
12851   case OMPC_threads:
12852   case OMPC_simd:
12853   case OMPC_map:
12854   case OMPC_num_teams:
12855   case OMPC_thread_limit:
12856   case OMPC_priority:
12857   case OMPC_grainsize:
12858   case OMPC_nogroup:
12859   case OMPC_num_tasks:
12860   case OMPC_hint:
12861   case OMPC_dist_schedule:
12862   case OMPC_defaultmap:
12863   case OMPC_unknown:
12864   case OMPC_uniform:
12865   case OMPC_to:
12866   case OMPC_from:
12867   case OMPC_use_device_ptr:
12868   case OMPC_use_device_addr:
12869   case OMPC_is_device_ptr:
12870   case OMPC_unified_address:
12871   case OMPC_unified_shared_memory:
12872   case OMPC_reverse_offload:
12873   case OMPC_dynamic_allocators:
12874   case OMPC_device_type:
12875   case OMPC_match:
12876   case OMPC_nontemporal:
12877   case OMPC_destroy:
12878   case OMPC_detach:
12879   case OMPC_inclusive:
12880   case OMPC_exclusive:
12881   case OMPC_uses_allocators:
12882   case OMPC_affinity:
12883     llvm_unreachable("Clause is not allowed.");
12884   }
12885   return Res;
12886 }
12887 
12888 static std::string
12889 getListOfPossibleValues(OpenMPClauseKind K, unsigned First, unsigned Last,
12890                         ArrayRef<unsigned> Exclude = llvm::None) {
12891   SmallString<256> Buffer;
12892   llvm::raw_svector_ostream Out(Buffer);
12893   unsigned Skipped = Exclude.size();
12894   auto S = Exclude.begin(), E = Exclude.end();
12895   for (unsigned I = First; I < Last; ++I) {
12896     if (std::find(S, E, I) != E) {
12897       --Skipped;
12898       continue;
12899     }
12900     Out << "'" << getOpenMPSimpleClauseTypeName(K, I) << "'";
12901     if (I + Skipped + 2 == Last)
12902       Out << " or ";
12903     else if (I + Skipped + 1 != Last)
12904       Out << ", ";
12905   }
12906   return std::string(Out.str());
12907 }
12908 
12909 OMPClause *Sema::ActOnOpenMPDefaultClause(DefaultKind Kind,
12910                                           SourceLocation KindKwLoc,
12911                                           SourceLocation StartLoc,
12912                                           SourceLocation LParenLoc,
12913                                           SourceLocation EndLoc) {
12914   if (Kind == OMP_DEFAULT_unknown) {
12915     Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
12916         << getListOfPossibleValues(OMPC_default, /*First=*/0,
12917                                    /*Last=*/unsigned(OMP_DEFAULT_unknown))
12918         << getOpenMPClauseName(OMPC_default);
12919     return nullptr;
12920   }
12921   if (Kind == OMP_DEFAULT_none)
12922     DSAStack->setDefaultDSANone(KindKwLoc);
12923   else if (Kind == OMP_DEFAULT_shared)
12924     DSAStack->setDefaultDSAShared(KindKwLoc);
12925 
12926   return new (Context)
12927       OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
12928 }
12929 
12930 OMPClause *Sema::ActOnOpenMPProcBindClause(ProcBindKind Kind,
12931                                            SourceLocation KindKwLoc,
12932                                            SourceLocation StartLoc,
12933                                            SourceLocation LParenLoc,
12934                                            SourceLocation EndLoc) {
12935   if (Kind == OMP_PROC_BIND_unknown) {
12936     Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
12937         << getListOfPossibleValues(OMPC_proc_bind,
12938                                    /*First=*/unsigned(OMP_PROC_BIND_master),
12939                                    /*Last=*/5)
12940         << getOpenMPClauseName(OMPC_proc_bind);
12941     return nullptr;
12942   }
12943   return new (Context)
12944       OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
12945 }
12946 
12947 OMPClause *Sema::ActOnOpenMPAtomicDefaultMemOrderClause(
12948     OpenMPAtomicDefaultMemOrderClauseKind Kind, SourceLocation KindKwLoc,
12949     SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
12950   if (Kind == OMPC_ATOMIC_DEFAULT_MEM_ORDER_unknown) {
12951     Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
12952         << getListOfPossibleValues(
12953                OMPC_atomic_default_mem_order, /*First=*/0,
12954                /*Last=*/OMPC_ATOMIC_DEFAULT_MEM_ORDER_unknown)
12955         << getOpenMPClauseName(OMPC_atomic_default_mem_order);
12956     return nullptr;
12957   }
12958   return new (Context) OMPAtomicDefaultMemOrderClause(Kind, KindKwLoc, StartLoc,
12959                                                       LParenLoc, EndLoc);
12960 }
12961 
12962 OMPClause *Sema::ActOnOpenMPOrderClause(OpenMPOrderClauseKind Kind,
12963                                         SourceLocation KindKwLoc,
12964                                         SourceLocation StartLoc,
12965                                         SourceLocation LParenLoc,
12966                                         SourceLocation EndLoc) {
12967   if (Kind == OMPC_ORDER_unknown) {
12968     static_assert(OMPC_ORDER_unknown > 0,
12969                   "OMPC_ORDER_unknown not greater than 0");
12970     Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
12971         << getListOfPossibleValues(OMPC_order, /*First=*/0,
12972                                    /*Last=*/OMPC_ORDER_unknown)
12973         << getOpenMPClauseName(OMPC_order);
12974     return nullptr;
12975   }
12976   return new (Context)
12977       OMPOrderClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
12978 }
12979 
12980 OMPClause *Sema::ActOnOpenMPUpdateClause(OpenMPDependClauseKind Kind,
12981                                          SourceLocation KindKwLoc,
12982                                          SourceLocation StartLoc,
12983                                          SourceLocation LParenLoc,
12984                                          SourceLocation EndLoc) {
12985   if (Kind == OMPC_DEPEND_unknown || Kind == OMPC_DEPEND_source ||
12986       Kind == OMPC_DEPEND_sink || Kind == OMPC_DEPEND_depobj) {
12987     unsigned Except[] = {OMPC_DEPEND_source, OMPC_DEPEND_sink,
12988                          OMPC_DEPEND_depobj};
12989     Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
12990         << getListOfPossibleValues(OMPC_depend, /*First=*/0,
12991                                    /*Last=*/OMPC_DEPEND_unknown, Except)
12992         << getOpenMPClauseName(OMPC_update);
12993     return nullptr;
12994   }
12995   return OMPUpdateClause::Create(Context, StartLoc, LParenLoc, KindKwLoc, Kind,
12996                                  EndLoc);
12997 }
12998 
12999 OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause(
13000     OpenMPClauseKind Kind, ArrayRef<unsigned> Argument, Expr *Expr,
13001     SourceLocation StartLoc, SourceLocation LParenLoc,
13002     ArrayRef<SourceLocation> ArgumentLoc, SourceLocation DelimLoc,
13003     SourceLocation EndLoc) {
13004   OMPClause *Res = nullptr;
13005   switch (Kind) {
13006   case OMPC_schedule:
13007     enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements };
13008     assert(Argument.size() == NumberOfElements &&
13009            ArgumentLoc.size() == NumberOfElements);
13010     Res = ActOnOpenMPScheduleClause(
13011         static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier1]),
13012         static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier2]),
13013         static_cast<OpenMPScheduleClauseKind>(Argument[ScheduleKind]), Expr,
13014         StartLoc, LParenLoc, ArgumentLoc[Modifier1], ArgumentLoc[Modifier2],
13015         ArgumentLoc[ScheduleKind], DelimLoc, EndLoc);
13016     break;
13017   case OMPC_if:
13018     assert(Argument.size() == 1 && ArgumentLoc.size() == 1);
13019     Res = ActOnOpenMPIfClause(static_cast<OpenMPDirectiveKind>(Argument.back()),
13020                               Expr, StartLoc, LParenLoc, ArgumentLoc.back(),
13021                               DelimLoc, EndLoc);
13022     break;
13023   case OMPC_dist_schedule:
13024     Res = ActOnOpenMPDistScheduleClause(
13025         static_cast<OpenMPDistScheduleClauseKind>(Argument.back()), Expr,
13026         StartLoc, LParenLoc, ArgumentLoc.back(), DelimLoc, EndLoc);
13027     break;
13028   case OMPC_defaultmap:
13029     enum { Modifier, DefaultmapKind };
13030     Res = ActOnOpenMPDefaultmapClause(
13031         static_cast<OpenMPDefaultmapClauseModifier>(Argument[Modifier]),
13032         static_cast<OpenMPDefaultmapClauseKind>(Argument[DefaultmapKind]),
13033         StartLoc, LParenLoc, ArgumentLoc[Modifier], ArgumentLoc[DefaultmapKind],
13034         EndLoc);
13035     break;
13036   case OMPC_device:
13037     assert(Argument.size() == 1 && ArgumentLoc.size() == 1);
13038     Res = ActOnOpenMPDeviceClause(
13039         static_cast<OpenMPDeviceClauseModifier>(Argument.back()), Expr,
13040         StartLoc, LParenLoc, ArgumentLoc.back(), EndLoc);
13041     break;
13042   case OMPC_final:
13043   case OMPC_num_threads:
13044   case OMPC_safelen:
13045   case OMPC_simdlen:
13046   case OMPC_allocator:
13047   case OMPC_collapse:
13048   case OMPC_default:
13049   case OMPC_proc_bind:
13050   case OMPC_private:
13051   case OMPC_firstprivate:
13052   case OMPC_lastprivate:
13053   case OMPC_shared:
13054   case OMPC_reduction:
13055   case OMPC_task_reduction:
13056   case OMPC_in_reduction:
13057   case OMPC_linear:
13058   case OMPC_aligned:
13059   case OMPC_copyin:
13060   case OMPC_copyprivate:
13061   case OMPC_ordered:
13062   case OMPC_nowait:
13063   case OMPC_untied:
13064   case OMPC_mergeable:
13065   case OMPC_threadprivate:
13066   case OMPC_allocate:
13067   case OMPC_flush:
13068   case OMPC_depobj:
13069   case OMPC_read:
13070   case OMPC_write:
13071   case OMPC_update:
13072   case OMPC_capture:
13073   case OMPC_seq_cst:
13074   case OMPC_acq_rel:
13075   case OMPC_acquire:
13076   case OMPC_release:
13077   case OMPC_relaxed:
13078   case OMPC_depend:
13079   case OMPC_threads:
13080   case OMPC_simd:
13081   case OMPC_map:
13082   case OMPC_num_teams:
13083   case OMPC_thread_limit:
13084   case OMPC_priority:
13085   case OMPC_grainsize:
13086   case OMPC_nogroup:
13087   case OMPC_num_tasks:
13088   case OMPC_hint:
13089   case OMPC_unknown:
13090   case OMPC_uniform:
13091   case OMPC_to:
13092   case OMPC_from:
13093   case OMPC_use_device_ptr:
13094   case OMPC_use_device_addr:
13095   case OMPC_is_device_ptr:
13096   case OMPC_unified_address:
13097   case OMPC_unified_shared_memory:
13098   case OMPC_reverse_offload:
13099   case OMPC_dynamic_allocators:
13100   case OMPC_atomic_default_mem_order:
13101   case OMPC_device_type:
13102   case OMPC_match:
13103   case OMPC_nontemporal:
13104   case OMPC_order:
13105   case OMPC_destroy:
13106   case OMPC_detach:
13107   case OMPC_inclusive:
13108   case OMPC_exclusive:
13109   case OMPC_uses_allocators:
13110   case OMPC_affinity:
13111     llvm_unreachable("Clause is not allowed.");
13112   }
13113   return Res;
13114 }
13115 
13116 static bool checkScheduleModifiers(Sema &S, OpenMPScheduleClauseModifier M1,
13117                                    OpenMPScheduleClauseModifier M2,
13118                                    SourceLocation M1Loc, SourceLocation M2Loc) {
13119   if (M1 == OMPC_SCHEDULE_MODIFIER_unknown && M1Loc.isValid()) {
13120     SmallVector<unsigned, 2> Excluded;
13121     if (M2 != OMPC_SCHEDULE_MODIFIER_unknown)
13122       Excluded.push_back(M2);
13123     if (M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic)
13124       Excluded.push_back(OMPC_SCHEDULE_MODIFIER_monotonic);
13125     if (M2 == OMPC_SCHEDULE_MODIFIER_monotonic)
13126       Excluded.push_back(OMPC_SCHEDULE_MODIFIER_nonmonotonic);
13127     S.Diag(M1Loc, diag::err_omp_unexpected_clause_value)
13128         << getListOfPossibleValues(OMPC_schedule,
13129                                    /*First=*/OMPC_SCHEDULE_MODIFIER_unknown + 1,
13130                                    /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
13131                                    Excluded)
13132         << getOpenMPClauseName(OMPC_schedule);
13133     return true;
13134   }
13135   return false;
13136 }
13137 
13138 OMPClause *Sema::ActOnOpenMPScheduleClause(
13139     OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
13140     OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
13141     SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
13142     SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) {
13143   if (checkScheduleModifiers(*this, M1, M2, M1Loc, M2Loc) ||
13144       checkScheduleModifiers(*this, M2, M1, M2Loc, M1Loc))
13145     return nullptr;
13146   // OpenMP, 2.7.1, Loop Construct, Restrictions
13147   // Either the monotonic modifier or the nonmonotonic modifier can be specified
13148   // but not both.
13149   if ((M1 == M2 && M1 != OMPC_SCHEDULE_MODIFIER_unknown) ||
13150       (M1 == OMPC_SCHEDULE_MODIFIER_monotonic &&
13151        M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) ||
13152       (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic &&
13153        M2 == OMPC_SCHEDULE_MODIFIER_monotonic)) {
13154     Diag(M2Loc, diag::err_omp_unexpected_schedule_modifier)
13155         << getOpenMPSimpleClauseTypeName(OMPC_schedule, M2)
13156         << getOpenMPSimpleClauseTypeName(OMPC_schedule, M1);
13157     return nullptr;
13158   }
13159   if (Kind == OMPC_SCHEDULE_unknown) {
13160     std::string Values;
13161     if (M1Loc.isInvalid() && M2Loc.isInvalid()) {
13162       unsigned Exclude[] = {OMPC_SCHEDULE_unknown};
13163       Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
13164                                        /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
13165                                        Exclude);
13166     } else {
13167       Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
13168                                        /*Last=*/OMPC_SCHEDULE_unknown);
13169     }
13170     Diag(KindLoc, diag::err_omp_unexpected_clause_value)
13171         << Values << getOpenMPClauseName(OMPC_schedule);
13172     return nullptr;
13173   }
13174   // OpenMP, 2.7.1, Loop Construct, Restrictions
13175   // The nonmonotonic modifier can only be specified with schedule(dynamic) or
13176   // schedule(guided).
13177   // OpenMP 5.0 does not have this restriction.
13178   if (LangOpts.OpenMP < 50 &&
13179       (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
13180        M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
13181       Kind != OMPC_SCHEDULE_dynamic && Kind != OMPC_SCHEDULE_guided) {
13182     Diag(M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ? M1Loc : M2Loc,
13183          diag::err_omp_schedule_nonmonotonic_static);
13184     return nullptr;
13185   }
13186   Expr *ValExpr = ChunkSize;
13187   Stmt *HelperValStmt = nullptr;
13188   if (ChunkSize) {
13189     if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
13190         !ChunkSize->isInstantiationDependent() &&
13191         !ChunkSize->containsUnexpandedParameterPack()) {
13192       SourceLocation ChunkSizeLoc = ChunkSize->getBeginLoc();
13193       ExprResult Val =
13194           PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
13195       if (Val.isInvalid())
13196         return nullptr;
13197 
13198       ValExpr = Val.get();
13199 
13200       // OpenMP [2.7.1, Restrictions]
13201       //  chunk_size must be a loop invariant integer expression with a positive
13202       //  value.
13203       llvm::APSInt Result;
13204       if (ValExpr->isIntegerConstantExpr(Result, Context)) {
13205         if (Result.isSigned() && !Result.isStrictlyPositive()) {
13206           Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
13207               << "schedule" << 1 << ChunkSize->getSourceRange();
13208           return nullptr;
13209         }
13210       } else if (getOpenMPCaptureRegionForClause(
13211                      DSAStack->getCurrentDirective(), OMPC_schedule,
13212                      LangOpts.OpenMP) != OMPD_unknown &&
13213                  !CurContext->isDependentContext()) {
13214         ValExpr = MakeFullExpr(ValExpr).get();
13215         llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
13216         ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
13217         HelperValStmt = buildPreInits(Context, Captures);
13218       }
13219     }
13220   }
13221 
13222   return new (Context)
13223       OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, Kind,
13224                         ValExpr, HelperValStmt, M1, M1Loc, M2, M2Loc);
13225 }
13226 
13227 OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind,
13228                                    SourceLocation StartLoc,
13229                                    SourceLocation EndLoc) {
13230   OMPClause *Res = nullptr;
13231   switch (Kind) {
13232   case OMPC_ordered:
13233     Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc);
13234     break;
13235   case OMPC_nowait:
13236     Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc);
13237     break;
13238   case OMPC_untied:
13239     Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc);
13240     break;
13241   case OMPC_mergeable:
13242     Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc);
13243     break;
13244   case OMPC_read:
13245     Res = ActOnOpenMPReadClause(StartLoc, EndLoc);
13246     break;
13247   case OMPC_write:
13248     Res = ActOnOpenMPWriteClause(StartLoc, EndLoc);
13249     break;
13250   case OMPC_update:
13251     Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc);
13252     break;
13253   case OMPC_capture:
13254     Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc);
13255     break;
13256   case OMPC_seq_cst:
13257     Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc);
13258     break;
13259   case OMPC_acq_rel:
13260     Res = ActOnOpenMPAcqRelClause(StartLoc, EndLoc);
13261     break;
13262   case OMPC_acquire:
13263     Res = ActOnOpenMPAcquireClause(StartLoc, EndLoc);
13264     break;
13265   case OMPC_release:
13266     Res = ActOnOpenMPReleaseClause(StartLoc, EndLoc);
13267     break;
13268   case OMPC_relaxed:
13269     Res = ActOnOpenMPRelaxedClause(StartLoc, EndLoc);
13270     break;
13271   case OMPC_threads:
13272     Res = ActOnOpenMPThreadsClause(StartLoc, EndLoc);
13273     break;
13274   case OMPC_simd:
13275     Res = ActOnOpenMPSIMDClause(StartLoc, EndLoc);
13276     break;
13277   case OMPC_nogroup:
13278     Res = ActOnOpenMPNogroupClause(StartLoc, EndLoc);
13279     break;
13280   case OMPC_unified_address:
13281     Res = ActOnOpenMPUnifiedAddressClause(StartLoc, EndLoc);
13282     break;
13283   case OMPC_unified_shared_memory:
13284     Res = ActOnOpenMPUnifiedSharedMemoryClause(StartLoc, EndLoc);
13285     break;
13286   case OMPC_reverse_offload:
13287     Res = ActOnOpenMPReverseOffloadClause(StartLoc, EndLoc);
13288     break;
13289   case OMPC_dynamic_allocators:
13290     Res = ActOnOpenMPDynamicAllocatorsClause(StartLoc, EndLoc);
13291     break;
13292   case OMPC_destroy:
13293     Res = ActOnOpenMPDestroyClause(StartLoc, EndLoc);
13294     break;
13295   case OMPC_if:
13296   case OMPC_final:
13297   case OMPC_num_threads:
13298   case OMPC_safelen:
13299   case OMPC_simdlen:
13300   case OMPC_allocator:
13301   case OMPC_collapse:
13302   case OMPC_schedule:
13303   case OMPC_private:
13304   case OMPC_firstprivate:
13305   case OMPC_lastprivate:
13306   case OMPC_shared:
13307   case OMPC_reduction:
13308   case OMPC_task_reduction:
13309   case OMPC_in_reduction:
13310   case OMPC_linear:
13311   case OMPC_aligned:
13312   case OMPC_copyin:
13313   case OMPC_copyprivate:
13314   case OMPC_default:
13315   case OMPC_proc_bind:
13316   case OMPC_threadprivate:
13317   case OMPC_allocate:
13318   case OMPC_flush:
13319   case OMPC_depobj:
13320   case OMPC_depend:
13321   case OMPC_device:
13322   case OMPC_map:
13323   case OMPC_num_teams:
13324   case OMPC_thread_limit:
13325   case OMPC_priority:
13326   case OMPC_grainsize:
13327   case OMPC_num_tasks:
13328   case OMPC_hint:
13329   case OMPC_dist_schedule:
13330   case OMPC_defaultmap:
13331   case OMPC_unknown:
13332   case OMPC_uniform:
13333   case OMPC_to:
13334   case OMPC_from:
13335   case OMPC_use_device_ptr:
13336   case OMPC_use_device_addr:
13337   case OMPC_is_device_ptr:
13338   case OMPC_atomic_default_mem_order:
13339   case OMPC_device_type:
13340   case OMPC_match:
13341   case OMPC_nontemporal:
13342   case OMPC_order:
13343   case OMPC_detach:
13344   case OMPC_inclusive:
13345   case OMPC_exclusive:
13346   case OMPC_uses_allocators:
13347   case OMPC_affinity:
13348     llvm_unreachable("Clause is not allowed.");
13349   }
13350   return Res;
13351 }
13352 
13353 OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc,
13354                                          SourceLocation EndLoc) {
13355   DSAStack->setNowaitRegion();
13356   return new (Context) OMPNowaitClause(StartLoc, EndLoc);
13357 }
13358 
13359 OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc,
13360                                          SourceLocation EndLoc) {
13361   return new (Context) OMPUntiedClause(StartLoc, EndLoc);
13362 }
13363 
13364 OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc,
13365                                             SourceLocation EndLoc) {
13366   return new (Context) OMPMergeableClause(StartLoc, EndLoc);
13367 }
13368 
13369 OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc,
13370                                        SourceLocation EndLoc) {
13371   return new (Context) OMPReadClause(StartLoc, EndLoc);
13372 }
13373 
13374 OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc,
13375                                         SourceLocation EndLoc) {
13376   return new (Context) OMPWriteClause(StartLoc, EndLoc);
13377 }
13378 
13379 OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc,
13380                                          SourceLocation EndLoc) {
13381   return OMPUpdateClause::Create(Context, StartLoc, EndLoc);
13382 }
13383 
13384 OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc,
13385                                           SourceLocation EndLoc) {
13386   return new (Context) OMPCaptureClause(StartLoc, EndLoc);
13387 }
13388 
13389 OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
13390                                          SourceLocation EndLoc) {
13391   return new (Context) OMPSeqCstClause(StartLoc, EndLoc);
13392 }
13393 
13394 OMPClause *Sema::ActOnOpenMPAcqRelClause(SourceLocation StartLoc,
13395                                          SourceLocation EndLoc) {
13396   return new (Context) OMPAcqRelClause(StartLoc, EndLoc);
13397 }
13398 
13399 OMPClause *Sema::ActOnOpenMPAcquireClause(SourceLocation StartLoc,
13400                                           SourceLocation EndLoc) {
13401   return new (Context) OMPAcquireClause(StartLoc, EndLoc);
13402 }
13403 
13404 OMPClause *Sema::ActOnOpenMPReleaseClause(SourceLocation StartLoc,
13405                                           SourceLocation EndLoc) {
13406   return new (Context) OMPReleaseClause(StartLoc, EndLoc);
13407 }
13408 
13409 OMPClause *Sema::ActOnOpenMPRelaxedClause(SourceLocation StartLoc,
13410                                           SourceLocation EndLoc) {
13411   return new (Context) OMPRelaxedClause(StartLoc, EndLoc);
13412 }
13413 
13414 OMPClause *Sema::ActOnOpenMPThreadsClause(SourceLocation StartLoc,
13415                                           SourceLocation EndLoc) {
13416   return new (Context) OMPThreadsClause(StartLoc, EndLoc);
13417 }
13418 
13419 OMPClause *Sema::ActOnOpenMPSIMDClause(SourceLocation StartLoc,
13420                                        SourceLocation EndLoc) {
13421   return new (Context) OMPSIMDClause(StartLoc, EndLoc);
13422 }
13423 
13424 OMPClause *Sema::ActOnOpenMPNogroupClause(SourceLocation StartLoc,
13425                                           SourceLocation EndLoc) {
13426   return new (Context) OMPNogroupClause(StartLoc, EndLoc);
13427 }
13428 
13429 OMPClause *Sema::ActOnOpenMPUnifiedAddressClause(SourceLocation StartLoc,
13430                                                  SourceLocation EndLoc) {
13431   return new (Context) OMPUnifiedAddressClause(StartLoc, EndLoc);
13432 }
13433 
13434 OMPClause *Sema::ActOnOpenMPUnifiedSharedMemoryClause(SourceLocation StartLoc,
13435                                                       SourceLocation EndLoc) {
13436   return new (Context) OMPUnifiedSharedMemoryClause(StartLoc, EndLoc);
13437 }
13438 
13439 OMPClause *Sema::ActOnOpenMPReverseOffloadClause(SourceLocation StartLoc,
13440                                                  SourceLocation EndLoc) {
13441   return new (Context) OMPReverseOffloadClause(StartLoc, EndLoc);
13442 }
13443 
13444 OMPClause *Sema::ActOnOpenMPDynamicAllocatorsClause(SourceLocation StartLoc,
13445                                                     SourceLocation EndLoc) {
13446   return new (Context) OMPDynamicAllocatorsClause(StartLoc, EndLoc);
13447 }
13448 
13449 OMPClause *Sema::ActOnOpenMPDestroyClause(SourceLocation StartLoc,
13450                                           SourceLocation EndLoc) {
13451   return new (Context) OMPDestroyClause(StartLoc, EndLoc);
13452 }
13453 
13454 OMPClause *Sema::ActOnOpenMPVarListClause(
13455     OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *DepModOrTailExpr,
13456     const OMPVarListLocTy &Locs, SourceLocation ColonLoc,
13457     CXXScopeSpec &ReductionOrMapperIdScopeSpec,
13458     DeclarationNameInfo &ReductionOrMapperId, int ExtraModifier,
13459     ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
13460     ArrayRef<SourceLocation> MapTypeModifiersLoc, bool IsMapTypeImplicit,
13461     SourceLocation ExtraModifierLoc) {
13462   SourceLocation StartLoc = Locs.StartLoc;
13463   SourceLocation LParenLoc = Locs.LParenLoc;
13464   SourceLocation EndLoc = Locs.EndLoc;
13465   OMPClause *Res = nullptr;
13466   switch (Kind) {
13467   case OMPC_private:
13468     Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
13469     break;
13470   case OMPC_firstprivate:
13471     Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
13472     break;
13473   case OMPC_lastprivate:
13474     assert(0 <= ExtraModifier && ExtraModifier <= OMPC_LASTPRIVATE_unknown &&
13475            "Unexpected lastprivate modifier.");
13476     Res = ActOnOpenMPLastprivateClause(
13477         VarList, static_cast<OpenMPLastprivateModifier>(ExtraModifier),
13478         ExtraModifierLoc, ColonLoc, StartLoc, LParenLoc, EndLoc);
13479     break;
13480   case OMPC_shared:
13481     Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
13482     break;
13483   case OMPC_reduction:
13484     assert(0 <= ExtraModifier && ExtraModifier <= OMPC_REDUCTION_unknown &&
13485            "Unexpected lastprivate modifier.");
13486     Res = ActOnOpenMPReductionClause(
13487         VarList, static_cast<OpenMPReductionClauseModifier>(ExtraModifier),
13488         StartLoc, LParenLoc, ExtraModifierLoc, ColonLoc, EndLoc,
13489         ReductionOrMapperIdScopeSpec, ReductionOrMapperId);
13490     break;
13491   case OMPC_task_reduction:
13492     Res = ActOnOpenMPTaskReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
13493                                          EndLoc, ReductionOrMapperIdScopeSpec,
13494                                          ReductionOrMapperId);
13495     break;
13496   case OMPC_in_reduction:
13497     Res = ActOnOpenMPInReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
13498                                        EndLoc, ReductionOrMapperIdScopeSpec,
13499                                        ReductionOrMapperId);
13500     break;
13501   case OMPC_linear:
13502     assert(0 <= ExtraModifier && ExtraModifier <= OMPC_LINEAR_unknown &&
13503            "Unexpected linear modifier.");
13504     Res = ActOnOpenMPLinearClause(
13505         VarList, DepModOrTailExpr, StartLoc, LParenLoc,
13506         static_cast<OpenMPLinearClauseKind>(ExtraModifier), ExtraModifierLoc,
13507         ColonLoc, EndLoc);
13508     break;
13509   case OMPC_aligned:
13510     Res = ActOnOpenMPAlignedClause(VarList, DepModOrTailExpr, StartLoc,
13511                                    LParenLoc, ColonLoc, EndLoc);
13512     break;
13513   case OMPC_copyin:
13514     Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
13515     break;
13516   case OMPC_copyprivate:
13517     Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
13518     break;
13519   case OMPC_flush:
13520     Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc);
13521     break;
13522   case OMPC_depend:
13523     assert(0 <= ExtraModifier && ExtraModifier <= OMPC_DEPEND_unknown &&
13524            "Unexpected depend modifier.");
13525     Res = ActOnOpenMPDependClause(
13526         DepModOrTailExpr, static_cast<OpenMPDependClauseKind>(ExtraModifier),
13527         ExtraModifierLoc, ColonLoc, VarList, StartLoc, LParenLoc, EndLoc);
13528     break;
13529   case OMPC_map:
13530     assert(0 <= ExtraModifier && ExtraModifier <= OMPC_MAP_unknown &&
13531            "Unexpected map modifier.");
13532     Res = ActOnOpenMPMapClause(
13533         MapTypeModifiers, MapTypeModifiersLoc, ReductionOrMapperIdScopeSpec,
13534         ReductionOrMapperId, static_cast<OpenMPMapClauseKind>(ExtraModifier),
13535         IsMapTypeImplicit, ExtraModifierLoc, ColonLoc, VarList, Locs);
13536     break;
13537   case OMPC_to:
13538     Res = ActOnOpenMPToClause(VarList, ReductionOrMapperIdScopeSpec,
13539                               ReductionOrMapperId, Locs);
13540     break;
13541   case OMPC_from:
13542     Res = ActOnOpenMPFromClause(VarList, ReductionOrMapperIdScopeSpec,
13543                                 ReductionOrMapperId, Locs);
13544     break;
13545   case OMPC_use_device_ptr:
13546     Res = ActOnOpenMPUseDevicePtrClause(VarList, Locs);
13547     break;
13548   case OMPC_use_device_addr:
13549     Res = ActOnOpenMPUseDeviceAddrClause(VarList, Locs);
13550     break;
13551   case OMPC_is_device_ptr:
13552     Res = ActOnOpenMPIsDevicePtrClause(VarList, Locs);
13553     break;
13554   case OMPC_allocate:
13555     Res = ActOnOpenMPAllocateClause(DepModOrTailExpr, VarList, StartLoc,
13556                                     LParenLoc, ColonLoc, EndLoc);
13557     break;
13558   case OMPC_nontemporal:
13559     Res = ActOnOpenMPNontemporalClause(VarList, StartLoc, LParenLoc, EndLoc);
13560     break;
13561   case OMPC_inclusive:
13562     Res = ActOnOpenMPInclusiveClause(VarList, StartLoc, LParenLoc, EndLoc);
13563     break;
13564   case OMPC_exclusive:
13565     Res = ActOnOpenMPExclusiveClause(VarList, StartLoc, LParenLoc, EndLoc);
13566     break;
13567   case OMPC_affinity:
13568     Res = ActOnOpenMPAffinityClause(StartLoc, LParenLoc, ColonLoc, EndLoc,
13569                                     DepModOrTailExpr, VarList);
13570     break;
13571   case OMPC_if:
13572   case OMPC_depobj:
13573   case OMPC_final:
13574   case OMPC_num_threads:
13575   case OMPC_safelen:
13576   case OMPC_simdlen:
13577   case OMPC_allocator:
13578   case OMPC_collapse:
13579   case OMPC_default:
13580   case OMPC_proc_bind:
13581   case OMPC_schedule:
13582   case OMPC_ordered:
13583   case OMPC_nowait:
13584   case OMPC_untied:
13585   case OMPC_mergeable:
13586   case OMPC_threadprivate:
13587   case OMPC_read:
13588   case OMPC_write:
13589   case OMPC_update:
13590   case OMPC_capture:
13591   case OMPC_seq_cst:
13592   case OMPC_acq_rel:
13593   case OMPC_acquire:
13594   case OMPC_release:
13595   case OMPC_relaxed:
13596   case OMPC_device:
13597   case OMPC_threads:
13598   case OMPC_simd:
13599   case OMPC_num_teams:
13600   case OMPC_thread_limit:
13601   case OMPC_priority:
13602   case OMPC_grainsize:
13603   case OMPC_nogroup:
13604   case OMPC_num_tasks:
13605   case OMPC_hint:
13606   case OMPC_dist_schedule:
13607   case OMPC_defaultmap:
13608   case OMPC_unknown:
13609   case OMPC_uniform:
13610   case OMPC_unified_address:
13611   case OMPC_unified_shared_memory:
13612   case OMPC_reverse_offload:
13613   case OMPC_dynamic_allocators:
13614   case OMPC_atomic_default_mem_order:
13615   case OMPC_device_type:
13616   case OMPC_match:
13617   case OMPC_order:
13618   case OMPC_destroy:
13619   case OMPC_detach:
13620   case OMPC_uses_allocators:
13621     llvm_unreachable("Clause is not allowed.");
13622   }
13623   return Res;
13624 }
13625 
13626 ExprResult Sema::getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
13627                                        ExprObjectKind OK, SourceLocation Loc) {
13628   ExprResult Res = BuildDeclRefExpr(
13629       Capture, Capture->getType().getNonReferenceType(), VK_LValue, Loc);
13630   if (!Res.isUsable())
13631     return ExprError();
13632   if (OK == OK_Ordinary && !getLangOpts().CPlusPlus) {
13633     Res = CreateBuiltinUnaryOp(Loc, UO_Deref, Res.get());
13634     if (!Res.isUsable())
13635       return ExprError();
13636   }
13637   if (VK != VK_LValue && Res.get()->isGLValue()) {
13638     Res = DefaultLvalueConversion(Res.get());
13639     if (!Res.isUsable())
13640       return ExprError();
13641   }
13642   return Res;
13643 }
13644 
13645 OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
13646                                           SourceLocation StartLoc,
13647                                           SourceLocation LParenLoc,
13648                                           SourceLocation EndLoc) {
13649   SmallVector<Expr *, 8> Vars;
13650   SmallVector<Expr *, 8> PrivateCopies;
13651   for (Expr *RefExpr : VarList) {
13652     assert(RefExpr && "NULL expr in OpenMP private clause.");
13653     SourceLocation ELoc;
13654     SourceRange ERange;
13655     Expr *SimpleRefExpr = RefExpr;
13656     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
13657     if (Res.second) {
13658       // It will be analyzed later.
13659       Vars.push_back(RefExpr);
13660       PrivateCopies.push_back(nullptr);
13661     }
13662     ValueDecl *D = Res.first;
13663     if (!D)
13664       continue;
13665 
13666     QualType Type = D->getType();
13667     auto *VD = dyn_cast<VarDecl>(D);
13668 
13669     // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
13670     //  A variable that appears in a private clause must not have an incomplete
13671     //  type or a reference type.
13672     if (RequireCompleteType(ELoc, Type, diag::err_omp_private_incomplete_type))
13673       continue;
13674     Type = Type.getNonReferenceType();
13675 
13676     // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
13677     // A variable that is privatized must not have a const-qualified type
13678     // unless it is of class type with a mutable member. This restriction does
13679     // not apply to the firstprivate clause.
13680     //
13681     // OpenMP 3.1 [2.9.3.3, private clause, Restrictions]
13682     // A variable that appears in a private clause must not have a
13683     // const-qualified type unless it is of class type with a mutable member.
13684     if (rejectConstNotMutableType(*this, D, Type, OMPC_private, ELoc))
13685       continue;
13686 
13687     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
13688     // in a Construct]
13689     //  Variables with the predetermined data-sharing attributes may not be
13690     //  listed in data-sharing attributes clauses, except for the cases
13691     //  listed below. For these exceptions only, listing a predetermined
13692     //  variable in a data-sharing attribute clause is allowed and overrides
13693     //  the variable's predetermined data-sharing attributes.
13694     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
13695     if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
13696       Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
13697                                           << getOpenMPClauseName(OMPC_private);
13698       reportOriginalDsa(*this, DSAStack, D, DVar);
13699       continue;
13700     }
13701 
13702     OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
13703     // Variably modified types are not supported for tasks.
13704     if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
13705         isOpenMPTaskingDirective(CurrDir)) {
13706       Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
13707           << getOpenMPClauseName(OMPC_private) << Type
13708           << getOpenMPDirectiveName(CurrDir);
13709       bool IsDecl =
13710           !VD ||
13711           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
13712       Diag(D->getLocation(),
13713            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
13714           << D;
13715       continue;
13716     }
13717 
13718     // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
13719     // A list item cannot appear in both a map clause and a data-sharing
13720     // attribute clause on the same construct
13721     //
13722     // OpenMP 5.0 [2.19.7.1, Restrictions, p.7]
13723     // A list item cannot appear in both a map clause and a data-sharing
13724     // attribute clause on the same construct unless the construct is a
13725     // combined construct.
13726     if ((LangOpts.OpenMP <= 45 && isOpenMPTargetExecutionDirective(CurrDir)) ||
13727         CurrDir == OMPD_target) {
13728       OpenMPClauseKind ConflictKind;
13729       if (DSAStack->checkMappableExprComponentListsForDecl(
13730               VD, /*CurrentRegionOnly=*/true,
13731               [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
13732                   OpenMPClauseKind WhereFoundClauseKind) -> bool {
13733                 ConflictKind = WhereFoundClauseKind;
13734                 return true;
13735               })) {
13736         Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
13737             << getOpenMPClauseName(OMPC_private)
13738             << getOpenMPClauseName(ConflictKind)
13739             << getOpenMPDirectiveName(CurrDir);
13740         reportOriginalDsa(*this, DSAStack, D, DVar);
13741         continue;
13742       }
13743     }
13744 
13745     // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
13746     //  A variable of class type (or array thereof) that appears in a private
13747     //  clause requires an accessible, unambiguous default constructor for the
13748     //  class type.
13749     // Generate helper private variable and initialize it with the default
13750     // value. The address of the original variable is replaced by the address of
13751     // the new private variable in CodeGen. This new variable is not added to
13752     // IdResolver, so the code in the OpenMP region uses original variable for
13753     // proper diagnostics.
13754     Type = Type.getUnqualifiedType();
13755     VarDecl *VDPrivate =
13756         buildVarDecl(*this, ELoc, Type, D->getName(),
13757                      D->hasAttrs() ? &D->getAttrs() : nullptr,
13758                      VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
13759     ActOnUninitializedDecl(VDPrivate);
13760     if (VDPrivate->isInvalidDecl())
13761       continue;
13762     DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
13763         *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
13764 
13765     DeclRefExpr *Ref = nullptr;
13766     if (!VD && !CurContext->isDependentContext())
13767       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
13768     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_private, Ref);
13769     Vars.push_back((VD || CurContext->isDependentContext())
13770                        ? RefExpr->IgnoreParens()
13771                        : Ref);
13772     PrivateCopies.push_back(VDPrivateRefExpr);
13773   }
13774 
13775   if (Vars.empty())
13776     return nullptr;
13777 
13778   return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
13779                                   PrivateCopies);
13780 }
13781 
13782 namespace {
13783 class DiagsUninitializedSeveretyRAII {
13784 private:
13785   DiagnosticsEngine &Diags;
13786   SourceLocation SavedLoc;
13787   bool IsIgnored = false;
13788 
13789 public:
13790   DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc,
13791                                  bool IsIgnored)
13792       : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) {
13793     if (!IsIgnored) {
13794       Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init,
13795                         /*Map*/ diag::Severity::Ignored, Loc);
13796     }
13797   }
13798   ~DiagsUninitializedSeveretyRAII() {
13799     if (!IsIgnored)
13800       Diags.popMappings(SavedLoc);
13801   }
13802 };
13803 }
13804 
13805 OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
13806                                                SourceLocation StartLoc,
13807                                                SourceLocation LParenLoc,
13808                                                SourceLocation EndLoc) {
13809   SmallVector<Expr *, 8> Vars;
13810   SmallVector<Expr *, 8> PrivateCopies;
13811   SmallVector<Expr *, 8> Inits;
13812   SmallVector<Decl *, 4> ExprCaptures;
13813   bool IsImplicitClause =
13814       StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid();
13815   SourceLocation ImplicitClauseLoc = DSAStack->getConstructLoc();
13816 
13817   for (Expr *RefExpr : VarList) {
13818     assert(RefExpr && "NULL expr in OpenMP firstprivate clause.");
13819     SourceLocation ELoc;
13820     SourceRange ERange;
13821     Expr *SimpleRefExpr = RefExpr;
13822     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
13823     if (Res.second) {
13824       // It will be analyzed later.
13825       Vars.push_back(RefExpr);
13826       PrivateCopies.push_back(nullptr);
13827       Inits.push_back(nullptr);
13828     }
13829     ValueDecl *D = Res.first;
13830     if (!D)
13831       continue;
13832 
13833     ELoc = IsImplicitClause ? ImplicitClauseLoc : ELoc;
13834     QualType Type = D->getType();
13835     auto *VD = dyn_cast<VarDecl>(D);
13836 
13837     // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
13838     //  A variable that appears in a private clause must not have an incomplete
13839     //  type or a reference type.
13840     if (RequireCompleteType(ELoc, Type,
13841                             diag::err_omp_firstprivate_incomplete_type))
13842       continue;
13843     Type = Type.getNonReferenceType();
13844 
13845     // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
13846     //  A variable of class type (or array thereof) that appears in a private
13847     //  clause requires an accessible, unambiguous copy constructor for the
13848     //  class type.
13849     QualType ElemType = Context.getBaseElementType(Type).getNonReferenceType();
13850 
13851     // If an implicit firstprivate variable found it was checked already.
13852     DSAStackTy::DSAVarData TopDVar;
13853     if (!IsImplicitClause) {
13854       DSAStackTy::DSAVarData DVar =
13855           DSAStack->getTopDSA(D, /*FromParent=*/false);
13856       TopDVar = DVar;
13857       OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
13858       bool IsConstant = ElemType.isConstant(Context);
13859       // OpenMP [2.4.13, Data-sharing Attribute Clauses]
13860       //  A list item that specifies a given variable may not appear in more
13861       // than one clause on the same directive, except that a variable may be
13862       //  specified in both firstprivate and lastprivate clauses.
13863       // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
13864       // A list item may appear in a firstprivate or lastprivate clause but not
13865       // both.
13866       if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
13867           (isOpenMPDistributeDirective(CurrDir) ||
13868            DVar.CKind != OMPC_lastprivate) &&
13869           DVar.RefExpr) {
13870         Diag(ELoc, diag::err_omp_wrong_dsa)
13871             << getOpenMPClauseName(DVar.CKind)
13872             << getOpenMPClauseName(OMPC_firstprivate);
13873         reportOriginalDsa(*this, DSAStack, D, DVar);
13874         continue;
13875       }
13876 
13877       // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
13878       // in a Construct]
13879       //  Variables with the predetermined data-sharing attributes may not be
13880       //  listed in data-sharing attributes clauses, except for the cases
13881       //  listed below. For these exceptions only, listing a predetermined
13882       //  variable in a data-sharing attribute clause is allowed and overrides
13883       //  the variable's predetermined data-sharing attributes.
13884       // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
13885       // in a Construct, C/C++, p.2]
13886       //  Variables with const-qualified type having no mutable member may be
13887       //  listed in a firstprivate clause, even if they are static data members.
13888       if (!(IsConstant || (VD && VD->isStaticDataMember())) && !DVar.RefExpr &&
13889           DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
13890         Diag(ELoc, diag::err_omp_wrong_dsa)
13891             << getOpenMPClauseName(DVar.CKind)
13892             << getOpenMPClauseName(OMPC_firstprivate);
13893         reportOriginalDsa(*this, DSAStack, D, DVar);
13894         continue;
13895       }
13896 
13897       // OpenMP [2.9.3.4, Restrictions, p.2]
13898       //  A list item that is private within a parallel region must not appear
13899       //  in a firstprivate clause on a worksharing construct if any of the
13900       //  worksharing regions arising from the worksharing construct ever bind
13901       //  to any of the parallel regions arising from the parallel construct.
13902       // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
13903       // A list item that is private within a teams region must not appear in a
13904       // firstprivate clause on a distribute construct if any of the distribute
13905       // regions arising from the distribute construct ever bind to any of the
13906       // teams regions arising from the teams construct.
13907       // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
13908       // A list item that appears in a reduction clause of a teams construct
13909       // must not appear in a firstprivate clause on a distribute construct if
13910       // any of the distribute regions arising from the distribute construct
13911       // ever bind to any of the teams regions arising from the teams construct.
13912       if ((isOpenMPWorksharingDirective(CurrDir) ||
13913            isOpenMPDistributeDirective(CurrDir)) &&
13914           !isOpenMPParallelDirective(CurrDir) &&
13915           !isOpenMPTeamsDirective(CurrDir)) {
13916         DVar = DSAStack->getImplicitDSA(D, true);
13917         if (DVar.CKind != OMPC_shared &&
13918             (isOpenMPParallelDirective(DVar.DKind) ||
13919              isOpenMPTeamsDirective(DVar.DKind) ||
13920              DVar.DKind == OMPD_unknown)) {
13921           Diag(ELoc, diag::err_omp_required_access)
13922               << getOpenMPClauseName(OMPC_firstprivate)
13923               << getOpenMPClauseName(OMPC_shared);
13924           reportOriginalDsa(*this, DSAStack, D, DVar);
13925           continue;
13926         }
13927       }
13928       // OpenMP [2.9.3.4, Restrictions, p.3]
13929       //  A list item that appears in a reduction clause of a parallel construct
13930       //  must not appear in a firstprivate clause on a worksharing or task
13931       //  construct if any of the worksharing or task regions arising from the
13932       //  worksharing or task construct ever bind to any of the parallel regions
13933       //  arising from the parallel construct.
13934       // OpenMP [2.9.3.4, Restrictions, p.4]
13935       //  A list item that appears in a reduction clause in worksharing
13936       //  construct must not appear in a firstprivate clause in a task construct
13937       //  encountered during execution of any of the worksharing regions arising
13938       //  from the worksharing construct.
13939       if (isOpenMPTaskingDirective(CurrDir)) {
13940         DVar = DSAStack->hasInnermostDSA(
13941             D, [](OpenMPClauseKind C) { return C == OMPC_reduction; },
13942             [](OpenMPDirectiveKind K) {
13943               return isOpenMPParallelDirective(K) ||
13944                      isOpenMPWorksharingDirective(K) ||
13945                      isOpenMPTeamsDirective(K);
13946             },
13947             /*FromParent=*/true);
13948         if (DVar.CKind == OMPC_reduction &&
13949             (isOpenMPParallelDirective(DVar.DKind) ||
13950              isOpenMPWorksharingDirective(DVar.DKind) ||
13951              isOpenMPTeamsDirective(DVar.DKind))) {
13952           Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate)
13953               << getOpenMPDirectiveName(DVar.DKind);
13954           reportOriginalDsa(*this, DSAStack, D, DVar);
13955           continue;
13956         }
13957       }
13958 
13959       // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
13960       // A list item cannot appear in both a map clause and a data-sharing
13961       // attribute clause on the same construct
13962       //
13963       // OpenMP 5.0 [2.19.7.1, Restrictions, p.7]
13964       // A list item cannot appear in both a map clause and a data-sharing
13965       // attribute clause on the same construct unless the construct is a
13966       // combined construct.
13967       if ((LangOpts.OpenMP <= 45 &&
13968            isOpenMPTargetExecutionDirective(CurrDir)) ||
13969           CurrDir == OMPD_target) {
13970         OpenMPClauseKind ConflictKind;
13971         if (DSAStack->checkMappableExprComponentListsForDecl(
13972                 VD, /*CurrentRegionOnly=*/true,
13973                 [&ConflictKind](
13974                     OMPClauseMappableExprCommon::MappableExprComponentListRef,
13975                     OpenMPClauseKind WhereFoundClauseKind) {
13976                   ConflictKind = WhereFoundClauseKind;
13977                   return true;
13978                 })) {
13979           Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
13980               << getOpenMPClauseName(OMPC_firstprivate)
13981               << getOpenMPClauseName(ConflictKind)
13982               << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
13983           reportOriginalDsa(*this, DSAStack, D, DVar);
13984           continue;
13985         }
13986       }
13987     }
13988 
13989     // Variably modified types are not supported for tasks.
13990     if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
13991         isOpenMPTaskingDirective(DSAStack->getCurrentDirective())) {
13992       Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
13993           << getOpenMPClauseName(OMPC_firstprivate) << Type
13994           << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
13995       bool IsDecl =
13996           !VD ||
13997           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
13998       Diag(D->getLocation(),
13999            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
14000           << D;
14001       continue;
14002     }
14003 
14004     Type = Type.getUnqualifiedType();
14005     VarDecl *VDPrivate =
14006         buildVarDecl(*this, ELoc, Type, D->getName(),
14007                      D->hasAttrs() ? &D->getAttrs() : nullptr,
14008                      VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
14009     // Generate helper private variable and initialize it with the value of the
14010     // original variable. The address of the original variable is replaced by
14011     // the address of the new private variable in the CodeGen. This new variable
14012     // is not added to IdResolver, so the code in the OpenMP region uses
14013     // original variable for proper diagnostics and variable capturing.
14014     Expr *VDInitRefExpr = nullptr;
14015     // For arrays generate initializer for single element and replace it by the
14016     // original array element in CodeGen.
14017     if (Type->isArrayType()) {
14018       VarDecl *VDInit =
14019           buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, D->getName());
14020       VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc);
14021       Expr *Init = DefaultLvalueConversion(VDInitRefExpr).get();
14022       ElemType = ElemType.getUnqualifiedType();
14023       VarDecl *VDInitTemp = buildVarDecl(*this, RefExpr->getExprLoc(), ElemType,
14024                                          ".firstprivate.temp");
14025       InitializedEntity Entity =
14026           InitializedEntity::InitializeVariable(VDInitTemp);
14027       InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc);
14028 
14029       InitializationSequence InitSeq(*this, Entity, Kind, Init);
14030       ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init);
14031       if (Result.isInvalid())
14032         VDPrivate->setInvalidDecl();
14033       else
14034         VDPrivate->setInit(Result.getAs<Expr>());
14035       // Remove temp variable declaration.
14036       Context.Deallocate(VDInitTemp);
14037     } else {
14038       VarDecl *VDInit = buildVarDecl(*this, RefExpr->getExprLoc(), Type,
14039                                      ".firstprivate.temp");
14040       VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
14041                                        RefExpr->getExprLoc());
14042       AddInitializerToDecl(VDPrivate,
14043                            DefaultLvalueConversion(VDInitRefExpr).get(),
14044                            /*DirectInit=*/false);
14045     }
14046     if (VDPrivate->isInvalidDecl()) {
14047       if (IsImplicitClause) {
14048         Diag(RefExpr->getExprLoc(),
14049              diag::note_omp_task_predetermined_firstprivate_here);
14050       }
14051       continue;
14052     }
14053     CurContext->addDecl(VDPrivate);
14054     DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
14055         *this, VDPrivate, RefExpr->getType().getUnqualifiedType(),
14056         RefExpr->getExprLoc());
14057     DeclRefExpr *Ref = nullptr;
14058     if (!VD && !CurContext->isDependentContext()) {
14059       if (TopDVar.CKind == OMPC_lastprivate) {
14060         Ref = TopDVar.PrivateCopy;
14061       } else {
14062         Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
14063         if (!isOpenMPCapturedDecl(D))
14064           ExprCaptures.push_back(Ref->getDecl());
14065       }
14066     }
14067     if (!IsImplicitClause)
14068       DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
14069     Vars.push_back((VD || CurContext->isDependentContext())
14070                        ? RefExpr->IgnoreParens()
14071                        : Ref);
14072     PrivateCopies.push_back(VDPrivateRefExpr);
14073     Inits.push_back(VDInitRefExpr);
14074   }
14075 
14076   if (Vars.empty())
14077     return nullptr;
14078 
14079   return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
14080                                        Vars, PrivateCopies, Inits,
14081                                        buildPreInits(Context, ExprCaptures));
14082 }
14083 
14084 OMPClause *Sema::ActOnOpenMPLastprivateClause(
14085     ArrayRef<Expr *> VarList, OpenMPLastprivateModifier LPKind,
14086     SourceLocation LPKindLoc, SourceLocation ColonLoc, SourceLocation StartLoc,
14087     SourceLocation LParenLoc, SourceLocation EndLoc) {
14088   if (LPKind == OMPC_LASTPRIVATE_unknown && LPKindLoc.isValid()) {
14089     assert(ColonLoc.isValid() && "Colon location must be valid.");
14090     Diag(LPKindLoc, diag::err_omp_unexpected_clause_value)
14091         << getListOfPossibleValues(OMPC_lastprivate, /*First=*/0,
14092                                    /*Last=*/OMPC_LASTPRIVATE_unknown)
14093         << getOpenMPClauseName(OMPC_lastprivate);
14094     return nullptr;
14095   }
14096 
14097   SmallVector<Expr *, 8> Vars;
14098   SmallVector<Expr *, 8> SrcExprs;
14099   SmallVector<Expr *, 8> DstExprs;
14100   SmallVector<Expr *, 8> AssignmentOps;
14101   SmallVector<Decl *, 4> ExprCaptures;
14102   SmallVector<Expr *, 4> ExprPostUpdates;
14103   for (Expr *RefExpr : VarList) {
14104     assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
14105     SourceLocation ELoc;
14106     SourceRange ERange;
14107     Expr *SimpleRefExpr = RefExpr;
14108     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
14109     if (Res.second) {
14110       // It will be analyzed later.
14111       Vars.push_back(RefExpr);
14112       SrcExprs.push_back(nullptr);
14113       DstExprs.push_back(nullptr);
14114       AssignmentOps.push_back(nullptr);
14115     }
14116     ValueDecl *D = Res.first;
14117     if (!D)
14118       continue;
14119 
14120     QualType Type = D->getType();
14121     auto *VD = dyn_cast<VarDecl>(D);
14122 
14123     // OpenMP [2.14.3.5, Restrictions, C/C++, p.2]
14124     //  A variable that appears in a lastprivate clause must not have an
14125     //  incomplete type or a reference type.
14126     if (RequireCompleteType(ELoc, Type,
14127                             diag::err_omp_lastprivate_incomplete_type))
14128       continue;
14129     Type = Type.getNonReferenceType();
14130 
14131     // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
14132     // A variable that is privatized must not have a const-qualified type
14133     // unless it is of class type with a mutable member. This restriction does
14134     // not apply to the firstprivate clause.
14135     //
14136     // OpenMP 3.1 [2.9.3.5, lastprivate clause, Restrictions]
14137     // A variable that appears in a lastprivate clause must not have a
14138     // const-qualified type unless it is of class type with a mutable member.
14139     if (rejectConstNotMutableType(*this, D, Type, OMPC_lastprivate, ELoc))
14140       continue;
14141 
14142     // OpenMP 5.0 [2.19.4.5 lastprivate Clause, Restrictions]
14143     // A list item that appears in a lastprivate clause with the conditional
14144     // modifier must be a scalar variable.
14145     if (LPKind == OMPC_LASTPRIVATE_conditional && !Type->isScalarType()) {
14146       Diag(ELoc, diag::err_omp_lastprivate_conditional_non_scalar);
14147       bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
14148                                VarDecl::DeclarationOnly;
14149       Diag(D->getLocation(),
14150            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
14151           << D;
14152       continue;
14153     }
14154 
14155     OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
14156     // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
14157     // in a Construct]
14158     //  Variables with the predetermined data-sharing attributes may not be
14159     //  listed in data-sharing attributes clauses, except for the cases
14160     //  listed below.
14161     // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
14162     // A list item may appear in a firstprivate or lastprivate clause but not
14163     // both.
14164     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
14165     if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate &&
14166         (isOpenMPDistributeDirective(CurrDir) ||
14167          DVar.CKind != OMPC_firstprivate) &&
14168         (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
14169       Diag(ELoc, diag::err_omp_wrong_dsa)
14170           << getOpenMPClauseName(DVar.CKind)
14171           << getOpenMPClauseName(OMPC_lastprivate);
14172       reportOriginalDsa(*this, DSAStack, D, DVar);
14173       continue;
14174     }
14175 
14176     // OpenMP [2.14.3.5, Restrictions, p.2]
14177     // A list item that is private within a parallel region, or that appears in
14178     // the reduction clause of a parallel construct, must not appear in a
14179     // lastprivate clause on a worksharing construct if any of the corresponding
14180     // worksharing regions ever binds to any of the corresponding parallel
14181     // regions.
14182     DSAStackTy::DSAVarData TopDVar = DVar;
14183     if (isOpenMPWorksharingDirective(CurrDir) &&
14184         !isOpenMPParallelDirective(CurrDir) &&
14185         !isOpenMPTeamsDirective(CurrDir)) {
14186       DVar = DSAStack->getImplicitDSA(D, true);
14187       if (DVar.CKind != OMPC_shared) {
14188         Diag(ELoc, diag::err_omp_required_access)
14189             << getOpenMPClauseName(OMPC_lastprivate)
14190             << getOpenMPClauseName(OMPC_shared);
14191         reportOriginalDsa(*this, DSAStack, D, DVar);
14192         continue;
14193       }
14194     }
14195 
14196     // OpenMP [2.14.3.5, Restrictions, C++, p.1,2]
14197     //  A variable of class type (or array thereof) that appears in a
14198     //  lastprivate clause requires an accessible, unambiguous default
14199     //  constructor for the class type, unless the list item is also specified
14200     //  in a firstprivate clause.
14201     //  A variable of class type (or array thereof) that appears in a
14202     //  lastprivate clause requires an accessible, unambiguous copy assignment
14203     //  operator for the class type.
14204     Type = Context.getBaseElementType(Type).getNonReferenceType();
14205     VarDecl *SrcVD = buildVarDecl(*this, ERange.getBegin(),
14206                                   Type.getUnqualifiedType(), ".lastprivate.src",
14207                                   D->hasAttrs() ? &D->getAttrs() : nullptr);
14208     DeclRefExpr *PseudoSrcExpr =
14209         buildDeclRefExpr(*this, SrcVD, Type.getUnqualifiedType(), ELoc);
14210     VarDecl *DstVD =
14211         buildVarDecl(*this, ERange.getBegin(), Type, ".lastprivate.dst",
14212                      D->hasAttrs() ? &D->getAttrs() : nullptr);
14213     DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
14214     // For arrays generate assignment operation for single element and replace
14215     // it by the original array element in CodeGen.
14216     ExprResult AssignmentOp = BuildBinOp(/*S=*/nullptr, ELoc, BO_Assign,
14217                                          PseudoDstExpr, PseudoSrcExpr);
14218     if (AssignmentOp.isInvalid())
14219       continue;
14220     AssignmentOp =
14221         ActOnFinishFullExpr(AssignmentOp.get(), ELoc, /*DiscardedValue*/ false);
14222     if (AssignmentOp.isInvalid())
14223       continue;
14224 
14225     DeclRefExpr *Ref = nullptr;
14226     if (!VD && !CurContext->isDependentContext()) {
14227       if (TopDVar.CKind == OMPC_firstprivate) {
14228         Ref = TopDVar.PrivateCopy;
14229       } else {
14230         Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
14231         if (!isOpenMPCapturedDecl(D))
14232           ExprCaptures.push_back(Ref->getDecl());
14233       }
14234       if (TopDVar.CKind == OMPC_firstprivate ||
14235           (!isOpenMPCapturedDecl(D) &&
14236            Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>())) {
14237         ExprResult RefRes = DefaultLvalueConversion(Ref);
14238         if (!RefRes.isUsable())
14239           continue;
14240         ExprResult PostUpdateRes =
14241             BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
14242                        RefRes.get());
14243         if (!PostUpdateRes.isUsable())
14244           continue;
14245         ExprPostUpdates.push_back(
14246             IgnoredValueConversions(PostUpdateRes.get()).get());
14247       }
14248     }
14249     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_lastprivate, Ref);
14250     Vars.push_back((VD || CurContext->isDependentContext())
14251                        ? RefExpr->IgnoreParens()
14252                        : Ref);
14253     SrcExprs.push_back(PseudoSrcExpr);
14254     DstExprs.push_back(PseudoDstExpr);
14255     AssignmentOps.push_back(AssignmentOp.get());
14256   }
14257 
14258   if (Vars.empty())
14259     return nullptr;
14260 
14261   return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
14262                                       Vars, SrcExprs, DstExprs, AssignmentOps,
14263                                       LPKind, LPKindLoc, ColonLoc,
14264                                       buildPreInits(Context, ExprCaptures),
14265                                       buildPostUpdate(*this, ExprPostUpdates));
14266 }
14267 
14268 OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
14269                                          SourceLocation StartLoc,
14270                                          SourceLocation LParenLoc,
14271                                          SourceLocation EndLoc) {
14272   SmallVector<Expr *, 8> Vars;
14273   for (Expr *RefExpr : VarList) {
14274     assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
14275     SourceLocation ELoc;
14276     SourceRange ERange;
14277     Expr *SimpleRefExpr = RefExpr;
14278     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
14279     if (Res.second) {
14280       // It will be analyzed later.
14281       Vars.push_back(RefExpr);
14282     }
14283     ValueDecl *D = Res.first;
14284     if (!D)
14285       continue;
14286 
14287     auto *VD = dyn_cast<VarDecl>(D);
14288     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
14289     // in a Construct]
14290     //  Variables with the predetermined data-sharing attributes may not be
14291     //  listed in data-sharing attributes clauses, except for the cases
14292     //  listed below. For these exceptions only, listing a predetermined
14293     //  variable in a data-sharing attribute clause is allowed and overrides
14294     //  the variable's predetermined data-sharing attributes.
14295     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
14296     if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared &&
14297         DVar.RefExpr) {
14298       Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
14299                                           << getOpenMPClauseName(OMPC_shared);
14300       reportOriginalDsa(*this, DSAStack, D, DVar);
14301       continue;
14302     }
14303 
14304     DeclRefExpr *Ref = nullptr;
14305     if (!VD && isOpenMPCapturedDecl(D) && !CurContext->isDependentContext())
14306       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
14307     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_shared, Ref);
14308     Vars.push_back((VD || !Ref || CurContext->isDependentContext())
14309                        ? RefExpr->IgnoreParens()
14310                        : Ref);
14311   }
14312 
14313   if (Vars.empty())
14314     return nullptr;
14315 
14316   return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
14317 }
14318 
14319 namespace {
14320 class DSARefChecker : public StmtVisitor<DSARefChecker, bool> {
14321   DSAStackTy *Stack;
14322 
14323 public:
14324   bool VisitDeclRefExpr(DeclRefExpr *E) {
14325     if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
14326       DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, /*FromParent=*/false);
14327       if (DVar.CKind == OMPC_shared && !DVar.RefExpr)
14328         return false;
14329       if (DVar.CKind != OMPC_unknown)
14330         return true;
14331       DSAStackTy::DSAVarData DVarPrivate = Stack->hasDSA(
14332           VD, isOpenMPPrivate, [](OpenMPDirectiveKind) { return true; },
14333           /*FromParent=*/true);
14334       return DVarPrivate.CKind != OMPC_unknown;
14335     }
14336     return false;
14337   }
14338   bool VisitStmt(Stmt *S) {
14339     for (Stmt *Child : S->children()) {
14340       if (Child && Visit(Child))
14341         return true;
14342     }
14343     return false;
14344   }
14345   explicit DSARefChecker(DSAStackTy *S) : Stack(S) {}
14346 };
14347 } // namespace
14348 
14349 namespace {
14350 // Transform MemberExpression for specified FieldDecl of current class to
14351 // DeclRefExpr to specified OMPCapturedExprDecl.
14352 class TransformExprToCaptures : public TreeTransform<TransformExprToCaptures> {
14353   typedef TreeTransform<TransformExprToCaptures> BaseTransform;
14354   ValueDecl *Field = nullptr;
14355   DeclRefExpr *CapturedExpr = nullptr;
14356 
14357 public:
14358   TransformExprToCaptures(Sema &SemaRef, ValueDecl *FieldDecl)
14359       : BaseTransform(SemaRef), Field(FieldDecl), CapturedExpr(nullptr) {}
14360 
14361   ExprResult TransformMemberExpr(MemberExpr *E) {
14362     if (isa<CXXThisExpr>(E->getBase()->IgnoreParenImpCasts()) &&
14363         E->getMemberDecl() == Field) {
14364       CapturedExpr = buildCapture(SemaRef, Field, E, /*WithInit=*/false);
14365       return CapturedExpr;
14366     }
14367     return BaseTransform::TransformMemberExpr(E);
14368   }
14369   DeclRefExpr *getCapturedExpr() { return CapturedExpr; }
14370 };
14371 } // namespace
14372 
14373 template <typename T, typename U>
14374 static T filterLookupForUDReductionAndMapper(
14375     SmallVectorImpl<U> &Lookups, const llvm::function_ref<T(ValueDecl *)> Gen) {
14376   for (U &Set : Lookups) {
14377     for (auto *D : Set) {
14378       if (T Res = Gen(cast<ValueDecl>(D)))
14379         return Res;
14380     }
14381   }
14382   return T();
14383 }
14384 
14385 static NamedDecl *findAcceptableDecl(Sema &SemaRef, NamedDecl *D) {
14386   assert(!LookupResult::isVisible(SemaRef, D) && "not in slow case");
14387 
14388   for (auto RD : D->redecls()) {
14389     // Don't bother with extra checks if we already know this one isn't visible.
14390     if (RD == D)
14391       continue;
14392 
14393     auto ND = cast<NamedDecl>(RD);
14394     if (LookupResult::isVisible(SemaRef, ND))
14395       return ND;
14396   }
14397 
14398   return nullptr;
14399 }
14400 
14401 static void
14402 argumentDependentLookup(Sema &SemaRef, const DeclarationNameInfo &Id,
14403                         SourceLocation Loc, QualType Ty,
14404                         SmallVectorImpl<UnresolvedSet<8>> &Lookups) {
14405   // Find all of the associated namespaces and classes based on the
14406   // arguments we have.
14407   Sema::AssociatedNamespaceSet AssociatedNamespaces;
14408   Sema::AssociatedClassSet AssociatedClasses;
14409   OpaqueValueExpr OVE(Loc, Ty, VK_LValue);
14410   SemaRef.FindAssociatedClassesAndNamespaces(Loc, &OVE, AssociatedNamespaces,
14411                                              AssociatedClasses);
14412 
14413   // C++ [basic.lookup.argdep]p3:
14414   //   Let X be the lookup set produced by unqualified lookup (3.4.1)
14415   //   and let Y be the lookup set produced by argument dependent
14416   //   lookup (defined as follows). If X contains [...] then Y is
14417   //   empty. Otherwise Y is the set of declarations found in the
14418   //   namespaces associated with the argument types as described
14419   //   below. The set of declarations found by the lookup of the name
14420   //   is the union of X and Y.
14421   //
14422   // Here, we compute Y and add its members to the overloaded
14423   // candidate set.
14424   for (auto *NS : AssociatedNamespaces) {
14425     //   When considering an associated namespace, the lookup is the
14426     //   same as the lookup performed when the associated namespace is
14427     //   used as a qualifier (3.4.3.2) except that:
14428     //
14429     //     -- Any using-directives in the associated namespace are
14430     //        ignored.
14431     //
14432     //     -- Any namespace-scope friend functions declared in
14433     //        associated classes are visible within their respective
14434     //        namespaces even if they are not visible during an ordinary
14435     //        lookup (11.4).
14436     DeclContext::lookup_result R = NS->lookup(Id.getName());
14437     for (auto *D : R) {
14438       auto *Underlying = D;
14439       if (auto *USD = dyn_cast<UsingShadowDecl>(D))
14440         Underlying = USD->getTargetDecl();
14441 
14442       if (!isa<OMPDeclareReductionDecl>(Underlying) &&
14443           !isa<OMPDeclareMapperDecl>(Underlying))
14444         continue;
14445 
14446       if (!SemaRef.isVisible(D)) {
14447         D = findAcceptableDecl(SemaRef, D);
14448         if (!D)
14449           continue;
14450         if (auto *USD = dyn_cast<UsingShadowDecl>(D))
14451           Underlying = USD->getTargetDecl();
14452       }
14453       Lookups.emplace_back();
14454       Lookups.back().addDecl(Underlying);
14455     }
14456   }
14457 }
14458 
14459 static ExprResult
14460 buildDeclareReductionRef(Sema &SemaRef, SourceLocation Loc, SourceRange Range,
14461                          Scope *S, CXXScopeSpec &ReductionIdScopeSpec,
14462                          const DeclarationNameInfo &ReductionId, QualType Ty,
14463                          CXXCastPath &BasePath, Expr *UnresolvedReduction) {
14464   if (ReductionIdScopeSpec.isInvalid())
14465     return ExprError();
14466   SmallVector<UnresolvedSet<8>, 4> Lookups;
14467   if (S) {
14468     LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
14469     Lookup.suppressDiagnostics();
14470     while (S && SemaRef.LookupParsedName(Lookup, S, &ReductionIdScopeSpec)) {
14471       NamedDecl *D = Lookup.getRepresentativeDecl();
14472       do {
14473         S = S->getParent();
14474       } while (S && !S->isDeclScope(D));
14475       if (S)
14476         S = S->getParent();
14477       Lookups.emplace_back();
14478       Lookups.back().append(Lookup.begin(), Lookup.end());
14479       Lookup.clear();
14480     }
14481   } else if (auto *ULE =
14482                  cast_or_null<UnresolvedLookupExpr>(UnresolvedReduction)) {
14483     Lookups.push_back(UnresolvedSet<8>());
14484     Decl *PrevD = nullptr;
14485     for (NamedDecl *D : ULE->decls()) {
14486       if (D == PrevD)
14487         Lookups.push_back(UnresolvedSet<8>());
14488       else if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(D))
14489         Lookups.back().addDecl(DRD);
14490       PrevD = D;
14491     }
14492   }
14493   if (SemaRef.CurContext->isDependentContext() || Ty->isDependentType() ||
14494       Ty->isInstantiationDependentType() ||
14495       Ty->containsUnexpandedParameterPack() ||
14496       filterLookupForUDReductionAndMapper<bool>(Lookups, [](ValueDecl *D) {
14497         return !D->isInvalidDecl() &&
14498                (D->getType()->isDependentType() ||
14499                 D->getType()->isInstantiationDependentType() ||
14500                 D->getType()->containsUnexpandedParameterPack());
14501       })) {
14502     UnresolvedSet<8> ResSet;
14503     for (const UnresolvedSet<8> &Set : Lookups) {
14504       if (Set.empty())
14505         continue;
14506       ResSet.append(Set.begin(), Set.end());
14507       // The last item marks the end of all declarations at the specified scope.
14508       ResSet.addDecl(Set[Set.size() - 1]);
14509     }
14510     return UnresolvedLookupExpr::Create(
14511         SemaRef.Context, /*NamingClass=*/nullptr,
14512         ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), ReductionId,
14513         /*ADL=*/true, /*Overloaded=*/true, ResSet.begin(), ResSet.end());
14514   }
14515   // Lookup inside the classes.
14516   // C++ [over.match.oper]p3:
14517   //   For a unary operator @ with an operand of a type whose
14518   //   cv-unqualified version is T1, and for a binary operator @ with
14519   //   a left operand of a type whose cv-unqualified version is T1 and
14520   //   a right operand of a type whose cv-unqualified version is T2,
14521   //   three sets of candidate functions, designated member
14522   //   candidates, non-member candidates and built-in candidates, are
14523   //   constructed as follows:
14524   //     -- If T1 is a complete class type or a class currently being
14525   //        defined, the set of member candidates is the result of the
14526   //        qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
14527   //        the set of member candidates is empty.
14528   LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
14529   Lookup.suppressDiagnostics();
14530   if (const auto *TyRec = Ty->getAs<RecordType>()) {
14531     // Complete the type if it can be completed.
14532     // If the type is neither complete nor being defined, bail out now.
14533     if (SemaRef.isCompleteType(Loc, Ty) || TyRec->isBeingDefined() ||
14534         TyRec->getDecl()->getDefinition()) {
14535       Lookup.clear();
14536       SemaRef.LookupQualifiedName(Lookup, TyRec->getDecl());
14537       if (Lookup.empty()) {
14538         Lookups.emplace_back();
14539         Lookups.back().append(Lookup.begin(), Lookup.end());
14540       }
14541     }
14542   }
14543   // Perform ADL.
14544   if (SemaRef.getLangOpts().CPlusPlus)
14545     argumentDependentLookup(SemaRef, ReductionId, Loc, Ty, Lookups);
14546   if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
14547           Lookups, [&SemaRef, Ty](ValueDecl *D) -> ValueDecl * {
14548             if (!D->isInvalidDecl() &&
14549                 SemaRef.Context.hasSameType(D->getType(), Ty))
14550               return D;
14551             return nullptr;
14552           }))
14553     return SemaRef.BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(),
14554                                     VK_LValue, Loc);
14555   if (SemaRef.getLangOpts().CPlusPlus) {
14556     if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
14557             Lookups, [&SemaRef, Ty, Loc](ValueDecl *D) -> ValueDecl * {
14558               if (!D->isInvalidDecl() &&
14559                   SemaRef.IsDerivedFrom(Loc, Ty, D->getType()) &&
14560                   !Ty.isMoreQualifiedThan(D->getType()))
14561                 return D;
14562               return nullptr;
14563             })) {
14564       CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
14565                          /*DetectVirtual=*/false);
14566       if (SemaRef.IsDerivedFrom(Loc, Ty, VD->getType(), Paths)) {
14567         if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
14568                 VD->getType().getUnqualifiedType()))) {
14569           if (SemaRef.CheckBaseClassAccess(
14570                   Loc, VD->getType(), Ty, Paths.front(),
14571                   /*DiagID=*/0) != Sema::AR_inaccessible) {
14572             SemaRef.BuildBasePathArray(Paths, BasePath);
14573             return SemaRef.BuildDeclRefExpr(
14574                 VD, VD->getType().getNonReferenceType(), VK_LValue, Loc);
14575           }
14576         }
14577       }
14578     }
14579   }
14580   if (ReductionIdScopeSpec.isSet()) {
14581     SemaRef.Diag(Loc, diag::err_omp_not_resolved_reduction_identifier)
14582         << Ty << Range;
14583     return ExprError();
14584   }
14585   return ExprEmpty();
14586 }
14587 
14588 namespace {
14589 /// Data for the reduction-based clauses.
14590 struct ReductionData {
14591   /// List of original reduction items.
14592   SmallVector<Expr *, 8> Vars;
14593   /// List of private copies of the reduction items.
14594   SmallVector<Expr *, 8> Privates;
14595   /// LHS expressions for the reduction_op expressions.
14596   SmallVector<Expr *, 8> LHSs;
14597   /// RHS expressions for the reduction_op expressions.
14598   SmallVector<Expr *, 8> RHSs;
14599   /// Reduction operation expression.
14600   SmallVector<Expr *, 8> ReductionOps;
14601   /// inscan copy operation expressions.
14602   SmallVector<Expr *, 8> InscanCopyOps;
14603   /// inscan copy temp array expressions for prefix sums.
14604   SmallVector<Expr *, 8> InscanCopyArrayTemps;
14605   /// inscan copy temp array element expressions for prefix sums.
14606   SmallVector<Expr *, 8> InscanCopyArrayElems;
14607   /// Taskgroup descriptors for the corresponding reduction items in
14608   /// in_reduction clauses.
14609   SmallVector<Expr *, 8> TaskgroupDescriptors;
14610   /// List of captures for clause.
14611   SmallVector<Decl *, 4> ExprCaptures;
14612   /// List of postupdate expressions.
14613   SmallVector<Expr *, 4> ExprPostUpdates;
14614   /// Reduction modifier.
14615   unsigned RedModifier = 0;
14616   ReductionData() = delete;
14617   /// Reserves required memory for the reduction data.
14618   ReductionData(unsigned Size, unsigned Modifier = 0) : RedModifier(Modifier) {
14619     Vars.reserve(Size);
14620     Privates.reserve(Size);
14621     LHSs.reserve(Size);
14622     RHSs.reserve(Size);
14623     ReductionOps.reserve(Size);
14624     if (RedModifier == OMPC_REDUCTION_inscan) {
14625       InscanCopyOps.reserve(Size);
14626       InscanCopyArrayTemps.reserve(Size);
14627       InscanCopyArrayElems.reserve(Size);
14628     }
14629     TaskgroupDescriptors.reserve(Size);
14630     ExprCaptures.reserve(Size);
14631     ExprPostUpdates.reserve(Size);
14632   }
14633   /// Stores reduction item and reduction operation only (required for dependent
14634   /// reduction item).
14635   void push(Expr *Item, Expr *ReductionOp) {
14636     Vars.emplace_back(Item);
14637     Privates.emplace_back(nullptr);
14638     LHSs.emplace_back(nullptr);
14639     RHSs.emplace_back(nullptr);
14640     ReductionOps.emplace_back(ReductionOp);
14641     TaskgroupDescriptors.emplace_back(nullptr);
14642     if (RedModifier == OMPC_REDUCTION_inscan) {
14643       InscanCopyOps.push_back(nullptr);
14644       InscanCopyArrayTemps.push_back(nullptr);
14645       InscanCopyArrayElems.push_back(nullptr);
14646     }
14647   }
14648   /// Stores reduction data.
14649   void push(Expr *Item, Expr *Private, Expr *LHS, Expr *RHS, Expr *ReductionOp,
14650             Expr *TaskgroupDescriptor, Expr *CopyOp, Expr *CopyArrayTemp,
14651             Expr *CopyArrayElem) {
14652     Vars.emplace_back(Item);
14653     Privates.emplace_back(Private);
14654     LHSs.emplace_back(LHS);
14655     RHSs.emplace_back(RHS);
14656     ReductionOps.emplace_back(ReductionOp);
14657     TaskgroupDescriptors.emplace_back(TaskgroupDescriptor);
14658     if (RedModifier == OMPC_REDUCTION_inscan) {
14659       InscanCopyOps.push_back(CopyOp);
14660       InscanCopyArrayTemps.push_back(CopyArrayTemp);
14661       InscanCopyArrayElems.push_back(CopyArrayElem);
14662     } else {
14663       assert(CopyOp == nullptr && CopyArrayTemp == nullptr &&
14664              CopyArrayElem == nullptr &&
14665              "Copy operation must be used for inscan reductions only.");
14666     }
14667   }
14668 };
14669 } // namespace
14670 
14671 static bool checkOMPArraySectionConstantForReduction(
14672     ASTContext &Context, const OMPArraySectionExpr *OASE, bool &SingleElement,
14673     SmallVectorImpl<llvm::APSInt> &ArraySizes) {
14674   const Expr *Length = OASE->getLength();
14675   if (Length == nullptr) {
14676     // For array sections of the form [1:] or [:], we would need to analyze
14677     // the lower bound...
14678     if (OASE->getColonLoc().isValid())
14679       return false;
14680 
14681     // This is an array subscript which has implicit length 1!
14682     SingleElement = true;
14683     ArraySizes.push_back(llvm::APSInt::get(1));
14684   } else {
14685     Expr::EvalResult Result;
14686     if (!Length->EvaluateAsInt(Result, Context))
14687       return false;
14688 
14689     llvm::APSInt ConstantLengthValue = Result.Val.getInt();
14690     SingleElement = (ConstantLengthValue.getSExtValue() == 1);
14691     ArraySizes.push_back(ConstantLengthValue);
14692   }
14693 
14694   // Get the base of this array section and walk up from there.
14695   const Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
14696 
14697   // We require length = 1 for all array sections except the right-most to
14698   // guarantee that the memory region is contiguous and has no holes in it.
14699   while (const auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base)) {
14700     Length = TempOASE->getLength();
14701     if (Length == nullptr) {
14702       // For array sections of the form [1:] or [:], we would need to analyze
14703       // the lower bound...
14704       if (OASE->getColonLoc().isValid())
14705         return false;
14706 
14707       // This is an array subscript which has implicit length 1!
14708       ArraySizes.push_back(llvm::APSInt::get(1));
14709     } else {
14710       Expr::EvalResult Result;
14711       if (!Length->EvaluateAsInt(Result, Context))
14712         return false;
14713 
14714       llvm::APSInt ConstantLengthValue = Result.Val.getInt();
14715       if (ConstantLengthValue.getSExtValue() != 1)
14716         return false;
14717 
14718       ArraySizes.push_back(ConstantLengthValue);
14719     }
14720     Base = TempOASE->getBase()->IgnoreParenImpCasts();
14721   }
14722 
14723   // If we have a single element, we don't need to add the implicit lengths.
14724   if (!SingleElement) {
14725     while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) {
14726       // Has implicit length 1!
14727       ArraySizes.push_back(llvm::APSInt::get(1));
14728       Base = TempASE->getBase()->IgnoreParenImpCasts();
14729     }
14730   }
14731 
14732   // This array section can be privatized as a single value or as a constant
14733   // sized array.
14734   return true;
14735 }
14736 
14737 static bool actOnOMPReductionKindClause(
14738     Sema &S, DSAStackTy *Stack, OpenMPClauseKind ClauseKind,
14739     ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
14740     SourceLocation ColonLoc, SourceLocation EndLoc,
14741     CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
14742     ArrayRef<Expr *> UnresolvedReductions, ReductionData &RD) {
14743   DeclarationName DN = ReductionId.getName();
14744   OverloadedOperatorKind OOK = DN.getCXXOverloadedOperator();
14745   BinaryOperatorKind BOK = BO_Comma;
14746 
14747   ASTContext &Context = S.Context;
14748   // OpenMP [2.14.3.6, reduction clause]
14749   // C
14750   // reduction-identifier is either an identifier or one of the following
14751   // operators: +, -, *,  &, |, ^, && and ||
14752   // C++
14753   // reduction-identifier is either an id-expression or one of the following
14754   // operators: +, -, *, &, |, ^, && and ||
14755   switch (OOK) {
14756   case OO_Plus:
14757   case OO_Minus:
14758     BOK = BO_Add;
14759     break;
14760   case OO_Star:
14761     BOK = BO_Mul;
14762     break;
14763   case OO_Amp:
14764     BOK = BO_And;
14765     break;
14766   case OO_Pipe:
14767     BOK = BO_Or;
14768     break;
14769   case OO_Caret:
14770     BOK = BO_Xor;
14771     break;
14772   case OO_AmpAmp:
14773     BOK = BO_LAnd;
14774     break;
14775   case OO_PipePipe:
14776     BOK = BO_LOr;
14777     break;
14778   case OO_New:
14779   case OO_Delete:
14780   case OO_Array_New:
14781   case OO_Array_Delete:
14782   case OO_Slash:
14783   case OO_Percent:
14784   case OO_Tilde:
14785   case OO_Exclaim:
14786   case OO_Equal:
14787   case OO_Less:
14788   case OO_Greater:
14789   case OO_LessEqual:
14790   case OO_GreaterEqual:
14791   case OO_PlusEqual:
14792   case OO_MinusEqual:
14793   case OO_StarEqual:
14794   case OO_SlashEqual:
14795   case OO_PercentEqual:
14796   case OO_CaretEqual:
14797   case OO_AmpEqual:
14798   case OO_PipeEqual:
14799   case OO_LessLess:
14800   case OO_GreaterGreater:
14801   case OO_LessLessEqual:
14802   case OO_GreaterGreaterEqual:
14803   case OO_EqualEqual:
14804   case OO_ExclaimEqual:
14805   case OO_Spaceship:
14806   case OO_PlusPlus:
14807   case OO_MinusMinus:
14808   case OO_Comma:
14809   case OO_ArrowStar:
14810   case OO_Arrow:
14811   case OO_Call:
14812   case OO_Subscript:
14813   case OO_Conditional:
14814   case OO_Coawait:
14815   case NUM_OVERLOADED_OPERATORS:
14816     llvm_unreachable("Unexpected reduction identifier");
14817   case OO_None:
14818     if (IdentifierInfo *II = DN.getAsIdentifierInfo()) {
14819       if (II->isStr("max"))
14820         BOK = BO_GT;
14821       else if (II->isStr("min"))
14822         BOK = BO_LT;
14823     }
14824     break;
14825   }
14826   SourceRange ReductionIdRange;
14827   if (ReductionIdScopeSpec.isValid())
14828     ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc());
14829   else
14830     ReductionIdRange.setBegin(ReductionId.getBeginLoc());
14831   ReductionIdRange.setEnd(ReductionId.getEndLoc());
14832 
14833   auto IR = UnresolvedReductions.begin(), ER = UnresolvedReductions.end();
14834   bool FirstIter = true;
14835   for (Expr *RefExpr : VarList) {
14836     assert(RefExpr && "nullptr expr in OpenMP reduction clause.");
14837     // OpenMP [2.1, C/C++]
14838     //  A list item is a variable or array section, subject to the restrictions
14839     //  specified in Section 2.4 on page 42 and in each of the sections
14840     // describing clauses and directives for which a list appears.
14841     // OpenMP  [2.14.3.3, Restrictions, p.1]
14842     //  A variable that is part of another variable (as an array or
14843     //  structure element) cannot appear in a private clause.
14844     if (!FirstIter && IR != ER)
14845       ++IR;
14846     FirstIter = false;
14847     SourceLocation ELoc;
14848     SourceRange ERange;
14849     Expr *SimpleRefExpr = RefExpr;
14850     auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange,
14851                               /*AllowArraySection=*/true);
14852     if (Res.second) {
14853       // Try to find 'declare reduction' corresponding construct before using
14854       // builtin/overloaded operators.
14855       QualType Type = Context.DependentTy;
14856       CXXCastPath BasePath;
14857       ExprResult DeclareReductionRef = buildDeclareReductionRef(
14858           S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
14859           ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
14860       Expr *ReductionOp = nullptr;
14861       if (S.CurContext->isDependentContext() &&
14862           (DeclareReductionRef.isUnset() ||
14863            isa<UnresolvedLookupExpr>(DeclareReductionRef.get())))
14864         ReductionOp = DeclareReductionRef.get();
14865       // It will be analyzed later.
14866       RD.push(RefExpr, ReductionOp);
14867     }
14868     ValueDecl *D = Res.first;
14869     if (!D)
14870       continue;
14871 
14872     Expr *TaskgroupDescriptor = nullptr;
14873     QualType Type;
14874     auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr->IgnoreParens());
14875     auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr->IgnoreParens());
14876     if (ASE) {
14877       Type = ASE->getType().getNonReferenceType();
14878     } else if (OASE) {
14879       QualType BaseType =
14880           OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
14881       if (const auto *ATy = BaseType->getAsArrayTypeUnsafe())
14882         Type = ATy->getElementType();
14883       else
14884         Type = BaseType->getPointeeType();
14885       Type = Type.getNonReferenceType();
14886     } else {
14887       Type = Context.getBaseElementType(D->getType().getNonReferenceType());
14888     }
14889     auto *VD = dyn_cast<VarDecl>(D);
14890 
14891     // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
14892     //  A variable that appears in a private clause must not have an incomplete
14893     //  type or a reference type.
14894     if (S.RequireCompleteType(ELoc, D->getType(),
14895                               diag::err_omp_reduction_incomplete_type))
14896       continue;
14897     // OpenMP [2.14.3.6, reduction clause, Restrictions]
14898     // A list item that appears in a reduction clause must not be
14899     // const-qualified.
14900     if (rejectConstNotMutableType(S, D, Type, ClauseKind, ELoc,
14901                                   /*AcceptIfMutable*/ false, ASE || OASE))
14902       continue;
14903 
14904     OpenMPDirectiveKind CurrDir = Stack->getCurrentDirective();
14905     // OpenMP [2.9.3.6, Restrictions, C/C++, p.4]
14906     //  If a list-item is a reference type then it must bind to the same object
14907     //  for all threads of the team.
14908     if (!ASE && !OASE) {
14909       if (VD) {
14910         VarDecl *VDDef = VD->getDefinition();
14911         if (VD->getType()->isReferenceType() && VDDef && VDDef->hasInit()) {
14912           DSARefChecker Check(Stack);
14913           if (Check.Visit(VDDef->getInit())) {
14914             S.Diag(ELoc, diag::err_omp_reduction_ref_type_arg)
14915                 << getOpenMPClauseName(ClauseKind) << ERange;
14916             S.Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef;
14917             continue;
14918           }
14919         }
14920       }
14921 
14922       // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
14923       // in a Construct]
14924       //  Variables with the predetermined data-sharing attributes may not be
14925       //  listed in data-sharing attributes clauses, except for the cases
14926       //  listed below. For these exceptions only, listing a predetermined
14927       //  variable in a data-sharing attribute clause is allowed and overrides
14928       //  the variable's predetermined data-sharing attributes.
14929       // OpenMP [2.14.3.6, Restrictions, p.3]
14930       //  Any number of reduction clauses can be specified on the directive,
14931       //  but a list item can appear only once in the reduction clauses for that
14932       //  directive.
14933       DSAStackTy::DSAVarData DVar = Stack->getTopDSA(D, /*FromParent=*/false);
14934       if (DVar.CKind == OMPC_reduction) {
14935         S.Diag(ELoc, diag::err_omp_once_referenced)
14936             << getOpenMPClauseName(ClauseKind);
14937         if (DVar.RefExpr)
14938           S.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced);
14939         continue;
14940       }
14941       if (DVar.CKind != OMPC_unknown) {
14942         S.Diag(ELoc, diag::err_omp_wrong_dsa)
14943             << getOpenMPClauseName(DVar.CKind)
14944             << getOpenMPClauseName(OMPC_reduction);
14945         reportOriginalDsa(S, Stack, D, DVar);
14946         continue;
14947       }
14948 
14949       // OpenMP [2.14.3.6, Restrictions, p.1]
14950       //  A list item that appears in a reduction clause of a worksharing
14951       //  construct must be shared in the parallel regions to which any of the
14952       //  worksharing regions arising from the worksharing construct bind.
14953       if (isOpenMPWorksharingDirective(CurrDir) &&
14954           !isOpenMPParallelDirective(CurrDir) &&
14955           !isOpenMPTeamsDirective(CurrDir)) {
14956         DVar = Stack->getImplicitDSA(D, true);
14957         if (DVar.CKind != OMPC_shared) {
14958           S.Diag(ELoc, diag::err_omp_required_access)
14959               << getOpenMPClauseName(OMPC_reduction)
14960               << getOpenMPClauseName(OMPC_shared);
14961           reportOriginalDsa(S, Stack, D, DVar);
14962           continue;
14963         }
14964       }
14965     }
14966 
14967     // Try to find 'declare reduction' corresponding construct before using
14968     // builtin/overloaded operators.
14969     CXXCastPath BasePath;
14970     ExprResult DeclareReductionRef = buildDeclareReductionRef(
14971         S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
14972         ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
14973     if (DeclareReductionRef.isInvalid())
14974       continue;
14975     if (S.CurContext->isDependentContext() &&
14976         (DeclareReductionRef.isUnset() ||
14977          isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) {
14978       RD.push(RefExpr, DeclareReductionRef.get());
14979       continue;
14980     }
14981     if (BOK == BO_Comma && DeclareReductionRef.isUnset()) {
14982       // Not allowed reduction identifier is found.
14983       S.Diag(ReductionId.getBeginLoc(),
14984              diag::err_omp_unknown_reduction_identifier)
14985           << Type << ReductionIdRange;
14986       continue;
14987     }
14988 
14989     // OpenMP [2.14.3.6, reduction clause, Restrictions]
14990     // The type of a list item that appears in a reduction clause must be valid
14991     // for the reduction-identifier. For a max or min reduction in C, the type
14992     // of the list item must be an allowed arithmetic data type: char, int,
14993     // float, double, or _Bool, possibly modified with long, short, signed, or
14994     // unsigned. For a max or min reduction in C++, the type of the list item
14995     // must be an allowed arithmetic data type: char, wchar_t, int, float,
14996     // double, or bool, possibly modified with long, short, signed, or unsigned.
14997     if (DeclareReductionRef.isUnset()) {
14998       if ((BOK == BO_GT || BOK == BO_LT) &&
14999           !(Type->isScalarType() ||
15000             (S.getLangOpts().CPlusPlus && Type->isArithmeticType()))) {
15001         S.Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg)
15002             << getOpenMPClauseName(ClauseKind) << S.getLangOpts().CPlusPlus;
15003         if (!ASE && !OASE) {
15004           bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
15005                                    VarDecl::DeclarationOnly;
15006           S.Diag(D->getLocation(),
15007                  IsDecl ? diag::note_previous_decl : diag::note_defined_here)
15008               << D;
15009         }
15010         continue;
15011       }
15012       if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) &&
15013           !S.getLangOpts().CPlusPlus && Type->isFloatingType()) {
15014         S.Diag(ELoc, diag::err_omp_clause_floating_type_arg)
15015             << getOpenMPClauseName(ClauseKind);
15016         if (!ASE && !OASE) {
15017           bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
15018                                    VarDecl::DeclarationOnly;
15019           S.Diag(D->getLocation(),
15020                  IsDecl ? diag::note_previous_decl : diag::note_defined_here)
15021               << D;
15022         }
15023         continue;
15024       }
15025     }
15026 
15027     Type = Type.getNonLValueExprType(Context).getUnqualifiedType();
15028     VarDecl *LHSVD = buildVarDecl(S, ELoc, Type, ".reduction.lhs",
15029                                   D->hasAttrs() ? &D->getAttrs() : nullptr);
15030     VarDecl *RHSVD = buildVarDecl(S, ELoc, Type, D->getName(),
15031                                   D->hasAttrs() ? &D->getAttrs() : nullptr);
15032     QualType PrivateTy = Type;
15033 
15034     // Try if we can determine constant lengths for all array sections and avoid
15035     // the VLA.
15036     bool ConstantLengthOASE = false;
15037     if (OASE) {
15038       bool SingleElement;
15039       llvm::SmallVector<llvm::APSInt, 4> ArraySizes;
15040       ConstantLengthOASE = checkOMPArraySectionConstantForReduction(
15041           Context, OASE, SingleElement, ArraySizes);
15042 
15043       // If we don't have a single element, we must emit a constant array type.
15044       if (ConstantLengthOASE && !SingleElement) {
15045         for (llvm::APSInt &Size : ArraySizes)
15046           PrivateTy = Context.getConstantArrayType(PrivateTy, Size, nullptr,
15047                                                    ArrayType::Normal,
15048                                                    /*IndexTypeQuals=*/0);
15049       }
15050     }
15051 
15052     if ((OASE && !ConstantLengthOASE) ||
15053         (!OASE && !ASE &&
15054          D->getType().getNonReferenceType()->isVariablyModifiedType())) {
15055       if (!Context.getTargetInfo().isVLASupported()) {
15056         if (isOpenMPTargetExecutionDirective(Stack->getCurrentDirective())) {
15057           S.Diag(ELoc, diag::err_omp_reduction_vla_unsupported) << !!OASE;
15058           S.Diag(ELoc, diag::note_vla_unsupported);
15059           continue;
15060         } else {
15061           S.targetDiag(ELoc, diag::err_omp_reduction_vla_unsupported) << !!OASE;
15062           S.targetDiag(ELoc, diag::note_vla_unsupported);
15063         }
15064       }
15065       // For arrays/array sections only:
15066       // Create pseudo array type for private copy. The size for this array will
15067       // be generated during codegen.
15068       // For array subscripts or single variables Private Ty is the same as Type
15069       // (type of the variable or single array element).
15070       PrivateTy = Context.getVariableArrayType(
15071           Type,
15072           new (Context) OpaqueValueExpr(ELoc, Context.getSizeType(), VK_RValue),
15073           ArrayType::Normal, /*IndexTypeQuals=*/0, SourceRange());
15074     } else if (!ASE && !OASE &&
15075                Context.getAsArrayType(D->getType().getNonReferenceType())) {
15076       PrivateTy = D->getType().getNonReferenceType();
15077     }
15078     // Private copy.
15079     VarDecl *PrivateVD =
15080         buildVarDecl(S, ELoc, PrivateTy, D->getName(),
15081                      D->hasAttrs() ? &D->getAttrs() : nullptr,
15082                      VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
15083     // Add initializer for private variable.
15084     Expr *Init = nullptr;
15085     DeclRefExpr *LHSDRE = buildDeclRefExpr(S, LHSVD, Type, ELoc);
15086     DeclRefExpr *RHSDRE = buildDeclRefExpr(S, RHSVD, Type, ELoc);
15087     if (DeclareReductionRef.isUsable()) {
15088       auto *DRDRef = DeclareReductionRef.getAs<DeclRefExpr>();
15089       auto *DRD = cast<OMPDeclareReductionDecl>(DRDRef->getDecl());
15090       if (DRD->getInitializer()) {
15091         Init = DRDRef;
15092         RHSVD->setInit(DRDRef);
15093         RHSVD->setInitStyle(VarDecl::CallInit);
15094       }
15095     } else {
15096       switch (BOK) {
15097       case BO_Add:
15098       case BO_Xor:
15099       case BO_Or:
15100       case BO_LOr:
15101         // '+', '-', '^', '|', '||' reduction ops - initializer is '0'.
15102         if (Type->isScalarType() || Type->isAnyComplexType())
15103           Init = S.ActOnIntegerConstant(ELoc, /*Val=*/0).get();
15104         break;
15105       case BO_Mul:
15106       case BO_LAnd:
15107         if (Type->isScalarType() || Type->isAnyComplexType()) {
15108           // '*' and '&&' reduction ops - initializer is '1'.
15109           Init = S.ActOnIntegerConstant(ELoc, /*Val=*/1).get();
15110         }
15111         break;
15112       case BO_And: {
15113         // '&' reduction op - initializer is '~0'.
15114         QualType OrigType = Type;
15115         if (auto *ComplexTy = OrigType->getAs<ComplexType>())
15116           Type = ComplexTy->getElementType();
15117         if (Type->isRealFloatingType()) {
15118           llvm::APFloat InitValue = llvm::APFloat::getAllOnesValue(
15119               Context.getFloatTypeSemantics(Type),
15120               Context.getTypeSize(Type));
15121           Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
15122                                          Type, ELoc);
15123         } else if (Type->isScalarType()) {
15124           uint64_t Size = Context.getTypeSize(Type);
15125           QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0);
15126           llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size);
15127           Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
15128         }
15129         if (Init && OrigType->isAnyComplexType()) {
15130           // Init = 0xFFFF + 0xFFFFi;
15131           auto *Im = new (Context) ImaginaryLiteral(Init, OrigType);
15132           Init = S.CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get();
15133         }
15134         Type = OrigType;
15135         break;
15136       }
15137       case BO_LT:
15138       case BO_GT: {
15139         // 'min' reduction op - initializer is 'Largest representable number in
15140         // the reduction list item type'.
15141         // 'max' reduction op - initializer is 'Least representable number in
15142         // the reduction list item type'.
15143         if (Type->isIntegerType() || Type->isPointerType()) {
15144           bool IsSigned = Type->hasSignedIntegerRepresentation();
15145           uint64_t Size = Context.getTypeSize(Type);
15146           QualType IntTy =
15147               Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned);
15148           llvm::APInt InitValue =
15149               (BOK != BO_LT) ? IsSigned ? llvm::APInt::getSignedMinValue(Size)
15150                                         : llvm::APInt::getMinValue(Size)
15151                              : IsSigned ? llvm::APInt::getSignedMaxValue(Size)
15152                                         : llvm::APInt::getMaxValue(Size);
15153           Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
15154           if (Type->isPointerType()) {
15155             // Cast to pointer type.
15156             ExprResult CastExpr = S.BuildCStyleCastExpr(
15157                 ELoc, Context.getTrivialTypeSourceInfo(Type, ELoc), ELoc, Init);
15158             if (CastExpr.isInvalid())
15159               continue;
15160             Init = CastExpr.get();
15161           }
15162         } else if (Type->isRealFloatingType()) {
15163           llvm::APFloat InitValue = llvm::APFloat::getLargest(
15164               Context.getFloatTypeSemantics(Type), BOK != BO_LT);
15165           Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
15166                                          Type, ELoc);
15167         }
15168         break;
15169       }
15170       case BO_PtrMemD:
15171       case BO_PtrMemI:
15172       case BO_MulAssign:
15173       case BO_Div:
15174       case BO_Rem:
15175       case BO_Sub:
15176       case BO_Shl:
15177       case BO_Shr:
15178       case BO_LE:
15179       case BO_GE:
15180       case BO_EQ:
15181       case BO_NE:
15182       case BO_Cmp:
15183       case BO_AndAssign:
15184       case BO_XorAssign:
15185       case BO_OrAssign:
15186       case BO_Assign:
15187       case BO_AddAssign:
15188       case BO_SubAssign:
15189       case BO_DivAssign:
15190       case BO_RemAssign:
15191       case BO_ShlAssign:
15192       case BO_ShrAssign:
15193       case BO_Comma:
15194         llvm_unreachable("Unexpected reduction operation");
15195       }
15196     }
15197     if (Init && DeclareReductionRef.isUnset())
15198       S.AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false);
15199     else if (!Init)
15200       S.ActOnUninitializedDecl(RHSVD);
15201     if (RHSVD->isInvalidDecl())
15202       continue;
15203     if (!RHSVD->hasInit() &&
15204         (DeclareReductionRef.isUnset() || !S.LangOpts.CPlusPlus)) {
15205       S.Diag(ELoc, diag::err_omp_reduction_id_not_compatible)
15206           << Type << ReductionIdRange;
15207       bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
15208                                VarDecl::DeclarationOnly;
15209       S.Diag(D->getLocation(),
15210              IsDecl ? diag::note_previous_decl : diag::note_defined_here)
15211           << D;
15212       continue;
15213     }
15214     // Store initializer for single element in private copy. Will be used during
15215     // codegen.
15216     PrivateVD->setInit(RHSVD->getInit());
15217     PrivateVD->setInitStyle(RHSVD->getInitStyle());
15218     DeclRefExpr *PrivateDRE = buildDeclRefExpr(S, PrivateVD, PrivateTy, ELoc);
15219     ExprResult ReductionOp;
15220     if (DeclareReductionRef.isUsable()) {
15221       QualType RedTy = DeclareReductionRef.get()->getType();
15222       QualType PtrRedTy = Context.getPointerType(RedTy);
15223       ExprResult LHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, LHSDRE);
15224       ExprResult RHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RHSDRE);
15225       if (!BasePath.empty()) {
15226         LHS = S.DefaultLvalueConversion(LHS.get());
15227         RHS = S.DefaultLvalueConversion(RHS.get());
15228         LHS = ImplicitCastExpr::Create(Context, PtrRedTy,
15229                                        CK_UncheckedDerivedToBase, LHS.get(),
15230                                        &BasePath, LHS.get()->getValueKind());
15231         RHS = ImplicitCastExpr::Create(Context, PtrRedTy,
15232                                        CK_UncheckedDerivedToBase, RHS.get(),
15233                                        &BasePath, RHS.get()->getValueKind());
15234       }
15235       FunctionProtoType::ExtProtoInfo EPI;
15236       QualType Params[] = {PtrRedTy, PtrRedTy};
15237       QualType FnTy = Context.getFunctionType(Context.VoidTy, Params, EPI);
15238       auto *OVE = new (Context) OpaqueValueExpr(
15239           ELoc, Context.getPointerType(FnTy), VK_RValue, OK_Ordinary,
15240           S.DefaultLvalueConversion(DeclareReductionRef.get()).get());
15241       Expr *Args[] = {LHS.get(), RHS.get()};
15242       ReductionOp =
15243           CallExpr::Create(Context, OVE, Args, Context.VoidTy, VK_RValue, ELoc);
15244     } else {
15245       ReductionOp = S.BuildBinOp(
15246           Stack->getCurScope(), ReductionId.getBeginLoc(), BOK, LHSDRE, RHSDRE);
15247       if (ReductionOp.isUsable()) {
15248         if (BOK != BO_LT && BOK != BO_GT) {
15249           ReductionOp =
15250               S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(),
15251                            BO_Assign, LHSDRE, ReductionOp.get());
15252         } else {
15253           auto *ConditionalOp = new (Context)
15254               ConditionalOperator(ReductionOp.get(), ELoc, LHSDRE, ELoc, RHSDRE,
15255                                   Type, VK_LValue, OK_Ordinary);
15256           ReductionOp =
15257               S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(),
15258                            BO_Assign, LHSDRE, ConditionalOp);
15259         }
15260         if (ReductionOp.isUsable())
15261           ReductionOp = S.ActOnFinishFullExpr(ReductionOp.get(),
15262                                               /*DiscardedValue*/ false);
15263       }
15264       if (!ReductionOp.isUsable())
15265         continue;
15266     }
15267 
15268     // Add copy operations for inscan reductions.
15269     // LHS = RHS;
15270     ExprResult CopyOpRes, TempArrayRes, TempArrayElem;
15271     if (ClauseKind == OMPC_reduction &&
15272         RD.RedModifier == OMPC_REDUCTION_inscan) {
15273       ExprResult RHS = S.DefaultLvalueConversion(RHSDRE);
15274       CopyOpRes = S.BuildBinOp(Stack->getCurScope(), ELoc, BO_Assign, LHSDRE,
15275                                RHS.get());
15276       if (!CopyOpRes.isUsable())
15277         continue;
15278       CopyOpRes =
15279           S.ActOnFinishFullExpr(CopyOpRes.get(), /*DiscardedValue=*/true);
15280       if (!CopyOpRes.isUsable())
15281         continue;
15282       // For simd directive and simd-based directives in simd mode no need to
15283       // construct temp array, need just a single temp element.
15284       if (Stack->getCurrentDirective() == OMPD_simd ||
15285           (S.getLangOpts().OpenMPSimd &&
15286            isOpenMPSimdDirective(Stack->getCurrentDirective()))) {
15287         VarDecl *TempArrayVD =
15288             buildVarDecl(S, ELoc, PrivateTy, D->getName(),
15289                          D->hasAttrs() ? &D->getAttrs() : nullptr);
15290         // Add a constructor to the temp decl.
15291         S.ActOnUninitializedDecl(TempArrayVD);
15292         TempArrayRes = buildDeclRefExpr(S, TempArrayVD, PrivateTy, ELoc);
15293       } else {
15294         // Build temp array for prefix sum.
15295         auto *Dim = new (S.Context)
15296             OpaqueValueExpr(ELoc, S.Context.getSizeType(), VK_RValue);
15297         QualType ArrayTy =
15298             S.Context.getVariableArrayType(PrivateTy, Dim, ArrayType::Normal,
15299                                            /*IndexTypeQuals=*/0, {ELoc, ELoc});
15300         VarDecl *TempArrayVD =
15301             buildVarDecl(S, ELoc, ArrayTy, D->getName(),
15302                          D->hasAttrs() ? &D->getAttrs() : nullptr);
15303         // Add a constructor to the temp decl.
15304         S.ActOnUninitializedDecl(TempArrayVD);
15305         TempArrayRes = buildDeclRefExpr(S, TempArrayVD, ArrayTy, ELoc);
15306         TempArrayElem =
15307             S.DefaultFunctionArrayLvalueConversion(TempArrayRes.get());
15308         auto *Idx = new (S.Context)
15309             OpaqueValueExpr(ELoc, S.Context.getSizeType(), VK_RValue);
15310         TempArrayElem = S.CreateBuiltinArraySubscriptExpr(TempArrayElem.get(),
15311                                                           ELoc, Idx, ELoc);
15312       }
15313     }
15314 
15315     // OpenMP [2.15.4.6, Restrictions, p.2]
15316     // A list item that appears in an in_reduction clause of a task construct
15317     // must appear in a task_reduction clause of a construct associated with a
15318     // taskgroup region that includes the participating task in its taskgroup
15319     // set. The construct associated with the innermost region that meets this
15320     // condition must specify the same reduction-identifier as the in_reduction
15321     // clause.
15322     if (ClauseKind == OMPC_in_reduction) {
15323       SourceRange ParentSR;
15324       BinaryOperatorKind ParentBOK;
15325       const Expr *ParentReductionOp = nullptr;
15326       Expr *ParentBOKTD = nullptr, *ParentReductionOpTD = nullptr;
15327       DSAStackTy::DSAVarData ParentBOKDSA =
15328           Stack->getTopMostTaskgroupReductionData(D, ParentSR, ParentBOK,
15329                                                   ParentBOKTD);
15330       DSAStackTy::DSAVarData ParentReductionOpDSA =
15331           Stack->getTopMostTaskgroupReductionData(
15332               D, ParentSR, ParentReductionOp, ParentReductionOpTD);
15333       bool IsParentBOK = ParentBOKDSA.DKind != OMPD_unknown;
15334       bool IsParentReductionOp = ParentReductionOpDSA.DKind != OMPD_unknown;
15335       if ((DeclareReductionRef.isUnset() && IsParentReductionOp) ||
15336           (DeclareReductionRef.isUsable() && IsParentBOK) ||
15337           (IsParentBOK && BOK != ParentBOK) || IsParentReductionOp) {
15338         bool EmitError = true;
15339         if (IsParentReductionOp && DeclareReductionRef.isUsable()) {
15340           llvm::FoldingSetNodeID RedId, ParentRedId;
15341           ParentReductionOp->Profile(ParentRedId, Context, /*Canonical=*/true);
15342           DeclareReductionRef.get()->Profile(RedId, Context,
15343                                              /*Canonical=*/true);
15344           EmitError = RedId != ParentRedId;
15345         }
15346         if (EmitError) {
15347           S.Diag(ReductionId.getBeginLoc(),
15348                  diag::err_omp_reduction_identifier_mismatch)
15349               << ReductionIdRange << RefExpr->getSourceRange();
15350           S.Diag(ParentSR.getBegin(),
15351                  diag::note_omp_previous_reduction_identifier)
15352               << ParentSR
15353               << (IsParentBOK ? ParentBOKDSA.RefExpr
15354                               : ParentReductionOpDSA.RefExpr)
15355                      ->getSourceRange();
15356           continue;
15357         }
15358       }
15359       TaskgroupDescriptor = IsParentBOK ? ParentBOKTD : ParentReductionOpTD;
15360     }
15361 
15362     DeclRefExpr *Ref = nullptr;
15363     Expr *VarsExpr = RefExpr->IgnoreParens();
15364     if (!VD && !S.CurContext->isDependentContext()) {
15365       if (ASE || OASE) {
15366         TransformExprToCaptures RebuildToCapture(S, D);
15367         VarsExpr =
15368             RebuildToCapture.TransformExpr(RefExpr->IgnoreParens()).get();
15369         Ref = RebuildToCapture.getCapturedExpr();
15370       } else {
15371         VarsExpr = Ref = buildCapture(S, D, SimpleRefExpr, /*WithInit=*/false);
15372       }
15373       if (!S.isOpenMPCapturedDecl(D)) {
15374         RD.ExprCaptures.emplace_back(Ref->getDecl());
15375         if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
15376           ExprResult RefRes = S.DefaultLvalueConversion(Ref);
15377           if (!RefRes.isUsable())
15378             continue;
15379           ExprResult PostUpdateRes =
15380               S.BuildBinOp(Stack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
15381                            RefRes.get());
15382           if (!PostUpdateRes.isUsable())
15383             continue;
15384           if (isOpenMPTaskingDirective(Stack->getCurrentDirective()) ||
15385               Stack->getCurrentDirective() == OMPD_taskgroup) {
15386             S.Diag(RefExpr->getExprLoc(),
15387                    diag::err_omp_reduction_non_addressable_expression)
15388                 << RefExpr->getSourceRange();
15389             continue;
15390           }
15391           RD.ExprPostUpdates.emplace_back(
15392               S.IgnoredValueConversions(PostUpdateRes.get()).get());
15393         }
15394       }
15395     }
15396     // All reduction items are still marked as reduction (to do not increase
15397     // code base size).
15398     unsigned Modifier = RD.RedModifier;
15399     // Consider task_reductions as reductions with task modifier. Required for
15400     // correct analysis of in_reduction clauses.
15401     if (CurrDir == OMPD_taskgroup && ClauseKind == OMPC_task_reduction)
15402       Modifier = OMPC_REDUCTION_task;
15403     Stack->addDSA(D, RefExpr->IgnoreParens(), OMPC_reduction, Ref, Modifier);
15404     if (Modifier == OMPC_REDUCTION_task &&
15405         (CurrDir == OMPD_taskgroup ||
15406          ((isOpenMPParallelDirective(CurrDir) ||
15407            isOpenMPWorksharingDirective(CurrDir)) &&
15408           !isOpenMPSimdDirective(CurrDir)))) {
15409       if (DeclareReductionRef.isUsable())
15410         Stack->addTaskgroupReductionData(D, ReductionIdRange,
15411                                          DeclareReductionRef.get());
15412       else
15413         Stack->addTaskgroupReductionData(D, ReductionIdRange, BOK);
15414     }
15415     RD.push(VarsExpr, PrivateDRE, LHSDRE, RHSDRE, ReductionOp.get(),
15416             TaskgroupDescriptor, CopyOpRes.get(), TempArrayRes.get(),
15417             TempArrayElem.get());
15418   }
15419   return RD.Vars.empty();
15420 }
15421 
15422 OMPClause *Sema::ActOnOpenMPReductionClause(
15423     ArrayRef<Expr *> VarList, OpenMPReductionClauseModifier Modifier,
15424     SourceLocation StartLoc, SourceLocation LParenLoc,
15425     SourceLocation ModifierLoc, SourceLocation ColonLoc, SourceLocation EndLoc,
15426     CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
15427     ArrayRef<Expr *> UnresolvedReductions) {
15428   if (ModifierLoc.isValid() && Modifier == OMPC_REDUCTION_unknown) {
15429     Diag(LParenLoc, diag::err_omp_unexpected_clause_value)
15430         << getListOfPossibleValues(OMPC_reduction, /*First=*/0,
15431                                    /*Last=*/OMPC_REDUCTION_unknown)
15432         << getOpenMPClauseName(OMPC_reduction);
15433     return nullptr;
15434   }
15435   // OpenMP 5.0, 2.19.5.4 reduction Clause, Restrictions
15436   // A reduction clause with the inscan reduction-modifier may only appear on a
15437   // worksharing-loop construct, a worksharing-loop SIMD construct, a simd
15438   // construct, a parallel worksharing-loop construct or a parallel
15439   // worksharing-loop SIMD construct.
15440   if (Modifier == OMPC_REDUCTION_inscan &&
15441       (DSAStack->getCurrentDirective() != OMPD_for &&
15442        DSAStack->getCurrentDirective() != OMPD_for_simd &&
15443        DSAStack->getCurrentDirective() != OMPD_simd &&
15444        DSAStack->getCurrentDirective() != OMPD_parallel_for &&
15445        DSAStack->getCurrentDirective() != OMPD_parallel_for_simd)) {
15446     Diag(ModifierLoc, diag::err_omp_wrong_inscan_reduction);
15447     return nullptr;
15448   }
15449 
15450   ReductionData RD(VarList.size(), Modifier);
15451   if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_reduction, VarList,
15452                                   StartLoc, LParenLoc, ColonLoc, EndLoc,
15453                                   ReductionIdScopeSpec, ReductionId,
15454                                   UnresolvedReductions, RD))
15455     return nullptr;
15456 
15457   return OMPReductionClause::Create(
15458       Context, StartLoc, LParenLoc, ModifierLoc, ColonLoc, EndLoc, Modifier,
15459       RD.Vars, ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
15460       RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, RD.InscanCopyOps,
15461       RD.InscanCopyArrayTemps, RD.InscanCopyArrayElems,
15462       buildPreInits(Context, RD.ExprCaptures),
15463       buildPostUpdate(*this, RD.ExprPostUpdates));
15464 }
15465 
15466 OMPClause *Sema::ActOnOpenMPTaskReductionClause(
15467     ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
15468     SourceLocation ColonLoc, SourceLocation EndLoc,
15469     CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
15470     ArrayRef<Expr *> UnresolvedReductions) {
15471   ReductionData RD(VarList.size());
15472   if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_task_reduction, VarList,
15473                                   StartLoc, LParenLoc, ColonLoc, EndLoc,
15474                                   ReductionIdScopeSpec, ReductionId,
15475                                   UnresolvedReductions, RD))
15476     return nullptr;
15477 
15478   return OMPTaskReductionClause::Create(
15479       Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
15480       ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
15481       RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
15482       buildPreInits(Context, RD.ExprCaptures),
15483       buildPostUpdate(*this, RD.ExprPostUpdates));
15484 }
15485 
15486 OMPClause *Sema::ActOnOpenMPInReductionClause(
15487     ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
15488     SourceLocation ColonLoc, SourceLocation EndLoc,
15489     CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
15490     ArrayRef<Expr *> UnresolvedReductions) {
15491   ReductionData RD(VarList.size());
15492   if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_in_reduction, VarList,
15493                                   StartLoc, LParenLoc, ColonLoc, EndLoc,
15494                                   ReductionIdScopeSpec, ReductionId,
15495                                   UnresolvedReductions, RD))
15496     return nullptr;
15497 
15498   return OMPInReductionClause::Create(
15499       Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
15500       ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
15501       RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, RD.TaskgroupDescriptors,
15502       buildPreInits(Context, RD.ExprCaptures),
15503       buildPostUpdate(*this, RD.ExprPostUpdates));
15504 }
15505 
15506 bool Sema::CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
15507                                      SourceLocation LinLoc) {
15508   if ((!LangOpts.CPlusPlus && LinKind != OMPC_LINEAR_val) ||
15509       LinKind == OMPC_LINEAR_unknown) {
15510     Diag(LinLoc, diag::err_omp_wrong_linear_modifier) << LangOpts.CPlusPlus;
15511     return true;
15512   }
15513   return false;
15514 }
15515 
15516 bool Sema::CheckOpenMPLinearDecl(const ValueDecl *D, SourceLocation ELoc,
15517                                  OpenMPLinearClauseKind LinKind, QualType Type,
15518                                  bool IsDeclareSimd) {
15519   const auto *VD = dyn_cast_or_null<VarDecl>(D);
15520   // A variable must not have an incomplete type or a reference type.
15521   if (RequireCompleteType(ELoc, Type, diag::err_omp_linear_incomplete_type))
15522     return true;
15523   if ((LinKind == OMPC_LINEAR_uval || LinKind == OMPC_LINEAR_ref) &&
15524       !Type->isReferenceType()) {
15525     Diag(ELoc, diag::err_omp_wrong_linear_modifier_non_reference)
15526         << Type << getOpenMPSimpleClauseTypeName(OMPC_linear, LinKind);
15527     return true;
15528   }
15529   Type = Type.getNonReferenceType();
15530 
15531   // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
15532   // A variable that is privatized must not have a const-qualified type
15533   // unless it is of class type with a mutable member. This restriction does
15534   // not apply to the firstprivate clause, nor to the linear clause on
15535   // declarative directives (like declare simd).
15536   if (!IsDeclareSimd &&
15537       rejectConstNotMutableType(*this, D, Type, OMPC_linear, ELoc))
15538     return true;
15539 
15540   // A list item must be of integral or pointer type.
15541   Type = Type.getUnqualifiedType().getCanonicalType();
15542   const auto *Ty = Type.getTypePtrOrNull();
15543   if (!Ty || (LinKind != OMPC_LINEAR_ref && !Ty->isDependentType() &&
15544               !Ty->isIntegralType(Context) && !Ty->isPointerType())) {
15545     Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << Type;
15546     if (D) {
15547       bool IsDecl =
15548           !VD ||
15549           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
15550       Diag(D->getLocation(),
15551            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
15552           << D;
15553     }
15554     return true;
15555   }
15556   return false;
15557 }
15558 
15559 OMPClause *Sema::ActOnOpenMPLinearClause(
15560     ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc,
15561     SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind,
15562     SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
15563   SmallVector<Expr *, 8> Vars;
15564   SmallVector<Expr *, 8> Privates;
15565   SmallVector<Expr *, 8> Inits;
15566   SmallVector<Decl *, 4> ExprCaptures;
15567   SmallVector<Expr *, 4> ExprPostUpdates;
15568   if (CheckOpenMPLinearModifier(LinKind, LinLoc))
15569     LinKind = OMPC_LINEAR_val;
15570   for (Expr *RefExpr : VarList) {
15571     assert(RefExpr && "NULL expr in OpenMP linear clause.");
15572     SourceLocation ELoc;
15573     SourceRange ERange;
15574     Expr *SimpleRefExpr = RefExpr;
15575     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
15576     if (Res.second) {
15577       // It will be analyzed later.
15578       Vars.push_back(RefExpr);
15579       Privates.push_back(nullptr);
15580       Inits.push_back(nullptr);
15581     }
15582     ValueDecl *D = Res.first;
15583     if (!D)
15584       continue;
15585 
15586     QualType Type = D->getType();
15587     auto *VD = dyn_cast<VarDecl>(D);
15588 
15589     // OpenMP [2.14.3.7, linear clause]
15590     //  A list-item cannot appear in more than one linear clause.
15591     //  A list-item that appears in a linear clause cannot appear in any
15592     //  other data-sharing attribute clause.
15593     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
15594     if (DVar.RefExpr) {
15595       Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
15596                                           << getOpenMPClauseName(OMPC_linear);
15597       reportOriginalDsa(*this, DSAStack, D, DVar);
15598       continue;
15599     }
15600 
15601     if (CheckOpenMPLinearDecl(D, ELoc, LinKind, Type))
15602       continue;
15603     Type = Type.getNonReferenceType().getUnqualifiedType().getCanonicalType();
15604 
15605     // Build private copy of original var.
15606     VarDecl *Private =
15607         buildVarDecl(*this, ELoc, Type, D->getName(),
15608                      D->hasAttrs() ? &D->getAttrs() : nullptr,
15609                      VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
15610     DeclRefExpr *PrivateRef = buildDeclRefExpr(*this, Private, Type, ELoc);
15611     // Build var to save initial value.
15612     VarDecl *Init = buildVarDecl(*this, ELoc, Type, ".linear.start");
15613     Expr *InitExpr;
15614     DeclRefExpr *Ref = nullptr;
15615     if (!VD && !CurContext->isDependentContext()) {
15616       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
15617       if (!isOpenMPCapturedDecl(D)) {
15618         ExprCaptures.push_back(Ref->getDecl());
15619         if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
15620           ExprResult RefRes = DefaultLvalueConversion(Ref);
15621           if (!RefRes.isUsable())
15622             continue;
15623           ExprResult PostUpdateRes =
15624               BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
15625                          SimpleRefExpr, RefRes.get());
15626           if (!PostUpdateRes.isUsable())
15627             continue;
15628           ExprPostUpdates.push_back(
15629               IgnoredValueConversions(PostUpdateRes.get()).get());
15630         }
15631       }
15632     }
15633     if (LinKind == OMPC_LINEAR_uval)
15634       InitExpr = VD ? VD->getInit() : SimpleRefExpr;
15635     else
15636       InitExpr = VD ? SimpleRefExpr : Ref;
15637     AddInitializerToDecl(Init, DefaultLvalueConversion(InitExpr).get(),
15638                          /*DirectInit=*/false);
15639     DeclRefExpr *InitRef = buildDeclRefExpr(*this, Init, Type, ELoc);
15640 
15641     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_linear, Ref);
15642     Vars.push_back((VD || CurContext->isDependentContext())
15643                        ? RefExpr->IgnoreParens()
15644                        : Ref);
15645     Privates.push_back(PrivateRef);
15646     Inits.push_back(InitRef);
15647   }
15648 
15649   if (Vars.empty())
15650     return nullptr;
15651 
15652   Expr *StepExpr = Step;
15653   Expr *CalcStepExpr = nullptr;
15654   if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
15655       !Step->isInstantiationDependent() &&
15656       !Step->containsUnexpandedParameterPack()) {
15657     SourceLocation StepLoc = Step->getBeginLoc();
15658     ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step);
15659     if (Val.isInvalid())
15660       return nullptr;
15661     StepExpr = Val.get();
15662 
15663     // Build var to save the step value.
15664     VarDecl *SaveVar =
15665         buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step");
15666     ExprResult SaveRef =
15667         buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc);
15668     ExprResult CalcStep =
15669         BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr);
15670     CalcStep = ActOnFinishFullExpr(CalcStep.get(), /*DiscardedValue*/ false);
15671 
15672     // Warn about zero linear step (it would be probably better specified as
15673     // making corresponding variables 'const').
15674     llvm::APSInt Result;
15675     bool IsConstant = StepExpr->isIntegerConstantExpr(Result, Context);
15676     if (IsConstant && !Result.isNegative() && !Result.isStrictlyPositive())
15677       Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0]
15678                                                      << (Vars.size() > 1);
15679     if (!IsConstant && CalcStep.isUsable()) {
15680       // Calculate the step beforehand instead of doing this on each iteration.
15681       // (This is not used if the number of iterations may be kfold-ed).
15682       CalcStepExpr = CalcStep.get();
15683     }
15684   }
15685 
15686   return OMPLinearClause::Create(Context, StartLoc, LParenLoc, LinKind, LinLoc,
15687                                  ColonLoc, EndLoc, Vars, Privates, Inits,
15688                                  StepExpr, CalcStepExpr,
15689                                  buildPreInits(Context, ExprCaptures),
15690                                  buildPostUpdate(*this, ExprPostUpdates));
15691 }
15692 
15693 static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
15694                                      Expr *NumIterations, Sema &SemaRef,
15695                                      Scope *S, DSAStackTy *Stack) {
15696   // Walk the vars and build update/final expressions for the CodeGen.
15697   SmallVector<Expr *, 8> Updates;
15698   SmallVector<Expr *, 8> Finals;
15699   SmallVector<Expr *, 8> UsedExprs;
15700   Expr *Step = Clause.getStep();
15701   Expr *CalcStep = Clause.getCalcStep();
15702   // OpenMP [2.14.3.7, linear clause]
15703   // If linear-step is not specified it is assumed to be 1.
15704   if (!Step)
15705     Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
15706   else if (CalcStep)
15707     Step = cast<BinaryOperator>(CalcStep)->getLHS();
15708   bool HasErrors = false;
15709   auto CurInit = Clause.inits().begin();
15710   auto CurPrivate = Clause.privates().begin();
15711   OpenMPLinearClauseKind LinKind = Clause.getModifier();
15712   for (Expr *RefExpr : Clause.varlists()) {
15713     SourceLocation ELoc;
15714     SourceRange ERange;
15715     Expr *SimpleRefExpr = RefExpr;
15716     auto Res = getPrivateItem(SemaRef, SimpleRefExpr, ELoc, ERange);
15717     ValueDecl *D = Res.first;
15718     if (Res.second || !D) {
15719       Updates.push_back(nullptr);
15720       Finals.push_back(nullptr);
15721       HasErrors = true;
15722       continue;
15723     }
15724     auto &&Info = Stack->isLoopControlVariable(D);
15725     // OpenMP [2.15.11, distribute simd Construct]
15726     // A list item may not appear in a linear clause, unless it is the loop
15727     // iteration variable.
15728     if (isOpenMPDistributeDirective(Stack->getCurrentDirective()) &&
15729         isOpenMPSimdDirective(Stack->getCurrentDirective()) && !Info.first) {
15730       SemaRef.Diag(ELoc,
15731                    diag::err_omp_linear_distribute_var_non_loop_iteration);
15732       Updates.push_back(nullptr);
15733       Finals.push_back(nullptr);
15734       HasErrors = true;
15735       continue;
15736     }
15737     Expr *InitExpr = *CurInit;
15738 
15739     // Build privatized reference to the current linear var.
15740     auto *DE = cast<DeclRefExpr>(SimpleRefExpr);
15741     Expr *CapturedRef;
15742     if (LinKind == OMPC_LINEAR_uval)
15743       CapturedRef = cast<VarDecl>(DE->getDecl())->getInit();
15744     else
15745       CapturedRef =
15746           buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()),
15747                            DE->getType().getUnqualifiedType(), DE->getExprLoc(),
15748                            /*RefersToCapture=*/true);
15749 
15750     // Build update: Var = InitExpr + IV * Step
15751     ExprResult Update;
15752     if (!Info.first)
15753       Update = buildCounterUpdate(
15754           SemaRef, S, RefExpr->getExprLoc(), *CurPrivate, InitExpr, IV, Step,
15755           /*Subtract=*/false, /*IsNonRectangularLB=*/false);
15756     else
15757       Update = *CurPrivate;
15758     Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getBeginLoc(),
15759                                          /*DiscardedValue*/ false);
15760 
15761     // Build final: Var = InitExpr + NumIterations * Step
15762     ExprResult Final;
15763     if (!Info.first)
15764       Final =
15765           buildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), CapturedRef,
15766                              InitExpr, NumIterations, Step, /*Subtract=*/false,
15767                              /*IsNonRectangularLB=*/false);
15768     else
15769       Final = *CurPrivate;
15770     Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getBeginLoc(),
15771                                         /*DiscardedValue*/ false);
15772 
15773     if (!Update.isUsable() || !Final.isUsable()) {
15774       Updates.push_back(nullptr);
15775       Finals.push_back(nullptr);
15776       UsedExprs.push_back(nullptr);
15777       HasErrors = true;
15778     } else {
15779       Updates.push_back(Update.get());
15780       Finals.push_back(Final.get());
15781       if (!Info.first)
15782         UsedExprs.push_back(SimpleRefExpr);
15783     }
15784     ++CurInit;
15785     ++CurPrivate;
15786   }
15787   if (Expr *S = Clause.getStep())
15788     UsedExprs.push_back(S);
15789   // Fill the remaining part with the nullptr.
15790   UsedExprs.append(Clause.varlist_size() + 1 - UsedExprs.size(), nullptr);
15791   Clause.setUpdates(Updates);
15792   Clause.setFinals(Finals);
15793   Clause.setUsedExprs(UsedExprs);
15794   return HasErrors;
15795 }
15796 
15797 OMPClause *Sema::ActOnOpenMPAlignedClause(
15798     ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc,
15799     SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
15800   SmallVector<Expr *, 8> Vars;
15801   for (Expr *RefExpr : VarList) {
15802     assert(RefExpr && "NULL expr in OpenMP linear clause.");
15803     SourceLocation ELoc;
15804     SourceRange ERange;
15805     Expr *SimpleRefExpr = RefExpr;
15806     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
15807     if (Res.second) {
15808       // It will be analyzed later.
15809       Vars.push_back(RefExpr);
15810     }
15811     ValueDecl *D = Res.first;
15812     if (!D)
15813       continue;
15814 
15815     QualType QType = D->getType();
15816     auto *VD = dyn_cast<VarDecl>(D);
15817 
15818     // OpenMP  [2.8.1, simd construct, Restrictions]
15819     // The type of list items appearing in the aligned clause must be
15820     // array, pointer, reference to array, or reference to pointer.
15821     QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType();
15822     const Type *Ty = QType.getTypePtrOrNull();
15823     if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
15824       Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr)
15825           << QType << getLangOpts().CPlusPlus << ERange;
15826       bool IsDecl =
15827           !VD ||
15828           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
15829       Diag(D->getLocation(),
15830            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
15831           << D;
15832       continue;
15833     }
15834 
15835     // OpenMP  [2.8.1, simd construct, Restrictions]
15836     // A list-item cannot appear in more than one aligned clause.
15837     if (const Expr *PrevRef = DSAStack->addUniqueAligned(D, SimpleRefExpr)) {
15838       Diag(ELoc, diag::err_omp_used_in_clause_twice)
15839           << 0 << getOpenMPClauseName(OMPC_aligned) << ERange;
15840       Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
15841           << getOpenMPClauseName(OMPC_aligned);
15842       continue;
15843     }
15844 
15845     DeclRefExpr *Ref = nullptr;
15846     if (!VD && isOpenMPCapturedDecl(D))
15847       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
15848     Vars.push_back(DefaultFunctionArrayConversion(
15849                        (VD || !Ref) ? RefExpr->IgnoreParens() : Ref)
15850                        .get());
15851   }
15852 
15853   // OpenMP [2.8.1, simd construct, Description]
15854   // The parameter of the aligned clause, alignment, must be a constant
15855   // positive integer expression.
15856   // If no optional parameter is specified, implementation-defined default
15857   // alignments for SIMD instructions on the target platforms are assumed.
15858   if (Alignment != nullptr) {
15859     ExprResult AlignResult =
15860         VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned);
15861     if (AlignResult.isInvalid())
15862       return nullptr;
15863     Alignment = AlignResult.get();
15864   }
15865   if (Vars.empty())
15866     return nullptr;
15867 
15868   return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
15869                                   EndLoc, Vars, Alignment);
15870 }
15871 
15872 OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
15873                                          SourceLocation StartLoc,
15874                                          SourceLocation LParenLoc,
15875                                          SourceLocation EndLoc) {
15876   SmallVector<Expr *, 8> Vars;
15877   SmallVector<Expr *, 8> SrcExprs;
15878   SmallVector<Expr *, 8> DstExprs;
15879   SmallVector<Expr *, 8> AssignmentOps;
15880   for (Expr *RefExpr : VarList) {
15881     assert(RefExpr && "NULL expr in OpenMP copyin clause.");
15882     if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
15883       // It will be analyzed later.
15884       Vars.push_back(RefExpr);
15885       SrcExprs.push_back(nullptr);
15886       DstExprs.push_back(nullptr);
15887       AssignmentOps.push_back(nullptr);
15888       continue;
15889     }
15890 
15891     SourceLocation ELoc = RefExpr->getExprLoc();
15892     // OpenMP [2.1, C/C++]
15893     //  A list item is a variable name.
15894     // OpenMP  [2.14.4.1, Restrictions, p.1]
15895     //  A list item that appears in a copyin clause must be threadprivate.
15896     auto *DE = dyn_cast<DeclRefExpr>(RefExpr);
15897     if (!DE || !isa<VarDecl>(DE->getDecl())) {
15898       Diag(ELoc, diag::err_omp_expected_var_name_member_expr)
15899           << 0 << RefExpr->getSourceRange();
15900       continue;
15901     }
15902 
15903     Decl *D = DE->getDecl();
15904     auto *VD = cast<VarDecl>(D);
15905 
15906     QualType Type = VD->getType();
15907     if (Type->isDependentType() || Type->isInstantiationDependentType()) {
15908       // It will be analyzed later.
15909       Vars.push_back(DE);
15910       SrcExprs.push_back(nullptr);
15911       DstExprs.push_back(nullptr);
15912       AssignmentOps.push_back(nullptr);
15913       continue;
15914     }
15915 
15916     // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
15917     //  A list item that appears in a copyin clause must be threadprivate.
15918     if (!DSAStack->isThreadPrivate(VD)) {
15919       Diag(ELoc, diag::err_omp_required_access)
15920           << getOpenMPClauseName(OMPC_copyin)
15921           << getOpenMPDirectiveName(OMPD_threadprivate);
15922       continue;
15923     }
15924 
15925     // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
15926     //  A variable of class type (or array thereof) that appears in a
15927     //  copyin clause requires an accessible, unambiguous copy assignment
15928     //  operator for the class type.
15929     QualType ElemType = Context.getBaseElementType(Type).getNonReferenceType();
15930     VarDecl *SrcVD =
15931         buildVarDecl(*this, DE->getBeginLoc(), ElemType.getUnqualifiedType(),
15932                      ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr);
15933     DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr(
15934         *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc());
15935     VarDecl *DstVD =
15936         buildVarDecl(*this, DE->getBeginLoc(), ElemType, ".copyin.dst",
15937                      VD->hasAttrs() ? &VD->getAttrs() : nullptr);
15938     DeclRefExpr *PseudoDstExpr =
15939         buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc());
15940     // For arrays generate assignment operation for single element and replace
15941     // it by the original array element in CodeGen.
15942     ExprResult AssignmentOp =
15943         BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign, PseudoDstExpr,
15944                    PseudoSrcExpr);
15945     if (AssignmentOp.isInvalid())
15946       continue;
15947     AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
15948                                        /*DiscardedValue*/ false);
15949     if (AssignmentOp.isInvalid())
15950       continue;
15951 
15952     DSAStack->addDSA(VD, DE, OMPC_copyin);
15953     Vars.push_back(DE);
15954     SrcExprs.push_back(PseudoSrcExpr);
15955     DstExprs.push_back(PseudoDstExpr);
15956     AssignmentOps.push_back(AssignmentOp.get());
15957   }
15958 
15959   if (Vars.empty())
15960     return nullptr;
15961 
15962   return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
15963                                  SrcExprs, DstExprs, AssignmentOps);
15964 }
15965 
15966 OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
15967                                               SourceLocation StartLoc,
15968                                               SourceLocation LParenLoc,
15969                                               SourceLocation EndLoc) {
15970   SmallVector<Expr *, 8> Vars;
15971   SmallVector<Expr *, 8> SrcExprs;
15972   SmallVector<Expr *, 8> DstExprs;
15973   SmallVector<Expr *, 8> AssignmentOps;
15974   for (Expr *RefExpr : VarList) {
15975     assert(RefExpr && "NULL expr in OpenMP linear clause.");
15976     SourceLocation ELoc;
15977     SourceRange ERange;
15978     Expr *SimpleRefExpr = RefExpr;
15979     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
15980     if (Res.second) {
15981       // It will be analyzed later.
15982       Vars.push_back(RefExpr);
15983       SrcExprs.push_back(nullptr);
15984       DstExprs.push_back(nullptr);
15985       AssignmentOps.push_back(nullptr);
15986     }
15987     ValueDecl *D = Res.first;
15988     if (!D)
15989       continue;
15990 
15991     QualType Type = D->getType();
15992     auto *VD = dyn_cast<VarDecl>(D);
15993 
15994     // OpenMP [2.14.4.2, Restrictions, p.2]
15995     //  A list item that appears in a copyprivate clause may not appear in a
15996     //  private or firstprivate clause on the single construct.
15997     if (!VD || !DSAStack->isThreadPrivate(VD)) {
15998       DSAStackTy::DSAVarData DVar =
15999           DSAStack->getTopDSA(D, /*FromParent=*/false);
16000       if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate &&
16001           DVar.RefExpr) {
16002         Diag(ELoc, diag::err_omp_wrong_dsa)
16003             << getOpenMPClauseName(DVar.CKind)
16004             << getOpenMPClauseName(OMPC_copyprivate);
16005         reportOriginalDsa(*this, DSAStack, D, DVar);
16006         continue;
16007       }
16008 
16009       // OpenMP [2.11.4.2, Restrictions, p.1]
16010       //  All list items that appear in a copyprivate clause must be either
16011       //  threadprivate or private in the enclosing context.
16012       if (DVar.CKind == OMPC_unknown) {
16013         DVar = DSAStack->getImplicitDSA(D, false);
16014         if (DVar.CKind == OMPC_shared) {
16015           Diag(ELoc, diag::err_omp_required_access)
16016               << getOpenMPClauseName(OMPC_copyprivate)
16017               << "threadprivate or private in the enclosing context";
16018           reportOriginalDsa(*this, DSAStack, D, DVar);
16019           continue;
16020         }
16021       }
16022     }
16023 
16024     // Variably modified types are not supported.
16025     if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) {
16026       Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
16027           << getOpenMPClauseName(OMPC_copyprivate) << Type
16028           << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
16029       bool IsDecl =
16030           !VD ||
16031           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
16032       Diag(D->getLocation(),
16033            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
16034           << D;
16035       continue;
16036     }
16037 
16038     // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
16039     //  A variable of class type (or array thereof) that appears in a
16040     //  copyin clause requires an accessible, unambiguous copy assignment
16041     //  operator for the class type.
16042     Type = Context.getBaseElementType(Type.getNonReferenceType())
16043                .getUnqualifiedType();
16044     VarDecl *SrcVD =
16045         buildVarDecl(*this, RefExpr->getBeginLoc(), Type, ".copyprivate.src",
16046                      D->hasAttrs() ? &D->getAttrs() : nullptr);
16047     DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr(*this, SrcVD, Type, ELoc);
16048     VarDecl *DstVD =
16049         buildVarDecl(*this, RefExpr->getBeginLoc(), Type, ".copyprivate.dst",
16050                      D->hasAttrs() ? &D->getAttrs() : nullptr);
16051     DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
16052     ExprResult AssignmentOp = BuildBinOp(
16053         DSAStack->getCurScope(), ELoc, BO_Assign, PseudoDstExpr, PseudoSrcExpr);
16054     if (AssignmentOp.isInvalid())
16055       continue;
16056     AssignmentOp =
16057         ActOnFinishFullExpr(AssignmentOp.get(), ELoc, /*DiscardedValue*/ false);
16058     if (AssignmentOp.isInvalid())
16059       continue;
16060 
16061     // No need to mark vars as copyprivate, they are already threadprivate or
16062     // implicitly private.
16063     assert(VD || isOpenMPCapturedDecl(D));
16064     Vars.push_back(
16065         VD ? RefExpr->IgnoreParens()
16066            : buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false));
16067     SrcExprs.push_back(PseudoSrcExpr);
16068     DstExprs.push_back(PseudoDstExpr);
16069     AssignmentOps.push_back(AssignmentOp.get());
16070   }
16071 
16072   if (Vars.empty())
16073     return nullptr;
16074 
16075   return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
16076                                       Vars, SrcExprs, DstExprs, AssignmentOps);
16077 }
16078 
16079 OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
16080                                         SourceLocation StartLoc,
16081                                         SourceLocation LParenLoc,
16082                                         SourceLocation EndLoc) {
16083   if (VarList.empty())
16084     return nullptr;
16085 
16086   return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList);
16087 }
16088 
16089 /// Tries to find omp_depend_t. type.
16090 static bool findOMPDependT(Sema &S, SourceLocation Loc, DSAStackTy *Stack,
16091                            bool Diagnose = true) {
16092   QualType OMPDependT = Stack->getOMPDependT();
16093   if (!OMPDependT.isNull())
16094     return true;
16095   IdentifierInfo *II = &S.PP.getIdentifierTable().get("omp_depend_t");
16096   ParsedType PT = S.getTypeName(*II, Loc, S.getCurScope());
16097   if (!PT.getAsOpaquePtr() || PT.get().isNull()) {
16098     if (Diagnose)
16099       S.Diag(Loc, diag::err_omp_implied_type_not_found) << "omp_depend_t";
16100     return false;
16101   }
16102   Stack->setOMPDependT(PT.get());
16103   return true;
16104 }
16105 
16106 OMPClause *Sema::ActOnOpenMPDepobjClause(Expr *Depobj, SourceLocation StartLoc,
16107                                          SourceLocation LParenLoc,
16108                                          SourceLocation EndLoc) {
16109   if (!Depobj)
16110     return nullptr;
16111 
16112   bool OMPDependTFound = findOMPDependT(*this, StartLoc, DSAStack);
16113 
16114   // OpenMP 5.0, 2.17.10.1 depobj Construct
16115   // depobj is an lvalue expression of type omp_depend_t.
16116   if (!Depobj->isTypeDependent() && !Depobj->isValueDependent() &&
16117       !Depobj->isInstantiationDependent() &&
16118       !Depobj->containsUnexpandedParameterPack() &&
16119       (OMPDependTFound &&
16120        !Context.typesAreCompatible(DSAStack->getOMPDependT(), Depobj->getType(),
16121                                    /*CompareUnqualified=*/true))) {
16122     Diag(Depobj->getExprLoc(), diag::err_omp_expected_omp_depend_t_lvalue)
16123         << 0 << Depobj->getType() << Depobj->getSourceRange();
16124   }
16125 
16126   if (!Depobj->isLValue()) {
16127     Diag(Depobj->getExprLoc(), diag::err_omp_expected_omp_depend_t_lvalue)
16128         << 1 << Depobj->getSourceRange();
16129   }
16130 
16131   return OMPDepobjClause::Create(Context, StartLoc, LParenLoc, EndLoc, Depobj);
16132 }
16133 
16134 OMPClause *
16135 Sema::ActOnOpenMPDependClause(Expr *DepModifier, OpenMPDependClauseKind DepKind,
16136                               SourceLocation DepLoc, SourceLocation ColonLoc,
16137                               ArrayRef<Expr *> VarList, SourceLocation StartLoc,
16138                               SourceLocation LParenLoc, SourceLocation EndLoc) {
16139   if (DSAStack->getCurrentDirective() == OMPD_ordered &&
16140       DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink) {
16141     Diag(DepLoc, diag::err_omp_unexpected_clause_value)
16142         << "'source' or 'sink'" << getOpenMPClauseName(OMPC_depend);
16143     return nullptr;
16144   }
16145   if ((DSAStack->getCurrentDirective() != OMPD_ordered ||
16146        DSAStack->getCurrentDirective() == OMPD_depobj) &&
16147       (DepKind == OMPC_DEPEND_unknown || DepKind == OMPC_DEPEND_source ||
16148        DepKind == OMPC_DEPEND_sink ||
16149        ((LangOpts.OpenMP < 50 ||
16150          DSAStack->getCurrentDirective() == OMPD_depobj) &&
16151         DepKind == OMPC_DEPEND_depobj))) {
16152     SmallVector<unsigned, 3> Except;
16153     Except.push_back(OMPC_DEPEND_source);
16154     Except.push_back(OMPC_DEPEND_sink);
16155     if (LangOpts.OpenMP < 50 || DSAStack->getCurrentDirective() == OMPD_depobj)
16156       Except.push_back(OMPC_DEPEND_depobj);
16157     std::string Expected = (LangOpts.OpenMP >= 50 && !DepModifier)
16158                                ? "depend modifier(iterator) or "
16159                                : "";
16160     Diag(DepLoc, diag::err_omp_unexpected_clause_value)
16161         << Expected + getListOfPossibleValues(OMPC_depend, /*First=*/0,
16162                                               /*Last=*/OMPC_DEPEND_unknown,
16163                                               Except)
16164         << getOpenMPClauseName(OMPC_depend);
16165     return nullptr;
16166   }
16167   if (DepModifier &&
16168       (DepKind == OMPC_DEPEND_source || DepKind == OMPC_DEPEND_sink)) {
16169     Diag(DepModifier->getExprLoc(),
16170          diag::err_omp_depend_sink_source_with_modifier);
16171     return nullptr;
16172   }
16173   if (DepModifier &&
16174       !DepModifier->getType()->isSpecificBuiltinType(BuiltinType::OMPIterator))
16175     Diag(DepModifier->getExprLoc(), diag::err_omp_depend_modifier_not_iterator);
16176 
16177   SmallVector<Expr *, 8> Vars;
16178   DSAStackTy::OperatorOffsetTy OpsOffs;
16179   llvm::APSInt DepCounter(/*BitWidth=*/32);
16180   llvm::APSInt TotalDepCount(/*BitWidth=*/32);
16181   if (DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) {
16182     if (const Expr *OrderedCountExpr =
16183             DSAStack->getParentOrderedRegionParam().first) {
16184       TotalDepCount = OrderedCountExpr->EvaluateKnownConstInt(Context);
16185       TotalDepCount.setIsUnsigned(/*Val=*/true);
16186     }
16187   }
16188   for (Expr *RefExpr : VarList) {
16189     assert(RefExpr && "NULL expr in OpenMP shared clause.");
16190     if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
16191       // It will be analyzed later.
16192       Vars.push_back(RefExpr);
16193       continue;
16194     }
16195 
16196     SourceLocation ELoc = RefExpr->getExprLoc();
16197     Expr *SimpleExpr = RefExpr->IgnoreParenCasts();
16198     if (DepKind == OMPC_DEPEND_sink) {
16199       if (DSAStack->getParentOrderedRegionParam().first &&
16200           DepCounter >= TotalDepCount) {
16201         Diag(ELoc, diag::err_omp_depend_sink_unexpected_expr);
16202         continue;
16203       }
16204       ++DepCounter;
16205       // OpenMP  [2.13.9, Summary]
16206       // depend(dependence-type : vec), where dependence-type is:
16207       // 'sink' and where vec is the iteration vector, which has the form:
16208       //  x1 [+- d1], x2 [+- d2 ], . . . , xn [+- dn]
16209       // where n is the value specified by the ordered clause in the loop
16210       // directive, xi denotes the loop iteration variable of the i-th nested
16211       // loop associated with the loop directive, and di is a constant
16212       // non-negative integer.
16213       if (CurContext->isDependentContext()) {
16214         // It will be analyzed later.
16215         Vars.push_back(RefExpr);
16216         continue;
16217       }
16218       SimpleExpr = SimpleExpr->IgnoreImplicit();
16219       OverloadedOperatorKind OOK = OO_None;
16220       SourceLocation OOLoc;
16221       Expr *LHS = SimpleExpr;
16222       Expr *RHS = nullptr;
16223       if (auto *BO = dyn_cast<BinaryOperator>(SimpleExpr)) {
16224         OOK = BinaryOperator::getOverloadedOperator(BO->getOpcode());
16225         OOLoc = BO->getOperatorLoc();
16226         LHS = BO->getLHS()->IgnoreParenImpCasts();
16227         RHS = BO->getRHS()->IgnoreParenImpCasts();
16228       } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(SimpleExpr)) {
16229         OOK = OCE->getOperator();
16230         OOLoc = OCE->getOperatorLoc();
16231         LHS = OCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
16232         RHS = OCE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
16233       } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SimpleExpr)) {
16234         OOK = MCE->getMethodDecl()
16235                   ->getNameInfo()
16236                   .getName()
16237                   .getCXXOverloadedOperator();
16238         OOLoc = MCE->getCallee()->getExprLoc();
16239         LHS = MCE->getImplicitObjectArgument()->IgnoreParenImpCasts();
16240         RHS = MCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
16241       }
16242       SourceLocation ELoc;
16243       SourceRange ERange;
16244       auto Res = getPrivateItem(*this, LHS, ELoc, ERange);
16245       if (Res.second) {
16246         // It will be analyzed later.
16247         Vars.push_back(RefExpr);
16248       }
16249       ValueDecl *D = Res.first;
16250       if (!D)
16251         continue;
16252 
16253       if (OOK != OO_Plus && OOK != OO_Minus && (RHS || OOK != OO_None)) {
16254         Diag(OOLoc, diag::err_omp_depend_sink_expected_plus_minus);
16255         continue;
16256       }
16257       if (RHS) {
16258         ExprResult RHSRes = VerifyPositiveIntegerConstantInClause(
16259             RHS, OMPC_depend, /*StrictlyPositive=*/false);
16260         if (RHSRes.isInvalid())
16261           continue;
16262       }
16263       if (!CurContext->isDependentContext() &&
16264           DSAStack->getParentOrderedRegionParam().first &&
16265           DepCounter != DSAStack->isParentLoopControlVariable(D).first) {
16266         const ValueDecl *VD =
16267             DSAStack->getParentLoopControlVariable(DepCounter.getZExtValue());
16268         if (VD)
16269           Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration)
16270               << 1 << VD;
16271         else
16272           Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration) << 0;
16273         continue;
16274       }
16275       OpsOffs.emplace_back(RHS, OOK);
16276     } else {
16277       bool OMPDependTFound = LangOpts.OpenMP >= 50;
16278       if (OMPDependTFound)
16279         OMPDependTFound = findOMPDependT(*this, StartLoc, DSAStack,
16280                                          DepKind == OMPC_DEPEND_depobj);
16281       if (DepKind == OMPC_DEPEND_depobj) {
16282         // OpenMP 5.0, 2.17.11 depend Clause, Restrictions, C/C++
16283         // List items used in depend clauses with the depobj dependence type
16284         // must be expressions of the omp_depend_t type.
16285         if (!RefExpr->isValueDependent() && !RefExpr->isTypeDependent() &&
16286             !RefExpr->isInstantiationDependent() &&
16287             !RefExpr->containsUnexpandedParameterPack() &&
16288             (OMPDependTFound &&
16289              !Context.hasSameUnqualifiedType(DSAStack->getOMPDependT(),
16290                                              RefExpr->getType()))) {
16291           Diag(ELoc, diag::err_omp_expected_omp_depend_t_lvalue)
16292               << 0 << RefExpr->getType() << RefExpr->getSourceRange();
16293           continue;
16294         }
16295         if (!RefExpr->isLValue()) {
16296           Diag(ELoc, diag::err_omp_expected_omp_depend_t_lvalue)
16297               << 1 << RefExpr->getType() << RefExpr->getSourceRange();
16298           continue;
16299         }
16300       } else {
16301         // OpenMP 5.0 [2.17.11, Restrictions]
16302         // List items used in depend clauses cannot be zero-length array
16303         // sections.
16304         QualType ExprTy = RefExpr->getType().getNonReferenceType();
16305         const auto *OASE = dyn_cast<OMPArraySectionExpr>(SimpleExpr);
16306         if (OASE) {
16307           QualType BaseType =
16308               OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
16309           if (const auto *ATy = BaseType->getAsArrayTypeUnsafe())
16310             ExprTy = ATy->getElementType();
16311           else
16312             ExprTy = BaseType->getPointeeType();
16313           ExprTy = ExprTy.getNonReferenceType();
16314           const Expr *Length = OASE->getLength();
16315           Expr::EvalResult Result;
16316           if (Length && !Length->isValueDependent() &&
16317               Length->EvaluateAsInt(Result, Context) &&
16318               Result.Val.getInt().isNullValue()) {
16319             Diag(ELoc,
16320                  diag::err_omp_depend_zero_length_array_section_not_allowed)
16321                 << SimpleExpr->getSourceRange();
16322             continue;
16323           }
16324         }
16325 
16326         // OpenMP 5.0, 2.17.11 depend Clause, Restrictions, C/C++
16327         // List items used in depend clauses with the in, out, inout or
16328         // mutexinoutset dependence types cannot be expressions of the
16329         // omp_depend_t type.
16330         if (!RefExpr->isValueDependent() && !RefExpr->isTypeDependent() &&
16331             !RefExpr->isInstantiationDependent() &&
16332             !RefExpr->containsUnexpandedParameterPack() &&
16333             (OMPDependTFound &&
16334              DSAStack->getOMPDependT().getTypePtr() == ExprTy.getTypePtr())) {
16335           Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
16336               << (LangOpts.OpenMP >= 50 ? 1 : 0) << 1
16337               << RefExpr->getSourceRange();
16338           continue;
16339         }
16340 
16341         auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr);
16342         if (!RefExpr->IgnoreParenImpCasts()->isLValue() ||
16343             (ASE && !ASE->getBase()->isTypeDependent() &&
16344              !ASE->getBase()
16345                   ->getType()
16346                   .getNonReferenceType()
16347                   ->isPointerType() &&
16348              !ASE->getBase()->getType().getNonReferenceType()->isArrayType())) {
16349           Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
16350               << (LangOpts.OpenMP >= 50 ? 1 : 0)
16351               << (LangOpts.OpenMP >= 50 ? 1 : 0) << RefExpr->getSourceRange();
16352           continue;
16353         }
16354 
16355         ExprResult Res;
16356         {
16357           Sema::TentativeAnalysisScope Trap(*this);
16358           Res = CreateBuiltinUnaryOp(ELoc, UO_AddrOf,
16359                                      RefExpr->IgnoreParenImpCasts());
16360         }
16361         if (!Res.isUsable() && !isa<OMPArraySectionExpr>(SimpleExpr) &&
16362             !isa<OMPArrayShapingExpr>(SimpleExpr)) {
16363           Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
16364               << (LangOpts.OpenMP >= 50 ? 1 : 0)
16365               << (LangOpts.OpenMP >= 50 ? 1 : 0) << RefExpr->getSourceRange();
16366           continue;
16367         }
16368       }
16369     }
16370     Vars.push_back(RefExpr->IgnoreParenImpCasts());
16371   }
16372 
16373   if (!CurContext->isDependentContext() && DepKind == OMPC_DEPEND_sink &&
16374       TotalDepCount > VarList.size() &&
16375       DSAStack->getParentOrderedRegionParam().first &&
16376       DSAStack->getParentLoopControlVariable(VarList.size() + 1)) {
16377     Diag(EndLoc, diag::err_omp_depend_sink_expected_loop_iteration)
16378         << 1 << DSAStack->getParentLoopControlVariable(VarList.size() + 1);
16379   }
16380   if (DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink &&
16381       Vars.empty())
16382     return nullptr;
16383 
16384   auto *C = OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc,
16385                                     DepModifier, DepKind, DepLoc, ColonLoc,
16386                                     Vars, TotalDepCount.getZExtValue());
16387   if ((DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) &&
16388       DSAStack->isParentOrderedRegion())
16389     DSAStack->addDoacrossDependClause(C, OpsOffs);
16390   return C;
16391 }
16392 
16393 OMPClause *Sema::ActOnOpenMPDeviceClause(OpenMPDeviceClauseModifier Modifier,
16394                                          Expr *Device, SourceLocation StartLoc,
16395                                          SourceLocation LParenLoc,
16396                                          SourceLocation ModifierLoc,
16397                                          SourceLocation EndLoc) {
16398   assert((ModifierLoc.isInvalid() || LangOpts.OpenMP >= 50) &&
16399          "Unexpected device modifier in OpenMP < 50.");
16400 
16401   bool ErrorFound = false;
16402   if (ModifierLoc.isValid() && Modifier == OMPC_DEVICE_unknown) {
16403     std::string Values =
16404         getListOfPossibleValues(OMPC_device, /*First=*/0, OMPC_DEVICE_unknown);
16405     Diag(ModifierLoc, diag::err_omp_unexpected_clause_value)
16406         << Values << getOpenMPClauseName(OMPC_device);
16407     ErrorFound = true;
16408   }
16409 
16410   Expr *ValExpr = Device;
16411   Stmt *HelperValStmt = nullptr;
16412 
16413   // OpenMP [2.9.1, Restrictions]
16414   // The device expression must evaluate to a non-negative integer value.
16415   ErrorFound = !isNonNegativeIntegerValue(ValExpr, *this, OMPC_device,
16416                                           /*StrictlyPositive=*/false) ||
16417                ErrorFound;
16418   if (ErrorFound)
16419     return nullptr;
16420 
16421   OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
16422   OpenMPDirectiveKind CaptureRegion =
16423       getOpenMPCaptureRegionForClause(DKind, OMPC_device, LangOpts.OpenMP);
16424   if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
16425     ValExpr = MakeFullExpr(ValExpr).get();
16426     llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
16427     ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
16428     HelperValStmt = buildPreInits(Context, Captures);
16429   }
16430 
16431   return new (Context)
16432       OMPDeviceClause(Modifier, ValExpr, HelperValStmt, CaptureRegion, StartLoc,
16433                       LParenLoc, ModifierLoc, EndLoc);
16434 }
16435 
16436 static bool checkTypeMappable(SourceLocation SL, SourceRange SR, Sema &SemaRef,
16437                               DSAStackTy *Stack, QualType QTy,
16438                               bool FullCheck = true) {
16439   NamedDecl *ND;
16440   if (QTy->isIncompleteType(&ND)) {
16441     SemaRef.Diag(SL, diag::err_incomplete_type) << QTy << SR;
16442     return false;
16443   }
16444   if (FullCheck && !SemaRef.CurContext->isDependentContext() &&
16445       !QTy.isTriviallyCopyableType(SemaRef.Context))
16446     SemaRef.Diag(SL, diag::warn_omp_non_trivial_type_mapped) << QTy << SR;
16447   return true;
16448 }
16449 
16450 /// Return true if it can be proven that the provided array expression
16451 /// (array section or array subscript) does NOT specify the whole size of the
16452 /// array whose base type is \a BaseQTy.
16453 static bool checkArrayExpressionDoesNotReferToWholeSize(Sema &SemaRef,
16454                                                         const Expr *E,
16455                                                         QualType BaseQTy) {
16456   const auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
16457 
16458   // If this is an array subscript, it refers to the whole size if the size of
16459   // the dimension is constant and equals 1. Also, an array section assumes the
16460   // format of an array subscript if no colon is used.
16461   if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid())) {
16462     if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
16463       return ATy->getSize().getSExtValue() != 1;
16464     // Size can't be evaluated statically.
16465     return false;
16466   }
16467 
16468   assert(OASE && "Expecting array section if not an array subscript.");
16469   const Expr *LowerBound = OASE->getLowerBound();
16470   const Expr *Length = OASE->getLength();
16471 
16472   // If there is a lower bound that does not evaluates to zero, we are not
16473   // covering the whole dimension.
16474   if (LowerBound) {
16475     Expr::EvalResult Result;
16476     if (!LowerBound->EvaluateAsInt(Result, SemaRef.getASTContext()))
16477       return false; // Can't get the integer value as a constant.
16478 
16479     llvm::APSInt ConstLowerBound = Result.Val.getInt();
16480     if (ConstLowerBound.getSExtValue())
16481       return true;
16482   }
16483 
16484   // If we don't have a length we covering the whole dimension.
16485   if (!Length)
16486     return false;
16487 
16488   // If the base is a pointer, we don't have a way to get the size of the
16489   // pointee.
16490   if (BaseQTy->isPointerType())
16491     return false;
16492 
16493   // We can only check if the length is the same as the size of the dimension
16494   // if we have a constant array.
16495   const auto *CATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr());
16496   if (!CATy)
16497     return false;
16498 
16499   Expr::EvalResult Result;
16500   if (!Length->EvaluateAsInt(Result, SemaRef.getASTContext()))
16501     return false; // Can't get the integer value as a constant.
16502 
16503   llvm::APSInt ConstLength = Result.Val.getInt();
16504   return CATy->getSize().getSExtValue() != ConstLength.getSExtValue();
16505 }
16506 
16507 // Return true if it can be proven that the provided array expression (array
16508 // section or array subscript) does NOT specify a single element of the array
16509 // whose base type is \a BaseQTy.
16510 static bool checkArrayExpressionDoesNotReferToUnitySize(Sema &SemaRef,
16511                                                         const Expr *E,
16512                                                         QualType BaseQTy) {
16513   const auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
16514 
16515   // An array subscript always refer to a single element. Also, an array section
16516   // assumes the format of an array subscript if no colon is used.
16517   if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid()))
16518     return false;
16519 
16520   assert(OASE && "Expecting array section if not an array subscript.");
16521   const Expr *Length = OASE->getLength();
16522 
16523   // If we don't have a length we have to check if the array has unitary size
16524   // for this dimension. Also, we should always expect a length if the base type
16525   // is pointer.
16526   if (!Length) {
16527     if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
16528       return ATy->getSize().getSExtValue() != 1;
16529     // We cannot assume anything.
16530     return false;
16531   }
16532 
16533   // Check if the length evaluates to 1.
16534   Expr::EvalResult Result;
16535   if (!Length->EvaluateAsInt(Result, SemaRef.getASTContext()))
16536     return false; // Can't get the integer value as a constant.
16537 
16538   llvm::APSInt ConstLength = Result.Val.getInt();
16539   return ConstLength.getSExtValue() != 1;
16540 }
16541 
16542 // The base of elements of list in a map clause have to be either:
16543 //  - a reference to variable or field.
16544 //  - a member expression.
16545 //  - an array expression.
16546 //
16547 // E.g. if we have the expression 'r.S.Arr[:12]', we want to retrieve the
16548 // reference to 'r'.
16549 //
16550 // If we have:
16551 //
16552 // struct SS {
16553 //   Bla S;
16554 //   foo() {
16555 //     #pragma omp target map (S.Arr[:12]);
16556 //   }
16557 // }
16558 //
16559 // We want to retrieve the member expression 'this->S';
16560 
16561 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.2]
16562 //  If a list item is an array section, it must specify contiguous storage.
16563 //
16564 // For this restriction it is sufficient that we make sure only references
16565 // to variables or fields and array expressions, and that no array sections
16566 // exist except in the rightmost expression (unless they cover the whole
16567 // dimension of the array). E.g. these would be invalid:
16568 //
16569 //   r.ArrS[3:5].Arr[6:7]
16570 //
16571 //   r.ArrS[3:5].x
16572 //
16573 // but these would be valid:
16574 //   r.ArrS[3].Arr[6:7]
16575 //
16576 //   r.ArrS[3].x
16577 namespace {
16578 class MapBaseChecker final : public StmtVisitor<MapBaseChecker, bool> {
16579   Sema &SemaRef;
16580   OpenMPClauseKind CKind = OMPC_unknown;
16581   OMPClauseMappableExprCommon::MappableExprComponentList &Components;
16582   bool NoDiagnose = false;
16583   const Expr *RelevantExpr = nullptr;
16584   bool AllowUnitySizeArraySection = true;
16585   bool AllowWholeSizeArraySection = true;
16586   SourceLocation ELoc;
16587   SourceRange ERange;
16588 
16589   void emitErrorMsg() {
16590     // If nothing else worked, this is not a valid map clause expression.
16591     if (SemaRef.getLangOpts().OpenMP < 50) {
16592       SemaRef.Diag(ELoc,
16593                    diag::err_omp_expected_named_var_member_or_array_expression)
16594           << ERange;
16595     } else {
16596       SemaRef.Diag(ELoc, diag::err_omp_non_lvalue_in_map_or_motion_clauses)
16597           << getOpenMPClauseName(CKind) << ERange;
16598     }
16599   }
16600 
16601 public:
16602   bool VisitDeclRefExpr(DeclRefExpr *DRE) {
16603     if (!isa<VarDecl>(DRE->getDecl())) {
16604       emitErrorMsg();
16605       return false;
16606     }
16607     assert(!RelevantExpr && "RelevantExpr is expected to be nullptr");
16608     RelevantExpr = DRE;
16609     // Record the component.
16610     Components.emplace_back(DRE, DRE->getDecl());
16611     return true;
16612   }
16613 
16614   bool VisitMemberExpr(MemberExpr *ME) {
16615     Expr *E = ME;
16616     Expr *BaseE = ME->getBase()->IgnoreParenCasts();
16617 
16618     if (isa<CXXThisExpr>(BaseE)) {
16619       assert(!RelevantExpr && "RelevantExpr is expected to be nullptr");
16620       // We found a base expression: this->Val.
16621       RelevantExpr = ME;
16622     } else {
16623       E = BaseE;
16624     }
16625 
16626     if (!isa<FieldDecl>(ME->getMemberDecl())) {
16627       if (!NoDiagnose) {
16628         SemaRef.Diag(ELoc, diag::err_omp_expected_access_to_data_field)
16629           << ME->getSourceRange();
16630         return false;
16631       }
16632       if (RelevantExpr)
16633         return false;
16634       return Visit(E);
16635     }
16636 
16637     auto *FD = cast<FieldDecl>(ME->getMemberDecl());
16638 
16639     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
16640     //  A bit-field cannot appear in a map clause.
16641     //
16642     if (FD->isBitField()) {
16643       if (!NoDiagnose) {
16644         SemaRef.Diag(ELoc, diag::err_omp_bit_fields_forbidden_in_clause)
16645           << ME->getSourceRange() << getOpenMPClauseName(CKind);
16646         return false;
16647       }
16648       if (RelevantExpr)
16649         return false;
16650       return Visit(E);
16651     }
16652 
16653     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
16654     //  If the type of a list item is a reference to a type T then the type
16655     //  will be considered to be T for all purposes of this clause.
16656     QualType CurType = BaseE->getType().getNonReferenceType();
16657 
16658     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.2]
16659     //  A list item cannot be a variable that is a member of a structure with
16660     //  a union type.
16661     //
16662     if (CurType->isUnionType()) {
16663       if (!NoDiagnose) {
16664         SemaRef.Diag(ELoc, diag::err_omp_union_type_not_allowed)
16665           << ME->getSourceRange();
16666         return false;
16667       }
16668       return RelevantExpr || Visit(E);
16669     }
16670 
16671     // If we got a member expression, we should not expect any array section
16672     // before that:
16673     //
16674     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.7]
16675     //  If a list item is an element of a structure, only the rightmost symbol
16676     //  of the variable reference can be an array section.
16677     //
16678     AllowUnitySizeArraySection = false;
16679     AllowWholeSizeArraySection = false;
16680 
16681     // Record the component.
16682     Components.emplace_back(ME, FD);
16683     return RelevantExpr || Visit(E);
16684   }
16685 
16686   bool VisitArraySubscriptExpr(ArraySubscriptExpr *AE) {
16687     Expr *E = AE->getBase()->IgnoreParenImpCasts();
16688 
16689     if (!E->getType()->isAnyPointerType() && !E->getType()->isArrayType()) {
16690       if (!NoDiagnose) {
16691         SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
16692           << 0 << AE->getSourceRange();
16693         return false;
16694       }
16695       return RelevantExpr || Visit(E);
16696     }
16697 
16698     // If we got an array subscript that express the whole dimension we
16699     // can have any array expressions before. If it only expressing part of
16700     // the dimension, we can only have unitary-size array expressions.
16701     if (checkArrayExpressionDoesNotReferToWholeSize(SemaRef, AE,
16702                                                     E->getType()))
16703       AllowWholeSizeArraySection = false;
16704 
16705     if (const auto *TE = dyn_cast<CXXThisExpr>(E->IgnoreParenCasts())) {
16706       Expr::EvalResult Result;
16707       if (!AE->getIdx()->isValueDependent() &&
16708           AE->getIdx()->EvaluateAsInt(Result, SemaRef.getASTContext()) &&
16709           !Result.Val.getInt().isNullValue()) {
16710         SemaRef.Diag(AE->getIdx()->getExprLoc(),
16711                      diag::err_omp_invalid_map_this_expr);
16712         SemaRef.Diag(AE->getIdx()->getExprLoc(),
16713                      diag::note_omp_invalid_subscript_on_this_ptr_map);
16714       }
16715       assert(!RelevantExpr && "RelevantExpr is expected to be nullptr");
16716       RelevantExpr = TE;
16717     }
16718 
16719     // Record the component - we don't have any declaration associated.
16720     Components.emplace_back(AE, nullptr);
16721 
16722     return RelevantExpr || Visit(E);
16723   }
16724 
16725   bool VisitOMPArraySectionExpr(OMPArraySectionExpr *OASE) {
16726     assert(!NoDiagnose && "Array sections cannot be implicitly mapped.");
16727     Expr *E = OASE->getBase()->IgnoreParenImpCasts();
16728     QualType CurType =
16729       OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
16730 
16731     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
16732     //  If the type of a list item is a reference to a type T then the type
16733     //  will be considered to be T for all purposes of this clause.
16734     if (CurType->isReferenceType())
16735       CurType = CurType->getPointeeType();
16736 
16737     bool IsPointer = CurType->isAnyPointerType();
16738 
16739     if (!IsPointer && !CurType->isArrayType()) {
16740       SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
16741         << 0 << OASE->getSourceRange();
16742       return false;
16743     }
16744 
16745     bool NotWhole =
16746       checkArrayExpressionDoesNotReferToWholeSize(SemaRef, OASE, CurType);
16747     bool NotUnity =
16748       checkArrayExpressionDoesNotReferToUnitySize(SemaRef, OASE, CurType);
16749 
16750     if (AllowWholeSizeArraySection) {
16751       // Any array section is currently allowed. Allowing a whole size array
16752       // section implies allowing a unity array section as well.
16753       //
16754       // If this array section refers to the whole dimension we can still
16755       // accept other array sections before this one, except if the base is a
16756       // pointer. Otherwise, only unitary sections are accepted.
16757       if (NotWhole || IsPointer)
16758         AllowWholeSizeArraySection = false;
16759     } else if (AllowUnitySizeArraySection && NotUnity) {
16760       // A unity or whole array section is not allowed and that is not
16761       // compatible with the properties of the current array section.
16762       SemaRef.Diag(
16763         ELoc, diag::err_array_section_does_not_specify_contiguous_storage)
16764         << OASE->getSourceRange();
16765       return false;
16766     }
16767 
16768     if (const auto *TE = dyn_cast<CXXThisExpr>(E)) {
16769       Expr::EvalResult ResultR;
16770       Expr::EvalResult ResultL;
16771       if (!OASE->getLength()->isValueDependent() &&
16772           OASE->getLength()->EvaluateAsInt(ResultR, SemaRef.getASTContext()) &&
16773           !ResultR.Val.getInt().isOneValue()) {
16774         SemaRef.Diag(OASE->getLength()->getExprLoc(),
16775                      diag::err_omp_invalid_map_this_expr);
16776         SemaRef.Diag(OASE->getLength()->getExprLoc(),
16777                      diag::note_omp_invalid_length_on_this_ptr_mapping);
16778       }
16779       if (OASE->getLowerBound() && !OASE->getLowerBound()->isValueDependent() &&
16780           OASE->getLowerBound()->EvaluateAsInt(ResultL,
16781                                                SemaRef.getASTContext()) &&
16782           !ResultL.Val.getInt().isNullValue()) {
16783         SemaRef.Diag(OASE->getLowerBound()->getExprLoc(),
16784                      diag::err_omp_invalid_map_this_expr);
16785         SemaRef.Diag(OASE->getLowerBound()->getExprLoc(),
16786                      diag::note_omp_invalid_lower_bound_on_this_ptr_mapping);
16787       }
16788       assert(!RelevantExpr && "RelevantExpr is expected to be nullptr");
16789       RelevantExpr = TE;
16790     }
16791 
16792     // Record the component - we don't have any declaration associated.
16793     Components.emplace_back(OASE, nullptr);
16794     return RelevantExpr || Visit(E);
16795   }
16796   bool VisitOMPArrayShapingExpr(OMPArrayShapingExpr *E) {
16797     Expr *Base = E->getBase();
16798 
16799     // Record the component - we don't have any declaration associated.
16800     Components.emplace_back(E, nullptr);
16801 
16802     return Visit(Base->IgnoreParenImpCasts());
16803   }
16804 
16805   bool VisitUnaryOperator(UnaryOperator *UO) {
16806     if (SemaRef.getLangOpts().OpenMP < 50 || !UO->isLValue() ||
16807         UO->getOpcode() != UO_Deref) {
16808       emitErrorMsg();
16809       return false;
16810     }
16811     if (!RelevantExpr) {
16812       // Record the component if haven't found base decl.
16813       Components.emplace_back(UO, nullptr);
16814     }
16815     return RelevantExpr || Visit(UO->getSubExpr()->IgnoreParenImpCasts());
16816   }
16817   bool VisitBinaryOperator(BinaryOperator *BO) {
16818     if (SemaRef.getLangOpts().OpenMP < 50 || !BO->getType()->isPointerType()) {
16819       emitErrorMsg();
16820       return false;
16821     }
16822 
16823     // Pointer arithmetic is the only thing we expect to happen here so after we
16824     // make sure the binary operator is a pointer type, the we only thing need
16825     // to to is to visit the subtree that has the same type as root (so that we
16826     // know the other subtree is just an offset)
16827     Expr *LE = BO->getLHS()->IgnoreParenImpCasts();
16828     Expr *RE = BO->getRHS()->IgnoreParenImpCasts();
16829     Components.emplace_back(BO, nullptr);
16830     assert((LE->getType().getTypePtr() == BO->getType().getTypePtr() ||
16831             RE->getType().getTypePtr() == BO->getType().getTypePtr()) &&
16832            "Either LHS or RHS have base decl inside");
16833     if (BO->getType().getTypePtr() == LE->getType().getTypePtr())
16834       return RelevantExpr || Visit(LE);
16835     return RelevantExpr || Visit(RE);
16836   }
16837   bool VisitCXXThisExpr(CXXThisExpr *CTE) {
16838     assert(!RelevantExpr && "RelevantExpr is expected to be nullptr");
16839     RelevantExpr = CTE;
16840     Components.emplace_back(CTE, nullptr);
16841     return true;
16842   }
16843   bool VisitStmt(Stmt *) {
16844     emitErrorMsg();
16845     return false;
16846   }
16847   const Expr *getFoundBase() const {
16848     return RelevantExpr;
16849   }
16850   explicit MapBaseChecker(
16851       Sema &SemaRef, OpenMPClauseKind CKind,
16852       OMPClauseMappableExprCommon::MappableExprComponentList &Components,
16853       bool NoDiagnose, SourceLocation &ELoc, SourceRange &ERange)
16854       : SemaRef(SemaRef), CKind(CKind), Components(Components),
16855         NoDiagnose(NoDiagnose), ELoc(ELoc), ERange(ERange) {}
16856 };
16857 } // namespace
16858 
16859 /// Return the expression of the base of the mappable expression or null if it
16860 /// cannot be determined and do all the necessary checks to see if the expression
16861 /// is valid as a standalone mappable expression. In the process, record all the
16862 /// components of the expression.
16863 static const Expr *checkMapClauseExpressionBase(
16864     Sema &SemaRef, Expr *E,
16865     OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
16866     OpenMPClauseKind CKind, bool NoDiagnose) {
16867   SourceLocation ELoc = E->getExprLoc();
16868   SourceRange ERange = E->getSourceRange();
16869   MapBaseChecker Checker(SemaRef, CKind, CurComponents, NoDiagnose, ELoc,
16870                          ERange);
16871   if (Checker.Visit(E->IgnoreParens()))
16872     return Checker.getFoundBase();
16873   return nullptr;
16874 }
16875 
16876 // Return true if expression E associated with value VD has conflicts with other
16877 // map information.
16878 static bool checkMapConflicts(
16879     Sema &SemaRef, DSAStackTy *DSAS, const ValueDecl *VD, const Expr *E,
16880     bool CurrentRegionOnly,
16881     OMPClauseMappableExprCommon::MappableExprComponentListRef CurComponents,
16882     OpenMPClauseKind CKind) {
16883   assert(VD && E);
16884   SourceLocation ELoc = E->getExprLoc();
16885   SourceRange ERange = E->getSourceRange();
16886 
16887   // In order to easily check the conflicts we need to match each component of
16888   // the expression under test with the components of the expressions that are
16889   // already in the stack.
16890 
16891   assert(!CurComponents.empty() && "Map clause expression with no components!");
16892   assert(CurComponents.back().getAssociatedDeclaration() == VD &&
16893          "Map clause expression with unexpected base!");
16894 
16895   // Variables to help detecting enclosing problems in data environment nests.
16896   bool IsEnclosedByDataEnvironmentExpr = false;
16897   const Expr *EnclosingExpr = nullptr;
16898 
16899   bool FoundError = DSAS->checkMappableExprComponentListsForDecl(
16900       VD, CurrentRegionOnly,
16901       [&IsEnclosedByDataEnvironmentExpr, &SemaRef, VD, CurrentRegionOnly, ELoc,
16902        ERange, CKind, &EnclosingExpr,
16903        CurComponents](OMPClauseMappableExprCommon::MappableExprComponentListRef
16904                           StackComponents,
16905                       OpenMPClauseKind) {
16906         assert(!StackComponents.empty() &&
16907                "Map clause expression with no components!");
16908         assert(StackComponents.back().getAssociatedDeclaration() == VD &&
16909                "Map clause expression with unexpected base!");
16910         (void)VD;
16911 
16912         // The whole expression in the stack.
16913         const Expr *RE = StackComponents.front().getAssociatedExpression();
16914 
16915         // Expressions must start from the same base. Here we detect at which
16916         // point both expressions diverge from each other and see if we can
16917         // detect if the memory referred to both expressions is contiguous and
16918         // do not overlap.
16919         auto CI = CurComponents.rbegin();
16920         auto CE = CurComponents.rend();
16921         auto SI = StackComponents.rbegin();
16922         auto SE = StackComponents.rend();
16923         for (; CI != CE && SI != SE; ++CI, ++SI) {
16924 
16925           // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.3]
16926           //  At most one list item can be an array item derived from a given
16927           //  variable in map clauses of the same construct.
16928           if (CurrentRegionOnly &&
16929               (isa<ArraySubscriptExpr>(CI->getAssociatedExpression()) ||
16930                isa<OMPArraySectionExpr>(CI->getAssociatedExpression()) ||
16931                isa<OMPArrayShapingExpr>(CI->getAssociatedExpression())) &&
16932               (isa<ArraySubscriptExpr>(SI->getAssociatedExpression()) ||
16933                isa<OMPArraySectionExpr>(SI->getAssociatedExpression()) ||
16934                isa<OMPArrayShapingExpr>(SI->getAssociatedExpression()))) {
16935             SemaRef.Diag(CI->getAssociatedExpression()->getExprLoc(),
16936                          diag::err_omp_multiple_array_items_in_map_clause)
16937                 << CI->getAssociatedExpression()->getSourceRange();
16938             SemaRef.Diag(SI->getAssociatedExpression()->getExprLoc(),
16939                          diag::note_used_here)
16940                 << SI->getAssociatedExpression()->getSourceRange();
16941             return true;
16942           }
16943 
16944           // Do both expressions have the same kind?
16945           if (CI->getAssociatedExpression()->getStmtClass() !=
16946               SI->getAssociatedExpression()->getStmtClass())
16947             break;
16948 
16949           // Are we dealing with different variables/fields?
16950           if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration())
16951             break;
16952         }
16953         // Check if the extra components of the expressions in the enclosing
16954         // data environment are redundant for the current base declaration.
16955         // If they are, the maps completely overlap, which is legal.
16956         for (; SI != SE; ++SI) {
16957           QualType Type;
16958           if (const auto *ASE =
16959                   dyn_cast<ArraySubscriptExpr>(SI->getAssociatedExpression())) {
16960             Type = ASE->getBase()->IgnoreParenImpCasts()->getType();
16961           } else if (const auto *OASE = dyn_cast<OMPArraySectionExpr>(
16962                          SI->getAssociatedExpression())) {
16963             const Expr *E = OASE->getBase()->IgnoreParenImpCasts();
16964             Type =
16965                 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
16966           } else if (const auto *OASE = dyn_cast<OMPArrayShapingExpr>(
16967                          SI->getAssociatedExpression())) {
16968             Type = OASE->getBase()->getType()->getPointeeType();
16969           }
16970           if (Type.isNull() || Type->isAnyPointerType() ||
16971               checkArrayExpressionDoesNotReferToWholeSize(
16972                   SemaRef, SI->getAssociatedExpression(), Type))
16973             break;
16974         }
16975 
16976         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
16977         //  List items of map clauses in the same construct must not share
16978         //  original storage.
16979         //
16980         // If the expressions are exactly the same or one is a subset of the
16981         // other, it means they are sharing storage.
16982         if (CI == CE && SI == SE) {
16983           if (CurrentRegionOnly) {
16984             if (CKind == OMPC_map) {
16985               SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
16986             } else {
16987               assert(CKind == OMPC_to || CKind == OMPC_from);
16988               SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
16989                   << ERange;
16990             }
16991             SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
16992                 << RE->getSourceRange();
16993             return true;
16994           }
16995           // If we find the same expression in the enclosing data environment,
16996           // that is legal.
16997           IsEnclosedByDataEnvironmentExpr = true;
16998           return false;
16999         }
17000 
17001         QualType DerivedType =
17002             std::prev(CI)->getAssociatedDeclaration()->getType();
17003         SourceLocation DerivedLoc =
17004             std::prev(CI)->getAssociatedExpression()->getExprLoc();
17005 
17006         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
17007         //  If the type of a list item is a reference to a type T then the type
17008         //  will be considered to be T for all purposes of this clause.
17009         DerivedType = DerivedType.getNonReferenceType();
17010 
17011         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.1]
17012         //  A variable for which the type is pointer and an array section
17013         //  derived from that variable must not appear as list items of map
17014         //  clauses of the same construct.
17015         //
17016         // Also, cover one of the cases in:
17017         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
17018         //  If any part of the original storage of a list item has corresponding
17019         //  storage in the device data environment, all of the original storage
17020         //  must have corresponding storage in the device data environment.
17021         //
17022         if (DerivedType->isAnyPointerType()) {
17023           if (CI == CE || SI == SE) {
17024             SemaRef.Diag(
17025                 DerivedLoc,
17026                 diag::err_omp_pointer_mapped_along_with_derived_section)
17027                 << DerivedLoc;
17028             SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
17029                 << RE->getSourceRange();
17030             return true;
17031           }
17032           if (CI->getAssociatedExpression()->getStmtClass() !=
17033                          SI->getAssociatedExpression()->getStmtClass() ||
17034                      CI->getAssociatedDeclaration()->getCanonicalDecl() ==
17035                          SI->getAssociatedDeclaration()->getCanonicalDecl()) {
17036             assert(CI != CE && SI != SE);
17037             SemaRef.Diag(DerivedLoc, diag::err_omp_same_pointer_dereferenced)
17038                 << DerivedLoc;
17039             SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
17040                 << RE->getSourceRange();
17041             return true;
17042           }
17043         }
17044 
17045         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
17046         //  List items of map clauses in the same construct must not share
17047         //  original storage.
17048         //
17049         // An expression is a subset of the other.
17050         if (CurrentRegionOnly && (CI == CE || SI == SE)) {
17051           if (CKind == OMPC_map) {
17052             if (CI != CE || SI != SE) {
17053               // Allow constructs like this: map(s, s.ptr[0:1]), where s.ptr is
17054               // a pointer.
17055               auto Begin =
17056                   CI != CE ? CurComponents.begin() : StackComponents.begin();
17057               auto End = CI != CE ? CurComponents.end() : StackComponents.end();
17058               auto It = Begin;
17059               while (It != End && !It->getAssociatedDeclaration())
17060                 std::advance(It, 1);
17061               assert(It != End &&
17062                      "Expected at least one component with the declaration.");
17063               if (It != Begin && It->getAssociatedDeclaration()
17064                                      ->getType()
17065                                      .getCanonicalType()
17066                                      ->isAnyPointerType()) {
17067                 IsEnclosedByDataEnvironmentExpr = false;
17068                 EnclosingExpr = nullptr;
17069                 return false;
17070               }
17071             }
17072             SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
17073           } else {
17074             assert(CKind == OMPC_to || CKind == OMPC_from);
17075             SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
17076                 << ERange;
17077           }
17078           SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
17079               << RE->getSourceRange();
17080           return true;
17081         }
17082 
17083         // The current expression uses the same base as other expression in the
17084         // data environment but does not contain it completely.
17085         if (!CurrentRegionOnly && SI != SE)
17086           EnclosingExpr = RE;
17087 
17088         // The current expression is a subset of the expression in the data
17089         // environment.
17090         IsEnclosedByDataEnvironmentExpr |=
17091             (!CurrentRegionOnly && CI != CE && SI == SE);
17092 
17093         return false;
17094       });
17095 
17096   if (CurrentRegionOnly)
17097     return FoundError;
17098 
17099   // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
17100   //  If any part of the original storage of a list item has corresponding
17101   //  storage in the device data environment, all of the original storage must
17102   //  have corresponding storage in the device data environment.
17103   // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.6]
17104   //  If a list item is an element of a structure, and a different element of
17105   //  the structure has a corresponding list item in the device data environment
17106   //  prior to a task encountering the construct associated with the map clause,
17107   //  then the list item must also have a corresponding list item in the device
17108   //  data environment prior to the task encountering the construct.
17109   //
17110   if (EnclosingExpr && !IsEnclosedByDataEnvironmentExpr) {
17111     SemaRef.Diag(ELoc,
17112                  diag::err_omp_original_storage_is_shared_and_does_not_contain)
17113         << ERange;
17114     SemaRef.Diag(EnclosingExpr->getExprLoc(), diag::note_used_here)
17115         << EnclosingExpr->getSourceRange();
17116     return true;
17117   }
17118 
17119   return FoundError;
17120 }
17121 
17122 // Look up the user-defined mapper given the mapper name and mapped type, and
17123 // build a reference to it.
17124 static ExprResult buildUserDefinedMapperRef(Sema &SemaRef, Scope *S,
17125                                             CXXScopeSpec &MapperIdScopeSpec,
17126                                             const DeclarationNameInfo &MapperId,
17127                                             QualType Type,
17128                                             Expr *UnresolvedMapper) {
17129   if (MapperIdScopeSpec.isInvalid())
17130     return ExprError();
17131   // Get the actual type for the array type.
17132   if (Type->isArrayType()) {
17133     assert(Type->getAsArrayTypeUnsafe() && "Expect to get a valid array type");
17134     Type = Type->getAsArrayTypeUnsafe()->getElementType().getCanonicalType();
17135   }
17136   // Find all user-defined mappers with the given MapperId.
17137   SmallVector<UnresolvedSet<8>, 4> Lookups;
17138   LookupResult Lookup(SemaRef, MapperId, Sema::LookupOMPMapperName);
17139   Lookup.suppressDiagnostics();
17140   if (S) {
17141     while (S && SemaRef.LookupParsedName(Lookup, S, &MapperIdScopeSpec)) {
17142       NamedDecl *D = Lookup.getRepresentativeDecl();
17143       while (S && !S->isDeclScope(D))
17144         S = S->getParent();
17145       if (S)
17146         S = S->getParent();
17147       Lookups.emplace_back();
17148       Lookups.back().append(Lookup.begin(), Lookup.end());
17149       Lookup.clear();
17150     }
17151   } else if (auto *ULE = cast_or_null<UnresolvedLookupExpr>(UnresolvedMapper)) {
17152     // Extract the user-defined mappers with the given MapperId.
17153     Lookups.push_back(UnresolvedSet<8>());
17154     for (NamedDecl *D : ULE->decls()) {
17155       auto *DMD = cast<OMPDeclareMapperDecl>(D);
17156       assert(DMD && "Expect valid OMPDeclareMapperDecl during instantiation.");
17157       Lookups.back().addDecl(DMD);
17158     }
17159   }
17160   // Defer the lookup for dependent types. The results will be passed through
17161   // UnresolvedMapper on instantiation.
17162   if (SemaRef.CurContext->isDependentContext() || Type->isDependentType() ||
17163       Type->isInstantiationDependentType() ||
17164       Type->containsUnexpandedParameterPack() ||
17165       filterLookupForUDReductionAndMapper<bool>(Lookups, [](ValueDecl *D) {
17166         return !D->isInvalidDecl() &&
17167                (D->getType()->isDependentType() ||
17168                 D->getType()->isInstantiationDependentType() ||
17169                 D->getType()->containsUnexpandedParameterPack());
17170       })) {
17171     UnresolvedSet<8> URS;
17172     for (const UnresolvedSet<8> &Set : Lookups) {
17173       if (Set.empty())
17174         continue;
17175       URS.append(Set.begin(), Set.end());
17176     }
17177     return UnresolvedLookupExpr::Create(
17178         SemaRef.Context, /*NamingClass=*/nullptr,
17179         MapperIdScopeSpec.getWithLocInContext(SemaRef.Context), MapperId,
17180         /*ADL=*/false, /*Overloaded=*/true, URS.begin(), URS.end());
17181   }
17182   SourceLocation Loc = MapperId.getLoc();
17183   // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
17184   //  The type must be of struct, union or class type in C and C++
17185   if (!Type->isStructureOrClassType() && !Type->isUnionType() &&
17186       (MapperIdScopeSpec.isSet() || MapperId.getAsString() != "default")) {
17187     SemaRef.Diag(Loc, diag::err_omp_mapper_wrong_type);
17188     return ExprError();
17189   }
17190   // Perform argument dependent lookup.
17191   if (SemaRef.getLangOpts().CPlusPlus && !MapperIdScopeSpec.isSet())
17192     argumentDependentLookup(SemaRef, MapperId, Loc, Type, Lookups);
17193   // Return the first user-defined mapper with the desired type.
17194   if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
17195           Lookups, [&SemaRef, Type](ValueDecl *D) -> ValueDecl * {
17196             if (!D->isInvalidDecl() &&
17197                 SemaRef.Context.hasSameType(D->getType(), Type))
17198               return D;
17199             return nullptr;
17200           }))
17201     return SemaRef.BuildDeclRefExpr(VD, Type, VK_LValue, Loc);
17202   // Find the first user-defined mapper with a type derived from the desired
17203   // type.
17204   if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
17205           Lookups, [&SemaRef, Type, Loc](ValueDecl *D) -> ValueDecl * {
17206             if (!D->isInvalidDecl() &&
17207                 SemaRef.IsDerivedFrom(Loc, Type, D->getType()) &&
17208                 !Type.isMoreQualifiedThan(D->getType()))
17209               return D;
17210             return nullptr;
17211           })) {
17212     CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
17213                        /*DetectVirtual=*/false);
17214     if (SemaRef.IsDerivedFrom(Loc, Type, VD->getType(), Paths)) {
17215       if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
17216               VD->getType().getUnqualifiedType()))) {
17217         if (SemaRef.CheckBaseClassAccess(
17218                 Loc, VD->getType(), Type, Paths.front(),
17219                 /*DiagID=*/0) != Sema::AR_inaccessible) {
17220           return SemaRef.BuildDeclRefExpr(VD, Type, VK_LValue, Loc);
17221         }
17222       }
17223     }
17224   }
17225   // Report error if a mapper is specified, but cannot be found.
17226   if (MapperIdScopeSpec.isSet() || MapperId.getAsString() != "default") {
17227     SemaRef.Diag(Loc, diag::err_omp_invalid_mapper)
17228         << Type << MapperId.getName();
17229     return ExprError();
17230   }
17231   return ExprEmpty();
17232 }
17233 
17234 namespace {
17235 // Utility struct that gathers all the related lists associated with a mappable
17236 // expression.
17237 struct MappableVarListInfo {
17238   // The list of expressions.
17239   ArrayRef<Expr *> VarList;
17240   // The list of processed expressions.
17241   SmallVector<Expr *, 16> ProcessedVarList;
17242   // The mappble components for each expression.
17243   OMPClauseMappableExprCommon::MappableExprComponentLists VarComponents;
17244   // The base declaration of the variable.
17245   SmallVector<ValueDecl *, 16> VarBaseDeclarations;
17246   // The reference to the user-defined mapper associated with every expression.
17247   SmallVector<Expr *, 16> UDMapperList;
17248 
17249   MappableVarListInfo(ArrayRef<Expr *> VarList) : VarList(VarList) {
17250     // We have a list of components and base declarations for each entry in the
17251     // variable list.
17252     VarComponents.reserve(VarList.size());
17253     VarBaseDeclarations.reserve(VarList.size());
17254   }
17255 };
17256 }
17257 
17258 // Check the validity of the provided variable list for the provided clause kind
17259 // \a CKind. In the check process the valid expressions, mappable expression
17260 // components, variables, and user-defined mappers are extracted and used to
17261 // fill \a ProcessedVarList, \a VarComponents, \a VarBaseDeclarations, and \a
17262 // UDMapperList in MVLI. \a MapType, \a IsMapTypeImplicit, \a MapperIdScopeSpec,
17263 // and \a MapperId are expected to be valid if the clause kind is 'map'.
17264 static void checkMappableExpressionList(
17265     Sema &SemaRef, DSAStackTy *DSAS, OpenMPClauseKind CKind,
17266     MappableVarListInfo &MVLI, SourceLocation StartLoc,
17267     CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo MapperId,
17268     ArrayRef<Expr *> UnresolvedMappers,
17269     OpenMPMapClauseKind MapType = OMPC_MAP_unknown,
17270     bool IsMapTypeImplicit = false) {
17271   // We only expect mappable expressions in 'to', 'from', and 'map' clauses.
17272   assert((CKind == OMPC_map || CKind == OMPC_to || CKind == OMPC_from) &&
17273          "Unexpected clause kind with mappable expressions!");
17274 
17275   // If the identifier of user-defined mapper is not specified, it is "default".
17276   // We do not change the actual name in this clause to distinguish whether a
17277   // mapper is specified explicitly, i.e., it is not explicitly specified when
17278   // MapperId.getName() is empty.
17279   if (!MapperId.getName() || MapperId.getName().isEmpty()) {
17280     auto &DeclNames = SemaRef.getASTContext().DeclarationNames;
17281     MapperId.setName(DeclNames.getIdentifier(
17282         &SemaRef.getASTContext().Idents.get("default")));
17283   }
17284 
17285   // Iterators to find the current unresolved mapper expression.
17286   auto UMIt = UnresolvedMappers.begin(), UMEnd = UnresolvedMappers.end();
17287   bool UpdateUMIt = false;
17288   Expr *UnresolvedMapper = nullptr;
17289 
17290   // Keep track of the mappable components and base declarations in this clause.
17291   // Each entry in the list is going to have a list of components associated. We
17292   // record each set of the components so that we can build the clause later on.
17293   // In the end we should have the same amount of declarations and component
17294   // lists.
17295 
17296   for (Expr *RE : MVLI.VarList) {
17297     assert(RE && "Null expr in omp to/from/map clause");
17298     SourceLocation ELoc = RE->getExprLoc();
17299 
17300     // Find the current unresolved mapper expression.
17301     if (UpdateUMIt && UMIt != UMEnd) {
17302       UMIt++;
17303       assert(
17304           UMIt != UMEnd &&
17305           "Expect the size of UnresolvedMappers to match with that of VarList");
17306     }
17307     UpdateUMIt = true;
17308     if (UMIt != UMEnd)
17309       UnresolvedMapper = *UMIt;
17310 
17311     const Expr *VE = RE->IgnoreParenLValueCasts();
17312 
17313     if (VE->isValueDependent() || VE->isTypeDependent() ||
17314         VE->isInstantiationDependent() ||
17315         VE->containsUnexpandedParameterPack()) {
17316       // Try to find the associated user-defined mapper.
17317       ExprResult ER = buildUserDefinedMapperRef(
17318           SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
17319           VE->getType().getCanonicalType(), UnresolvedMapper);
17320       if (ER.isInvalid())
17321         continue;
17322       MVLI.UDMapperList.push_back(ER.get());
17323       // We can only analyze this information once the missing information is
17324       // resolved.
17325       MVLI.ProcessedVarList.push_back(RE);
17326       continue;
17327     }
17328 
17329     Expr *SimpleExpr = RE->IgnoreParenCasts();
17330 
17331     if (!RE->isLValue()) {
17332       if (SemaRef.getLangOpts().OpenMP < 50) {
17333         SemaRef.Diag(
17334             ELoc, diag::err_omp_expected_named_var_member_or_array_expression)
17335             << RE->getSourceRange();
17336       } else {
17337         SemaRef.Diag(ELoc, diag::err_omp_non_lvalue_in_map_or_motion_clauses)
17338             << getOpenMPClauseName(CKind) << RE->getSourceRange();
17339       }
17340       continue;
17341     }
17342 
17343     OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
17344     ValueDecl *CurDeclaration = nullptr;
17345 
17346     // Obtain the array or member expression bases if required. Also, fill the
17347     // components array with all the components identified in the process.
17348     const Expr *BE = checkMapClauseExpressionBase(
17349         SemaRef, SimpleExpr, CurComponents, CKind, /*NoDiagnose=*/false);
17350     if (!BE)
17351       continue;
17352 
17353     assert(!CurComponents.empty() &&
17354            "Invalid mappable expression information.");
17355 
17356     if (const auto *TE = dyn_cast<CXXThisExpr>(BE)) {
17357       // Add store "this" pointer to class in DSAStackTy for future checking
17358       DSAS->addMappedClassesQualTypes(TE->getType());
17359       // Try to find the associated user-defined mapper.
17360       ExprResult ER = buildUserDefinedMapperRef(
17361           SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
17362           VE->getType().getCanonicalType(), UnresolvedMapper);
17363       if (ER.isInvalid())
17364         continue;
17365       MVLI.UDMapperList.push_back(ER.get());
17366       // Skip restriction checking for variable or field declarations
17367       MVLI.ProcessedVarList.push_back(RE);
17368       MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
17369       MVLI.VarComponents.back().append(CurComponents.begin(),
17370                                        CurComponents.end());
17371       MVLI.VarBaseDeclarations.push_back(nullptr);
17372       continue;
17373     }
17374 
17375     // For the following checks, we rely on the base declaration which is
17376     // expected to be associated with the last component. The declaration is
17377     // expected to be a variable or a field (if 'this' is being mapped).
17378     CurDeclaration = CurComponents.back().getAssociatedDeclaration();
17379     assert(CurDeclaration && "Null decl on map clause.");
17380     assert(
17381         CurDeclaration->isCanonicalDecl() &&
17382         "Expecting components to have associated only canonical declarations.");
17383 
17384     auto *VD = dyn_cast<VarDecl>(CurDeclaration);
17385     const auto *FD = dyn_cast<FieldDecl>(CurDeclaration);
17386 
17387     assert((VD || FD) && "Only variables or fields are expected here!");
17388     (void)FD;
17389 
17390     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.10]
17391     // threadprivate variables cannot appear in a map clause.
17392     // OpenMP 4.5 [2.10.5, target update Construct]
17393     // threadprivate variables cannot appear in a from clause.
17394     if (VD && DSAS->isThreadPrivate(VD)) {
17395       DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false);
17396       SemaRef.Diag(ELoc, diag::err_omp_threadprivate_in_clause)
17397           << getOpenMPClauseName(CKind);
17398       reportOriginalDsa(SemaRef, DSAS, VD, DVar);
17399       continue;
17400     }
17401 
17402     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
17403     //  A list item cannot appear in both a map clause and a data-sharing
17404     //  attribute clause on the same construct.
17405 
17406     // Check conflicts with other map clause expressions. We check the conflicts
17407     // with the current construct separately from the enclosing data
17408     // environment, because the restrictions are different. We only have to
17409     // check conflicts across regions for the map clauses.
17410     if (checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
17411                           /*CurrentRegionOnly=*/true, CurComponents, CKind))
17412       break;
17413     if (CKind == OMPC_map &&
17414         checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
17415                           /*CurrentRegionOnly=*/false, CurComponents, CKind))
17416       break;
17417 
17418     // OpenMP 4.5 [2.10.5, target update Construct]
17419     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
17420     //  If the type of a list item is a reference to a type T then the type will
17421     //  be considered to be T for all purposes of this clause.
17422     auto I = llvm::find_if(
17423         CurComponents,
17424         [](const OMPClauseMappableExprCommon::MappableComponent &MC) {
17425           return MC.getAssociatedDeclaration();
17426         });
17427     assert(I != CurComponents.end() && "Null decl on map clause.");
17428     QualType Type;
17429     auto *ASE = dyn_cast<ArraySubscriptExpr>(VE->IgnoreParens());
17430     auto *OASE = dyn_cast<OMPArraySectionExpr>(VE->IgnoreParens());
17431     auto *OAShE = dyn_cast<OMPArrayShapingExpr>(VE->IgnoreParens());
17432     if (ASE) {
17433       Type = ASE->getType().getNonReferenceType();
17434     } else if (OASE) {
17435       QualType BaseType =
17436           OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
17437       if (const auto *ATy = BaseType->getAsArrayTypeUnsafe())
17438         Type = ATy->getElementType();
17439       else
17440         Type = BaseType->getPointeeType();
17441       Type = Type.getNonReferenceType();
17442     } else if (OAShE) {
17443       Type = OAShE->getBase()->getType()->getPointeeType();
17444     } else {
17445       Type = VE->getType();
17446     }
17447 
17448     // OpenMP 4.5 [2.10.5, target update Construct, Restrictions, p.4]
17449     // A list item in a to or from clause must have a mappable type.
17450     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
17451     //  A list item must have a mappable type.
17452     if (!checkTypeMappable(VE->getExprLoc(), VE->getSourceRange(), SemaRef,
17453                            DSAS, Type))
17454       continue;
17455 
17456     Type = I->getAssociatedDeclaration()->getType().getNonReferenceType();
17457 
17458     if (CKind == OMPC_map) {
17459       // target enter data
17460       // OpenMP [2.10.2, Restrictions, p. 99]
17461       // A map-type must be specified in all map clauses and must be either
17462       // to or alloc.
17463       OpenMPDirectiveKind DKind = DSAS->getCurrentDirective();
17464       if (DKind == OMPD_target_enter_data &&
17465           !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_alloc)) {
17466         SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
17467             << (IsMapTypeImplicit ? 1 : 0)
17468             << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
17469             << getOpenMPDirectiveName(DKind);
17470         continue;
17471       }
17472 
17473       // target exit_data
17474       // OpenMP [2.10.3, Restrictions, p. 102]
17475       // A map-type must be specified in all map clauses and must be either
17476       // from, release, or delete.
17477       if (DKind == OMPD_target_exit_data &&
17478           !(MapType == OMPC_MAP_from || MapType == OMPC_MAP_release ||
17479             MapType == OMPC_MAP_delete)) {
17480         SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
17481             << (IsMapTypeImplicit ? 1 : 0)
17482             << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
17483             << getOpenMPDirectiveName(DKind);
17484         continue;
17485       }
17486 
17487       // target, target data
17488       // OpenMP 5.0 [2.12.2, Restrictions, p. 163]
17489       // OpenMP 5.0 [2.12.5, Restrictions, p. 174]
17490       // A map-type in a map clause must be to, from, tofrom or alloc
17491       if ((DKind == OMPD_target_data ||
17492            isOpenMPTargetExecutionDirective(DKind)) &&
17493           !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_from ||
17494             MapType == OMPC_MAP_tofrom || MapType == OMPC_MAP_alloc)) {
17495         SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
17496             << (IsMapTypeImplicit ? 1 : 0)
17497             << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
17498             << getOpenMPDirectiveName(DKind);
17499         continue;
17500       }
17501 
17502       // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
17503       // A list item cannot appear in both a map clause and a data-sharing
17504       // attribute clause on the same construct
17505       //
17506       // OpenMP 5.0 [2.19.7.1, Restrictions, p.7]
17507       // A list item cannot appear in both a map clause and a data-sharing
17508       // attribute clause on the same construct unless the construct is a
17509       // combined construct.
17510       if (VD && ((SemaRef.LangOpts.OpenMP <= 45 &&
17511                   isOpenMPTargetExecutionDirective(DKind)) ||
17512                  DKind == OMPD_target)) {
17513         DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false);
17514         if (isOpenMPPrivate(DVar.CKind)) {
17515           SemaRef.Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
17516               << getOpenMPClauseName(DVar.CKind)
17517               << getOpenMPClauseName(OMPC_map)
17518               << getOpenMPDirectiveName(DSAS->getCurrentDirective());
17519           reportOriginalDsa(SemaRef, DSAS, CurDeclaration, DVar);
17520           continue;
17521         }
17522       }
17523     }
17524 
17525     // Try to find the associated user-defined mapper.
17526     ExprResult ER = buildUserDefinedMapperRef(
17527         SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
17528         Type.getCanonicalType(), UnresolvedMapper);
17529     if (ER.isInvalid())
17530       continue;
17531     MVLI.UDMapperList.push_back(ER.get());
17532 
17533     // Save the current expression.
17534     MVLI.ProcessedVarList.push_back(RE);
17535 
17536     // Store the components in the stack so that they can be used to check
17537     // against other clauses later on.
17538     DSAS->addMappableExpressionComponents(CurDeclaration, CurComponents,
17539                                           /*WhereFoundClauseKind=*/OMPC_map);
17540 
17541     // Save the components and declaration to create the clause. For purposes of
17542     // the clause creation, any component list that has has base 'this' uses
17543     // null as base declaration.
17544     MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
17545     MVLI.VarComponents.back().append(CurComponents.begin(),
17546                                      CurComponents.end());
17547     MVLI.VarBaseDeclarations.push_back(isa<MemberExpr>(BE) ? nullptr
17548                                                            : CurDeclaration);
17549   }
17550 }
17551 
17552 OMPClause *Sema::ActOnOpenMPMapClause(
17553     ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
17554     ArrayRef<SourceLocation> MapTypeModifiersLoc,
17555     CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo &MapperId,
17556     OpenMPMapClauseKind MapType, bool IsMapTypeImplicit, SourceLocation MapLoc,
17557     SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
17558     const OMPVarListLocTy &Locs, ArrayRef<Expr *> UnresolvedMappers) {
17559   OpenMPMapModifierKind Modifiers[] = {OMPC_MAP_MODIFIER_unknown,
17560                                        OMPC_MAP_MODIFIER_unknown,
17561                                        OMPC_MAP_MODIFIER_unknown};
17562   SourceLocation ModifiersLoc[NumberOfOMPMapClauseModifiers];
17563 
17564   // Process map-type-modifiers, flag errors for duplicate modifiers.
17565   unsigned Count = 0;
17566   for (unsigned I = 0, E = MapTypeModifiers.size(); I < E; ++I) {
17567     if (MapTypeModifiers[I] != OMPC_MAP_MODIFIER_unknown &&
17568         llvm::find(Modifiers, MapTypeModifiers[I]) != std::end(Modifiers)) {
17569       Diag(MapTypeModifiersLoc[I], diag::err_omp_duplicate_map_type_modifier);
17570       continue;
17571     }
17572     assert(Count < NumberOfOMPMapClauseModifiers &&
17573            "Modifiers exceed the allowed number of map type modifiers");
17574     Modifiers[Count] = MapTypeModifiers[I];
17575     ModifiersLoc[Count] = MapTypeModifiersLoc[I];
17576     ++Count;
17577   }
17578 
17579   MappableVarListInfo MVLI(VarList);
17580   checkMappableExpressionList(*this, DSAStack, OMPC_map, MVLI, Locs.StartLoc,
17581                               MapperIdScopeSpec, MapperId, UnresolvedMappers,
17582                               MapType, IsMapTypeImplicit);
17583 
17584   // We need to produce a map clause even if we don't have variables so that
17585   // other diagnostics related with non-existing map clauses are accurate.
17586   return OMPMapClause::Create(Context, Locs, MVLI.ProcessedVarList,
17587                               MVLI.VarBaseDeclarations, MVLI.VarComponents,
17588                               MVLI.UDMapperList, Modifiers, ModifiersLoc,
17589                               MapperIdScopeSpec.getWithLocInContext(Context),
17590                               MapperId, MapType, IsMapTypeImplicit, MapLoc);
17591 }
17592 
17593 QualType Sema::ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
17594                                                TypeResult ParsedType) {
17595   assert(ParsedType.isUsable());
17596 
17597   QualType ReductionType = GetTypeFromParser(ParsedType.get());
17598   if (ReductionType.isNull())
17599     return QualType();
17600 
17601   // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions, C\C++
17602   // A type name in a declare reduction directive cannot be a function type, an
17603   // array type, a reference type, or a type qualified with const, volatile or
17604   // restrict.
17605   if (ReductionType.hasQualifiers()) {
17606     Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 0;
17607     return QualType();
17608   }
17609 
17610   if (ReductionType->isFunctionType()) {
17611     Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 1;
17612     return QualType();
17613   }
17614   if (ReductionType->isReferenceType()) {
17615     Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 2;
17616     return QualType();
17617   }
17618   if (ReductionType->isArrayType()) {
17619     Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 3;
17620     return QualType();
17621   }
17622   return ReductionType;
17623 }
17624 
17625 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveStart(
17626     Scope *S, DeclContext *DC, DeclarationName Name,
17627     ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
17628     AccessSpecifier AS, Decl *PrevDeclInScope) {
17629   SmallVector<Decl *, 8> Decls;
17630   Decls.reserve(ReductionTypes.size());
17631 
17632   LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPReductionName,
17633                       forRedeclarationInCurContext());
17634   // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
17635   // A reduction-identifier may not be re-declared in the current scope for the
17636   // same type or for a type that is compatible according to the base language
17637   // rules.
17638   llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
17639   OMPDeclareReductionDecl *PrevDRD = nullptr;
17640   bool InCompoundScope = true;
17641   if (S != nullptr) {
17642     // Find previous declaration with the same name not referenced in other
17643     // declarations.
17644     FunctionScopeInfo *ParentFn = getEnclosingFunction();
17645     InCompoundScope =
17646         (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
17647     LookupName(Lookup, S);
17648     FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
17649                          /*AllowInlineNamespace=*/false);
17650     llvm::DenseMap<OMPDeclareReductionDecl *, bool> UsedAsPrevious;
17651     LookupResult::Filter Filter = Lookup.makeFilter();
17652     while (Filter.hasNext()) {
17653       auto *PrevDecl = cast<OMPDeclareReductionDecl>(Filter.next());
17654       if (InCompoundScope) {
17655         auto I = UsedAsPrevious.find(PrevDecl);
17656         if (I == UsedAsPrevious.end())
17657           UsedAsPrevious[PrevDecl] = false;
17658         if (OMPDeclareReductionDecl *D = PrevDecl->getPrevDeclInScope())
17659           UsedAsPrevious[D] = true;
17660       }
17661       PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
17662           PrevDecl->getLocation();
17663     }
17664     Filter.done();
17665     if (InCompoundScope) {
17666       for (const auto &PrevData : UsedAsPrevious) {
17667         if (!PrevData.second) {
17668           PrevDRD = PrevData.first;
17669           break;
17670         }
17671       }
17672     }
17673   } else if (PrevDeclInScope != nullptr) {
17674     auto *PrevDRDInScope = PrevDRD =
17675         cast<OMPDeclareReductionDecl>(PrevDeclInScope);
17676     do {
17677       PreviousRedeclTypes[PrevDRDInScope->getType().getCanonicalType()] =
17678           PrevDRDInScope->getLocation();
17679       PrevDRDInScope = PrevDRDInScope->getPrevDeclInScope();
17680     } while (PrevDRDInScope != nullptr);
17681   }
17682   for (const auto &TyData : ReductionTypes) {
17683     const auto I = PreviousRedeclTypes.find(TyData.first.getCanonicalType());
17684     bool Invalid = false;
17685     if (I != PreviousRedeclTypes.end()) {
17686       Diag(TyData.second, diag::err_omp_declare_reduction_redefinition)
17687           << TyData.first;
17688       Diag(I->second, diag::note_previous_definition);
17689       Invalid = true;
17690     }
17691     PreviousRedeclTypes[TyData.first.getCanonicalType()] = TyData.second;
17692     auto *DRD = OMPDeclareReductionDecl::Create(Context, DC, TyData.second,
17693                                                 Name, TyData.first, PrevDRD);
17694     DC->addDecl(DRD);
17695     DRD->setAccess(AS);
17696     Decls.push_back(DRD);
17697     if (Invalid)
17698       DRD->setInvalidDecl();
17699     else
17700       PrevDRD = DRD;
17701   }
17702 
17703   return DeclGroupPtrTy::make(
17704       DeclGroupRef::Create(Context, Decls.begin(), Decls.size()));
17705 }
17706 
17707 void Sema::ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D) {
17708   auto *DRD = cast<OMPDeclareReductionDecl>(D);
17709 
17710   // Enter new function scope.
17711   PushFunctionScope();
17712   setFunctionHasBranchProtectedScope();
17713   getCurFunction()->setHasOMPDeclareReductionCombiner();
17714 
17715   if (S != nullptr)
17716     PushDeclContext(S, DRD);
17717   else
17718     CurContext = DRD;
17719 
17720   PushExpressionEvaluationContext(
17721       ExpressionEvaluationContext::PotentiallyEvaluated);
17722 
17723   QualType ReductionType = DRD->getType();
17724   // Create 'T* omp_parm;T omp_in;'. All references to 'omp_in' will
17725   // be replaced by '*omp_parm' during codegen. This required because 'omp_in'
17726   // uses semantics of argument handles by value, but it should be passed by
17727   // reference. C lang does not support references, so pass all parameters as
17728   // pointers.
17729   // Create 'T omp_in;' variable.
17730   VarDecl *OmpInParm =
17731       buildVarDecl(*this, D->getLocation(), ReductionType, "omp_in");
17732   // Create 'T* omp_parm;T omp_out;'. All references to 'omp_out' will
17733   // be replaced by '*omp_parm' during codegen. This required because 'omp_out'
17734   // uses semantics of argument handles by value, but it should be passed by
17735   // reference. C lang does not support references, so pass all parameters as
17736   // pointers.
17737   // Create 'T omp_out;' variable.
17738   VarDecl *OmpOutParm =
17739       buildVarDecl(*this, D->getLocation(), ReductionType, "omp_out");
17740   if (S != nullptr) {
17741     PushOnScopeChains(OmpInParm, S);
17742     PushOnScopeChains(OmpOutParm, S);
17743   } else {
17744     DRD->addDecl(OmpInParm);
17745     DRD->addDecl(OmpOutParm);
17746   }
17747   Expr *InE =
17748       ::buildDeclRefExpr(*this, OmpInParm, ReductionType, D->getLocation());
17749   Expr *OutE =
17750       ::buildDeclRefExpr(*this, OmpOutParm, ReductionType, D->getLocation());
17751   DRD->setCombinerData(InE, OutE);
17752 }
17753 
17754 void Sema::ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner) {
17755   auto *DRD = cast<OMPDeclareReductionDecl>(D);
17756   DiscardCleanupsInEvaluationContext();
17757   PopExpressionEvaluationContext();
17758 
17759   PopDeclContext();
17760   PopFunctionScopeInfo();
17761 
17762   if (Combiner != nullptr)
17763     DRD->setCombiner(Combiner);
17764   else
17765     DRD->setInvalidDecl();
17766 }
17767 
17768 VarDecl *Sema::ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D) {
17769   auto *DRD = cast<OMPDeclareReductionDecl>(D);
17770 
17771   // Enter new function scope.
17772   PushFunctionScope();
17773   setFunctionHasBranchProtectedScope();
17774 
17775   if (S != nullptr)
17776     PushDeclContext(S, DRD);
17777   else
17778     CurContext = DRD;
17779 
17780   PushExpressionEvaluationContext(
17781       ExpressionEvaluationContext::PotentiallyEvaluated);
17782 
17783   QualType ReductionType = DRD->getType();
17784   // Create 'T* omp_parm;T omp_priv;'. All references to 'omp_priv' will
17785   // be replaced by '*omp_parm' during codegen. This required because 'omp_priv'
17786   // uses semantics of argument handles by value, but it should be passed by
17787   // reference. C lang does not support references, so pass all parameters as
17788   // pointers.
17789   // Create 'T omp_priv;' variable.
17790   VarDecl *OmpPrivParm =
17791       buildVarDecl(*this, D->getLocation(), ReductionType, "omp_priv");
17792   // Create 'T* omp_parm;T omp_orig;'. All references to 'omp_orig' will
17793   // be replaced by '*omp_parm' during codegen. This required because 'omp_orig'
17794   // uses semantics of argument handles by value, but it should be passed by
17795   // reference. C lang does not support references, so pass all parameters as
17796   // pointers.
17797   // Create 'T omp_orig;' variable.
17798   VarDecl *OmpOrigParm =
17799       buildVarDecl(*this, D->getLocation(), ReductionType, "omp_orig");
17800   if (S != nullptr) {
17801     PushOnScopeChains(OmpPrivParm, S);
17802     PushOnScopeChains(OmpOrigParm, S);
17803   } else {
17804     DRD->addDecl(OmpPrivParm);
17805     DRD->addDecl(OmpOrigParm);
17806   }
17807   Expr *OrigE =
17808       ::buildDeclRefExpr(*this, OmpOrigParm, ReductionType, D->getLocation());
17809   Expr *PrivE =
17810       ::buildDeclRefExpr(*this, OmpPrivParm, ReductionType, D->getLocation());
17811   DRD->setInitializerData(OrigE, PrivE);
17812   return OmpPrivParm;
17813 }
17814 
17815 void Sema::ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer,
17816                                                      VarDecl *OmpPrivParm) {
17817   auto *DRD = cast<OMPDeclareReductionDecl>(D);
17818   DiscardCleanupsInEvaluationContext();
17819   PopExpressionEvaluationContext();
17820 
17821   PopDeclContext();
17822   PopFunctionScopeInfo();
17823 
17824   if (Initializer != nullptr) {
17825     DRD->setInitializer(Initializer, OMPDeclareReductionDecl::CallInit);
17826   } else if (OmpPrivParm->hasInit()) {
17827     DRD->setInitializer(OmpPrivParm->getInit(),
17828                         OmpPrivParm->isDirectInit()
17829                             ? OMPDeclareReductionDecl::DirectInit
17830                             : OMPDeclareReductionDecl::CopyInit);
17831   } else {
17832     DRD->setInvalidDecl();
17833   }
17834 }
17835 
17836 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveEnd(
17837     Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid) {
17838   for (Decl *D : DeclReductions.get()) {
17839     if (IsValid) {
17840       if (S)
17841         PushOnScopeChains(cast<OMPDeclareReductionDecl>(D), S,
17842                           /*AddToContext=*/false);
17843     } else {
17844       D->setInvalidDecl();
17845     }
17846   }
17847   return DeclReductions;
17848 }
17849 
17850 TypeResult Sema::ActOnOpenMPDeclareMapperVarDecl(Scope *S, Declarator &D) {
17851   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
17852   QualType T = TInfo->getType();
17853   if (D.isInvalidType())
17854     return true;
17855 
17856   if (getLangOpts().CPlusPlus) {
17857     // Check that there are no default arguments (C++ only).
17858     CheckExtraCXXDefaultArguments(D);
17859   }
17860 
17861   return CreateParsedType(T, TInfo);
17862 }
17863 
17864 QualType Sema::ActOnOpenMPDeclareMapperType(SourceLocation TyLoc,
17865                                             TypeResult ParsedType) {
17866   assert(ParsedType.isUsable() && "Expect usable parsed mapper type");
17867 
17868   QualType MapperType = GetTypeFromParser(ParsedType.get());
17869   assert(!MapperType.isNull() && "Expect valid mapper type");
17870 
17871   // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
17872   //  The type must be of struct, union or class type in C and C++
17873   if (!MapperType->isStructureOrClassType() && !MapperType->isUnionType()) {
17874     Diag(TyLoc, diag::err_omp_mapper_wrong_type);
17875     return QualType();
17876   }
17877   return MapperType;
17878 }
17879 
17880 OMPDeclareMapperDecl *Sema::ActOnOpenMPDeclareMapperDirectiveStart(
17881     Scope *S, DeclContext *DC, DeclarationName Name, QualType MapperType,
17882     SourceLocation StartLoc, DeclarationName VN, AccessSpecifier AS,
17883     Decl *PrevDeclInScope) {
17884   LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPMapperName,
17885                       forRedeclarationInCurContext());
17886   // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
17887   //  A mapper-identifier may not be redeclared in the current scope for the
17888   //  same type or for a type that is compatible according to the base language
17889   //  rules.
17890   llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
17891   OMPDeclareMapperDecl *PrevDMD = nullptr;
17892   bool InCompoundScope = true;
17893   if (S != nullptr) {
17894     // Find previous declaration with the same name not referenced in other
17895     // declarations.
17896     FunctionScopeInfo *ParentFn = getEnclosingFunction();
17897     InCompoundScope =
17898         (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
17899     LookupName(Lookup, S);
17900     FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
17901                          /*AllowInlineNamespace=*/false);
17902     llvm::DenseMap<OMPDeclareMapperDecl *, bool> UsedAsPrevious;
17903     LookupResult::Filter Filter = Lookup.makeFilter();
17904     while (Filter.hasNext()) {
17905       auto *PrevDecl = cast<OMPDeclareMapperDecl>(Filter.next());
17906       if (InCompoundScope) {
17907         auto I = UsedAsPrevious.find(PrevDecl);
17908         if (I == UsedAsPrevious.end())
17909           UsedAsPrevious[PrevDecl] = false;
17910         if (OMPDeclareMapperDecl *D = PrevDecl->getPrevDeclInScope())
17911           UsedAsPrevious[D] = true;
17912       }
17913       PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
17914           PrevDecl->getLocation();
17915     }
17916     Filter.done();
17917     if (InCompoundScope) {
17918       for (const auto &PrevData : UsedAsPrevious) {
17919         if (!PrevData.second) {
17920           PrevDMD = PrevData.first;
17921           break;
17922         }
17923       }
17924     }
17925   } else if (PrevDeclInScope) {
17926     auto *PrevDMDInScope = PrevDMD =
17927         cast<OMPDeclareMapperDecl>(PrevDeclInScope);
17928     do {
17929       PreviousRedeclTypes[PrevDMDInScope->getType().getCanonicalType()] =
17930           PrevDMDInScope->getLocation();
17931       PrevDMDInScope = PrevDMDInScope->getPrevDeclInScope();
17932     } while (PrevDMDInScope != nullptr);
17933   }
17934   const auto I = PreviousRedeclTypes.find(MapperType.getCanonicalType());
17935   bool Invalid = false;
17936   if (I != PreviousRedeclTypes.end()) {
17937     Diag(StartLoc, diag::err_omp_declare_mapper_redefinition)
17938         << MapperType << Name;
17939     Diag(I->second, diag::note_previous_definition);
17940     Invalid = true;
17941   }
17942   auto *DMD = OMPDeclareMapperDecl::Create(Context, DC, StartLoc, Name,
17943                                            MapperType, VN, PrevDMD);
17944   DC->addDecl(DMD);
17945   DMD->setAccess(AS);
17946   if (Invalid)
17947     DMD->setInvalidDecl();
17948 
17949   // Enter new function scope.
17950   PushFunctionScope();
17951   setFunctionHasBranchProtectedScope();
17952 
17953   CurContext = DMD;
17954 
17955   return DMD;
17956 }
17957 
17958 void Sema::ActOnOpenMPDeclareMapperDirectiveVarDecl(OMPDeclareMapperDecl *DMD,
17959                                                     Scope *S,
17960                                                     QualType MapperType,
17961                                                     SourceLocation StartLoc,
17962                                                     DeclarationName VN) {
17963   VarDecl *VD = buildVarDecl(*this, StartLoc, MapperType, VN.getAsString());
17964   if (S)
17965     PushOnScopeChains(VD, S);
17966   else
17967     DMD->addDecl(VD);
17968   Expr *MapperVarRefExpr = buildDeclRefExpr(*this, VD, MapperType, StartLoc);
17969   DMD->setMapperVarRef(MapperVarRefExpr);
17970 }
17971 
17972 Sema::DeclGroupPtrTy
17973 Sema::ActOnOpenMPDeclareMapperDirectiveEnd(OMPDeclareMapperDecl *D, Scope *S,
17974                                            ArrayRef<OMPClause *> ClauseList) {
17975   PopDeclContext();
17976   PopFunctionScopeInfo();
17977 
17978   if (D) {
17979     if (S)
17980       PushOnScopeChains(D, S, /*AddToContext=*/false);
17981     D->CreateClauses(Context, ClauseList);
17982   }
17983 
17984   return DeclGroupPtrTy::make(DeclGroupRef(D));
17985 }
17986 
17987 OMPClause *Sema::ActOnOpenMPNumTeamsClause(Expr *NumTeams,
17988                                            SourceLocation StartLoc,
17989                                            SourceLocation LParenLoc,
17990                                            SourceLocation EndLoc) {
17991   Expr *ValExpr = NumTeams;
17992   Stmt *HelperValStmt = nullptr;
17993 
17994   // OpenMP [teams Constrcut, Restrictions]
17995   // The num_teams expression must evaluate to a positive integer value.
17996   if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_teams,
17997                                  /*StrictlyPositive=*/true))
17998     return nullptr;
17999 
18000   OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
18001   OpenMPDirectiveKind CaptureRegion =
18002       getOpenMPCaptureRegionForClause(DKind, OMPC_num_teams, LangOpts.OpenMP);
18003   if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
18004     ValExpr = MakeFullExpr(ValExpr).get();
18005     llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
18006     ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
18007     HelperValStmt = buildPreInits(Context, Captures);
18008   }
18009 
18010   return new (Context) OMPNumTeamsClause(ValExpr, HelperValStmt, CaptureRegion,
18011                                          StartLoc, LParenLoc, EndLoc);
18012 }
18013 
18014 OMPClause *Sema::ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
18015                                               SourceLocation StartLoc,
18016                                               SourceLocation LParenLoc,
18017                                               SourceLocation EndLoc) {
18018   Expr *ValExpr = ThreadLimit;
18019   Stmt *HelperValStmt = nullptr;
18020 
18021   // OpenMP [teams Constrcut, Restrictions]
18022   // The thread_limit expression must evaluate to a positive integer value.
18023   if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_thread_limit,
18024                                  /*StrictlyPositive=*/true))
18025     return nullptr;
18026 
18027   OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
18028   OpenMPDirectiveKind CaptureRegion = getOpenMPCaptureRegionForClause(
18029       DKind, OMPC_thread_limit, LangOpts.OpenMP);
18030   if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
18031     ValExpr = MakeFullExpr(ValExpr).get();
18032     llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
18033     ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
18034     HelperValStmt = buildPreInits(Context, Captures);
18035   }
18036 
18037   return new (Context) OMPThreadLimitClause(
18038       ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
18039 }
18040 
18041 OMPClause *Sema::ActOnOpenMPPriorityClause(Expr *Priority,
18042                                            SourceLocation StartLoc,
18043                                            SourceLocation LParenLoc,
18044                                            SourceLocation EndLoc) {
18045   Expr *ValExpr = Priority;
18046   Stmt *HelperValStmt = nullptr;
18047   OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
18048 
18049   // OpenMP [2.9.1, task Constrcut]
18050   // The priority-value is a non-negative numerical scalar expression.
18051   if (!isNonNegativeIntegerValue(
18052           ValExpr, *this, OMPC_priority,
18053           /*StrictlyPositive=*/false, /*BuildCapture=*/true,
18054           DSAStack->getCurrentDirective(), &CaptureRegion, &HelperValStmt))
18055     return nullptr;
18056 
18057   return new (Context) OMPPriorityClause(ValExpr, HelperValStmt, CaptureRegion,
18058                                          StartLoc, LParenLoc, EndLoc);
18059 }
18060 
18061 OMPClause *Sema::ActOnOpenMPGrainsizeClause(Expr *Grainsize,
18062                                             SourceLocation StartLoc,
18063                                             SourceLocation LParenLoc,
18064                                             SourceLocation EndLoc) {
18065   Expr *ValExpr = Grainsize;
18066   Stmt *HelperValStmt = nullptr;
18067   OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
18068 
18069   // OpenMP [2.9.2, taskloop Constrcut]
18070   // The parameter of the grainsize clause must be a positive integer
18071   // expression.
18072   if (!isNonNegativeIntegerValue(
18073           ValExpr, *this, OMPC_grainsize,
18074           /*StrictlyPositive=*/true, /*BuildCapture=*/true,
18075           DSAStack->getCurrentDirective(), &CaptureRegion, &HelperValStmt))
18076     return nullptr;
18077 
18078   return new (Context) OMPGrainsizeClause(ValExpr, HelperValStmt, CaptureRegion,
18079                                           StartLoc, LParenLoc, EndLoc);
18080 }
18081 
18082 OMPClause *Sema::ActOnOpenMPNumTasksClause(Expr *NumTasks,
18083                                            SourceLocation StartLoc,
18084                                            SourceLocation LParenLoc,
18085                                            SourceLocation EndLoc) {
18086   Expr *ValExpr = NumTasks;
18087   Stmt *HelperValStmt = nullptr;
18088   OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
18089 
18090   // OpenMP [2.9.2, taskloop Constrcut]
18091   // The parameter of the num_tasks clause must be a positive integer
18092   // expression.
18093   if (!isNonNegativeIntegerValue(
18094           ValExpr, *this, OMPC_num_tasks,
18095           /*StrictlyPositive=*/true, /*BuildCapture=*/true,
18096           DSAStack->getCurrentDirective(), &CaptureRegion, &HelperValStmt))
18097     return nullptr;
18098 
18099   return new (Context) OMPNumTasksClause(ValExpr, HelperValStmt, CaptureRegion,
18100                                          StartLoc, LParenLoc, EndLoc);
18101 }
18102 
18103 OMPClause *Sema::ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
18104                                        SourceLocation LParenLoc,
18105                                        SourceLocation EndLoc) {
18106   // OpenMP [2.13.2, critical construct, Description]
18107   // ... where hint-expression is an integer constant expression that evaluates
18108   // to a valid lock hint.
18109   ExprResult HintExpr = VerifyPositiveIntegerConstantInClause(Hint, OMPC_hint);
18110   if (HintExpr.isInvalid())
18111     return nullptr;
18112   return new (Context)
18113       OMPHintClause(HintExpr.get(), StartLoc, LParenLoc, EndLoc);
18114 }
18115 
18116 /// Tries to find omp_event_handle_t type.
18117 static bool findOMPEventHandleT(Sema &S, SourceLocation Loc,
18118                                 DSAStackTy *Stack) {
18119   QualType OMPEventHandleT = Stack->getOMPEventHandleT();
18120   if (!OMPEventHandleT.isNull())
18121     return true;
18122   IdentifierInfo *II = &S.PP.getIdentifierTable().get("omp_event_handle_t");
18123   ParsedType PT = S.getTypeName(*II, Loc, S.getCurScope());
18124   if (!PT.getAsOpaquePtr() || PT.get().isNull()) {
18125     S.Diag(Loc, diag::err_omp_implied_type_not_found) << "omp_event_handle_t";
18126     return false;
18127   }
18128   Stack->setOMPEventHandleT(PT.get());
18129   return true;
18130 }
18131 
18132 OMPClause *Sema::ActOnOpenMPDetachClause(Expr *Evt, SourceLocation StartLoc,
18133                                          SourceLocation LParenLoc,
18134                                          SourceLocation EndLoc) {
18135   if (!Evt->isValueDependent() && !Evt->isTypeDependent() &&
18136       !Evt->isInstantiationDependent() &&
18137       !Evt->containsUnexpandedParameterPack()) {
18138     if (!findOMPEventHandleT(*this, Evt->getExprLoc(), DSAStack))
18139       return nullptr;
18140     // OpenMP 5.0, 2.10.1 task Construct.
18141     // event-handle is a variable of the omp_event_handle_t type.
18142     auto *Ref = dyn_cast<DeclRefExpr>(Evt->IgnoreParenImpCasts());
18143     if (!Ref) {
18144       Diag(Evt->getExprLoc(), diag::err_omp_var_expected)
18145           << "omp_event_handle_t" << 0 << Evt->getSourceRange();
18146       return nullptr;
18147     }
18148     auto *VD = dyn_cast_or_null<VarDecl>(Ref->getDecl());
18149     if (!VD) {
18150       Diag(Evt->getExprLoc(), diag::err_omp_var_expected)
18151           << "omp_event_handle_t" << 0 << Evt->getSourceRange();
18152       return nullptr;
18153     }
18154     if (!Context.hasSameUnqualifiedType(DSAStack->getOMPEventHandleT(),
18155                                         VD->getType()) ||
18156         VD->getType().isConstant(Context)) {
18157       Diag(Evt->getExprLoc(), diag::err_omp_var_expected)
18158           << "omp_event_handle_t" << 1 << VD->getType()
18159           << Evt->getSourceRange();
18160       return nullptr;
18161     }
18162     // OpenMP 5.0, 2.10.1 task Construct
18163     // [detach clause]... The event-handle will be considered as if it was
18164     // specified on a firstprivate clause.
18165     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, /*FromParent=*/false);
18166     if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
18167         DVar.RefExpr) {
18168       Diag(Evt->getExprLoc(), diag::err_omp_wrong_dsa)
18169           << getOpenMPClauseName(DVar.CKind)
18170           << getOpenMPClauseName(OMPC_firstprivate);
18171       reportOriginalDsa(*this, DSAStack, VD, DVar);
18172       return nullptr;
18173     }
18174   }
18175 
18176   return new (Context) OMPDetachClause(Evt, StartLoc, LParenLoc, EndLoc);
18177 }
18178 
18179 OMPClause *Sema::ActOnOpenMPDistScheduleClause(
18180     OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
18181     SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc,
18182     SourceLocation EndLoc) {
18183   if (Kind == OMPC_DIST_SCHEDULE_unknown) {
18184     std::string Values;
18185     Values += "'";
18186     Values += getOpenMPSimpleClauseTypeName(OMPC_dist_schedule, 0);
18187     Values += "'";
18188     Diag(KindLoc, diag::err_omp_unexpected_clause_value)
18189         << Values << getOpenMPClauseName(OMPC_dist_schedule);
18190     return nullptr;
18191   }
18192   Expr *ValExpr = ChunkSize;
18193   Stmt *HelperValStmt = nullptr;
18194   if (ChunkSize) {
18195     if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
18196         !ChunkSize->isInstantiationDependent() &&
18197         !ChunkSize->containsUnexpandedParameterPack()) {
18198       SourceLocation ChunkSizeLoc = ChunkSize->getBeginLoc();
18199       ExprResult Val =
18200           PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
18201       if (Val.isInvalid())
18202         return nullptr;
18203 
18204       ValExpr = Val.get();
18205 
18206       // OpenMP [2.7.1, Restrictions]
18207       //  chunk_size must be a loop invariant integer expression with a positive
18208       //  value.
18209       llvm::APSInt Result;
18210       if (ValExpr->isIntegerConstantExpr(Result, Context)) {
18211         if (Result.isSigned() && !Result.isStrictlyPositive()) {
18212           Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
18213               << "dist_schedule" << ChunkSize->getSourceRange();
18214           return nullptr;
18215         }
18216       } else if (getOpenMPCaptureRegionForClause(
18217                      DSAStack->getCurrentDirective(), OMPC_dist_schedule,
18218                      LangOpts.OpenMP) != OMPD_unknown &&
18219                  !CurContext->isDependentContext()) {
18220         ValExpr = MakeFullExpr(ValExpr).get();
18221         llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
18222         ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
18223         HelperValStmt = buildPreInits(Context, Captures);
18224       }
18225     }
18226   }
18227 
18228   return new (Context)
18229       OMPDistScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc,
18230                             Kind, ValExpr, HelperValStmt);
18231 }
18232 
18233 OMPClause *Sema::ActOnOpenMPDefaultmapClause(
18234     OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
18235     SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
18236     SourceLocation KindLoc, SourceLocation EndLoc) {
18237   if (getLangOpts().OpenMP < 50) {
18238     if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom ||
18239         Kind != OMPC_DEFAULTMAP_scalar) {
18240       std::string Value;
18241       SourceLocation Loc;
18242       Value += "'";
18243       if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom) {
18244         Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
18245                                                OMPC_DEFAULTMAP_MODIFIER_tofrom);
18246         Loc = MLoc;
18247       } else {
18248         Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
18249                                                OMPC_DEFAULTMAP_scalar);
18250         Loc = KindLoc;
18251       }
18252       Value += "'";
18253       Diag(Loc, diag::err_omp_unexpected_clause_value)
18254           << Value << getOpenMPClauseName(OMPC_defaultmap);
18255       return nullptr;
18256     }
18257   } else {
18258     bool isDefaultmapModifier = (M != OMPC_DEFAULTMAP_MODIFIER_unknown);
18259     bool isDefaultmapKind = (Kind != OMPC_DEFAULTMAP_unknown) ||
18260                             (LangOpts.OpenMP >= 50 && KindLoc.isInvalid());
18261     if (!isDefaultmapKind || !isDefaultmapModifier) {
18262       std::string ModifierValue = "'alloc', 'from', 'to', 'tofrom', "
18263                                   "'firstprivate', 'none', 'default'";
18264       std::string KindValue = "'scalar', 'aggregate', 'pointer'";
18265       if (!isDefaultmapKind && isDefaultmapModifier) {
18266         Diag(KindLoc, diag::err_omp_unexpected_clause_value)
18267             << KindValue << getOpenMPClauseName(OMPC_defaultmap);
18268       } else if (isDefaultmapKind && !isDefaultmapModifier) {
18269         Diag(MLoc, diag::err_omp_unexpected_clause_value)
18270             << ModifierValue << getOpenMPClauseName(OMPC_defaultmap);
18271       } else {
18272         Diag(MLoc, diag::err_omp_unexpected_clause_value)
18273             << ModifierValue << getOpenMPClauseName(OMPC_defaultmap);
18274         Diag(KindLoc, diag::err_omp_unexpected_clause_value)
18275             << KindValue << getOpenMPClauseName(OMPC_defaultmap);
18276       }
18277       return nullptr;
18278     }
18279 
18280     // OpenMP [5.0, 2.12.5, Restrictions, p. 174]
18281     //  At most one defaultmap clause for each category can appear on the
18282     //  directive.
18283     if (DSAStack->checkDefaultmapCategory(Kind)) {
18284       Diag(StartLoc, diag::err_omp_one_defaultmap_each_category);
18285       return nullptr;
18286     }
18287   }
18288   if (Kind == OMPC_DEFAULTMAP_unknown) {
18289     // Variable category is not specified - mark all categories.
18290     DSAStack->setDefaultDMAAttr(M, OMPC_DEFAULTMAP_aggregate, StartLoc);
18291     DSAStack->setDefaultDMAAttr(M, OMPC_DEFAULTMAP_scalar, StartLoc);
18292     DSAStack->setDefaultDMAAttr(M, OMPC_DEFAULTMAP_pointer, StartLoc);
18293   } else {
18294     DSAStack->setDefaultDMAAttr(M, Kind, StartLoc);
18295   }
18296 
18297   return new (Context)
18298       OMPDefaultmapClause(StartLoc, LParenLoc, MLoc, KindLoc, EndLoc, Kind, M);
18299 }
18300 
18301 bool Sema::ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc) {
18302   DeclContext *CurLexicalContext = getCurLexicalContext();
18303   if (!CurLexicalContext->isFileContext() &&
18304       !CurLexicalContext->isExternCContext() &&
18305       !CurLexicalContext->isExternCXXContext() &&
18306       !isa<CXXRecordDecl>(CurLexicalContext) &&
18307       !isa<ClassTemplateDecl>(CurLexicalContext) &&
18308       !isa<ClassTemplatePartialSpecializationDecl>(CurLexicalContext) &&
18309       !isa<ClassTemplateSpecializationDecl>(CurLexicalContext)) {
18310     Diag(Loc, diag::err_omp_region_not_file_context);
18311     return false;
18312   }
18313   ++DeclareTargetNestingLevel;
18314   return true;
18315 }
18316 
18317 void Sema::ActOnFinishOpenMPDeclareTargetDirective() {
18318   assert(DeclareTargetNestingLevel > 0 &&
18319          "Unexpected ActOnFinishOpenMPDeclareTargetDirective");
18320   --DeclareTargetNestingLevel;
18321 }
18322 
18323 NamedDecl *
18324 Sema::lookupOpenMPDeclareTargetName(Scope *CurScope, CXXScopeSpec &ScopeSpec,
18325                                     const DeclarationNameInfo &Id,
18326                                     NamedDeclSetType &SameDirectiveDecls) {
18327   LookupResult Lookup(*this, Id, LookupOrdinaryName);
18328   LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
18329 
18330   if (Lookup.isAmbiguous())
18331     return nullptr;
18332   Lookup.suppressDiagnostics();
18333 
18334   if (!Lookup.isSingleResult()) {
18335     VarOrFuncDeclFilterCCC CCC(*this);
18336     if (TypoCorrection Corrected =
18337             CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr, CCC,
18338                         CTK_ErrorRecovery)) {
18339       diagnoseTypo(Corrected, PDiag(diag::err_undeclared_var_use_suggest)
18340                                   << Id.getName());
18341       checkDeclIsAllowedInOpenMPTarget(nullptr, Corrected.getCorrectionDecl());
18342       return nullptr;
18343     }
18344 
18345     Diag(Id.getLoc(), diag::err_undeclared_var_use) << Id.getName();
18346     return nullptr;
18347   }
18348 
18349   NamedDecl *ND = Lookup.getAsSingle<NamedDecl>();
18350   if (!isa<VarDecl>(ND) && !isa<FunctionDecl>(ND) &&
18351       !isa<FunctionTemplateDecl>(ND)) {
18352     Diag(Id.getLoc(), diag::err_omp_invalid_target_decl) << Id.getName();
18353     return nullptr;
18354   }
18355   if (!SameDirectiveDecls.insert(cast<NamedDecl>(ND->getCanonicalDecl())))
18356     Diag(Id.getLoc(), diag::err_omp_declare_target_multiple) << Id.getName();
18357   return ND;
18358 }
18359 
18360 void Sema::ActOnOpenMPDeclareTargetName(
18361     NamedDecl *ND, SourceLocation Loc, OMPDeclareTargetDeclAttr::MapTypeTy MT,
18362     OMPDeclareTargetDeclAttr::DevTypeTy DT) {
18363   assert((isa<VarDecl>(ND) || isa<FunctionDecl>(ND) ||
18364           isa<FunctionTemplateDecl>(ND)) &&
18365          "Expected variable, function or function template.");
18366 
18367   // Diagnose marking after use as it may lead to incorrect diagnosis and
18368   // codegen.
18369   if (LangOpts.OpenMP >= 50 &&
18370       (ND->isUsed(/*CheckUsedAttr=*/false) || ND->isReferenced()))
18371     Diag(Loc, diag::warn_omp_declare_target_after_first_use);
18372 
18373   Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
18374       OMPDeclareTargetDeclAttr::getDeviceType(cast<ValueDecl>(ND));
18375   if (DevTy.hasValue() && *DevTy != DT) {
18376     Diag(Loc, diag::err_omp_device_type_mismatch)
18377         << OMPDeclareTargetDeclAttr::ConvertDevTypeTyToStr(DT)
18378         << OMPDeclareTargetDeclAttr::ConvertDevTypeTyToStr(*DevTy);
18379     return;
18380   }
18381   Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
18382       OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(cast<ValueDecl>(ND));
18383   if (!Res) {
18384     auto *A = OMPDeclareTargetDeclAttr::CreateImplicit(Context, MT, DT,
18385                                                        SourceRange(Loc, Loc));
18386     ND->addAttr(A);
18387     if (ASTMutationListener *ML = Context.getASTMutationListener())
18388       ML->DeclarationMarkedOpenMPDeclareTarget(ND, A);
18389     checkDeclIsAllowedInOpenMPTarget(nullptr, ND, Loc);
18390   } else if (*Res != MT) {
18391     Diag(Loc, diag::err_omp_declare_target_to_and_link) << ND;
18392   }
18393 }
18394 
18395 static void checkDeclInTargetContext(SourceLocation SL, SourceRange SR,
18396                                      Sema &SemaRef, Decl *D) {
18397   if (!D || !isa<VarDecl>(D))
18398     return;
18399   auto *VD = cast<VarDecl>(D);
18400   Optional<OMPDeclareTargetDeclAttr::MapTypeTy> MapTy =
18401       OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
18402   if (SemaRef.LangOpts.OpenMP >= 50 &&
18403       (SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true) ||
18404        SemaRef.getCurBlock() || SemaRef.getCurCapturedRegion()) &&
18405       VD->hasGlobalStorage()) {
18406     llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> MapTy =
18407         OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
18408     if (!MapTy || *MapTy != OMPDeclareTargetDeclAttr::MT_To) {
18409       // OpenMP 5.0, 2.12.7 declare target Directive, Restrictions
18410       // If a lambda declaration and definition appears between a
18411       // declare target directive and the matching end declare target
18412       // directive, all variables that are captured by the lambda
18413       // expression must also appear in a to clause.
18414       SemaRef.Diag(VD->getLocation(),
18415                    diag::err_omp_lambda_capture_in_declare_target_not_to);
18416       SemaRef.Diag(SL, diag::note_var_explicitly_captured_here)
18417           << VD << 0 << SR;
18418       return;
18419     }
18420   }
18421   if (MapTy.hasValue())
18422     return;
18423   SemaRef.Diag(VD->getLocation(), diag::warn_omp_not_in_target_context);
18424   SemaRef.Diag(SL, diag::note_used_here) << SR;
18425 }
18426 
18427 static bool checkValueDeclInTarget(SourceLocation SL, SourceRange SR,
18428                                    Sema &SemaRef, DSAStackTy *Stack,
18429                                    ValueDecl *VD) {
18430   return OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD) ||
18431          checkTypeMappable(SL, SR, SemaRef, Stack, VD->getType(),
18432                            /*FullCheck=*/false);
18433 }
18434 
18435 void Sema::checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D,
18436                                             SourceLocation IdLoc) {
18437   if (!D || D->isInvalidDecl())
18438     return;
18439   SourceRange SR = E ? E->getSourceRange() : D->getSourceRange();
18440   SourceLocation SL = E ? E->getBeginLoc() : D->getLocation();
18441   if (auto *VD = dyn_cast<VarDecl>(D)) {
18442     // Only global variables can be marked as declare target.
18443     if (!VD->isFileVarDecl() && !VD->isStaticLocal() &&
18444         !VD->isStaticDataMember())
18445       return;
18446     // 2.10.6: threadprivate variable cannot appear in a declare target
18447     // directive.
18448     if (DSAStack->isThreadPrivate(VD)) {
18449       Diag(SL, diag::err_omp_threadprivate_in_target);
18450       reportOriginalDsa(*this, DSAStack, VD, DSAStack->getTopDSA(VD, false));
18451       return;
18452     }
18453   }
18454   if (const auto *FTD = dyn_cast<FunctionTemplateDecl>(D))
18455     D = FTD->getTemplatedDecl();
18456   if (auto *FD = dyn_cast<FunctionDecl>(D)) {
18457     llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
18458         OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(FD);
18459     if (IdLoc.isValid() && Res && *Res == OMPDeclareTargetDeclAttr::MT_Link) {
18460       Diag(IdLoc, diag::err_omp_function_in_link_clause);
18461       Diag(FD->getLocation(), diag::note_defined_here) << FD;
18462       return;
18463     }
18464   }
18465   if (auto *VD = dyn_cast<ValueDecl>(D)) {
18466     // Problem if any with var declared with incomplete type will be reported
18467     // as normal, so no need to check it here.
18468     if ((E || !VD->getType()->isIncompleteType()) &&
18469         !checkValueDeclInTarget(SL, SR, *this, DSAStack, VD))
18470       return;
18471     if (!E && !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) {
18472       // Checking declaration inside declare target region.
18473       if (isa<VarDecl>(D) || isa<FunctionDecl>(D) ||
18474           isa<FunctionTemplateDecl>(D)) {
18475         auto *A = OMPDeclareTargetDeclAttr::CreateImplicit(
18476             Context, OMPDeclareTargetDeclAttr::MT_To,
18477             OMPDeclareTargetDeclAttr::DT_Any, SourceRange(IdLoc, IdLoc));
18478         D->addAttr(A);
18479         if (ASTMutationListener *ML = Context.getASTMutationListener())
18480           ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
18481       }
18482       return;
18483     }
18484   }
18485   if (!E)
18486     return;
18487   checkDeclInTargetContext(E->getExprLoc(), E->getSourceRange(), *this, D);
18488 }
18489 
18490 OMPClause *Sema::ActOnOpenMPToClause(ArrayRef<Expr *> VarList,
18491                                      CXXScopeSpec &MapperIdScopeSpec,
18492                                      DeclarationNameInfo &MapperId,
18493                                      const OMPVarListLocTy &Locs,
18494                                      ArrayRef<Expr *> UnresolvedMappers) {
18495   MappableVarListInfo MVLI(VarList);
18496   checkMappableExpressionList(*this, DSAStack, OMPC_to, MVLI, Locs.StartLoc,
18497                               MapperIdScopeSpec, MapperId, UnresolvedMappers);
18498   if (MVLI.ProcessedVarList.empty())
18499     return nullptr;
18500 
18501   return OMPToClause::Create(
18502       Context, Locs, MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
18503       MVLI.VarComponents, MVLI.UDMapperList,
18504       MapperIdScopeSpec.getWithLocInContext(Context), MapperId);
18505 }
18506 
18507 OMPClause *Sema::ActOnOpenMPFromClause(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_from, MVLI, Locs.StartLoc,
18514                               MapperIdScopeSpec, MapperId, UnresolvedMappers);
18515   if (MVLI.ProcessedVarList.empty())
18516     return nullptr;
18517 
18518   return OMPFromClause::Create(
18519       Context, Locs, MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
18520       MVLI.VarComponents, MVLI.UDMapperList,
18521       MapperIdScopeSpec.getWithLocInContext(Context), MapperId);
18522 }
18523 
18524 OMPClause *Sema::ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
18525                                                const OMPVarListLocTy &Locs) {
18526   MappableVarListInfo MVLI(VarList);
18527   SmallVector<Expr *, 8> PrivateCopies;
18528   SmallVector<Expr *, 8> Inits;
18529 
18530   for (Expr *RefExpr : VarList) {
18531     assert(RefExpr && "NULL expr in OpenMP use_device_ptr clause.");
18532     SourceLocation ELoc;
18533     SourceRange ERange;
18534     Expr *SimpleRefExpr = RefExpr;
18535     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
18536     if (Res.second) {
18537       // It will be analyzed later.
18538       MVLI.ProcessedVarList.push_back(RefExpr);
18539       PrivateCopies.push_back(nullptr);
18540       Inits.push_back(nullptr);
18541     }
18542     ValueDecl *D = Res.first;
18543     if (!D)
18544       continue;
18545 
18546     QualType Type = D->getType();
18547     Type = Type.getNonReferenceType().getUnqualifiedType();
18548 
18549     auto *VD = dyn_cast<VarDecl>(D);
18550 
18551     // Item should be a pointer or reference to pointer.
18552     if (!Type->isPointerType()) {
18553       Diag(ELoc, diag::err_omp_usedeviceptr_not_a_pointer)
18554           << 0 << RefExpr->getSourceRange();
18555       continue;
18556     }
18557 
18558     // Build the private variable and the expression that refers to it.
18559     auto VDPrivate =
18560         buildVarDecl(*this, ELoc, Type, D->getName(),
18561                      D->hasAttrs() ? &D->getAttrs() : nullptr,
18562                      VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
18563     if (VDPrivate->isInvalidDecl())
18564       continue;
18565 
18566     CurContext->addDecl(VDPrivate);
18567     DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
18568         *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
18569 
18570     // Add temporary variable to initialize the private copy of the pointer.
18571     VarDecl *VDInit =
18572         buildVarDecl(*this, RefExpr->getExprLoc(), Type, ".devptr.temp");
18573     DeclRefExpr *VDInitRefExpr = buildDeclRefExpr(
18574         *this, VDInit, RefExpr->getType(), RefExpr->getExprLoc());
18575     AddInitializerToDecl(VDPrivate,
18576                          DefaultLvalueConversion(VDInitRefExpr).get(),
18577                          /*DirectInit=*/false);
18578 
18579     // If required, build a capture to implement the privatization initialized
18580     // with the current list item value.
18581     DeclRefExpr *Ref = nullptr;
18582     if (!VD)
18583       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
18584     MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref);
18585     PrivateCopies.push_back(VDPrivateRefExpr);
18586     Inits.push_back(VDInitRefExpr);
18587 
18588     // We need to add a data sharing attribute for this variable to make sure it
18589     // is correctly captured. A variable that shows up in a use_device_ptr has
18590     // similar properties of a first private variable.
18591     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
18592 
18593     // Create a mappable component for the list item. List items in this clause
18594     // only need a component.
18595     MVLI.VarBaseDeclarations.push_back(D);
18596     MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
18597     MVLI.VarComponents.back().push_back(
18598         OMPClauseMappableExprCommon::MappableComponent(SimpleRefExpr, D));
18599   }
18600 
18601   if (MVLI.ProcessedVarList.empty())
18602     return nullptr;
18603 
18604   return OMPUseDevicePtrClause::Create(
18605       Context, Locs, MVLI.ProcessedVarList, PrivateCopies, Inits,
18606       MVLI.VarBaseDeclarations, MVLI.VarComponents);
18607 }
18608 
18609 OMPClause *Sema::ActOnOpenMPUseDeviceAddrClause(ArrayRef<Expr *> VarList,
18610                                                 const OMPVarListLocTy &Locs) {
18611   MappableVarListInfo MVLI(VarList);
18612 
18613   for (Expr *RefExpr : VarList) {
18614     assert(RefExpr && "NULL expr in OpenMP use_device_addr clause.");
18615     SourceLocation ELoc;
18616     SourceRange ERange;
18617     Expr *SimpleRefExpr = RefExpr;
18618     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
18619                               /*AllowArraySection=*/true);
18620     if (Res.second) {
18621       // It will be analyzed later.
18622       MVLI.ProcessedVarList.push_back(RefExpr);
18623     }
18624     ValueDecl *D = Res.first;
18625     if (!D)
18626       continue;
18627     auto *VD = dyn_cast<VarDecl>(D);
18628 
18629     // If required, build a capture to implement the privatization initialized
18630     // with the current list item value.
18631     DeclRefExpr *Ref = nullptr;
18632     if (!VD)
18633       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
18634     MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref);
18635 
18636     // We need to add a data sharing attribute for this variable to make sure it
18637     // is correctly captured. A variable that shows up in a use_device_addr has
18638     // similar properties of a first private variable.
18639     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
18640 
18641     // Create a mappable component for the list item. List items in this clause
18642     // only need a component.
18643     MVLI.VarBaseDeclarations.push_back(D);
18644     MVLI.VarComponents.emplace_back();
18645     Expr *Component = SimpleRefExpr;
18646     if (VD && (isa<OMPArraySectionExpr>(RefExpr->IgnoreParenImpCasts()) ||
18647                isa<ArraySubscriptExpr>(RefExpr->IgnoreParenImpCasts())))
18648       Component = DefaultFunctionArrayLvalueConversion(SimpleRefExpr).get();
18649     MVLI.VarComponents.back().push_back(
18650         OMPClauseMappableExprCommon::MappableComponent(Component, D));
18651   }
18652 
18653   if (MVLI.ProcessedVarList.empty())
18654     return nullptr;
18655 
18656   return OMPUseDeviceAddrClause::Create(Context, Locs, MVLI.ProcessedVarList,
18657                                         MVLI.VarBaseDeclarations,
18658                                         MVLI.VarComponents);
18659 }
18660 
18661 OMPClause *Sema::ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
18662                                               const OMPVarListLocTy &Locs) {
18663   MappableVarListInfo MVLI(VarList);
18664   for (Expr *RefExpr : VarList) {
18665     assert(RefExpr && "NULL expr in OpenMP is_device_ptr clause.");
18666     SourceLocation ELoc;
18667     SourceRange ERange;
18668     Expr *SimpleRefExpr = RefExpr;
18669     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
18670     if (Res.second) {
18671       // It will be analyzed later.
18672       MVLI.ProcessedVarList.push_back(RefExpr);
18673     }
18674     ValueDecl *D = Res.first;
18675     if (!D)
18676       continue;
18677 
18678     QualType Type = D->getType();
18679     // item should be a pointer or array or reference to pointer or array
18680     if (!Type.getNonReferenceType()->isPointerType() &&
18681         !Type.getNonReferenceType()->isArrayType()) {
18682       Diag(ELoc, diag::err_omp_argument_type_isdeviceptr)
18683           << 0 << RefExpr->getSourceRange();
18684       continue;
18685     }
18686 
18687     // Check if the declaration in the clause does not show up in any data
18688     // sharing attribute.
18689     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
18690     if (isOpenMPPrivate(DVar.CKind)) {
18691       Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
18692           << getOpenMPClauseName(DVar.CKind)
18693           << getOpenMPClauseName(OMPC_is_device_ptr)
18694           << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
18695       reportOriginalDsa(*this, DSAStack, D, DVar);
18696       continue;
18697     }
18698 
18699     const Expr *ConflictExpr;
18700     if (DSAStack->checkMappableExprComponentListsForDecl(
18701             D, /*CurrentRegionOnly=*/true,
18702             [&ConflictExpr](
18703                 OMPClauseMappableExprCommon::MappableExprComponentListRef R,
18704                 OpenMPClauseKind) -> bool {
18705               ConflictExpr = R.front().getAssociatedExpression();
18706               return true;
18707             })) {
18708       Diag(ELoc, diag::err_omp_map_shared_storage) << RefExpr->getSourceRange();
18709       Diag(ConflictExpr->getExprLoc(), diag::note_used_here)
18710           << ConflictExpr->getSourceRange();
18711       continue;
18712     }
18713 
18714     // Store the components in the stack so that they can be used to check
18715     // against other clauses later on.
18716     OMPClauseMappableExprCommon::MappableComponent MC(SimpleRefExpr, D);
18717     DSAStack->addMappableExpressionComponents(
18718         D, MC, /*WhereFoundClauseKind=*/OMPC_is_device_ptr);
18719 
18720     // Record the expression we've just processed.
18721     MVLI.ProcessedVarList.push_back(SimpleRefExpr);
18722 
18723     // Create a mappable component for the list item. List items in this clause
18724     // only need a component. We use a null declaration to signal fields in
18725     // 'this'.
18726     assert((isa<DeclRefExpr>(SimpleRefExpr) ||
18727             isa<CXXThisExpr>(cast<MemberExpr>(SimpleRefExpr)->getBase())) &&
18728            "Unexpected device pointer expression!");
18729     MVLI.VarBaseDeclarations.push_back(
18730         isa<DeclRefExpr>(SimpleRefExpr) ? D : nullptr);
18731     MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
18732     MVLI.VarComponents.back().push_back(MC);
18733   }
18734 
18735   if (MVLI.ProcessedVarList.empty())
18736     return nullptr;
18737 
18738   return OMPIsDevicePtrClause::Create(Context, Locs, MVLI.ProcessedVarList,
18739                                       MVLI.VarBaseDeclarations,
18740                                       MVLI.VarComponents);
18741 }
18742 
18743 OMPClause *Sema::ActOnOpenMPAllocateClause(
18744     Expr *Allocator, ArrayRef<Expr *> VarList, SourceLocation StartLoc,
18745     SourceLocation ColonLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
18746   if (Allocator) {
18747     // OpenMP [2.11.4 allocate Clause, Description]
18748     // allocator is an expression of omp_allocator_handle_t type.
18749     if (!findOMPAllocatorHandleT(*this, Allocator->getExprLoc(), DSAStack))
18750       return nullptr;
18751 
18752     ExprResult AllocatorRes = DefaultLvalueConversion(Allocator);
18753     if (AllocatorRes.isInvalid())
18754       return nullptr;
18755     AllocatorRes = PerformImplicitConversion(AllocatorRes.get(),
18756                                              DSAStack->getOMPAllocatorHandleT(),
18757                                              Sema::AA_Initializing,
18758                                              /*AllowExplicit=*/true);
18759     if (AllocatorRes.isInvalid())
18760       return nullptr;
18761     Allocator = AllocatorRes.get();
18762   } else {
18763     // OpenMP 5.0, 2.11.4 allocate Clause, Restrictions.
18764     // allocate clauses that appear on a target construct or on constructs in a
18765     // target region must specify an allocator expression unless a requires
18766     // directive with the dynamic_allocators clause is present in the same
18767     // compilation unit.
18768     if (LangOpts.OpenMPIsDevice &&
18769         !DSAStack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>())
18770       targetDiag(StartLoc, diag::err_expected_allocator_expression);
18771   }
18772   // Analyze and build list of variables.
18773   SmallVector<Expr *, 8> Vars;
18774   for (Expr *RefExpr : VarList) {
18775     assert(RefExpr && "NULL expr in OpenMP private clause.");
18776     SourceLocation ELoc;
18777     SourceRange ERange;
18778     Expr *SimpleRefExpr = RefExpr;
18779     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
18780     if (Res.second) {
18781       // It will be analyzed later.
18782       Vars.push_back(RefExpr);
18783     }
18784     ValueDecl *D = Res.first;
18785     if (!D)
18786       continue;
18787 
18788     auto *VD = dyn_cast<VarDecl>(D);
18789     DeclRefExpr *Ref = nullptr;
18790     if (!VD && !CurContext->isDependentContext())
18791       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
18792     Vars.push_back((VD || CurContext->isDependentContext())
18793                        ? RefExpr->IgnoreParens()
18794                        : Ref);
18795   }
18796 
18797   if (Vars.empty())
18798     return nullptr;
18799 
18800   if (Allocator)
18801     DSAStack->addInnerAllocatorExpr(Allocator);
18802   return OMPAllocateClause::Create(Context, StartLoc, LParenLoc, Allocator,
18803                                    ColonLoc, EndLoc, Vars);
18804 }
18805 
18806 OMPClause *Sema::ActOnOpenMPNontemporalClause(ArrayRef<Expr *> VarList,
18807                                               SourceLocation StartLoc,
18808                                               SourceLocation LParenLoc,
18809                                               SourceLocation EndLoc) {
18810   SmallVector<Expr *, 8> Vars;
18811   for (Expr *RefExpr : VarList) {
18812     assert(RefExpr && "NULL expr in OpenMP nontemporal clause.");
18813     SourceLocation ELoc;
18814     SourceRange ERange;
18815     Expr *SimpleRefExpr = RefExpr;
18816     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
18817     if (Res.second)
18818       // It will be analyzed later.
18819       Vars.push_back(RefExpr);
18820     ValueDecl *D = Res.first;
18821     if (!D)
18822       continue;
18823 
18824     // OpenMP 5.0, 2.9.3.1 simd Construct, Restrictions.
18825     // A list-item cannot appear in more than one nontemporal clause.
18826     if (const Expr *PrevRef =
18827             DSAStack->addUniqueNontemporal(D, SimpleRefExpr)) {
18828       Diag(ELoc, diag::err_omp_used_in_clause_twice)
18829           << 0 << getOpenMPClauseName(OMPC_nontemporal) << ERange;
18830       Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
18831           << getOpenMPClauseName(OMPC_nontemporal);
18832       continue;
18833     }
18834 
18835     Vars.push_back(RefExpr);
18836   }
18837 
18838   if (Vars.empty())
18839     return nullptr;
18840 
18841   return OMPNontemporalClause::Create(Context, StartLoc, LParenLoc, EndLoc,
18842                                       Vars);
18843 }
18844 
18845 OMPClause *Sema::ActOnOpenMPInclusiveClause(ArrayRef<Expr *> VarList,
18846                                             SourceLocation StartLoc,
18847                                             SourceLocation LParenLoc,
18848                                             SourceLocation EndLoc) {
18849   SmallVector<Expr *, 8> Vars;
18850   for (Expr *RefExpr : VarList) {
18851     assert(RefExpr && "NULL expr in OpenMP nontemporal clause.");
18852     SourceLocation ELoc;
18853     SourceRange ERange;
18854     Expr *SimpleRefExpr = RefExpr;
18855     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
18856                               /*AllowArraySection=*/true);
18857     if (Res.second)
18858       // It will be analyzed later.
18859       Vars.push_back(RefExpr);
18860     ValueDecl *D = Res.first;
18861     if (!D)
18862       continue;
18863 
18864     const DSAStackTy::DSAVarData DVar =
18865         DSAStack->getTopDSA(D, /*FromParent=*/true);
18866     // OpenMP 5.0, 2.9.6, scan Directive, Restrictions.
18867     // A list item that appears in the inclusive or exclusive clause must appear
18868     // in a reduction clause with the inscan modifier on the enclosing
18869     // worksharing-loop, worksharing-loop SIMD, or simd construct.
18870     if (DVar.CKind != OMPC_reduction ||
18871         DVar.Modifier != OMPC_REDUCTION_inscan)
18872       Diag(ELoc, diag::err_omp_inclusive_exclusive_not_reduction)
18873           << RefExpr->getSourceRange();
18874 
18875     if (DSAStack->getParentDirective() != OMPD_unknown)
18876       DSAStack->markDeclAsUsedInScanDirective(D);
18877     Vars.push_back(RefExpr);
18878   }
18879 
18880   if (Vars.empty())
18881     return nullptr;
18882 
18883   return OMPInclusiveClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
18884 }
18885 
18886 OMPClause *Sema::ActOnOpenMPExclusiveClause(ArrayRef<Expr *> VarList,
18887                                             SourceLocation StartLoc,
18888                                             SourceLocation LParenLoc,
18889                                             SourceLocation EndLoc) {
18890   SmallVector<Expr *, 8> Vars;
18891   for (Expr *RefExpr : VarList) {
18892     assert(RefExpr && "NULL expr in OpenMP nontemporal clause.");
18893     SourceLocation ELoc;
18894     SourceRange ERange;
18895     Expr *SimpleRefExpr = RefExpr;
18896     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
18897                               /*AllowArraySection=*/true);
18898     if (Res.second)
18899       // It will be analyzed later.
18900       Vars.push_back(RefExpr);
18901     ValueDecl *D = Res.first;
18902     if (!D)
18903       continue;
18904 
18905     OpenMPDirectiveKind ParentDirective = DSAStack->getParentDirective();
18906     DSAStackTy::DSAVarData DVar;
18907     if (ParentDirective != OMPD_unknown)
18908       DVar = DSAStack->getTopDSA(D, /*FromParent=*/true);
18909     // OpenMP 5.0, 2.9.6, scan Directive, Restrictions.
18910     // A list item that appears in the inclusive or exclusive clause must appear
18911     // in a reduction clause with the inscan modifier on the enclosing
18912     // worksharing-loop, worksharing-loop SIMD, or simd construct.
18913     if (ParentDirective == OMPD_unknown || DVar.CKind != OMPC_reduction ||
18914         DVar.Modifier != OMPC_REDUCTION_inscan) {
18915       Diag(ELoc, diag::err_omp_inclusive_exclusive_not_reduction)
18916           << RefExpr->getSourceRange();
18917     } else {
18918       DSAStack->markDeclAsUsedInScanDirective(D);
18919     }
18920     Vars.push_back(RefExpr);
18921   }
18922 
18923   if (Vars.empty())
18924     return nullptr;
18925 
18926   return OMPExclusiveClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
18927 }
18928 
18929 /// Tries to find omp_alloctrait_t type.
18930 static bool findOMPAlloctraitT(Sema &S, SourceLocation Loc, DSAStackTy *Stack) {
18931   QualType OMPAlloctraitT = Stack->getOMPAlloctraitT();
18932   if (!OMPAlloctraitT.isNull())
18933     return true;
18934   IdentifierInfo &II = S.PP.getIdentifierTable().get("omp_alloctrait_t");
18935   ParsedType PT = S.getTypeName(II, Loc, S.getCurScope());
18936   if (!PT.getAsOpaquePtr() || PT.get().isNull()) {
18937     S.Diag(Loc, diag::err_omp_implied_type_not_found) << "omp_alloctrait_t";
18938     return false;
18939   }
18940   Stack->setOMPAlloctraitT(PT.get());
18941   return true;
18942 }
18943 
18944 OMPClause *Sema::ActOnOpenMPUsesAllocatorClause(
18945     SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc,
18946     ArrayRef<UsesAllocatorsData> Data) {
18947   // OpenMP [2.12.5, target Construct]
18948   // allocator is an identifier of omp_allocator_handle_t type.
18949   if (!findOMPAllocatorHandleT(*this, StartLoc, DSAStack))
18950     return nullptr;
18951   // OpenMP [2.12.5, target Construct]
18952   // allocator-traits-array is an identifier of const omp_alloctrait_t * type.
18953   if (llvm::any_of(
18954           Data,
18955           [](const UsesAllocatorsData &D) { return D.AllocatorTraits; }) &&
18956       !findOMPAlloctraitT(*this, StartLoc, DSAStack))
18957     return nullptr;
18958   llvm::SmallSet<CanonicalDeclPtr<Decl>, 4> PredefinedAllocators;
18959   for (int I = 0; I < OMPAllocateDeclAttr::OMPUserDefinedMemAlloc; ++I) {
18960     auto AllocatorKind = static_cast<OMPAllocateDeclAttr::AllocatorTypeTy>(I);
18961     StringRef Allocator =
18962         OMPAllocateDeclAttr::ConvertAllocatorTypeTyToStr(AllocatorKind);
18963     DeclarationName AllocatorName = &Context.Idents.get(Allocator);
18964     PredefinedAllocators.insert(LookupSingleName(
18965         TUScope, AllocatorName, StartLoc, Sema::LookupAnyName));
18966   }
18967 
18968   SmallVector<OMPUsesAllocatorsClause::Data, 4> NewData;
18969   for (const UsesAllocatorsData &D : Data) {
18970     Expr *AllocatorExpr = nullptr;
18971     // Check allocator expression.
18972     if (D.Allocator->isTypeDependent()) {
18973       AllocatorExpr = D.Allocator;
18974     } else {
18975       // Traits were specified - need to assign new allocator to the specified
18976       // allocator, so it must be an lvalue.
18977       AllocatorExpr = D.Allocator->IgnoreParenImpCasts();
18978       auto *DRE = dyn_cast<DeclRefExpr>(AllocatorExpr);
18979       bool IsPredefinedAllocator = false;
18980       if (DRE)
18981         IsPredefinedAllocator = PredefinedAllocators.count(DRE->getDecl());
18982       if (!DRE ||
18983           !(Context.hasSameUnqualifiedType(
18984                 AllocatorExpr->getType(), DSAStack->getOMPAllocatorHandleT()) ||
18985             Context.typesAreCompatible(AllocatorExpr->getType(),
18986                                        DSAStack->getOMPAllocatorHandleT(),
18987                                        /*CompareUnqualified=*/true)) ||
18988           (!IsPredefinedAllocator &&
18989            (AllocatorExpr->getType().isConstant(Context) ||
18990             !AllocatorExpr->isLValue()))) {
18991         Diag(D.Allocator->getExprLoc(), diag::err_omp_var_expected)
18992             << "omp_allocator_handle_t" << (DRE ? 1 : 0)
18993             << AllocatorExpr->getType() << D.Allocator->getSourceRange();
18994         continue;
18995       }
18996       // OpenMP [2.12.5, target Construct]
18997       // Predefined allocators appearing in a uses_allocators clause cannot have
18998       // traits specified.
18999       if (IsPredefinedAllocator && D.AllocatorTraits) {
19000         Diag(D.AllocatorTraits->getExprLoc(),
19001              diag::err_omp_predefined_allocator_with_traits)
19002             << D.AllocatorTraits->getSourceRange();
19003         Diag(D.Allocator->getExprLoc(), diag::note_omp_predefined_allocator)
19004             << cast<NamedDecl>(DRE->getDecl())->getName()
19005             << D.Allocator->getSourceRange();
19006         continue;
19007       }
19008       // OpenMP [2.12.5, target Construct]
19009       // Non-predefined allocators appearing in a uses_allocators clause must
19010       // have traits specified.
19011       if (!IsPredefinedAllocator && !D.AllocatorTraits) {
19012         Diag(D.Allocator->getExprLoc(),
19013              diag::err_omp_nonpredefined_allocator_without_traits);
19014         continue;
19015       }
19016       // No allocator traits - just convert it to rvalue.
19017       if (!D.AllocatorTraits)
19018         AllocatorExpr = DefaultLvalueConversion(AllocatorExpr).get();
19019       DSAStack->addUsesAllocatorsDecl(
19020           DRE->getDecl(),
19021           IsPredefinedAllocator
19022               ? DSAStackTy::UsesAllocatorsDeclKind::PredefinedAllocator
19023               : DSAStackTy::UsesAllocatorsDeclKind::UserDefinedAllocator);
19024     }
19025     Expr *AllocatorTraitsExpr = nullptr;
19026     if (D.AllocatorTraits) {
19027       if (D.AllocatorTraits->isTypeDependent()) {
19028         AllocatorTraitsExpr = D.AllocatorTraits;
19029       } else {
19030         // OpenMP [2.12.5, target Construct]
19031         // Arrays that contain allocator traits that appear in a uses_allocators
19032         // clause must be constant arrays, have constant values and be defined
19033         // in the same scope as the construct in which the clause appears.
19034         AllocatorTraitsExpr = D.AllocatorTraits->IgnoreParenImpCasts();
19035         // Check that traits expr is a constant array.
19036         QualType TraitTy;
19037         if (const ArrayType *Ty =
19038                 AllocatorTraitsExpr->getType()->getAsArrayTypeUnsafe())
19039           if (const auto *ConstArrayTy = dyn_cast<ConstantArrayType>(Ty))
19040             TraitTy = ConstArrayTy->getElementType();
19041         if (TraitTy.isNull() ||
19042             !(Context.hasSameUnqualifiedType(TraitTy,
19043                                              DSAStack->getOMPAlloctraitT()) ||
19044               Context.typesAreCompatible(TraitTy, DSAStack->getOMPAlloctraitT(),
19045                                          /*CompareUnqualified=*/true))) {
19046           Diag(D.AllocatorTraits->getExprLoc(),
19047                diag::err_omp_expected_array_alloctraits)
19048               << AllocatorTraitsExpr->getType();
19049           continue;
19050         }
19051         // Do not map by default allocator traits if it is a standalone
19052         // variable.
19053         if (auto *DRE = dyn_cast<DeclRefExpr>(AllocatorTraitsExpr))
19054           DSAStack->addUsesAllocatorsDecl(
19055               DRE->getDecl(),
19056               DSAStackTy::UsesAllocatorsDeclKind::AllocatorTrait);
19057       }
19058     }
19059     OMPUsesAllocatorsClause::Data &NewD = NewData.emplace_back();
19060     NewD.Allocator = AllocatorExpr;
19061     NewD.AllocatorTraits = AllocatorTraitsExpr;
19062     NewD.LParenLoc = D.LParenLoc;
19063     NewD.RParenLoc = D.RParenLoc;
19064   }
19065   return OMPUsesAllocatorsClause::Create(Context, StartLoc, LParenLoc, EndLoc,
19066                                          NewData);
19067 }
19068 
19069 OMPClause *Sema::ActOnOpenMPAffinityClause(
19070     SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc,
19071     SourceLocation EndLoc, Expr *Modifier, ArrayRef<Expr *> Locators) {
19072   SmallVector<Expr *, 8> Vars;
19073   for (Expr *RefExpr : Locators) {
19074     assert(RefExpr && "NULL expr in OpenMP shared clause.");
19075     if (isa<DependentScopeDeclRefExpr>(RefExpr) || RefExpr->isTypeDependent()) {
19076       // It will be analyzed later.
19077       Vars.push_back(RefExpr);
19078       continue;
19079     }
19080 
19081     SourceLocation ELoc = RefExpr->getExprLoc();
19082     Expr *SimpleExpr = RefExpr->IgnoreParenImpCasts();
19083 
19084     if (!SimpleExpr->isLValue()) {
19085       Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
19086           << 1 << 0 << RefExpr->getSourceRange();
19087       continue;
19088     }
19089 
19090     ExprResult Res;
19091     {
19092       Sema::TentativeAnalysisScope Trap(*this);
19093       Res = CreateBuiltinUnaryOp(ELoc, UO_AddrOf, SimpleExpr);
19094     }
19095     if (!Res.isUsable() && !isa<OMPArraySectionExpr>(SimpleExpr) &&
19096         !isa<OMPArrayShapingExpr>(SimpleExpr)) {
19097       Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
19098           << 1 << 0 << RefExpr->getSourceRange();
19099       continue;
19100     }
19101     Vars.push_back(SimpleExpr);
19102   }
19103 
19104   return OMPAffinityClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
19105                                    EndLoc, Modifier, Vars);
19106 }
19107