1 //===--- SemaOpenMP.cpp - Semantic Analysis for OpenMP constructs ---------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 /// \file
9 /// This file implements semantic analysis for OpenMP directives and
10 /// clauses.
11 ///
12 //===----------------------------------------------------------------------===//
13 
14 #include "TreeTransform.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/ASTMutationListener.h"
17 #include "clang/AST/CXXInheritance.h"
18 #include "clang/AST/Decl.h"
19 #include "clang/AST/DeclCXX.h"
20 #include "clang/AST/DeclOpenMP.h"
21 #include "clang/AST/OpenMPClause.h"
22 #include "clang/AST/StmtCXX.h"
23 #include "clang/AST/StmtOpenMP.h"
24 #include "clang/AST/StmtVisitor.h"
25 #include "clang/AST/TypeOrdering.h"
26 #include "clang/Basic/DiagnosticSema.h"
27 #include "clang/Basic/OpenMPKinds.h"
28 #include "clang/Basic/PartialDiagnostic.h"
29 #include "clang/Basic/TargetInfo.h"
30 #include "clang/Sema/Initialization.h"
31 #include "clang/Sema/Lookup.h"
32 #include "clang/Sema/Scope.h"
33 #include "clang/Sema/ScopeInfo.h"
34 #include "clang/Sema/SemaInternal.h"
35 #include "llvm/ADT/IndexedMap.h"
36 #include "llvm/ADT/PointerEmbeddedInt.h"
37 #include "llvm/ADT/STLExtras.h"
38 #include "llvm/ADT/StringExtras.h"
39 #include "llvm/Frontend/OpenMP/OMPConstants.h"
40 #include <set>
41 
42 using namespace clang;
43 using namespace llvm::omp;
44 
45 //===----------------------------------------------------------------------===//
46 // Stack of data-sharing attributes for variables
47 //===----------------------------------------------------------------------===//
48 
49 static const Expr *checkMapClauseExpressionBase(
50     Sema &SemaRef, Expr *E,
51     OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
52     OpenMPClauseKind CKind, OpenMPDirectiveKind DKind, bool NoDiagnose);
53 
54 namespace {
55 /// Default data sharing attributes, which can be applied to directive.
56 enum DefaultDataSharingAttributes {
57   DSA_unspecified = 0,       /// Data sharing attribute not specified.
58   DSA_none = 1 << 0,         /// Default data sharing attribute 'none'.
59   DSA_shared = 1 << 1,       /// Default data sharing attribute 'shared'.
60   DSA_firstprivate = 1 << 2, /// Default data sharing attribute 'firstprivate'.
61 };
62 
63 /// Stack for tracking declarations used in OpenMP directives and
64 /// clauses and their data-sharing attributes.
65 class DSAStackTy {
66 public:
67   struct DSAVarData {
68     OpenMPDirectiveKind DKind = OMPD_unknown;
69     OpenMPClauseKind CKind = OMPC_unknown;
70     unsigned Modifier = 0;
71     const Expr *RefExpr = nullptr;
72     DeclRefExpr *PrivateCopy = nullptr;
73     SourceLocation ImplicitDSALoc;
74     bool AppliedToPointee = false;
75     DSAVarData() = default;
76     DSAVarData(OpenMPDirectiveKind DKind, OpenMPClauseKind CKind,
77                const Expr *RefExpr, DeclRefExpr *PrivateCopy,
78                SourceLocation ImplicitDSALoc, unsigned Modifier,
79                bool AppliedToPointee)
80         : DKind(DKind), CKind(CKind), Modifier(Modifier), RefExpr(RefExpr),
81           PrivateCopy(PrivateCopy), ImplicitDSALoc(ImplicitDSALoc),
82           AppliedToPointee(AppliedToPointee) {}
83   };
84   using OperatorOffsetTy =
85       llvm::SmallVector<std::pair<Expr *, OverloadedOperatorKind>, 4>;
86   using DoacrossDependMapTy =
87       llvm::DenseMap<OMPDependClause *, OperatorOffsetTy>;
88   /// Kind of the declaration used in the uses_allocators clauses.
89   enum class UsesAllocatorsDeclKind {
90     /// Predefined allocator
91     PredefinedAllocator,
92     /// User-defined allocator
93     UserDefinedAllocator,
94     /// The declaration that represent allocator trait
95     AllocatorTrait,
96   };
97 
98 private:
99   struct DSAInfo {
100     OpenMPClauseKind Attributes = OMPC_unknown;
101     unsigned Modifier = 0;
102     /// Pointer to a reference expression and a flag which shows that the
103     /// variable is marked as lastprivate(true) or not (false).
104     llvm::PointerIntPair<const Expr *, 1, bool> RefExpr;
105     DeclRefExpr *PrivateCopy = nullptr;
106     /// true if the attribute is applied to the pointee, not the variable
107     /// itself.
108     bool AppliedToPointee = false;
109   };
110   using DeclSAMapTy = llvm::SmallDenseMap<const ValueDecl *, DSAInfo, 8>;
111   using UsedRefMapTy = llvm::SmallDenseMap<const ValueDecl *, const Expr *, 8>;
112   using LCDeclInfo = std::pair<unsigned, VarDecl *>;
113   using LoopControlVariablesMapTy =
114       llvm::SmallDenseMap<const ValueDecl *, LCDeclInfo, 8>;
115   /// Struct that associates a component with the clause kind where they are
116   /// found.
117   struct MappedExprComponentTy {
118     OMPClauseMappableExprCommon::MappableExprComponentLists Components;
119     OpenMPClauseKind Kind = OMPC_unknown;
120   };
121   using MappedExprComponentsTy =
122       llvm::DenseMap<const ValueDecl *, MappedExprComponentTy>;
123   using CriticalsWithHintsTy =
124       llvm::StringMap<std::pair<const OMPCriticalDirective *, llvm::APSInt>>;
125   struct ReductionData {
126     using BOKPtrType = llvm::PointerEmbeddedInt<BinaryOperatorKind, 16>;
127     SourceRange ReductionRange;
128     llvm::PointerUnion<const Expr *, BOKPtrType> ReductionOp;
129     ReductionData() = default;
130     void set(BinaryOperatorKind BO, SourceRange RR) {
131       ReductionRange = RR;
132       ReductionOp = BO;
133     }
134     void set(const Expr *RefExpr, SourceRange RR) {
135       ReductionRange = RR;
136       ReductionOp = RefExpr;
137     }
138   };
139   using DeclReductionMapTy =
140       llvm::SmallDenseMap<const ValueDecl *, ReductionData, 4>;
141   struct DefaultmapInfo {
142     OpenMPDefaultmapClauseModifier ImplicitBehavior =
143         OMPC_DEFAULTMAP_MODIFIER_unknown;
144     SourceLocation SLoc;
145     DefaultmapInfo() = default;
146     DefaultmapInfo(OpenMPDefaultmapClauseModifier M, SourceLocation Loc)
147         : ImplicitBehavior(M), SLoc(Loc) {}
148   };
149 
150   struct SharingMapTy {
151     DeclSAMapTy SharingMap;
152     DeclReductionMapTy ReductionMap;
153     UsedRefMapTy AlignedMap;
154     UsedRefMapTy NontemporalMap;
155     MappedExprComponentsTy MappedExprComponents;
156     LoopControlVariablesMapTy LCVMap;
157     DefaultDataSharingAttributes DefaultAttr = DSA_unspecified;
158     SourceLocation DefaultAttrLoc;
159     DefaultmapInfo DefaultmapMap[OMPC_DEFAULTMAP_unknown];
160     OpenMPDirectiveKind Directive = OMPD_unknown;
161     DeclarationNameInfo DirectiveName;
162     Scope *CurScope = nullptr;
163     DeclContext *Context = nullptr;
164     SourceLocation ConstructLoc;
165     /// Set of 'depend' clauses with 'sink|source' dependence kind. Required to
166     /// get the data (loop counters etc.) about enclosing loop-based construct.
167     /// This data is required during codegen.
168     DoacrossDependMapTy DoacrossDepends;
169     /// First argument (Expr *) contains optional argument of the
170     /// 'ordered' clause, the second one is true if the regions has 'ordered'
171     /// clause, false otherwise.
172     llvm::Optional<std::pair<const Expr *, OMPOrderedClause *>> OrderedRegion;
173     unsigned AssociatedLoops = 1;
174     bool HasMutipleLoops = false;
175     const Decl *PossiblyLoopCounter = nullptr;
176     bool NowaitRegion = false;
177     bool CancelRegion = false;
178     bool LoopStart = false;
179     bool BodyComplete = false;
180     SourceLocation PrevScanLocation;
181     SourceLocation PrevOrderedLocation;
182     SourceLocation InnerTeamsRegionLoc;
183     /// Reference to the taskgroup task_reduction reference expression.
184     Expr *TaskgroupReductionRef = nullptr;
185     llvm::DenseSet<QualType> MappedClassesQualTypes;
186     SmallVector<Expr *, 4> InnerUsedAllocators;
187     llvm::DenseSet<CanonicalDeclPtr<Decl>> ImplicitTaskFirstprivates;
188     /// List of globals marked as declare target link in this target region
189     /// (isOpenMPTargetExecutionDirective(Directive) == true).
190     llvm::SmallVector<DeclRefExpr *, 4> DeclareTargetLinkVarDecls;
191     /// List of decls used in inclusive/exclusive clauses of the scan directive.
192     llvm::DenseSet<CanonicalDeclPtr<Decl>> UsedInScanDirective;
193     llvm::DenseMap<CanonicalDeclPtr<const Decl>, UsesAllocatorsDeclKind>
194         UsesAllocatorsDecls;
195     Expr *DeclareMapperVar = nullptr;
196     SharingMapTy(OpenMPDirectiveKind DKind, DeclarationNameInfo Name,
197                  Scope *CurScope, SourceLocation Loc)
198         : Directive(DKind), DirectiveName(Name), CurScope(CurScope),
199           ConstructLoc(Loc) {}
200     SharingMapTy() = default;
201   };
202 
203   using StackTy = SmallVector<SharingMapTy, 4>;
204 
205   /// Stack of used declaration and their data-sharing attributes.
206   DeclSAMapTy Threadprivates;
207   const FunctionScopeInfo *CurrentNonCapturingFunctionScope = nullptr;
208   SmallVector<std::pair<StackTy, const FunctionScopeInfo *>, 4> Stack;
209   /// true, if check for DSA must be from parent directive, false, if
210   /// from current directive.
211   OpenMPClauseKind ClauseKindMode = OMPC_unknown;
212   Sema &SemaRef;
213   bool ForceCapturing = false;
214   /// true if all the variables in the target executable directives must be
215   /// captured by reference.
216   bool ForceCaptureByReferenceInTargetExecutable = false;
217   CriticalsWithHintsTy Criticals;
218   unsigned IgnoredStackElements = 0;
219 
220   /// Iterators over the stack iterate in order from innermost to outermost
221   /// directive.
222   using const_iterator = StackTy::const_reverse_iterator;
223   const_iterator begin() const {
224     return Stack.empty() ? const_iterator()
225                          : Stack.back().first.rbegin() + IgnoredStackElements;
226   }
227   const_iterator end() const {
228     return Stack.empty() ? const_iterator() : Stack.back().first.rend();
229   }
230   using iterator = StackTy::reverse_iterator;
231   iterator begin() {
232     return Stack.empty() ? iterator()
233                          : Stack.back().first.rbegin() + IgnoredStackElements;
234   }
235   iterator end() {
236     return Stack.empty() ? iterator() : Stack.back().first.rend();
237   }
238 
239   // Convenience operations to get at the elements of the stack.
240 
241   bool isStackEmpty() const {
242     return Stack.empty() ||
243            Stack.back().second != CurrentNonCapturingFunctionScope ||
244            Stack.back().first.size() <= IgnoredStackElements;
245   }
246   size_t getStackSize() const {
247     return isStackEmpty() ? 0
248                           : Stack.back().first.size() - IgnoredStackElements;
249   }
250 
251   SharingMapTy *getTopOfStackOrNull() {
252     size_t Size = getStackSize();
253     if (Size == 0)
254       return nullptr;
255     return &Stack.back().first[Size - 1];
256   }
257   const SharingMapTy *getTopOfStackOrNull() const {
258     return const_cast<DSAStackTy&>(*this).getTopOfStackOrNull();
259   }
260   SharingMapTy &getTopOfStack() {
261     assert(!isStackEmpty() && "no current directive");
262     return *getTopOfStackOrNull();
263   }
264   const SharingMapTy &getTopOfStack() const {
265     return const_cast<DSAStackTy&>(*this).getTopOfStack();
266   }
267 
268   SharingMapTy *getSecondOnStackOrNull() {
269     size_t Size = getStackSize();
270     if (Size <= 1)
271       return nullptr;
272     return &Stack.back().first[Size - 2];
273   }
274   const SharingMapTy *getSecondOnStackOrNull() const {
275     return const_cast<DSAStackTy&>(*this).getSecondOnStackOrNull();
276   }
277 
278   /// Get the stack element at a certain level (previously returned by
279   /// \c getNestingLevel).
280   ///
281   /// Note that nesting levels count from outermost to innermost, and this is
282   /// the reverse of our iteration order where new inner levels are pushed at
283   /// the front of the stack.
284   SharingMapTy &getStackElemAtLevel(unsigned Level) {
285     assert(Level < getStackSize() && "no such stack element");
286     return Stack.back().first[Level];
287   }
288   const SharingMapTy &getStackElemAtLevel(unsigned Level) const {
289     return const_cast<DSAStackTy&>(*this).getStackElemAtLevel(Level);
290   }
291 
292   DSAVarData getDSA(const_iterator &Iter, ValueDecl *D) const;
293 
294   /// Checks if the variable is a local for OpenMP region.
295   bool isOpenMPLocal(VarDecl *D, const_iterator Iter) const;
296 
297   /// Vector of previously declared requires directives
298   SmallVector<const OMPRequiresDecl *, 2> RequiresDecls;
299   /// omp_allocator_handle_t type.
300   QualType OMPAllocatorHandleT;
301   /// omp_depend_t type.
302   QualType OMPDependT;
303   /// omp_event_handle_t type.
304   QualType OMPEventHandleT;
305   /// omp_alloctrait_t type.
306   QualType OMPAlloctraitT;
307   /// Expression for the predefined allocators.
308   Expr *OMPPredefinedAllocators[OMPAllocateDeclAttr::OMPUserDefinedMemAlloc] = {
309       nullptr};
310   /// Vector of previously encountered target directives
311   SmallVector<SourceLocation, 2> TargetLocations;
312   SourceLocation AtomicLocation;
313 
314 public:
315   explicit DSAStackTy(Sema &S) : SemaRef(S) {}
316 
317   /// Sets omp_allocator_handle_t type.
318   void setOMPAllocatorHandleT(QualType Ty) { OMPAllocatorHandleT = Ty; }
319   /// Gets omp_allocator_handle_t type.
320   QualType getOMPAllocatorHandleT() const { return OMPAllocatorHandleT; }
321   /// Sets omp_alloctrait_t type.
322   void setOMPAlloctraitT(QualType Ty) { OMPAlloctraitT = Ty; }
323   /// Gets omp_alloctrait_t type.
324   QualType getOMPAlloctraitT() const { return OMPAlloctraitT; }
325   /// Sets the given default allocator.
326   void setAllocator(OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind,
327                     Expr *Allocator) {
328     OMPPredefinedAllocators[AllocatorKind] = Allocator;
329   }
330   /// Returns the specified default allocator.
331   Expr *getAllocator(OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind) const {
332     return OMPPredefinedAllocators[AllocatorKind];
333   }
334   /// Sets omp_depend_t type.
335   void setOMPDependT(QualType Ty) { OMPDependT = Ty; }
336   /// Gets omp_depend_t type.
337   QualType getOMPDependT() const { return OMPDependT; }
338 
339   /// Sets omp_event_handle_t type.
340   void setOMPEventHandleT(QualType Ty) { OMPEventHandleT = Ty; }
341   /// Gets omp_event_handle_t type.
342   QualType getOMPEventHandleT() const { return OMPEventHandleT; }
343 
344   bool isClauseParsingMode() const { return ClauseKindMode != OMPC_unknown; }
345   OpenMPClauseKind getClauseParsingMode() const {
346     assert(isClauseParsingMode() && "Must be in clause parsing mode.");
347     return ClauseKindMode;
348   }
349   void setClauseParsingMode(OpenMPClauseKind K) { ClauseKindMode = K; }
350 
351   bool isBodyComplete() const {
352     const SharingMapTy *Top = getTopOfStackOrNull();
353     return Top && Top->BodyComplete;
354   }
355   void setBodyComplete() {
356     getTopOfStack().BodyComplete = true;
357   }
358 
359   bool isForceVarCapturing() const { return ForceCapturing; }
360   void setForceVarCapturing(bool V) { ForceCapturing = V; }
361 
362   void setForceCaptureByReferenceInTargetExecutable(bool V) {
363     ForceCaptureByReferenceInTargetExecutable = V;
364   }
365   bool isForceCaptureByReferenceInTargetExecutable() const {
366     return ForceCaptureByReferenceInTargetExecutable;
367   }
368 
369   void push(OpenMPDirectiveKind DKind, const DeclarationNameInfo &DirName,
370             Scope *CurScope, SourceLocation Loc) {
371     assert(!IgnoredStackElements &&
372            "cannot change stack while ignoring elements");
373     if (Stack.empty() ||
374         Stack.back().second != CurrentNonCapturingFunctionScope)
375       Stack.emplace_back(StackTy(), CurrentNonCapturingFunctionScope);
376     Stack.back().first.emplace_back(DKind, DirName, CurScope, Loc);
377     Stack.back().first.back().DefaultAttrLoc = Loc;
378   }
379 
380   void pop() {
381     assert(!IgnoredStackElements &&
382            "cannot change stack while ignoring elements");
383     assert(!Stack.back().first.empty() &&
384            "Data-sharing attributes stack is empty!");
385     Stack.back().first.pop_back();
386   }
387 
388   /// RAII object to temporarily leave the scope of a directive when we want to
389   /// logically operate in its parent.
390   class ParentDirectiveScope {
391     DSAStackTy &Self;
392     bool Active;
393   public:
394     ParentDirectiveScope(DSAStackTy &Self, bool Activate)
395         : Self(Self), Active(false) {
396       if (Activate)
397         enable();
398     }
399     ~ParentDirectiveScope() { disable(); }
400     void disable() {
401       if (Active) {
402         --Self.IgnoredStackElements;
403         Active = false;
404       }
405     }
406     void enable() {
407       if (!Active) {
408         ++Self.IgnoredStackElements;
409         Active = true;
410       }
411     }
412   };
413 
414   /// Marks that we're started loop parsing.
415   void loopInit() {
416     assert(isOpenMPLoopDirective(getCurrentDirective()) &&
417            "Expected loop-based directive.");
418     getTopOfStack().LoopStart = true;
419   }
420   /// Start capturing of the variables in the loop context.
421   void loopStart() {
422     assert(isOpenMPLoopDirective(getCurrentDirective()) &&
423            "Expected loop-based directive.");
424     getTopOfStack().LoopStart = false;
425   }
426   /// true, if variables are captured, false otherwise.
427   bool isLoopStarted() const {
428     assert(isOpenMPLoopDirective(getCurrentDirective()) &&
429            "Expected loop-based directive.");
430     return !getTopOfStack().LoopStart;
431   }
432   /// Marks (or clears) declaration as possibly loop counter.
433   void resetPossibleLoopCounter(const Decl *D = nullptr) {
434     getTopOfStack().PossiblyLoopCounter =
435         D ? D->getCanonicalDecl() : D;
436   }
437   /// Gets the possible loop counter decl.
438   const Decl *getPossiblyLoopCunter() const {
439     return getTopOfStack().PossiblyLoopCounter;
440   }
441   /// Start new OpenMP region stack in new non-capturing function.
442   void pushFunction() {
443     assert(!IgnoredStackElements &&
444            "cannot change stack while ignoring elements");
445     const FunctionScopeInfo *CurFnScope = SemaRef.getCurFunction();
446     assert(!isa<CapturingScopeInfo>(CurFnScope));
447     CurrentNonCapturingFunctionScope = CurFnScope;
448   }
449   /// Pop region stack for non-capturing function.
450   void popFunction(const FunctionScopeInfo *OldFSI) {
451     assert(!IgnoredStackElements &&
452            "cannot change stack while ignoring elements");
453     if (!Stack.empty() && Stack.back().second == OldFSI) {
454       assert(Stack.back().first.empty());
455       Stack.pop_back();
456     }
457     CurrentNonCapturingFunctionScope = nullptr;
458     for (const FunctionScopeInfo *FSI : llvm::reverse(SemaRef.FunctionScopes)) {
459       if (!isa<CapturingScopeInfo>(FSI)) {
460         CurrentNonCapturingFunctionScope = FSI;
461         break;
462       }
463     }
464   }
465 
466   void addCriticalWithHint(const OMPCriticalDirective *D, llvm::APSInt Hint) {
467     Criticals.try_emplace(D->getDirectiveName().getAsString(), D, Hint);
468   }
469   const std::pair<const OMPCriticalDirective *, llvm::APSInt>
470   getCriticalWithHint(const DeclarationNameInfo &Name) const {
471     auto I = Criticals.find(Name.getAsString());
472     if (I != Criticals.end())
473       return I->second;
474     return std::make_pair(nullptr, llvm::APSInt());
475   }
476   /// If 'aligned' declaration for given variable \a D was not seen yet,
477   /// add it and return NULL; otherwise return previous occurrence's expression
478   /// for diagnostics.
479   const Expr *addUniqueAligned(const ValueDecl *D, const Expr *NewDE);
480   /// If 'nontemporal' declaration for given variable \a D was not seen yet,
481   /// add it and return NULL; otherwise return previous occurrence's expression
482   /// for diagnostics.
483   const Expr *addUniqueNontemporal(const ValueDecl *D, const Expr *NewDE);
484 
485   /// Register specified variable as loop control variable.
486   void addLoopControlVariable(const ValueDecl *D, VarDecl *Capture);
487   /// Check if the specified variable is a loop control variable for
488   /// current region.
489   /// \return The index of the loop control variable in the list of associated
490   /// for-loops (from outer to inner).
491   const LCDeclInfo isLoopControlVariable(const ValueDecl *D) const;
492   /// Check if the specified variable is a loop control variable for
493   /// parent region.
494   /// \return The index of the loop control variable in the list of associated
495   /// for-loops (from outer to inner).
496   const LCDeclInfo isParentLoopControlVariable(const ValueDecl *D) const;
497   /// Check if the specified variable is a loop control variable for
498   /// current region.
499   /// \return The index of the loop control variable in the list of associated
500   /// for-loops (from outer to inner).
501   const LCDeclInfo isLoopControlVariable(const ValueDecl *D,
502                                          unsigned Level) const;
503   /// Get the loop control variable for the I-th loop (or nullptr) in
504   /// parent directive.
505   const ValueDecl *getParentLoopControlVariable(unsigned I) const;
506 
507   /// Marks the specified decl \p D as used in scan directive.
508   void markDeclAsUsedInScanDirective(ValueDecl *D) {
509     if (SharingMapTy *Stack = getSecondOnStackOrNull())
510       Stack->UsedInScanDirective.insert(D);
511   }
512 
513   /// Checks if the specified declaration was used in the inner scan directive.
514   bool isUsedInScanDirective(ValueDecl *D) const {
515     if (const SharingMapTy *Stack = getTopOfStackOrNull())
516       return Stack->UsedInScanDirective.count(D) > 0;
517     return false;
518   }
519 
520   /// Adds explicit data sharing attribute to the specified declaration.
521   void addDSA(const ValueDecl *D, const Expr *E, OpenMPClauseKind A,
522               DeclRefExpr *PrivateCopy = nullptr, unsigned Modifier = 0,
523               bool AppliedToPointee = false);
524 
525   /// Adds additional information for the reduction items with the reduction id
526   /// represented as an operator.
527   void addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
528                                  BinaryOperatorKind BOK);
529   /// Adds additional information for the reduction items with the reduction id
530   /// represented as reduction identifier.
531   void addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
532                                  const Expr *ReductionRef);
533   /// Returns the location and reduction operation from the innermost parent
534   /// region for the given \p D.
535   const DSAVarData
536   getTopMostTaskgroupReductionData(const ValueDecl *D, SourceRange &SR,
537                                    BinaryOperatorKind &BOK,
538                                    Expr *&TaskgroupDescriptor) const;
539   /// Returns the location and reduction operation from the innermost parent
540   /// region for the given \p D.
541   const DSAVarData
542   getTopMostTaskgroupReductionData(const ValueDecl *D, SourceRange &SR,
543                                    const Expr *&ReductionRef,
544                                    Expr *&TaskgroupDescriptor) const;
545   /// Return reduction reference expression for the current taskgroup or
546   /// parallel/worksharing directives with task reductions.
547   Expr *getTaskgroupReductionRef() const {
548     assert((getTopOfStack().Directive == OMPD_taskgroup ||
549             ((isOpenMPParallelDirective(getTopOfStack().Directive) ||
550               isOpenMPWorksharingDirective(getTopOfStack().Directive)) &&
551              !isOpenMPSimdDirective(getTopOfStack().Directive))) &&
552            "taskgroup reference expression requested for non taskgroup or "
553            "parallel/worksharing directive.");
554     return getTopOfStack().TaskgroupReductionRef;
555   }
556   /// Checks if the given \p VD declaration is actually a taskgroup reduction
557   /// descriptor variable at the \p Level of OpenMP regions.
558   bool isTaskgroupReductionRef(const ValueDecl *VD, unsigned Level) const {
559     return getStackElemAtLevel(Level).TaskgroupReductionRef &&
560            cast<DeclRefExpr>(getStackElemAtLevel(Level).TaskgroupReductionRef)
561                    ->getDecl() == VD;
562   }
563 
564   /// Returns data sharing attributes from top of the stack for the
565   /// specified declaration.
566   const DSAVarData getTopDSA(ValueDecl *D, bool FromParent);
567   /// Returns data-sharing attributes for the specified declaration.
568   const DSAVarData getImplicitDSA(ValueDecl *D, bool FromParent) const;
569   /// Returns data-sharing attributes for the specified declaration.
570   const DSAVarData getImplicitDSA(ValueDecl *D, unsigned Level) const;
571   /// Checks if the specified variables has data-sharing attributes which
572   /// match specified \a CPred predicate in any directive which matches \a DPred
573   /// predicate.
574   const DSAVarData
575   hasDSA(ValueDecl *D,
576          const llvm::function_ref<bool(OpenMPClauseKind, bool)> CPred,
577          const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
578          bool FromParent) const;
579   /// Checks if the specified variables has data-sharing attributes which
580   /// match specified \a CPred predicate in any innermost directive which
581   /// matches \a DPred predicate.
582   const DSAVarData
583   hasInnermostDSA(ValueDecl *D,
584                   const llvm::function_ref<bool(OpenMPClauseKind, bool)> CPred,
585                   const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
586                   bool FromParent) const;
587   /// Checks if the specified variables has explicit data-sharing
588   /// attributes which match specified \a CPred predicate at the specified
589   /// OpenMP region.
590   bool
591   hasExplicitDSA(const ValueDecl *D,
592                  const llvm::function_ref<bool(OpenMPClauseKind, bool)> CPred,
593                  unsigned Level, bool NotLastprivate = false) const;
594 
595   /// Returns true if the directive at level \Level matches in the
596   /// specified \a DPred predicate.
597   bool hasExplicitDirective(
598       const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
599       unsigned Level) const;
600 
601   /// Finds a directive which matches specified \a DPred predicate.
602   bool hasDirective(
603       const llvm::function_ref<bool(
604           OpenMPDirectiveKind, const DeclarationNameInfo &, SourceLocation)>
605           DPred,
606       bool FromParent) const;
607 
608   /// Returns currently analyzed directive.
609   OpenMPDirectiveKind getCurrentDirective() const {
610     const SharingMapTy *Top = getTopOfStackOrNull();
611     return Top ? Top->Directive : OMPD_unknown;
612   }
613   /// Returns directive kind at specified level.
614   OpenMPDirectiveKind getDirective(unsigned Level) const {
615     assert(!isStackEmpty() && "No directive at specified level.");
616     return getStackElemAtLevel(Level).Directive;
617   }
618   /// Returns the capture region at the specified level.
619   OpenMPDirectiveKind getCaptureRegion(unsigned Level,
620                                        unsigned OpenMPCaptureLevel) const {
621     SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
622     getOpenMPCaptureRegions(CaptureRegions, getDirective(Level));
623     return CaptureRegions[OpenMPCaptureLevel];
624   }
625   /// Returns parent directive.
626   OpenMPDirectiveKind getParentDirective() const {
627     const SharingMapTy *Parent = getSecondOnStackOrNull();
628     return Parent ? Parent->Directive : OMPD_unknown;
629   }
630 
631   /// Add requires decl to internal vector
632   void addRequiresDecl(OMPRequiresDecl *RD) {
633     RequiresDecls.push_back(RD);
634   }
635 
636   /// Checks if the defined 'requires' directive has specified type of clause.
637   template <typename ClauseType>
638   bool hasRequiresDeclWithClause() const {
639     return llvm::any_of(RequiresDecls, [](const OMPRequiresDecl *D) {
640       return llvm::any_of(D->clauselists(), [](const OMPClause *C) {
641         return isa<ClauseType>(C);
642       });
643     });
644   }
645 
646   /// Checks for a duplicate clause amongst previously declared requires
647   /// directives
648   bool hasDuplicateRequiresClause(ArrayRef<OMPClause *> ClauseList) const {
649     bool IsDuplicate = false;
650     for (OMPClause *CNew : ClauseList) {
651       for (const OMPRequiresDecl *D : RequiresDecls) {
652         for (const OMPClause *CPrev : D->clauselists()) {
653           if (CNew->getClauseKind() == CPrev->getClauseKind()) {
654             SemaRef.Diag(CNew->getBeginLoc(),
655                          diag::err_omp_requires_clause_redeclaration)
656                 << getOpenMPClauseName(CNew->getClauseKind());
657             SemaRef.Diag(CPrev->getBeginLoc(),
658                          diag::note_omp_requires_previous_clause)
659                 << getOpenMPClauseName(CPrev->getClauseKind());
660             IsDuplicate = true;
661           }
662         }
663       }
664     }
665     return IsDuplicate;
666   }
667 
668   /// Add location of previously encountered target to internal vector
669   void addTargetDirLocation(SourceLocation LocStart) {
670     TargetLocations.push_back(LocStart);
671   }
672 
673   /// Add location for the first encountered atomicc directive.
674   void addAtomicDirectiveLoc(SourceLocation Loc) {
675     if (AtomicLocation.isInvalid())
676       AtomicLocation = Loc;
677   }
678 
679   /// Returns the location of the first encountered atomic directive in the
680   /// module.
681   SourceLocation getAtomicDirectiveLoc() const {
682     return AtomicLocation;
683   }
684 
685   // Return previously encountered target region locations.
686   ArrayRef<SourceLocation> getEncounteredTargetLocs() const {
687     return TargetLocations;
688   }
689 
690   /// Set default data sharing attribute to none.
691   void setDefaultDSANone(SourceLocation Loc) {
692     getTopOfStack().DefaultAttr = DSA_none;
693     getTopOfStack().DefaultAttrLoc = Loc;
694   }
695   /// Set default data sharing attribute to shared.
696   void setDefaultDSAShared(SourceLocation Loc) {
697     getTopOfStack().DefaultAttr = DSA_shared;
698     getTopOfStack().DefaultAttrLoc = Loc;
699   }
700   /// Set default data sharing attribute to firstprivate.
701   void setDefaultDSAFirstPrivate(SourceLocation Loc) {
702     getTopOfStack().DefaultAttr = DSA_firstprivate;
703     getTopOfStack().DefaultAttrLoc = Loc;
704   }
705   /// Set default data mapping attribute to Modifier:Kind
706   void setDefaultDMAAttr(OpenMPDefaultmapClauseModifier M,
707                          OpenMPDefaultmapClauseKind Kind,
708                          SourceLocation Loc) {
709     DefaultmapInfo &DMI = getTopOfStack().DefaultmapMap[Kind];
710     DMI.ImplicitBehavior = M;
711     DMI.SLoc = Loc;
712   }
713   /// Check whether the implicit-behavior has been set in defaultmap
714   bool checkDefaultmapCategory(OpenMPDefaultmapClauseKind VariableCategory) {
715     if (VariableCategory == OMPC_DEFAULTMAP_unknown)
716       return getTopOfStack()
717                      .DefaultmapMap[OMPC_DEFAULTMAP_aggregate]
718                      .ImplicitBehavior != OMPC_DEFAULTMAP_MODIFIER_unknown ||
719              getTopOfStack()
720                      .DefaultmapMap[OMPC_DEFAULTMAP_scalar]
721                      .ImplicitBehavior != OMPC_DEFAULTMAP_MODIFIER_unknown ||
722              getTopOfStack()
723                      .DefaultmapMap[OMPC_DEFAULTMAP_pointer]
724                      .ImplicitBehavior != OMPC_DEFAULTMAP_MODIFIER_unknown;
725     return getTopOfStack().DefaultmapMap[VariableCategory].ImplicitBehavior !=
726            OMPC_DEFAULTMAP_MODIFIER_unknown;
727   }
728 
729   DefaultDataSharingAttributes getDefaultDSA(unsigned Level) const {
730     return getStackSize() <= Level ? DSA_unspecified
731                                    : getStackElemAtLevel(Level).DefaultAttr;
732   }
733   DefaultDataSharingAttributes getDefaultDSA() const {
734     return isStackEmpty() ? DSA_unspecified
735                           : getTopOfStack().DefaultAttr;
736   }
737   SourceLocation getDefaultDSALocation() const {
738     return isStackEmpty() ? SourceLocation()
739                           : getTopOfStack().DefaultAttrLoc;
740   }
741   OpenMPDefaultmapClauseModifier
742   getDefaultmapModifier(OpenMPDefaultmapClauseKind Kind) const {
743     return isStackEmpty()
744                ? OMPC_DEFAULTMAP_MODIFIER_unknown
745                : getTopOfStack().DefaultmapMap[Kind].ImplicitBehavior;
746   }
747   OpenMPDefaultmapClauseModifier
748   getDefaultmapModifierAtLevel(unsigned Level,
749                                OpenMPDefaultmapClauseKind Kind) const {
750     return getStackElemAtLevel(Level).DefaultmapMap[Kind].ImplicitBehavior;
751   }
752   bool isDefaultmapCapturedByRef(unsigned Level,
753                                  OpenMPDefaultmapClauseKind Kind) const {
754     OpenMPDefaultmapClauseModifier M =
755         getDefaultmapModifierAtLevel(Level, Kind);
756     if (Kind == OMPC_DEFAULTMAP_scalar || Kind == OMPC_DEFAULTMAP_pointer) {
757       return (M == OMPC_DEFAULTMAP_MODIFIER_alloc) ||
758              (M == OMPC_DEFAULTMAP_MODIFIER_to) ||
759              (M == OMPC_DEFAULTMAP_MODIFIER_from) ||
760              (M == OMPC_DEFAULTMAP_MODIFIER_tofrom);
761     }
762     return true;
763   }
764   static bool mustBeFirstprivateBase(OpenMPDefaultmapClauseModifier M,
765                                      OpenMPDefaultmapClauseKind Kind) {
766     switch (Kind) {
767     case OMPC_DEFAULTMAP_scalar:
768     case OMPC_DEFAULTMAP_pointer:
769       return (M == OMPC_DEFAULTMAP_MODIFIER_unknown) ||
770              (M == OMPC_DEFAULTMAP_MODIFIER_firstprivate) ||
771              (M == OMPC_DEFAULTMAP_MODIFIER_default);
772     case OMPC_DEFAULTMAP_aggregate:
773       return M == OMPC_DEFAULTMAP_MODIFIER_firstprivate;
774     default:
775       break;
776     }
777     llvm_unreachable("Unexpected OpenMPDefaultmapClauseKind enum");
778   }
779   bool mustBeFirstprivateAtLevel(unsigned Level,
780                                  OpenMPDefaultmapClauseKind Kind) const {
781     OpenMPDefaultmapClauseModifier M =
782         getDefaultmapModifierAtLevel(Level, Kind);
783     return mustBeFirstprivateBase(M, Kind);
784   }
785   bool mustBeFirstprivate(OpenMPDefaultmapClauseKind Kind) const {
786     OpenMPDefaultmapClauseModifier M = getDefaultmapModifier(Kind);
787     return mustBeFirstprivateBase(M, Kind);
788   }
789 
790   /// Checks if the specified variable is a threadprivate.
791   bool isThreadPrivate(VarDecl *D) {
792     const DSAVarData DVar = getTopDSA(D, false);
793     return isOpenMPThreadPrivate(DVar.CKind);
794   }
795 
796   /// Marks current region as ordered (it has an 'ordered' clause).
797   void setOrderedRegion(bool IsOrdered, const Expr *Param,
798                         OMPOrderedClause *Clause) {
799     if (IsOrdered)
800       getTopOfStack().OrderedRegion.emplace(Param, Clause);
801     else
802       getTopOfStack().OrderedRegion.reset();
803   }
804   /// Returns true, if region is ordered (has associated 'ordered' clause),
805   /// false - otherwise.
806   bool isOrderedRegion() const {
807     if (const SharingMapTy *Top = getTopOfStackOrNull())
808       return Top->OrderedRegion.hasValue();
809     return false;
810   }
811   /// Returns optional parameter for the ordered region.
812   std::pair<const Expr *, OMPOrderedClause *> getOrderedRegionParam() const {
813     if (const SharingMapTy *Top = getTopOfStackOrNull())
814       if (Top->OrderedRegion.hasValue())
815         return Top->OrderedRegion.getValue();
816     return std::make_pair(nullptr, nullptr);
817   }
818   /// Returns true, if parent region is ordered (has associated
819   /// 'ordered' clause), false - otherwise.
820   bool isParentOrderedRegion() const {
821     if (const SharingMapTy *Parent = getSecondOnStackOrNull())
822       return Parent->OrderedRegion.hasValue();
823     return false;
824   }
825   /// Returns optional parameter for the ordered region.
826   std::pair<const Expr *, OMPOrderedClause *>
827   getParentOrderedRegionParam() const {
828     if (const SharingMapTy *Parent = getSecondOnStackOrNull())
829       if (Parent->OrderedRegion.hasValue())
830         return Parent->OrderedRegion.getValue();
831     return std::make_pair(nullptr, nullptr);
832   }
833   /// Marks current region as nowait (it has a 'nowait' clause).
834   void setNowaitRegion(bool IsNowait = true) {
835     getTopOfStack().NowaitRegion = IsNowait;
836   }
837   /// Returns true, if parent region is nowait (has associated
838   /// 'nowait' clause), false - otherwise.
839   bool isParentNowaitRegion() const {
840     if (const SharingMapTy *Parent = getSecondOnStackOrNull())
841       return Parent->NowaitRegion;
842     return false;
843   }
844   /// Marks parent region as cancel region.
845   void setParentCancelRegion(bool Cancel = true) {
846     if (SharingMapTy *Parent = getSecondOnStackOrNull())
847       Parent->CancelRegion |= Cancel;
848   }
849   /// Return true if current region has inner cancel construct.
850   bool isCancelRegion() const {
851     const SharingMapTy *Top = getTopOfStackOrNull();
852     return Top ? Top->CancelRegion : false;
853   }
854 
855   /// Mark that parent region already has scan directive.
856   void setParentHasScanDirective(SourceLocation Loc) {
857     if (SharingMapTy *Parent = getSecondOnStackOrNull())
858       Parent->PrevScanLocation = Loc;
859   }
860   /// Return true if current region has inner cancel construct.
861   bool doesParentHasScanDirective() const {
862     const SharingMapTy *Top = getSecondOnStackOrNull();
863     return Top ? Top->PrevScanLocation.isValid() : false;
864   }
865   /// Return true if current region has inner cancel construct.
866   SourceLocation getParentScanDirectiveLoc() const {
867     const SharingMapTy *Top = getSecondOnStackOrNull();
868     return Top ? Top->PrevScanLocation : SourceLocation();
869   }
870   /// Mark that parent region already has ordered directive.
871   void setParentHasOrderedDirective(SourceLocation Loc) {
872     if (SharingMapTy *Parent = getSecondOnStackOrNull())
873       Parent->PrevOrderedLocation = Loc;
874   }
875   /// Return true if current region has inner ordered construct.
876   bool doesParentHasOrderedDirective() const {
877     const SharingMapTy *Top = getSecondOnStackOrNull();
878     return Top ? Top->PrevOrderedLocation.isValid() : false;
879   }
880   /// Returns the location of the previously specified ordered directive.
881   SourceLocation getParentOrderedDirectiveLoc() const {
882     const SharingMapTy *Top = getSecondOnStackOrNull();
883     return Top ? Top->PrevOrderedLocation : SourceLocation();
884   }
885 
886   /// Set collapse value for the region.
887   void setAssociatedLoops(unsigned Val) {
888     getTopOfStack().AssociatedLoops = Val;
889     if (Val > 1)
890       getTopOfStack().HasMutipleLoops = true;
891   }
892   /// Return collapse value for region.
893   unsigned getAssociatedLoops() const {
894     const SharingMapTy *Top = getTopOfStackOrNull();
895     return Top ? Top->AssociatedLoops : 0;
896   }
897   /// Returns true if the construct is associated with multiple loops.
898   bool hasMutipleLoops() const {
899     const SharingMapTy *Top = getTopOfStackOrNull();
900     return Top ? Top->HasMutipleLoops : false;
901   }
902 
903   /// Marks current target region as one with closely nested teams
904   /// region.
905   void setParentTeamsRegionLoc(SourceLocation TeamsRegionLoc) {
906     if (SharingMapTy *Parent = getSecondOnStackOrNull())
907       Parent->InnerTeamsRegionLoc = TeamsRegionLoc;
908   }
909   /// Returns true, if current region has closely nested teams region.
910   bool hasInnerTeamsRegion() const {
911     return getInnerTeamsRegionLoc().isValid();
912   }
913   /// Returns location of the nested teams region (if any).
914   SourceLocation getInnerTeamsRegionLoc() const {
915     const SharingMapTy *Top = getTopOfStackOrNull();
916     return Top ? Top->InnerTeamsRegionLoc : SourceLocation();
917   }
918 
919   Scope *getCurScope() const {
920     const SharingMapTy *Top = getTopOfStackOrNull();
921     return Top ? Top->CurScope : nullptr;
922   }
923   void setContext(DeclContext *DC) { getTopOfStack().Context = DC; }
924   SourceLocation getConstructLoc() const {
925     const SharingMapTy *Top = getTopOfStackOrNull();
926     return Top ? Top->ConstructLoc : SourceLocation();
927   }
928 
929   /// Do the check specified in \a Check to all component lists and return true
930   /// if any issue is found.
931   bool checkMappableExprComponentListsForDecl(
932       const ValueDecl *VD, bool CurrentRegionOnly,
933       const llvm::function_ref<
934           bool(OMPClauseMappableExprCommon::MappableExprComponentListRef,
935                OpenMPClauseKind)>
936           Check) const {
937     if (isStackEmpty())
938       return false;
939     auto SI = begin();
940     auto SE = end();
941 
942     if (SI == SE)
943       return false;
944 
945     if (CurrentRegionOnly)
946       SE = std::next(SI);
947     else
948       std::advance(SI, 1);
949 
950     for (; SI != SE; ++SI) {
951       auto MI = SI->MappedExprComponents.find(VD);
952       if (MI != SI->MappedExprComponents.end())
953         for (OMPClauseMappableExprCommon::MappableExprComponentListRef L :
954              MI->second.Components)
955           if (Check(L, MI->second.Kind))
956             return true;
957     }
958     return false;
959   }
960 
961   /// Do the check specified in \a Check to all component lists at a given level
962   /// and return true if any issue is found.
963   bool checkMappableExprComponentListsForDeclAtLevel(
964       const ValueDecl *VD, unsigned Level,
965       const llvm::function_ref<
966           bool(OMPClauseMappableExprCommon::MappableExprComponentListRef,
967                OpenMPClauseKind)>
968           Check) const {
969     if (getStackSize() <= Level)
970       return false;
971 
972     const SharingMapTy &StackElem = getStackElemAtLevel(Level);
973     auto MI = StackElem.MappedExprComponents.find(VD);
974     if (MI != StackElem.MappedExprComponents.end())
975       for (OMPClauseMappableExprCommon::MappableExprComponentListRef L :
976            MI->second.Components)
977         if (Check(L, MI->second.Kind))
978           return true;
979     return false;
980   }
981 
982   /// Create a new mappable expression component list associated with a given
983   /// declaration and initialize it with the provided list of components.
984   void addMappableExpressionComponents(
985       const ValueDecl *VD,
986       OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
987       OpenMPClauseKind WhereFoundClauseKind) {
988     MappedExprComponentTy &MEC = getTopOfStack().MappedExprComponents[VD];
989     // Create new entry and append the new components there.
990     MEC.Components.resize(MEC.Components.size() + 1);
991     MEC.Components.back().append(Components.begin(), Components.end());
992     MEC.Kind = WhereFoundClauseKind;
993   }
994 
995   unsigned getNestingLevel() const {
996     assert(!isStackEmpty());
997     return getStackSize() - 1;
998   }
999   void addDoacrossDependClause(OMPDependClause *C,
1000                                const OperatorOffsetTy &OpsOffs) {
1001     SharingMapTy *Parent = getSecondOnStackOrNull();
1002     assert(Parent && isOpenMPWorksharingDirective(Parent->Directive));
1003     Parent->DoacrossDepends.try_emplace(C, OpsOffs);
1004   }
1005   llvm::iterator_range<DoacrossDependMapTy::const_iterator>
1006   getDoacrossDependClauses() const {
1007     const SharingMapTy &StackElem = getTopOfStack();
1008     if (isOpenMPWorksharingDirective(StackElem.Directive)) {
1009       const DoacrossDependMapTy &Ref = StackElem.DoacrossDepends;
1010       return llvm::make_range(Ref.begin(), Ref.end());
1011     }
1012     return llvm::make_range(StackElem.DoacrossDepends.end(),
1013                             StackElem.DoacrossDepends.end());
1014   }
1015 
1016   // Store types of classes which have been explicitly mapped
1017   void addMappedClassesQualTypes(QualType QT) {
1018     SharingMapTy &StackElem = getTopOfStack();
1019     StackElem.MappedClassesQualTypes.insert(QT);
1020   }
1021 
1022   // Return set of mapped classes types
1023   bool isClassPreviouslyMapped(QualType QT) const {
1024     const SharingMapTy &StackElem = getTopOfStack();
1025     return StackElem.MappedClassesQualTypes.count(QT) != 0;
1026   }
1027 
1028   /// Adds global declare target to the parent target region.
1029   void addToParentTargetRegionLinkGlobals(DeclRefExpr *E) {
1030     assert(*OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(
1031                E->getDecl()) == OMPDeclareTargetDeclAttr::MT_Link &&
1032            "Expected declare target link global.");
1033     for (auto &Elem : *this) {
1034       if (isOpenMPTargetExecutionDirective(Elem.Directive)) {
1035         Elem.DeclareTargetLinkVarDecls.push_back(E);
1036         return;
1037       }
1038     }
1039   }
1040 
1041   /// Returns the list of globals with declare target link if current directive
1042   /// is target.
1043   ArrayRef<DeclRefExpr *> getLinkGlobals() const {
1044     assert(isOpenMPTargetExecutionDirective(getCurrentDirective()) &&
1045            "Expected target executable directive.");
1046     return getTopOfStack().DeclareTargetLinkVarDecls;
1047   }
1048 
1049   /// Adds list of allocators expressions.
1050   void addInnerAllocatorExpr(Expr *E) {
1051     getTopOfStack().InnerUsedAllocators.push_back(E);
1052   }
1053   /// Return list of used allocators.
1054   ArrayRef<Expr *> getInnerAllocators() const {
1055     return getTopOfStack().InnerUsedAllocators;
1056   }
1057   /// Marks the declaration as implicitly firstprivate nin the task-based
1058   /// regions.
1059   void addImplicitTaskFirstprivate(unsigned Level, Decl *D) {
1060     getStackElemAtLevel(Level).ImplicitTaskFirstprivates.insert(D);
1061   }
1062   /// Checks if the decl is implicitly firstprivate in the task-based region.
1063   bool isImplicitTaskFirstprivate(Decl *D) const {
1064     return getTopOfStack().ImplicitTaskFirstprivates.count(D) > 0;
1065   }
1066 
1067   /// Marks decl as used in uses_allocators clause as the allocator.
1068   void addUsesAllocatorsDecl(const Decl *D, UsesAllocatorsDeclKind Kind) {
1069     getTopOfStack().UsesAllocatorsDecls.try_emplace(D, Kind);
1070   }
1071   /// Checks if specified decl is used in uses allocator clause as the
1072   /// allocator.
1073   Optional<UsesAllocatorsDeclKind> isUsesAllocatorsDecl(unsigned Level,
1074                                                         const Decl *D) const {
1075     const SharingMapTy &StackElem = getTopOfStack();
1076     auto I = StackElem.UsesAllocatorsDecls.find(D);
1077     if (I == StackElem.UsesAllocatorsDecls.end())
1078       return None;
1079     return I->getSecond();
1080   }
1081   Optional<UsesAllocatorsDeclKind> isUsesAllocatorsDecl(const Decl *D) const {
1082     const SharingMapTy &StackElem = getTopOfStack();
1083     auto I = StackElem.UsesAllocatorsDecls.find(D);
1084     if (I == StackElem.UsesAllocatorsDecls.end())
1085       return None;
1086     return I->getSecond();
1087   }
1088 
1089   void addDeclareMapperVarRef(Expr *Ref) {
1090     SharingMapTy &StackElem = getTopOfStack();
1091     StackElem.DeclareMapperVar = Ref;
1092   }
1093   const Expr *getDeclareMapperVarRef() const {
1094     const SharingMapTy *Top = getTopOfStackOrNull();
1095     return Top ? Top->DeclareMapperVar : nullptr;
1096   }
1097 };
1098 
1099 bool isImplicitTaskingRegion(OpenMPDirectiveKind DKind) {
1100   return isOpenMPParallelDirective(DKind) || isOpenMPTeamsDirective(DKind);
1101 }
1102 
1103 bool isImplicitOrExplicitTaskingRegion(OpenMPDirectiveKind DKind) {
1104   return isImplicitTaskingRegion(DKind) || isOpenMPTaskingDirective(DKind) ||
1105          DKind == OMPD_unknown;
1106 }
1107 
1108 } // namespace
1109 
1110 static const Expr *getExprAsWritten(const Expr *E) {
1111   if (const auto *FE = dyn_cast<FullExpr>(E))
1112     E = FE->getSubExpr();
1113 
1114   if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))
1115     E = MTE->getSubExpr();
1116 
1117   while (const auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E))
1118     E = Binder->getSubExpr();
1119 
1120   if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
1121     E = ICE->getSubExprAsWritten();
1122   return E->IgnoreParens();
1123 }
1124 
1125 static Expr *getExprAsWritten(Expr *E) {
1126   return const_cast<Expr *>(getExprAsWritten(const_cast<const Expr *>(E)));
1127 }
1128 
1129 static const ValueDecl *getCanonicalDecl(const ValueDecl *D) {
1130   if (const auto *CED = dyn_cast<OMPCapturedExprDecl>(D))
1131     if (const auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
1132       D = ME->getMemberDecl();
1133   const auto *VD = dyn_cast<VarDecl>(D);
1134   const auto *FD = dyn_cast<FieldDecl>(D);
1135   if (VD != nullptr) {
1136     VD = VD->getCanonicalDecl();
1137     D = VD;
1138   } else {
1139     assert(FD);
1140     FD = FD->getCanonicalDecl();
1141     D = FD;
1142   }
1143   return D;
1144 }
1145 
1146 static ValueDecl *getCanonicalDecl(ValueDecl *D) {
1147   return const_cast<ValueDecl *>(
1148       getCanonicalDecl(const_cast<const ValueDecl *>(D)));
1149 }
1150 
1151 DSAStackTy::DSAVarData DSAStackTy::getDSA(const_iterator &Iter,
1152                                           ValueDecl *D) const {
1153   D = getCanonicalDecl(D);
1154   auto *VD = dyn_cast<VarDecl>(D);
1155   const auto *FD = dyn_cast<FieldDecl>(D);
1156   DSAVarData DVar;
1157   if (Iter == end()) {
1158     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1159     // in a region but not in construct]
1160     //  File-scope or namespace-scope variables referenced in called routines
1161     //  in the region are shared unless they appear in a threadprivate
1162     //  directive.
1163     if (VD && !VD->isFunctionOrMethodVarDecl() && !isa<ParmVarDecl>(VD))
1164       DVar.CKind = OMPC_shared;
1165 
1166     // OpenMP [2.9.1.2, Data-sharing Attribute Rules for Variables Referenced
1167     // in a region but not in construct]
1168     //  Variables with static storage duration that are declared in called
1169     //  routines in the region are shared.
1170     if (VD && VD->hasGlobalStorage())
1171       DVar.CKind = OMPC_shared;
1172 
1173     // Non-static data members are shared by default.
1174     if (FD)
1175       DVar.CKind = OMPC_shared;
1176 
1177     return DVar;
1178   }
1179 
1180   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1181   // in a Construct, C/C++, predetermined, p.1]
1182   // Variables with automatic storage duration that are declared in a scope
1183   // inside the construct are private.
1184   if (VD && isOpenMPLocal(VD, Iter) && VD->isLocalVarDecl() &&
1185       (VD->getStorageClass() == SC_Auto || VD->getStorageClass() == SC_None)) {
1186     DVar.CKind = OMPC_private;
1187     return DVar;
1188   }
1189 
1190   DVar.DKind = Iter->Directive;
1191   // Explicitly specified attributes and local variables with predetermined
1192   // attributes.
1193   if (Iter->SharingMap.count(D)) {
1194     const DSAInfo &Data = Iter->SharingMap.lookup(D);
1195     DVar.RefExpr = Data.RefExpr.getPointer();
1196     DVar.PrivateCopy = Data.PrivateCopy;
1197     DVar.CKind = Data.Attributes;
1198     DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
1199     DVar.Modifier = Data.Modifier;
1200     DVar.AppliedToPointee = Data.AppliedToPointee;
1201     return DVar;
1202   }
1203 
1204   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1205   // in a Construct, C/C++, implicitly determined, p.1]
1206   //  In a parallel or task construct, the data-sharing attributes of these
1207   //  variables are determined by the default clause, if present.
1208   switch (Iter->DefaultAttr) {
1209   case DSA_shared:
1210     DVar.CKind = OMPC_shared;
1211     DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
1212     return DVar;
1213   case DSA_none:
1214     return DVar;
1215   case DSA_firstprivate:
1216     if (VD->getStorageDuration() == SD_Static &&
1217         VD->getDeclContext()->isFileContext()) {
1218       DVar.CKind = OMPC_unknown;
1219     } else {
1220       DVar.CKind = OMPC_firstprivate;
1221     }
1222     DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
1223     return DVar;
1224   case DSA_unspecified:
1225     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1226     // in a Construct, implicitly determined, p.2]
1227     //  In a parallel construct, if no default clause is present, these
1228     //  variables are shared.
1229     DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
1230     if ((isOpenMPParallelDirective(DVar.DKind) &&
1231          !isOpenMPTaskLoopDirective(DVar.DKind)) ||
1232         isOpenMPTeamsDirective(DVar.DKind)) {
1233       DVar.CKind = OMPC_shared;
1234       return DVar;
1235     }
1236 
1237     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1238     // in a Construct, implicitly determined, p.4]
1239     //  In a task construct, if no default clause is present, a variable that in
1240     //  the enclosing context is determined to be shared by all implicit tasks
1241     //  bound to the current team is shared.
1242     if (isOpenMPTaskingDirective(DVar.DKind)) {
1243       DSAVarData DVarTemp;
1244       const_iterator I = Iter, E = end();
1245       do {
1246         ++I;
1247         // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables
1248         // Referenced in a Construct, implicitly determined, p.6]
1249         //  In a task construct, if no default clause is present, a variable
1250         //  whose data-sharing attribute is not determined by the rules above is
1251         //  firstprivate.
1252         DVarTemp = getDSA(I, D);
1253         if (DVarTemp.CKind != OMPC_shared) {
1254           DVar.RefExpr = nullptr;
1255           DVar.CKind = OMPC_firstprivate;
1256           return DVar;
1257         }
1258       } while (I != E && !isImplicitTaskingRegion(I->Directive));
1259       DVar.CKind =
1260           (DVarTemp.CKind == OMPC_unknown) ? OMPC_firstprivate : OMPC_shared;
1261       return DVar;
1262     }
1263   }
1264   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1265   // in a Construct, implicitly determined, p.3]
1266   //  For constructs other than task, if no default clause is present, these
1267   //  variables inherit their data-sharing attributes from the enclosing
1268   //  context.
1269   return getDSA(++Iter, D);
1270 }
1271 
1272 const Expr *DSAStackTy::addUniqueAligned(const ValueDecl *D,
1273                                          const Expr *NewDE) {
1274   assert(!isStackEmpty() && "Data sharing attributes stack is empty");
1275   D = getCanonicalDecl(D);
1276   SharingMapTy &StackElem = getTopOfStack();
1277   auto It = StackElem.AlignedMap.find(D);
1278   if (It == StackElem.AlignedMap.end()) {
1279     assert(NewDE && "Unexpected nullptr expr to be added into aligned map");
1280     StackElem.AlignedMap[D] = NewDE;
1281     return nullptr;
1282   }
1283   assert(It->second && "Unexpected nullptr expr in the aligned map");
1284   return It->second;
1285 }
1286 
1287 const Expr *DSAStackTy::addUniqueNontemporal(const ValueDecl *D,
1288                                              const Expr *NewDE) {
1289   assert(!isStackEmpty() && "Data sharing attributes stack is empty");
1290   D = getCanonicalDecl(D);
1291   SharingMapTy &StackElem = getTopOfStack();
1292   auto It = StackElem.NontemporalMap.find(D);
1293   if (It == StackElem.NontemporalMap.end()) {
1294     assert(NewDE && "Unexpected nullptr expr to be added into aligned map");
1295     StackElem.NontemporalMap[D] = NewDE;
1296     return nullptr;
1297   }
1298   assert(It->second && "Unexpected nullptr expr in the aligned map");
1299   return It->second;
1300 }
1301 
1302 void DSAStackTy::addLoopControlVariable(const ValueDecl *D, VarDecl *Capture) {
1303   assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
1304   D = getCanonicalDecl(D);
1305   SharingMapTy &StackElem = getTopOfStack();
1306   StackElem.LCVMap.try_emplace(
1307       D, LCDeclInfo(StackElem.LCVMap.size() + 1, Capture));
1308 }
1309 
1310 const DSAStackTy::LCDeclInfo
1311 DSAStackTy::isLoopControlVariable(const ValueDecl *D) const {
1312   assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
1313   D = getCanonicalDecl(D);
1314   const SharingMapTy &StackElem = getTopOfStack();
1315   auto It = StackElem.LCVMap.find(D);
1316   if (It != StackElem.LCVMap.end())
1317     return It->second;
1318   return {0, nullptr};
1319 }
1320 
1321 const DSAStackTy::LCDeclInfo
1322 DSAStackTy::isLoopControlVariable(const ValueDecl *D, unsigned Level) const {
1323   assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
1324   D = getCanonicalDecl(D);
1325   for (unsigned I = Level + 1; I > 0; --I) {
1326     const SharingMapTy &StackElem = getStackElemAtLevel(I - 1);
1327     auto It = StackElem.LCVMap.find(D);
1328     if (It != StackElem.LCVMap.end())
1329       return It->second;
1330   }
1331   return {0, nullptr};
1332 }
1333 
1334 const DSAStackTy::LCDeclInfo
1335 DSAStackTy::isParentLoopControlVariable(const ValueDecl *D) const {
1336   const SharingMapTy *Parent = getSecondOnStackOrNull();
1337   assert(Parent && "Data-sharing attributes stack is empty");
1338   D = getCanonicalDecl(D);
1339   auto It = Parent->LCVMap.find(D);
1340   if (It != Parent->LCVMap.end())
1341     return It->second;
1342   return {0, nullptr};
1343 }
1344 
1345 const ValueDecl *DSAStackTy::getParentLoopControlVariable(unsigned I) const {
1346   const SharingMapTy *Parent = getSecondOnStackOrNull();
1347   assert(Parent && "Data-sharing attributes stack is empty");
1348   if (Parent->LCVMap.size() < I)
1349     return nullptr;
1350   for (const auto &Pair : Parent->LCVMap)
1351     if (Pair.second.first == I)
1352       return Pair.first;
1353   return nullptr;
1354 }
1355 
1356 void DSAStackTy::addDSA(const ValueDecl *D, const Expr *E, OpenMPClauseKind A,
1357                         DeclRefExpr *PrivateCopy, unsigned Modifier,
1358                         bool AppliedToPointee) {
1359   D = getCanonicalDecl(D);
1360   if (A == OMPC_threadprivate) {
1361     DSAInfo &Data = Threadprivates[D];
1362     Data.Attributes = A;
1363     Data.RefExpr.setPointer(E);
1364     Data.PrivateCopy = nullptr;
1365     Data.Modifier = Modifier;
1366   } else {
1367     DSAInfo &Data = getTopOfStack().SharingMap[D];
1368     assert(Data.Attributes == OMPC_unknown || (A == Data.Attributes) ||
1369            (A == OMPC_firstprivate && Data.Attributes == OMPC_lastprivate) ||
1370            (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) ||
1371            (isLoopControlVariable(D).first && A == OMPC_private));
1372     Data.Modifier = Modifier;
1373     if (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) {
1374       Data.RefExpr.setInt(/*IntVal=*/true);
1375       return;
1376     }
1377     const bool IsLastprivate =
1378         A == OMPC_lastprivate || Data.Attributes == OMPC_lastprivate;
1379     Data.Attributes = A;
1380     Data.RefExpr.setPointerAndInt(E, IsLastprivate);
1381     Data.PrivateCopy = PrivateCopy;
1382     Data.AppliedToPointee = AppliedToPointee;
1383     if (PrivateCopy) {
1384       DSAInfo &Data = getTopOfStack().SharingMap[PrivateCopy->getDecl()];
1385       Data.Modifier = Modifier;
1386       Data.Attributes = A;
1387       Data.RefExpr.setPointerAndInt(PrivateCopy, IsLastprivate);
1388       Data.PrivateCopy = nullptr;
1389       Data.AppliedToPointee = AppliedToPointee;
1390     }
1391   }
1392 }
1393 
1394 /// Build a variable declaration for OpenMP loop iteration variable.
1395 static VarDecl *buildVarDecl(Sema &SemaRef, SourceLocation Loc, QualType Type,
1396                              StringRef Name, const AttrVec *Attrs = nullptr,
1397                              DeclRefExpr *OrigRef = nullptr) {
1398   DeclContext *DC = SemaRef.CurContext;
1399   IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
1400   TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
1401   auto *Decl =
1402       VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, TInfo, SC_None);
1403   if (Attrs) {
1404     for (specific_attr_iterator<AlignedAttr> I(Attrs->begin()), E(Attrs->end());
1405          I != E; ++I)
1406       Decl->addAttr(*I);
1407   }
1408   Decl->setImplicit();
1409   if (OrigRef) {
1410     Decl->addAttr(
1411         OMPReferencedVarAttr::CreateImplicit(SemaRef.Context, OrigRef));
1412   }
1413   return Decl;
1414 }
1415 
1416 static DeclRefExpr *buildDeclRefExpr(Sema &S, VarDecl *D, QualType Ty,
1417                                      SourceLocation Loc,
1418                                      bool RefersToCapture = false) {
1419   D->setReferenced();
1420   D->markUsed(S.Context);
1421   return DeclRefExpr::Create(S.getASTContext(), NestedNameSpecifierLoc(),
1422                              SourceLocation(), D, RefersToCapture, Loc, Ty,
1423                              VK_LValue);
1424 }
1425 
1426 void DSAStackTy::addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
1427                                            BinaryOperatorKind BOK) {
1428   D = getCanonicalDecl(D);
1429   assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
1430   assert(
1431       getTopOfStack().SharingMap[D].Attributes == OMPC_reduction &&
1432       "Additional reduction info may be specified only for reduction items.");
1433   ReductionData &ReductionData = getTopOfStack().ReductionMap[D];
1434   assert(ReductionData.ReductionRange.isInvalid() &&
1435          (getTopOfStack().Directive == OMPD_taskgroup ||
1436           ((isOpenMPParallelDirective(getTopOfStack().Directive) ||
1437             isOpenMPWorksharingDirective(getTopOfStack().Directive)) &&
1438            !isOpenMPSimdDirective(getTopOfStack().Directive))) &&
1439          "Additional reduction info may be specified only once for reduction "
1440          "items.");
1441   ReductionData.set(BOK, SR);
1442   Expr *&TaskgroupReductionRef =
1443       getTopOfStack().TaskgroupReductionRef;
1444   if (!TaskgroupReductionRef) {
1445     VarDecl *VD = buildVarDecl(SemaRef, SR.getBegin(),
1446                                SemaRef.Context.VoidPtrTy, ".task_red.");
1447     TaskgroupReductionRef =
1448         buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin());
1449   }
1450 }
1451 
1452 void DSAStackTy::addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
1453                                            const Expr *ReductionRef) {
1454   D = getCanonicalDecl(D);
1455   assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
1456   assert(
1457       getTopOfStack().SharingMap[D].Attributes == OMPC_reduction &&
1458       "Additional reduction info may be specified only for reduction items.");
1459   ReductionData &ReductionData = getTopOfStack().ReductionMap[D];
1460   assert(ReductionData.ReductionRange.isInvalid() &&
1461          (getTopOfStack().Directive == OMPD_taskgroup ||
1462           ((isOpenMPParallelDirective(getTopOfStack().Directive) ||
1463             isOpenMPWorksharingDirective(getTopOfStack().Directive)) &&
1464            !isOpenMPSimdDirective(getTopOfStack().Directive))) &&
1465          "Additional reduction info may be specified only once for reduction "
1466          "items.");
1467   ReductionData.set(ReductionRef, SR);
1468   Expr *&TaskgroupReductionRef =
1469       getTopOfStack().TaskgroupReductionRef;
1470   if (!TaskgroupReductionRef) {
1471     VarDecl *VD = buildVarDecl(SemaRef, SR.getBegin(),
1472                                SemaRef.Context.VoidPtrTy, ".task_red.");
1473     TaskgroupReductionRef =
1474         buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin());
1475   }
1476 }
1477 
1478 const DSAStackTy::DSAVarData DSAStackTy::getTopMostTaskgroupReductionData(
1479     const ValueDecl *D, SourceRange &SR, BinaryOperatorKind &BOK,
1480     Expr *&TaskgroupDescriptor) const {
1481   D = getCanonicalDecl(D);
1482   assert(!isStackEmpty() && "Data-sharing attributes stack is empty.");
1483   for (const_iterator I = begin() + 1, E = end(); I != E; ++I) {
1484     const DSAInfo &Data = I->SharingMap.lookup(D);
1485     if (Data.Attributes != OMPC_reduction ||
1486         Data.Modifier != OMPC_REDUCTION_task)
1487       continue;
1488     const ReductionData &ReductionData = I->ReductionMap.lookup(D);
1489     if (!ReductionData.ReductionOp ||
1490         ReductionData.ReductionOp.is<const Expr *>())
1491       return DSAVarData();
1492     SR = ReductionData.ReductionRange;
1493     BOK = ReductionData.ReductionOp.get<ReductionData::BOKPtrType>();
1494     assert(I->TaskgroupReductionRef && "taskgroup reduction reference "
1495                                        "expression for the descriptor is not "
1496                                        "set.");
1497     TaskgroupDescriptor = I->TaskgroupReductionRef;
1498     return DSAVarData(I->Directive, OMPC_reduction, Data.RefExpr.getPointer(),
1499                       Data.PrivateCopy, I->DefaultAttrLoc, OMPC_REDUCTION_task,
1500                       /*AppliedToPointee=*/false);
1501   }
1502   return DSAVarData();
1503 }
1504 
1505 const DSAStackTy::DSAVarData DSAStackTy::getTopMostTaskgroupReductionData(
1506     const ValueDecl *D, SourceRange &SR, const Expr *&ReductionRef,
1507     Expr *&TaskgroupDescriptor) const {
1508   D = getCanonicalDecl(D);
1509   assert(!isStackEmpty() && "Data-sharing attributes stack is empty.");
1510   for (const_iterator I = begin() + 1, E = end(); I != E; ++I) {
1511     const DSAInfo &Data = I->SharingMap.lookup(D);
1512     if (Data.Attributes != OMPC_reduction ||
1513         Data.Modifier != OMPC_REDUCTION_task)
1514       continue;
1515     const ReductionData &ReductionData = I->ReductionMap.lookup(D);
1516     if (!ReductionData.ReductionOp ||
1517         !ReductionData.ReductionOp.is<const Expr *>())
1518       return DSAVarData();
1519     SR = ReductionData.ReductionRange;
1520     ReductionRef = ReductionData.ReductionOp.get<const Expr *>();
1521     assert(I->TaskgroupReductionRef && "taskgroup reduction reference "
1522                                        "expression for the descriptor is not "
1523                                        "set.");
1524     TaskgroupDescriptor = I->TaskgroupReductionRef;
1525     return DSAVarData(I->Directive, OMPC_reduction, Data.RefExpr.getPointer(),
1526                       Data.PrivateCopy, I->DefaultAttrLoc, OMPC_REDUCTION_task,
1527                       /*AppliedToPointee=*/false);
1528   }
1529   return DSAVarData();
1530 }
1531 
1532 bool DSAStackTy::isOpenMPLocal(VarDecl *D, const_iterator I) const {
1533   D = D->getCanonicalDecl();
1534   for (const_iterator E = end(); I != E; ++I) {
1535     if (isImplicitOrExplicitTaskingRegion(I->Directive) ||
1536         isOpenMPTargetExecutionDirective(I->Directive)) {
1537       if (I->CurScope) {
1538         Scope *TopScope = I->CurScope->getParent();
1539         Scope *CurScope = getCurScope();
1540         while (CurScope && CurScope != TopScope && !CurScope->isDeclScope(D))
1541           CurScope = CurScope->getParent();
1542         return CurScope != TopScope;
1543       }
1544       for (DeclContext *DC = D->getDeclContext(); DC; DC = DC->getParent())
1545         if (I->Context == DC)
1546           return true;
1547       return false;
1548     }
1549   }
1550   return false;
1551 }
1552 
1553 static bool isConstNotMutableType(Sema &SemaRef, QualType Type,
1554                                   bool AcceptIfMutable = true,
1555                                   bool *IsClassType = nullptr) {
1556   ASTContext &Context = SemaRef.getASTContext();
1557   Type = Type.getNonReferenceType().getCanonicalType();
1558   bool IsConstant = Type.isConstant(Context);
1559   Type = Context.getBaseElementType(Type);
1560   const CXXRecordDecl *RD = AcceptIfMutable && SemaRef.getLangOpts().CPlusPlus
1561                                 ? Type->getAsCXXRecordDecl()
1562                                 : nullptr;
1563   if (const auto *CTSD = dyn_cast_or_null<ClassTemplateSpecializationDecl>(RD))
1564     if (const ClassTemplateDecl *CTD = CTSD->getSpecializedTemplate())
1565       RD = CTD->getTemplatedDecl();
1566   if (IsClassType)
1567     *IsClassType = RD;
1568   return IsConstant && !(SemaRef.getLangOpts().CPlusPlus && RD &&
1569                          RD->hasDefinition() && RD->hasMutableFields());
1570 }
1571 
1572 static bool rejectConstNotMutableType(Sema &SemaRef, const ValueDecl *D,
1573                                       QualType Type, OpenMPClauseKind CKind,
1574                                       SourceLocation ELoc,
1575                                       bool AcceptIfMutable = true,
1576                                       bool ListItemNotVar = false) {
1577   ASTContext &Context = SemaRef.getASTContext();
1578   bool IsClassType;
1579   if (isConstNotMutableType(SemaRef, Type, AcceptIfMutable, &IsClassType)) {
1580     unsigned Diag = ListItemNotVar
1581                         ? diag::err_omp_const_list_item
1582                         : IsClassType ? diag::err_omp_const_not_mutable_variable
1583                                       : diag::err_omp_const_variable;
1584     SemaRef.Diag(ELoc, Diag) << getOpenMPClauseName(CKind);
1585     if (!ListItemNotVar && D) {
1586       const VarDecl *VD = dyn_cast<VarDecl>(D);
1587       bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
1588                                VarDecl::DeclarationOnly;
1589       SemaRef.Diag(D->getLocation(),
1590                    IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1591           << D;
1592     }
1593     return true;
1594   }
1595   return false;
1596 }
1597 
1598 const DSAStackTy::DSAVarData DSAStackTy::getTopDSA(ValueDecl *D,
1599                                                    bool FromParent) {
1600   D = getCanonicalDecl(D);
1601   DSAVarData DVar;
1602 
1603   auto *VD = dyn_cast<VarDecl>(D);
1604   auto TI = Threadprivates.find(D);
1605   if (TI != Threadprivates.end()) {
1606     DVar.RefExpr = TI->getSecond().RefExpr.getPointer();
1607     DVar.CKind = OMPC_threadprivate;
1608     DVar.Modifier = TI->getSecond().Modifier;
1609     return DVar;
1610   }
1611   if (VD && VD->hasAttr<OMPThreadPrivateDeclAttr>()) {
1612     DVar.RefExpr = buildDeclRefExpr(
1613         SemaRef, VD, D->getType().getNonReferenceType(),
1614         VD->getAttr<OMPThreadPrivateDeclAttr>()->getLocation());
1615     DVar.CKind = OMPC_threadprivate;
1616     addDSA(D, DVar.RefExpr, OMPC_threadprivate);
1617     return DVar;
1618   }
1619   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1620   // in a Construct, C/C++, predetermined, p.1]
1621   //  Variables appearing in threadprivate directives are threadprivate.
1622   if ((VD && VD->getTLSKind() != VarDecl::TLS_None &&
1623        !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
1624          SemaRef.getLangOpts().OpenMPUseTLS &&
1625          SemaRef.getASTContext().getTargetInfo().isTLSSupported())) ||
1626       (VD && VD->getStorageClass() == SC_Register &&
1627        VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())) {
1628     DVar.RefExpr = buildDeclRefExpr(
1629         SemaRef, VD, D->getType().getNonReferenceType(), D->getLocation());
1630     DVar.CKind = OMPC_threadprivate;
1631     addDSA(D, DVar.RefExpr, OMPC_threadprivate);
1632     return DVar;
1633   }
1634   if (SemaRef.getLangOpts().OpenMPCUDAMode && VD &&
1635       VD->isLocalVarDeclOrParm() && !isStackEmpty() &&
1636       !isLoopControlVariable(D).first) {
1637     const_iterator IterTarget =
1638         std::find_if(begin(), end(), [](const SharingMapTy &Data) {
1639           return isOpenMPTargetExecutionDirective(Data.Directive);
1640         });
1641     if (IterTarget != end()) {
1642       const_iterator ParentIterTarget = IterTarget + 1;
1643       for (const_iterator Iter = begin();
1644            Iter != ParentIterTarget; ++Iter) {
1645         if (isOpenMPLocal(VD, Iter)) {
1646           DVar.RefExpr =
1647               buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(),
1648                                D->getLocation());
1649           DVar.CKind = OMPC_threadprivate;
1650           return DVar;
1651         }
1652       }
1653       if (!isClauseParsingMode() || IterTarget != begin()) {
1654         auto DSAIter = IterTarget->SharingMap.find(D);
1655         if (DSAIter != IterTarget->SharingMap.end() &&
1656             isOpenMPPrivate(DSAIter->getSecond().Attributes)) {
1657           DVar.RefExpr = DSAIter->getSecond().RefExpr.getPointer();
1658           DVar.CKind = OMPC_threadprivate;
1659           return DVar;
1660         }
1661         const_iterator End = end();
1662         if (!SemaRef.isOpenMPCapturedByRef(
1663                 D, std::distance(ParentIterTarget, End),
1664                 /*OpenMPCaptureLevel=*/0)) {
1665           DVar.RefExpr =
1666               buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(),
1667                                IterTarget->ConstructLoc);
1668           DVar.CKind = OMPC_threadprivate;
1669           return DVar;
1670         }
1671       }
1672     }
1673   }
1674 
1675   if (isStackEmpty())
1676     // Not in OpenMP execution region and top scope was already checked.
1677     return DVar;
1678 
1679   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1680   // in a Construct, C/C++, predetermined, p.4]
1681   //  Static data members are shared.
1682   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1683   // in a Construct, C/C++, predetermined, p.7]
1684   //  Variables with static storage duration that are declared in a scope
1685   //  inside the construct are shared.
1686   if (VD && VD->isStaticDataMember()) {
1687     // Check for explicitly specified attributes.
1688     const_iterator I = begin();
1689     const_iterator EndI = end();
1690     if (FromParent && I != EndI)
1691       ++I;
1692     if (I != EndI) {
1693       auto It = I->SharingMap.find(D);
1694       if (It != I->SharingMap.end()) {
1695         const DSAInfo &Data = It->getSecond();
1696         DVar.RefExpr = Data.RefExpr.getPointer();
1697         DVar.PrivateCopy = Data.PrivateCopy;
1698         DVar.CKind = Data.Attributes;
1699         DVar.ImplicitDSALoc = I->DefaultAttrLoc;
1700         DVar.DKind = I->Directive;
1701         DVar.Modifier = Data.Modifier;
1702         DVar.AppliedToPointee = Data.AppliedToPointee;
1703         return DVar;
1704       }
1705     }
1706 
1707     DVar.CKind = OMPC_shared;
1708     return DVar;
1709   }
1710 
1711   auto &&MatchesAlways = [](OpenMPDirectiveKind) { return true; };
1712   // The predetermined shared attribute for const-qualified types having no
1713   // mutable members was removed after OpenMP 3.1.
1714   if (SemaRef.LangOpts.OpenMP <= 31) {
1715     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1716     // in a Construct, C/C++, predetermined, p.6]
1717     //  Variables with const qualified type having no mutable member are
1718     //  shared.
1719     if (isConstNotMutableType(SemaRef, D->getType())) {
1720       // Variables with const-qualified type having no mutable member may be
1721       // listed in a firstprivate clause, even if they are static data members.
1722       DSAVarData DVarTemp = hasInnermostDSA(
1723           D,
1724           [](OpenMPClauseKind C, bool) {
1725             return C == OMPC_firstprivate || C == OMPC_shared;
1726           },
1727           MatchesAlways, FromParent);
1728       if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr)
1729         return DVarTemp;
1730 
1731       DVar.CKind = OMPC_shared;
1732       return DVar;
1733     }
1734   }
1735 
1736   // Explicitly specified attributes and local variables with predetermined
1737   // attributes.
1738   const_iterator I = begin();
1739   const_iterator EndI = end();
1740   if (FromParent && I != EndI)
1741     ++I;
1742   if (I == EndI)
1743     return DVar;
1744   auto It = I->SharingMap.find(D);
1745   if (It != I->SharingMap.end()) {
1746     const DSAInfo &Data = It->getSecond();
1747     DVar.RefExpr = Data.RefExpr.getPointer();
1748     DVar.PrivateCopy = Data.PrivateCopy;
1749     DVar.CKind = Data.Attributes;
1750     DVar.ImplicitDSALoc = I->DefaultAttrLoc;
1751     DVar.DKind = I->Directive;
1752     DVar.Modifier = Data.Modifier;
1753     DVar.AppliedToPointee = Data.AppliedToPointee;
1754   }
1755 
1756   return DVar;
1757 }
1758 
1759 const DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(ValueDecl *D,
1760                                                         bool FromParent) const {
1761   if (isStackEmpty()) {
1762     const_iterator I;
1763     return getDSA(I, D);
1764   }
1765   D = getCanonicalDecl(D);
1766   const_iterator StartI = begin();
1767   const_iterator EndI = end();
1768   if (FromParent && StartI != EndI)
1769     ++StartI;
1770   return getDSA(StartI, D);
1771 }
1772 
1773 const DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(ValueDecl *D,
1774                                                         unsigned Level) const {
1775   if (getStackSize() <= Level)
1776     return DSAVarData();
1777   D = getCanonicalDecl(D);
1778   const_iterator StartI = std::next(begin(), getStackSize() - 1 - Level);
1779   return getDSA(StartI, D);
1780 }
1781 
1782 const DSAStackTy::DSAVarData
1783 DSAStackTy::hasDSA(ValueDecl *D,
1784                    const llvm::function_ref<bool(OpenMPClauseKind, bool)> CPred,
1785                    const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
1786                    bool FromParent) const {
1787   if (isStackEmpty())
1788     return {};
1789   D = getCanonicalDecl(D);
1790   const_iterator I = begin();
1791   const_iterator EndI = end();
1792   if (FromParent && I != EndI)
1793     ++I;
1794   for (; I != EndI; ++I) {
1795     if (!DPred(I->Directive) &&
1796         !isImplicitOrExplicitTaskingRegion(I->Directive))
1797       continue;
1798     const_iterator NewI = I;
1799     DSAVarData DVar = getDSA(NewI, D);
1800     if (I == NewI && CPred(DVar.CKind, DVar.AppliedToPointee))
1801       return DVar;
1802   }
1803   return {};
1804 }
1805 
1806 const DSAStackTy::DSAVarData DSAStackTy::hasInnermostDSA(
1807     ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind, bool)> CPred,
1808     const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
1809     bool FromParent) const {
1810   if (isStackEmpty())
1811     return {};
1812   D = getCanonicalDecl(D);
1813   const_iterator StartI = begin();
1814   const_iterator EndI = end();
1815   if (FromParent && StartI != EndI)
1816     ++StartI;
1817   if (StartI == EndI || !DPred(StartI->Directive))
1818     return {};
1819   const_iterator NewI = StartI;
1820   DSAVarData DVar = getDSA(NewI, D);
1821   return (NewI == StartI && CPred(DVar.CKind, DVar.AppliedToPointee))
1822              ? DVar
1823              : DSAVarData();
1824 }
1825 
1826 bool DSAStackTy::hasExplicitDSA(
1827     const ValueDecl *D,
1828     const llvm::function_ref<bool(OpenMPClauseKind, bool)> CPred,
1829     unsigned Level, bool NotLastprivate) const {
1830   if (getStackSize() <= Level)
1831     return false;
1832   D = getCanonicalDecl(D);
1833   const SharingMapTy &StackElem = getStackElemAtLevel(Level);
1834   auto I = StackElem.SharingMap.find(D);
1835   if (I != StackElem.SharingMap.end() && I->getSecond().RefExpr.getPointer() &&
1836       CPred(I->getSecond().Attributes, I->getSecond().AppliedToPointee) &&
1837       (!NotLastprivate || !I->getSecond().RefExpr.getInt()))
1838     return true;
1839   // Check predetermined rules for the loop control variables.
1840   auto LI = StackElem.LCVMap.find(D);
1841   if (LI != StackElem.LCVMap.end())
1842     return CPred(OMPC_private, /*AppliedToPointee=*/false);
1843   return false;
1844 }
1845 
1846 bool DSAStackTy::hasExplicitDirective(
1847     const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
1848     unsigned Level) const {
1849   if (getStackSize() <= Level)
1850     return false;
1851   const SharingMapTy &StackElem = getStackElemAtLevel(Level);
1852   return DPred(StackElem.Directive);
1853 }
1854 
1855 bool DSAStackTy::hasDirective(
1856     const llvm::function_ref<bool(OpenMPDirectiveKind,
1857                                   const DeclarationNameInfo &, SourceLocation)>
1858         DPred,
1859     bool FromParent) const {
1860   // We look only in the enclosing region.
1861   size_t Skip = FromParent ? 2 : 1;
1862   for (const_iterator I = begin() + std::min(Skip, getStackSize()), E = end();
1863        I != E; ++I) {
1864     if (DPred(I->Directive, I->DirectiveName, I->ConstructLoc))
1865       return true;
1866   }
1867   return false;
1868 }
1869 
1870 void Sema::InitDataSharingAttributesStack() {
1871   VarDataSharingAttributesStack = new DSAStackTy(*this);
1872 }
1873 
1874 #define DSAStack static_cast<DSAStackTy *>(VarDataSharingAttributesStack)
1875 
1876 void Sema::pushOpenMPFunctionRegion() {
1877   DSAStack->pushFunction();
1878 }
1879 
1880 void Sema::popOpenMPFunctionRegion(const FunctionScopeInfo *OldFSI) {
1881   DSAStack->popFunction(OldFSI);
1882 }
1883 
1884 static bool isOpenMPDeviceDelayedContext(Sema &S) {
1885   assert(S.LangOpts.OpenMP && S.LangOpts.OpenMPIsDevice &&
1886          "Expected OpenMP device compilation.");
1887   return !S.isInOpenMPTargetExecutionDirective() &&
1888          !S.isInOpenMPDeclareTargetContext();
1889 }
1890 
1891 namespace {
1892 /// Status of the function emission on the host/device.
1893 enum class FunctionEmissionStatus {
1894   Emitted,
1895   Discarded,
1896   Unknown,
1897 };
1898 } // anonymous namespace
1899 
1900 Sema::SemaDiagnosticBuilder Sema::diagIfOpenMPDeviceCode(SourceLocation Loc,
1901                                                          unsigned DiagID) {
1902   assert(LangOpts.OpenMP && LangOpts.OpenMPIsDevice &&
1903          "Expected OpenMP device compilation.");
1904 
1905   FunctionDecl *FD = getCurFunctionDecl();
1906   SemaDiagnosticBuilder::Kind Kind = SemaDiagnosticBuilder::K_Nop;
1907   if (FD) {
1908     FunctionEmissionStatus FES = getEmissionStatus(FD);
1909     switch (FES) {
1910     case FunctionEmissionStatus::Emitted:
1911       Kind = SemaDiagnosticBuilder::K_Immediate;
1912       break;
1913     case FunctionEmissionStatus::Unknown:
1914       Kind = isOpenMPDeviceDelayedContext(*this)
1915                  ? SemaDiagnosticBuilder::K_Deferred
1916                  : SemaDiagnosticBuilder::K_Immediate;
1917       break;
1918     case FunctionEmissionStatus::TemplateDiscarded:
1919     case FunctionEmissionStatus::OMPDiscarded:
1920       Kind = SemaDiagnosticBuilder::K_Nop;
1921       break;
1922     case FunctionEmissionStatus::CUDADiscarded:
1923       llvm_unreachable("CUDADiscarded unexpected in OpenMP device compilation");
1924       break;
1925     }
1926   }
1927 
1928   return SemaDiagnosticBuilder(Kind, Loc, DiagID, getCurFunctionDecl(), *this);
1929 }
1930 
1931 Sema::SemaDiagnosticBuilder Sema::diagIfOpenMPHostCode(SourceLocation Loc,
1932                                                        unsigned DiagID) {
1933   assert(LangOpts.OpenMP && !LangOpts.OpenMPIsDevice &&
1934          "Expected OpenMP host compilation.");
1935   FunctionEmissionStatus FES = getEmissionStatus(getCurFunctionDecl());
1936   SemaDiagnosticBuilder::Kind Kind = SemaDiagnosticBuilder::K_Nop;
1937   switch (FES) {
1938   case FunctionEmissionStatus::Emitted:
1939     Kind = SemaDiagnosticBuilder::K_Immediate;
1940     break;
1941   case FunctionEmissionStatus::Unknown:
1942     Kind = SemaDiagnosticBuilder::K_Deferred;
1943     break;
1944   case FunctionEmissionStatus::TemplateDiscarded:
1945   case FunctionEmissionStatus::OMPDiscarded:
1946   case FunctionEmissionStatus::CUDADiscarded:
1947     Kind = SemaDiagnosticBuilder::K_Nop;
1948     break;
1949   }
1950 
1951   return SemaDiagnosticBuilder(Kind, Loc, DiagID, getCurFunctionDecl(), *this);
1952 }
1953 
1954 static OpenMPDefaultmapClauseKind
1955 getVariableCategoryFromDecl(const LangOptions &LO, const ValueDecl *VD) {
1956   if (LO.OpenMP <= 45) {
1957     if (VD->getType().getNonReferenceType()->isScalarType())
1958       return OMPC_DEFAULTMAP_scalar;
1959     return OMPC_DEFAULTMAP_aggregate;
1960   }
1961   if (VD->getType().getNonReferenceType()->isAnyPointerType())
1962     return OMPC_DEFAULTMAP_pointer;
1963   if (VD->getType().getNonReferenceType()->isScalarType())
1964     return OMPC_DEFAULTMAP_scalar;
1965   return OMPC_DEFAULTMAP_aggregate;
1966 }
1967 
1968 bool Sema::isOpenMPCapturedByRef(const ValueDecl *D, unsigned Level,
1969                                  unsigned OpenMPCaptureLevel) const {
1970   assert(LangOpts.OpenMP && "OpenMP is not allowed");
1971 
1972   ASTContext &Ctx = getASTContext();
1973   bool IsByRef = true;
1974 
1975   // Find the directive that is associated with the provided scope.
1976   D = cast<ValueDecl>(D->getCanonicalDecl());
1977   QualType Ty = D->getType();
1978 
1979   bool IsVariableUsedInMapClause = false;
1980   if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, Level)) {
1981     // This table summarizes how a given variable should be passed to the device
1982     // given its type and the clauses where it appears. This table is based on
1983     // the description in OpenMP 4.5 [2.10.4, target Construct] and
1984     // OpenMP 4.5 [2.15.5, Data-mapping Attribute Rules and Clauses].
1985     //
1986     // =========================================================================
1987     // | type |  defaultmap   | pvt | first | is_device_ptr |    map   | res.  |
1988     // |      |(tofrom:scalar)|     |  pvt  |               |          |       |
1989     // =========================================================================
1990     // | scl  |               |     |       |       -       |          | bycopy|
1991     // | scl  |               |  -  |   x   |       -       |     -    | bycopy|
1992     // | scl  |               |  x  |   -   |       -       |     -    | null  |
1993     // | scl  |       x       |     |       |       -       |          | byref |
1994     // | scl  |       x       |  -  |   x   |       -       |     -    | bycopy|
1995     // | scl  |       x       |  x  |   -   |       -       |     -    | null  |
1996     // | scl  |               |  -  |   -   |       -       |     x    | byref |
1997     // | scl  |       x       |  -  |   -   |       -       |     x    | byref |
1998     //
1999     // | agg  |      n.a.     |     |       |       -       |          | byref |
2000     // | agg  |      n.a.     |  -  |   x   |       -       |     -    | byref |
2001     // | agg  |      n.a.     |  x  |   -   |       -       |     -    | null  |
2002     // | agg  |      n.a.     |  -  |   -   |       -       |     x    | byref |
2003     // | agg  |      n.a.     |  -  |   -   |       -       |    x[]   | byref |
2004     //
2005     // | ptr  |      n.a.     |     |       |       -       |          | bycopy|
2006     // | ptr  |      n.a.     |  -  |   x   |       -       |     -    | bycopy|
2007     // | ptr  |      n.a.     |  x  |   -   |       -       |     -    | null  |
2008     // | ptr  |      n.a.     |  -  |   -   |       -       |     x    | byref |
2009     // | ptr  |      n.a.     |  -  |   -   |       -       |    x[]   | bycopy|
2010     // | ptr  |      n.a.     |  -  |   -   |       x       |          | bycopy|
2011     // | ptr  |      n.a.     |  -  |   -   |       x       |     x    | bycopy|
2012     // | ptr  |      n.a.     |  -  |   -   |       x       |    x[]   | bycopy|
2013     // =========================================================================
2014     // Legend:
2015     //  scl - scalar
2016     //  ptr - pointer
2017     //  agg - aggregate
2018     //  x - applies
2019     //  - - invalid in this combination
2020     //  [] - mapped with an array section
2021     //  byref - should be mapped by reference
2022     //  byval - should be mapped by value
2023     //  null - initialize a local variable to null on the device
2024     //
2025     // Observations:
2026     //  - All scalar declarations that show up in a map clause have to be passed
2027     //    by reference, because they may have been mapped in the enclosing data
2028     //    environment.
2029     //  - If the scalar value does not fit the size of uintptr, it has to be
2030     //    passed by reference, regardless the result in the table above.
2031     //  - For pointers mapped by value that have either an implicit map or an
2032     //    array section, the runtime library may pass the NULL value to the
2033     //    device instead of the value passed to it by the compiler.
2034 
2035     if (Ty->isReferenceType())
2036       Ty = Ty->castAs<ReferenceType>()->getPointeeType();
2037 
2038     // Locate map clauses and see if the variable being captured is referred to
2039     // in any of those clauses. Here we only care about variables, not fields,
2040     // because fields are part of aggregates.
2041     bool IsVariableAssociatedWithSection = false;
2042 
2043     DSAStack->checkMappableExprComponentListsForDeclAtLevel(
2044         D, Level,
2045         [&IsVariableUsedInMapClause, &IsVariableAssociatedWithSection, D](
2046             OMPClauseMappableExprCommon::MappableExprComponentListRef
2047                 MapExprComponents,
2048             OpenMPClauseKind WhereFoundClauseKind) {
2049           // Only the map clause information influences how a variable is
2050           // captured. E.g. is_device_ptr does not require changing the default
2051           // behavior.
2052           if (WhereFoundClauseKind != OMPC_map)
2053             return false;
2054 
2055           auto EI = MapExprComponents.rbegin();
2056           auto EE = MapExprComponents.rend();
2057 
2058           assert(EI != EE && "Invalid map expression!");
2059 
2060           if (isa<DeclRefExpr>(EI->getAssociatedExpression()))
2061             IsVariableUsedInMapClause |= EI->getAssociatedDeclaration() == D;
2062 
2063           ++EI;
2064           if (EI == EE)
2065             return false;
2066 
2067           if (isa<ArraySubscriptExpr>(EI->getAssociatedExpression()) ||
2068               isa<OMPArraySectionExpr>(EI->getAssociatedExpression()) ||
2069               isa<MemberExpr>(EI->getAssociatedExpression()) ||
2070               isa<OMPArrayShapingExpr>(EI->getAssociatedExpression())) {
2071             IsVariableAssociatedWithSection = true;
2072             // There is nothing more we need to know about this variable.
2073             return true;
2074           }
2075 
2076           // Keep looking for more map info.
2077           return false;
2078         });
2079 
2080     if (IsVariableUsedInMapClause) {
2081       // If variable is identified in a map clause it is always captured by
2082       // reference except if it is a pointer that is dereferenced somehow.
2083       IsByRef = !(Ty->isPointerType() && IsVariableAssociatedWithSection);
2084     } else {
2085       // By default, all the data that has a scalar type is mapped by copy
2086       // (except for reduction variables).
2087       // Defaultmap scalar is mutual exclusive to defaultmap pointer
2088       IsByRef = (DSAStack->isForceCaptureByReferenceInTargetExecutable() &&
2089                  !Ty->isAnyPointerType()) ||
2090                 !Ty->isScalarType() ||
2091                 DSAStack->isDefaultmapCapturedByRef(
2092                     Level, getVariableCategoryFromDecl(LangOpts, D)) ||
2093                 DSAStack->hasExplicitDSA(
2094                     D,
2095                     [](OpenMPClauseKind K, bool AppliedToPointee) {
2096                       return K == OMPC_reduction && !AppliedToPointee;
2097                     },
2098                     Level);
2099     }
2100   }
2101 
2102   if (IsByRef && Ty.getNonReferenceType()->isScalarType()) {
2103     IsByRef =
2104         ((IsVariableUsedInMapClause &&
2105           DSAStack->getCaptureRegion(Level, OpenMPCaptureLevel) ==
2106               OMPD_target) ||
2107          !(DSAStack->hasExplicitDSA(
2108                D,
2109                [](OpenMPClauseKind K, bool AppliedToPointee) -> bool {
2110                  return K == OMPC_firstprivate ||
2111                         (K == OMPC_reduction && AppliedToPointee);
2112                },
2113                Level, /*NotLastprivate=*/true) ||
2114            DSAStack->isUsesAllocatorsDecl(Level, D))) &&
2115         // If the variable is artificial and must be captured by value - try to
2116         // capture by value.
2117         !(isa<OMPCapturedExprDecl>(D) && !D->hasAttr<OMPCaptureNoInitAttr>() &&
2118           !cast<OMPCapturedExprDecl>(D)->getInit()->isGLValue()) &&
2119         // If the variable is implicitly firstprivate and scalar - capture by
2120         // copy
2121         !(DSAStack->getDefaultDSA() == DSA_firstprivate &&
2122           !DSAStack->hasExplicitDSA(
2123               D, [](OpenMPClauseKind K, bool) { return K != OMPC_unknown; },
2124               Level) &&
2125           !DSAStack->isLoopControlVariable(D, Level).first);
2126   }
2127 
2128   // When passing data by copy, we need to make sure it fits the uintptr size
2129   // and alignment, because the runtime library only deals with uintptr types.
2130   // If it does not fit the uintptr size, we need to pass the data by reference
2131   // instead.
2132   if (!IsByRef &&
2133       (Ctx.getTypeSizeInChars(Ty) >
2134            Ctx.getTypeSizeInChars(Ctx.getUIntPtrType()) ||
2135        Ctx.getDeclAlign(D) > Ctx.getTypeAlignInChars(Ctx.getUIntPtrType()))) {
2136     IsByRef = true;
2137   }
2138 
2139   return IsByRef;
2140 }
2141 
2142 unsigned Sema::getOpenMPNestingLevel() const {
2143   assert(getLangOpts().OpenMP);
2144   return DSAStack->getNestingLevel();
2145 }
2146 
2147 bool Sema::isInOpenMPTargetExecutionDirective() const {
2148   return (isOpenMPTargetExecutionDirective(DSAStack->getCurrentDirective()) &&
2149           !DSAStack->isClauseParsingMode()) ||
2150          DSAStack->hasDirective(
2151              [](OpenMPDirectiveKind K, const DeclarationNameInfo &,
2152                 SourceLocation) -> bool {
2153                return isOpenMPTargetExecutionDirective(K);
2154              },
2155              false);
2156 }
2157 
2158 VarDecl *Sema::isOpenMPCapturedDecl(ValueDecl *D, bool CheckScopeInfo,
2159                                     unsigned StopAt) {
2160   assert(LangOpts.OpenMP && "OpenMP is not allowed");
2161   D = getCanonicalDecl(D);
2162 
2163   auto *VD = dyn_cast<VarDecl>(D);
2164   // Do not capture constexpr variables.
2165   if (VD && VD->isConstexpr())
2166     return nullptr;
2167 
2168   // If we want to determine whether the variable should be captured from the
2169   // perspective of the current capturing scope, and we've already left all the
2170   // capturing scopes of the top directive on the stack, check from the
2171   // perspective of its parent directive (if any) instead.
2172   DSAStackTy::ParentDirectiveScope InParentDirectiveRAII(
2173       *DSAStack, CheckScopeInfo && DSAStack->isBodyComplete());
2174 
2175   // If we are attempting to capture a global variable in a directive with
2176   // 'target' we return true so that this global is also mapped to the device.
2177   //
2178   if (VD && !VD->hasLocalStorage() &&
2179       (getCurCapturedRegion() || getCurBlock() || getCurLambda())) {
2180     if (isInOpenMPDeclareTargetContext()) {
2181       // Try to mark variable as declare target if it is used in capturing
2182       // regions.
2183       if (LangOpts.OpenMP <= 45 &&
2184           !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
2185         checkDeclIsAllowedInOpenMPTarget(nullptr, VD);
2186       return nullptr;
2187     }
2188     if (isInOpenMPTargetExecutionDirective()) {
2189       // If the declaration is enclosed in a 'declare target' directive,
2190       // then it should not be captured.
2191       //
2192       if (OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
2193         return nullptr;
2194       CapturedRegionScopeInfo *CSI = nullptr;
2195       for (FunctionScopeInfo *FSI : llvm::drop_begin(
2196                llvm::reverse(FunctionScopes),
2197                CheckScopeInfo ? (FunctionScopes.size() - (StopAt + 1)) : 0)) {
2198         if (!isa<CapturingScopeInfo>(FSI))
2199           return nullptr;
2200         if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(FSI))
2201           if (RSI->CapRegionKind == CR_OpenMP) {
2202             CSI = RSI;
2203             break;
2204           }
2205       }
2206       assert(CSI && "Failed to find CapturedRegionScopeInfo");
2207       SmallVector<OpenMPDirectiveKind, 4> Regions;
2208       getOpenMPCaptureRegions(Regions,
2209                               DSAStack->getDirective(CSI->OpenMPLevel));
2210       if (Regions[CSI->OpenMPCaptureLevel] != OMPD_task)
2211         return VD;
2212     }
2213   }
2214 
2215   if (CheckScopeInfo) {
2216     bool OpenMPFound = false;
2217     for (unsigned I = StopAt + 1; I > 0; --I) {
2218       FunctionScopeInfo *FSI = FunctionScopes[I - 1];
2219       if(!isa<CapturingScopeInfo>(FSI))
2220         return nullptr;
2221       if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(FSI))
2222         if (RSI->CapRegionKind == CR_OpenMP) {
2223           OpenMPFound = true;
2224           break;
2225         }
2226     }
2227     if (!OpenMPFound)
2228       return nullptr;
2229   }
2230 
2231   if (DSAStack->getCurrentDirective() != OMPD_unknown &&
2232       (!DSAStack->isClauseParsingMode() ||
2233        DSAStack->getParentDirective() != OMPD_unknown)) {
2234     auto &&Info = DSAStack->isLoopControlVariable(D);
2235     if (Info.first ||
2236         (VD && VD->hasLocalStorage() &&
2237          isImplicitOrExplicitTaskingRegion(DSAStack->getCurrentDirective())) ||
2238         (VD && DSAStack->isForceVarCapturing()))
2239       return VD ? VD : Info.second;
2240     DSAStackTy::DSAVarData DVarTop =
2241         DSAStack->getTopDSA(D, DSAStack->isClauseParsingMode());
2242     if (DVarTop.CKind != OMPC_unknown && isOpenMPPrivate(DVarTop.CKind) &&
2243         (!VD || VD->hasLocalStorage() || !DVarTop.AppliedToPointee))
2244       return VD ? VD : cast<VarDecl>(DVarTop.PrivateCopy->getDecl());
2245     // Threadprivate variables must not be captured.
2246     if (isOpenMPThreadPrivate(DVarTop.CKind))
2247       return nullptr;
2248     // The variable is not private or it is the variable in the directive with
2249     // default(none) clause and not used in any clause.
2250     DSAStackTy::DSAVarData DVarPrivate = DSAStack->hasDSA(
2251         D,
2252         [](OpenMPClauseKind C, bool AppliedToPointee) {
2253           return isOpenMPPrivate(C) && !AppliedToPointee;
2254         },
2255         [](OpenMPDirectiveKind) { return true; },
2256         DSAStack->isClauseParsingMode());
2257     // Global shared must not be captured.
2258     if (VD && !VD->hasLocalStorage() && DVarPrivate.CKind == OMPC_unknown &&
2259         ((DSAStack->getDefaultDSA() != DSA_none &&
2260           DSAStack->getDefaultDSA() != DSA_firstprivate) ||
2261          DVarTop.CKind == OMPC_shared))
2262       return nullptr;
2263     if (DVarPrivate.CKind != OMPC_unknown ||
2264         (VD && (DSAStack->getDefaultDSA() == DSA_none ||
2265                 DSAStack->getDefaultDSA() == DSA_firstprivate)))
2266       return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
2267   }
2268   return nullptr;
2269 }
2270 
2271 void Sema::adjustOpenMPTargetScopeIndex(unsigned &FunctionScopesIndex,
2272                                         unsigned Level) const {
2273   FunctionScopesIndex -= getOpenMPCaptureLevels(DSAStack->getDirective(Level));
2274 }
2275 
2276 void Sema::startOpenMPLoop() {
2277   assert(LangOpts.OpenMP && "OpenMP must be enabled.");
2278   if (isOpenMPLoopDirective(DSAStack->getCurrentDirective()))
2279     DSAStack->loopInit();
2280 }
2281 
2282 void Sema::startOpenMPCXXRangeFor() {
2283   assert(LangOpts.OpenMP && "OpenMP must be enabled.");
2284   if (isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
2285     DSAStack->resetPossibleLoopCounter();
2286     DSAStack->loopStart();
2287   }
2288 }
2289 
2290 OpenMPClauseKind Sema::isOpenMPPrivateDecl(ValueDecl *D, unsigned Level,
2291                                            unsigned CapLevel) const {
2292   assert(LangOpts.OpenMP && "OpenMP is not allowed");
2293   if (DSAStack->hasExplicitDirective(
2294           [](OpenMPDirectiveKind K) { return isOpenMPTaskingDirective(K); },
2295           Level)) {
2296     bool IsTriviallyCopyable =
2297         D->getType().getNonReferenceType().isTriviallyCopyableType(Context) &&
2298         !D->getType()
2299              .getNonReferenceType()
2300              .getCanonicalType()
2301              ->getAsCXXRecordDecl();
2302     OpenMPDirectiveKind DKind = DSAStack->getDirective(Level);
2303     SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
2304     getOpenMPCaptureRegions(CaptureRegions, DKind);
2305     if (isOpenMPTaskingDirective(CaptureRegions[CapLevel]) &&
2306         (IsTriviallyCopyable ||
2307          !isOpenMPTaskLoopDirective(CaptureRegions[CapLevel]))) {
2308       if (DSAStack->hasExplicitDSA(
2309               D,
2310               [](OpenMPClauseKind K, bool) { return K == OMPC_firstprivate; },
2311               Level, /*NotLastprivate=*/true))
2312         return OMPC_firstprivate;
2313       DSAStackTy::DSAVarData DVar = DSAStack->getImplicitDSA(D, Level);
2314       if (DVar.CKind != OMPC_shared &&
2315           !DSAStack->isLoopControlVariable(D, Level).first && !DVar.RefExpr) {
2316         DSAStack->addImplicitTaskFirstprivate(Level, D);
2317         return OMPC_firstprivate;
2318       }
2319     }
2320   }
2321   if (isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
2322     if (DSAStack->getAssociatedLoops() > 0 &&
2323         !DSAStack->isLoopStarted()) {
2324       DSAStack->resetPossibleLoopCounter(D);
2325       DSAStack->loopStart();
2326       return OMPC_private;
2327     }
2328     if ((DSAStack->getPossiblyLoopCunter() == D->getCanonicalDecl() ||
2329          DSAStack->isLoopControlVariable(D).first) &&
2330         !DSAStack->hasExplicitDSA(
2331             D, [](OpenMPClauseKind K, bool) { return K != OMPC_private; },
2332             Level) &&
2333         !isOpenMPSimdDirective(DSAStack->getCurrentDirective()))
2334       return OMPC_private;
2335   }
2336   if (const auto *VD = dyn_cast<VarDecl>(D)) {
2337     if (DSAStack->isThreadPrivate(const_cast<VarDecl *>(VD)) &&
2338         DSAStack->isForceVarCapturing() &&
2339         !DSAStack->hasExplicitDSA(
2340             D, [](OpenMPClauseKind K, bool) { return K == OMPC_copyin; },
2341             Level))
2342       return OMPC_private;
2343   }
2344   // User-defined allocators are private since they must be defined in the
2345   // context of target region.
2346   if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, Level) &&
2347       DSAStack->isUsesAllocatorsDecl(Level, D).getValueOr(
2348           DSAStackTy::UsesAllocatorsDeclKind::AllocatorTrait) ==
2349           DSAStackTy::UsesAllocatorsDeclKind::UserDefinedAllocator)
2350     return OMPC_private;
2351   return (DSAStack->hasExplicitDSA(
2352               D, [](OpenMPClauseKind K, bool) { return K == OMPC_private; },
2353               Level) ||
2354           (DSAStack->isClauseParsingMode() &&
2355            DSAStack->getClauseParsingMode() == OMPC_private) ||
2356           // Consider taskgroup reduction descriptor variable a private
2357           // to avoid possible capture in the region.
2358           (DSAStack->hasExplicitDirective(
2359                [](OpenMPDirectiveKind K) {
2360                  return K == OMPD_taskgroup ||
2361                         ((isOpenMPParallelDirective(K) ||
2362                           isOpenMPWorksharingDirective(K)) &&
2363                          !isOpenMPSimdDirective(K));
2364                },
2365                Level) &&
2366            DSAStack->isTaskgroupReductionRef(D, Level)))
2367              ? OMPC_private
2368              : OMPC_unknown;
2369 }
2370 
2371 void Sema::setOpenMPCaptureKind(FieldDecl *FD, const ValueDecl *D,
2372                                 unsigned Level) {
2373   assert(LangOpts.OpenMP && "OpenMP is not allowed");
2374   D = getCanonicalDecl(D);
2375   OpenMPClauseKind OMPC = OMPC_unknown;
2376   for (unsigned I = DSAStack->getNestingLevel() + 1; I > Level; --I) {
2377     const unsigned NewLevel = I - 1;
2378     if (DSAStack->hasExplicitDSA(
2379             D,
2380             [&OMPC](const OpenMPClauseKind K, bool AppliedToPointee) {
2381               if (isOpenMPPrivate(K) && !AppliedToPointee) {
2382                 OMPC = K;
2383                 return true;
2384               }
2385               return false;
2386             },
2387             NewLevel))
2388       break;
2389     if (DSAStack->checkMappableExprComponentListsForDeclAtLevel(
2390             D, NewLevel,
2391             [](OMPClauseMappableExprCommon::MappableExprComponentListRef,
2392                OpenMPClauseKind) { return true; })) {
2393       OMPC = OMPC_map;
2394       break;
2395     }
2396     if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
2397                                        NewLevel)) {
2398       OMPC = OMPC_map;
2399       if (DSAStack->mustBeFirstprivateAtLevel(
2400               NewLevel, getVariableCategoryFromDecl(LangOpts, D)))
2401         OMPC = OMPC_firstprivate;
2402       break;
2403     }
2404   }
2405   if (OMPC != OMPC_unknown)
2406     FD->addAttr(OMPCaptureKindAttr::CreateImplicit(Context, unsigned(OMPC)));
2407 }
2408 
2409 bool Sema::isOpenMPTargetCapturedDecl(const ValueDecl *D, unsigned Level,
2410                                       unsigned CaptureLevel) const {
2411   assert(LangOpts.OpenMP && "OpenMP is not allowed");
2412   // Return true if the current level is no longer enclosed in a target region.
2413 
2414   SmallVector<OpenMPDirectiveKind, 4> Regions;
2415   getOpenMPCaptureRegions(Regions, DSAStack->getDirective(Level));
2416   const auto *VD = dyn_cast<VarDecl>(D);
2417   return VD && !VD->hasLocalStorage() &&
2418          DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
2419                                         Level) &&
2420          Regions[CaptureLevel] != OMPD_task;
2421 }
2422 
2423 bool Sema::isOpenMPGlobalCapturedDecl(ValueDecl *D, unsigned Level,
2424                                       unsigned CaptureLevel) const {
2425   assert(LangOpts.OpenMP && "OpenMP is not allowed");
2426   // Return true if the current level is no longer enclosed in a target region.
2427 
2428   if (const auto *VD = dyn_cast<VarDecl>(D)) {
2429     if (!VD->hasLocalStorage()) {
2430       if (isInOpenMPTargetExecutionDirective())
2431         return true;
2432       DSAStackTy::DSAVarData TopDVar =
2433           DSAStack->getTopDSA(D, /*FromParent=*/false);
2434       unsigned NumLevels =
2435           getOpenMPCaptureLevels(DSAStack->getDirective(Level));
2436       if (Level == 0)
2437         return (NumLevels == CaptureLevel + 1) && TopDVar.CKind != OMPC_shared;
2438       do {
2439         --Level;
2440         DSAStackTy::DSAVarData DVar = DSAStack->getImplicitDSA(D, Level);
2441         if (DVar.CKind != OMPC_shared)
2442           return true;
2443       } while (Level > 0);
2444     }
2445   }
2446   return true;
2447 }
2448 
2449 void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; }
2450 
2451 void Sema::ActOnOpenMPBeginDeclareVariant(SourceLocation Loc,
2452                                           OMPTraitInfo &TI) {
2453   OMPDeclareVariantScopes.push_back(OMPDeclareVariantScope(TI));
2454 }
2455 
2456 void Sema::ActOnOpenMPEndDeclareVariant() {
2457   assert(isInOpenMPDeclareVariantScope() &&
2458          "Not in OpenMP declare variant scope!");
2459 
2460   OMPDeclareVariantScopes.pop_back();
2461 }
2462 
2463 void Sema::finalizeOpenMPDelayedAnalysis(const FunctionDecl *Caller,
2464                                          const FunctionDecl *Callee,
2465                                          SourceLocation Loc) {
2466   assert(LangOpts.OpenMP && "Expected OpenMP compilation mode.");
2467   Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
2468       OMPDeclareTargetDeclAttr::getDeviceType(Caller->getMostRecentDecl());
2469   // Ignore host functions during device analyzis.
2470   if (LangOpts.OpenMPIsDevice && DevTy &&
2471       *DevTy == OMPDeclareTargetDeclAttr::DT_Host)
2472     return;
2473   // Ignore nohost functions during host analyzis.
2474   if (!LangOpts.OpenMPIsDevice && DevTy &&
2475       *DevTy == OMPDeclareTargetDeclAttr::DT_NoHost)
2476     return;
2477   const FunctionDecl *FD = Callee->getMostRecentDecl();
2478   DevTy = OMPDeclareTargetDeclAttr::getDeviceType(FD);
2479   if (LangOpts.OpenMPIsDevice && DevTy &&
2480       *DevTy == OMPDeclareTargetDeclAttr::DT_Host) {
2481     // Diagnose host function called during device codegen.
2482     StringRef HostDevTy =
2483         getOpenMPSimpleClauseTypeName(OMPC_device_type, OMPC_DEVICE_TYPE_host);
2484     Diag(Loc, diag::err_omp_wrong_device_function_call) << HostDevTy << 0;
2485     Diag(*OMPDeclareTargetDeclAttr::getLocation(FD),
2486          diag::note_omp_marked_device_type_here)
2487         << HostDevTy;
2488     return;
2489   }
2490       if (!LangOpts.OpenMPIsDevice && DevTy &&
2491           *DevTy == OMPDeclareTargetDeclAttr::DT_NoHost) {
2492         // Diagnose nohost function called during host codegen.
2493         StringRef NoHostDevTy = getOpenMPSimpleClauseTypeName(
2494             OMPC_device_type, OMPC_DEVICE_TYPE_nohost);
2495         Diag(Loc, diag::err_omp_wrong_device_function_call) << NoHostDevTy << 1;
2496         Diag(*OMPDeclareTargetDeclAttr::getLocation(FD),
2497              diag::note_omp_marked_device_type_here)
2498             << NoHostDevTy;
2499       }
2500 }
2501 
2502 void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind,
2503                                const DeclarationNameInfo &DirName,
2504                                Scope *CurScope, SourceLocation Loc) {
2505   DSAStack->push(DKind, DirName, CurScope, Loc);
2506   PushExpressionEvaluationContext(
2507       ExpressionEvaluationContext::PotentiallyEvaluated);
2508 }
2509 
2510 void Sema::StartOpenMPClause(OpenMPClauseKind K) {
2511   DSAStack->setClauseParsingMode(K);
2512 }
2513 
2514 void Sema::EndOpenMPClause() {
2515   DSAStack->setClauseParsingMode(/*K=*/OMPC_unknown);
2516 }
2517 
2518 static std::pair<ValueDecl *, bool>
2519 getPrivateItem(Sema &S, Expr *&RefExpr, SourceLocation &ELoc,
2520                SourceRange &ERange, bool AllowArraySection = false);
2521 
2522 /// Check consistency of the reduction clauses.
2523 static void checkReductionClauses(Sema &S, DSAStackTy *Stack,
2524                                   ArrayRef<OMPClause *> Clauses) {
2525   bool InscanFound = false;
2526   SourceLocation InscanLoc;
2527   // OpenMP 5.0, 2.19.5.4 reduction Clause, Restrictions.
2528   // A reduction clause without the inscan reduction-modifier may not appear on
2529   // a construct on which a reduction clause with the inscan reduction-modifier
2530   // appears.
2531   for (OMPClause *C : Clauses) {
2532     if (C->getClauseKind() != OMPC_reduction)
2533       continue;
2534     auto *RC = cast<OMPReductionClause>(C);
2535     if (RC->getModifier() == OMPC_REDUCTION_inscan) {
2536       InscanFound = true;
2537       InscanLoc = RC->getModifierLoc();
2538       continue;
2539     }
2540     if (RC->getModifier() == OMPC_REDUCTION_task) {
2541       // OpenMP 5.0, 2.19.5.4 reduction Clause.
2542       // A reduction clause with the task reduction-modifier may only appear on
2543       // a parallel construct, a worksharing construct or a combined or
2544       // composite construct for which any of the aforementioned constructs is a
2545       // constituent construct and simd or loop are not constituent constructs.
2546       OpenMPDirectiveKind CurDir = Stack->getCurrentDirective();
2547       if (!(isOpenMPParallelDirective(CurDir) ||
2548             isOpenMPWorksharingDirective(CurDir)) ||
2549           isOpenMPSimdDirective(CurDir))
2550         S.Diag(RC->getModifierLoc(),
2551                diag::err_omp_reduction_task_not_parallel_or_worksharing);
2552       continue;
2553     }
2554   }
2555   if (InscanFound) {
2556     for (OMPClause *C : Clauses) {
2557       if (C->getClauseKind() != OMPC_reduction)
2558         continue;
2559       auto *RC = cast<OMPReductionClause>(C);
2560       if (RC->getModifier() != OMPC_REDUCTION_inscan) {
2561         S.Diag(RC->getModifier() == OMPC_REDUCTION_unknown
2562                    ? RC->getBeginLoc()
2563                    : RC->getModifierLoc(),
2564                diag::err_omp_inscan_reduction_expected);
2565         S.Diag(InscanLoc, diag::note_omp_previous_inscan_reduction);
2566         continue;
2567       }
2568       for (Expr *Ref : RC->varlists()) {
2569         assert(Ref && "NULL expr in OpenMP nontemporal clause.");
2570         SourceLocation ELoc;
2571         SourceRange ERange;
2572         Expr *SimpleRefExpr = Ref;
2573         auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange,
2574                                   /*AllowArraySection=*/true);
2575         ValueDecl *D = Res.first;
2576         if (!D)
2577           continue;
2578         if (!Stack->isUsedInScanDirective(getCanonicalDecl(D))) {
2579           S.Diag(Ref->getExprLoc(),
2580                  diag::err_omp_reduction_not_inclusive_exclusive)
2581               << Ref->getSourceRange();
2582         }
2583       }
2584     }
2585   }
2586 }
2587 
2588 static void checkAllocateClauses(Sema &S, DSAStackTy *Stack,
2589                                  ArrayRef<OMPClause *> Clauses);
2590 static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr,
2591                                  bool WithInit);
2592 
2593 static void reportOriginalDsa(Sema &SemaRef, const DSAStackTy *Stack,
2594                               const ValueDecl *D,
2595                               const DSAStackTy::DSAVarData &DVar,
2596                               bool IsLoopIterVar = false);
2597 
2598 void Sema::EndOpenMPDSABlock(Stmt *CurDirective) {
2599   // OpenMP [2.14.3.5, Restrictions, C/C++, p.1]
2600   //  A variable of class type (or array thereof) that appears in a lastprivate
2601   //  clause requires an accessible, unambiguous default constructor for the
2602   //  class type, unless the list item is also specified in a firstprivate
2603   //  clause.
2604   if (const auto *D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) {
2605     for (OMPClause *C : D->clauses()) {
2606       if (auto *Clause = dyn_cast<OMPLastprivateClause>(C)) {
2607         SmallVector<Expr *, 8> PrivateCopies;
2608         for (Expr *DE : Clause->varlists()) {
2609           if (DE->isValueDependent() || DE->isTypeDependent()) {
2610             PrivateCopies.push_back(nullptr);
2611             continue;
2612           }
2613           auto *DRE = cast<DeclRefExpr>(DE->IgnoreParens());
2614           auto *VD = cast<VarDecl>(DRE->getDecl());
2615           QualType Type = VD->getType().getNonReferenceType();
2616           const DSAStackTy::DSAVarData DVar =
2617               DSAStack->getTopDSA(VD, /*FromParent=*/false);
2618           if (DVar.CKind == OMPC_lastprivate) {
2619             // Generate helper private variable and initialize it with the
2620             // default value. The address of the original variable is replaced
2621             // by the address of the new private variable in CodeGen. This new
2622             // variable is not added to IdResolver, so the code in the OpenMP
2623             // region uses original variable for proper diagnostics.
2624             VarDecl *VDPrivate = buildVarDecl(
2625                 *this, DE->getExprLoc(), Type.getUnqualifiedType(),
2626                 VD->getName(), VD->hasAttrs() ? &VD->getAttrs() : nullptr, DRE);
2627             ActOnUninitializedDecl(VDPrivate);
2628             if (VDPrivate->isInvalidDecl()) {
2629               PrivateCopies.push_back(nullptr);
2630               continue;
2631             }
2632             PrivateCopies.push_back(buildDeclRefExpr(
2633                 *this, VDPrivate, DE->getType(), DE->getExprLoc()));
2634           } else {
2635             // The variable is also a firstprivate, so initialization sequence
2636             // for private copy is generated already.
2637             PrivateCopies.push_back(nullptr);
2638           }
2639         }
2640         Clause->setPrivateCopies(PrivateCopies);
2641         continue;
2642       }
2643       // Finalize nontemporal clause by handling private copies, if any.
2644       if (auto *Clause = dyn_cast<OMPNontemporalClause>(C)) {
2645         SmallVector<Expr *, 8> PrivateRefs;
2646         for (Expr *RefExpr : Clause->varlists()) {
2647           assert(RefExpr && "NULL expr in OpenMP nontemporal clause.");
2648           SourceLocation ELoc;
2649           SourceRange ERange;
2650           Expr *SimpleRefExpr = RefExpr;
2651           auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
2652           if (Res.second)
2653             // It will be analyzed later.
2654             PrivateRefs.push_back(RefExpr);
2655           ValueDecl *D = Res.first;
2656           if (!D)
2657             continue;
2658 
2659           const DSAStackTy::DSAVarData DVar =
2660               DSAStack->getTopDSA(D, /*FromParent=*/false);
2661           PrivateRefs.push_back(DVar.PrivateCopy ? DVar.PrivateCopy
2662                                                  : SimpleRefExpr);
2663         }
2664         Clause->setPrivateRefs(PrivateRefs);
2665         continue;
2666       }
2667       if (auto *Clause = dyn_cast<OMPUsesAllocatorsClause>(C)) {
2668         for (unsigned I = 0, E = Clause->getNumberOfAllocators(); I < E; ++I) {
2669           OMPUsesAllocatorsClause::Data D = Clause->getAllocatorData(I);
2670           auto *DRE = dyn_cast<DeclRefExpr>(D.Allocator->IgnoreParenImpCasts());
2671           if (!DRE)
2672             continue;
2673           ValueDecl *VD = DRE->getDecl();
2674           if (!VD || !isa<VarDecl>(VD))
2675             continue;
2676           DSAStackTy::DSAVarData DVar =
2677               DSAStack->getTopDSA(VD, /*FromParent=*/false);
2678           // OpenMP [2.12.5, target Construct]
2679           // Memory allocators that appear in a uses_allocators clause cannot
2680           // appear in other data-sharing attribute clauses or data-mapping
2681           // attribute clauses in the same construct.
2682           Expr *MapExpr = nullptr;
2683           if (DVar.RefExpr ||
2684               DSAStack->checkMappableExprComponentListsForDecl(
2685                   VD, /*CurrentRegionOnly=*/true,
2686                   [VD, &MapExpr](
2687                       OMPClauseMappableExprCommon::MappableExprComponentListRef
2688                           MapExprComponents,
2689                       OpenMPClauseKind C) {
2690                     auto MI = MapExprComponents.rbegin();
2691                     auto ME = MapExprComponents.rend();
2692                     if (MI != ME &&
2693                         MI->getAssociatedDeclaration()->getCanonicalDecl() ==
2694                             VD->getCanonicalDecl()) {
2695                       MapExpr = MI->getAssociatedExpression();
2696                       return true;
2697                     }
2698                     return false;
2699                   })) {
2700             Diag(D.Allocator->getExprLoc(),
2701                  diag::err_omp_allocator_used_in_clauses)
2702                 << D.Allocator->getSourceRange();
2703             if (DVar.RefExpr)
2704               reportOriginalDsa(*this, DSAStack, VD, DVar);
2705             else
2706               Diag(MapExpr->getExprLoc(), diag::note_used_here)
2707                   << MapExpr->getSourceRange();
2708           }
2709         }
2710         continue;
2711       }
2712     }
2713     // Check allocate clauses.
2714     if (!CurContext->isDependentContext())
2715       checkAllocateClauses(*this, DSAStack, D->clauses());
2716     checkReductionClauses(*this, DSAStack, D->clauses());
2717   }
2718 
2719   DSAStack->pop();
2720   DiscardCleanupsInEvaluationContext();
2721   PopExpressionEvaluationContext();
2722 }
2723 
2724 static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
2725                                      Expr *NumIterations, Sema &SemaRef,
2726                                      Scope *S, DSAStackTy *Stack);
2727 
2728 namespace {
2729 
2730 class VarDeclFilterCCC final : public CorrectionCandidateCallback {
2731 private:
2732   Sema &SemaRef;
2733 
2734 public:
2735   explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {}
2736   bool ValidateCandidate(const TypoCorrection &Candidate) override {
2737     NamedDecl *ND = Candidate.getCorrectionDecl();
2738     if (const auto *VD = dyn_cast_or_null<VarDecl>(ND)) {
2739       return VD->hasGlobalStorage() &&
2740              SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
2741                                    SemaRef.getCurScope());
2742     }
2743     return false;
2744   }
2745 
2746   std::unique_ptr<CorrectionCandidateCallback> clone() override {
2747     return std::make_unique<VarDeclFilterCCC>(*this);
2748   }
2749 
2750 };
2751 
2752 class VarOrFuncDeclFilterCCC final : public CorrectionCandidateCallback {
2753 private:
2754   Sema &SemaRef;
2755 
2756 public:
2757   explicit VarOrFuncDeclFilterCCC(Sema &S) : SemaRef(S) {}
2758   bool ValidateCandidate(const TypoCorrection &Candidate) override {
2759     NamedDecl *ND = Candidate.getCorrectionDecl();
2760     if (ND && ((isa<VarDecl>(ND) && ND->getKind() == Decl::Var) ||
2761                isa<FunctionDecl>(ND))) {
2762       return SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
2763                                    SemaRef.getCurScope());
2764     }
2765     return false;
2766   }
2767 
2768   std::unique_ptr<CorrectionCandidateCallback> clone() override {
2769     return std::make_unique<VarOrFuncDeclFilterCCC>(*this);
2770   }
2771 };
2772 
2773 } // namespace
2774 
2775 ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope,
2776                                          CXXScopeSpec &ScopeSpec,
2777                                          const DeclarationNameInfo &Id,
2778                                          OpenMPDirectiveKind Kind) {
2779   LookupResult Lookup(*this, Id, LookupOrdinaryName);
2780   LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
2781 
2782   if (Lookup.isAmbiguous())
2783     return ExprError();
2784 
2785   VarDecl *VD;
2786   if (!Lookup.isSingleResult()) {
2787     VarDeclFilterCCC CCC(*this);
2788     if (TypoCorrection Corrected =
2789             CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr, CCC,
2790                         CTK_ErrorRecovery)) {
2791       diagnoseTypo(Corrected,
2792                    PDiag(Lookup.empty()
2793                              ? diag::err_undeclared_var_use_suggest
2794                              : diag::err_omp_expected_var_arg_suggest)
2795                        << Id.getName());
2796       VD = Corrected.getCorrectionDeclAs<VarDecl>();
2797     } else {
2798       Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use
2799                                        : diag::err_omp_expected_var_arg)
2800           << Id.getName();
2801       return ExprError();
2802     }
2803   } else if (!(VD = Lookup.getAsSingle<VarDecl>())) {
2804     Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName();
2805     Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at);
2806     return ExprError();
2807   }
2808   Lookup.suppressDiagnostics();
2809 
2810   // OpenMP [2.9.2, Syntax, C/C++]
2811   //   Variables must be file-scope, namespace-scope, or static block-scope.
2812   if (Kind == OMPD_threadprivate && !VD->hasGlobalStorage()) {
2813     Diag(Id.getLoc(), diag::err_omp_global_var_arg)
2814         << getOpenMPDirectiveName(Kind) << !VD->isStaticLocal();
2815     bool IsDecl =
2816         VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2817     Diag(VD->getLocation(),
2818          IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2819         << VD;
2820     return ExprError();
2821   }
2822 
2823   VarDecl *CanonicalVD = VD->getCanonicalDecl();
2824   NamedDecl *ND = CanonicalVD;
2825   // OpenMP [2.9.2, Restrictions, C/C++, p.2]
2826   //   A threadprivate directive for file-scope variables must appear outside
2827   //   any definition or declaration.
2828   if (CanonicalVD->getDeclContext()->isTranslationUnit() &&
2829       !getCurLexicalContext()->isTranslationUnit()) {
2830     Diag(Id.getLoc(), diag::err_omp_var_scope)
2831         << getOpenMPDirectiveName(Kind) << VD;
2832     bool IsDecl =
2833         VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2834     Diag(VD->getLocation(),
2835          IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2836         << VD;
2837     return ExprError();
2838   }
2839   // OpenMP [2.9.2, Restrictions, C/C++, p.3]
2840   //   A threadprivate directive for static class member variables must appear
2841   //   in the class definition, in the same scope in which the member
2842   //   variables are declared.
2843   if (CanonicalVD->isStaticDataMember() &&
2844       !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) {
2845     Diag(Id.getLoc(), diag::err_omp_var_scope)
2846         << getOpenMPDirectiveName(Kind) << VD;
2847     bool IsDecl =
2848         VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2849     Diag(VD->getLocation(),
2850          IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2851         << VD;
2852     return ExprError();
2853   }
2854   // OpenMP [2.9.2, Restrictions, C/C++, p.4]
2855   //   A threadprivate directive for namespace-scope variables must appear
2856   //   outside any definition or declaration other than the namespace
2857   //   definition itself.
2858   if (CanonicalVD->getDeclContext()->isNamespace() &&
2859       (!getCurLexicalContext()->isFileContext() ||
2860        !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) {
2861     Diag(Id.getLoc(), diag::err_omp_var_scope)
2862         << getOpenMPDirectiveName(Kind) << VD;
2863     bool IsDecl =
2864         VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2865     Diag(VD->getLocation(),
2866          IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2867         << VD;
2868     return ExprError();
2869   }
2870   // OpenMP [2.9.2, Restrictions, C/C++, p.6]
2871   //   A threadprivate directive for static block-scope variables must appear
2872   //   in the scope of the variable and not in a nested scope.
2873   if (CanonicalVD->isLocalVarDecl() && CurScope &&
2874       !isDeclInScope(ND, getCurLexicalContext(), CurScope)) {
2875     Diag(Id.getLoc(), diag::err_omp_var_scope)
2876         << getOpenMPDirectiveName(Kind) << VD;
2877     bool IsDecl =
2878         VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2879     Diag(VD->getLocation(),
2880          IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2881         << VD;
2882     return ExprError();
2883   }
2884 
2885   // OpenMP [2.9.2, Restrictions, C/C++, p.2-6]
2886   //   A threadprivate directive must lexically precede all references to any
2887   //   of the variables in its list.
2888   if (Kind == OMPD_threadprivate && VD->isUsed() &&
2889       !DSAStack->isThreadPrivate(VD)) {
2890     Diag(Id.getLoc(), diag::err_omp_var_used)
2891         << getOpenMPDirectiveName(Kind) << VD;
2892     return ExprError();
2893   }
2894 
2895   QualType ExprType = VD->getType().getNonReferenceType();
2896   return DeclRefExpr::Create(Context, NestedNameSpecifierLoc(),
2897                              SourceLocation(), VD,
2898                              /*RefersToEnclosingVariableOrCapture=*/false,
2899                              Id.getLoc(), ExprType, VK_LValue);
2900 }
2901 
2902 Sema::DeclGroupPtrTy
2903 Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc,
2904                                         ArrayRef<Expr *> VarList) {
2905   if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) {
2906     CurContext->addDecl(D);
2907     return DeclGroupPtrTy::make(DeclGroupRef(D));
2908   }
2909   return nullptr;
2910 }
2911 
2912 namespace {
2913 class LocalVarRefChecker final
2914     : public ConstStmtVisitor<LocalVarRefChecker, bool> {
2915   Sema &SemaRef;
2916 
2917 public:
2918   bool VisitDeclRefExpr(const DeclRefExpr *E) {
2919     if (const auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
2920       if (VD->hasLocalStorage()) {
2921         SemaRef.Diag(E->getBeginLoc(),
2922                      diag::err_omp_local_var_in_threadprivate_init)
2923             << E->getSourceRange();
2924         SemaRef.Diag(VD->getLocation(), diag::note_defined_here)
2925             << VD << VD->getSourceRange();
2926         return true;
2927       }
2928     }
2929     return false;
2930   }
2931   bool VisitStmt(const Stmt *S) {
2932     for (const Stmt *Child : S->children()) {
2933       if (Child && Visit(Child))
2934         return true;
2935     }
2936     return false;
2937   }
2938   explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {}
2939 };
2940 } // namespace
2941 
2942 OMPThreadPrivateDecl *
2943 Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) {
2944   SmallVector<Expr *, 8> Vars;
2945   for (Expr *RefExpr : VarList) {
2946     auto *DE = cast<DeclRefExpr>(RefExpr);
2947     auto *VD = cast<VarDecl>(DE->getDecl());
2948     SourceLocation ILoc = DE->getExprLoc();
2949 
2950     // Mark variable as used.
2951     VD->setReferenced();
2952     VD->markUsed(Context);
2953 
2954     QualType QType = VD->getType();
2955     if (QType->isDependentType() || QType->isInstantiationDependentType()) {
2956       // It will be analyzed later.
2957       Vars.push_back(DE);
2958       continue;
2959     }
2960 
2961     // OpenMP [2.9.2, Restrictions, C/C++, p.10]
2962     //   A threadprivate variable must not have an incomplete type.
2963     if (RequireCompleteType(ILoc, VD->getType(),
2964                             diag::err_omp_threadprivate_incomplete_type)) {
2965       continue;
2966     }
2967 
2968     // OpenMP [2.9.2, Restrictions, C/C++, p.10]
2969     //   A threadprivate variable must not have a reference type.
2970     if (VD->getType()->isReferenceType()) {
2971       Diag(ILoc, diag::err_omp_ref_type_arg)
2972           << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType();
2973       bool IsDecl =
2974           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2975       Diag(VD->getLocation(),
2976            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2977           << VD;
2978       continue;
2979     }
2980 
2981     // Check if this is a TLS variable. If TLS is not being supported, produce
2982     // the corresponding diagnostic.
2983     if ((VD->getTLSKind() != VarDecl::TLS_None &&
2984          !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
2985            getLangOpts().OpenMPUseTLS &&
2986            getASTContext().getTargetInfo().isTLSSupported())) ||
2987         (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
2988          !VD->isLocalVarDecl())) {
2989       Diag(ILoc, diag::err_omp_var_thread_local)
2990           << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1);
2991       bool IsDecl =
2992           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2993       Diag(VD->getLocation(),
2994            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2995           << VD;
2996       continue;
2997     }
2998 
2999     // Check if initial value of threadprivate variable reference variable with
3000     // local storage (it is not supported by runtime).
3001     if (const Expr *Init = VD->getAnyInitializer()) {
3002       LocalVarRefChecker Checker(*this);
3003       if (Checker.Visit(Init))
3004         continue;
3005     }
3006 
3007     Vars.push_back(RefExpr);
3008     DSAStack->addDSA(VD, DE, OMPC_threadprivate);
3009     VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit(
3010         Context, SourceRange(Loc, Loc)));
3011     if (ASTMutationListener *ML = Context.getASTMutationListener())
3012       ML->DeclarationMarkedOpenMPThreadPrivate(VD);
3013   }
3014   OMPThreadPrivateDecl *D = nullptr;
3015   if (!Vars.empty()) {
3016     D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc,
3017                                      Vars);
3018     D->setAccess(AS_public);
3019   }
3020   return D;
3021 }
3022 
3023 static OMPAllocateDeclAttr::AllocatorTypeTy
3024 getAllocatorKind(Sema &S, DSAStackTy *Stack, Expr *Allocator) {
3025   if (!Allocator)
3026     return OMPAllocateDeclAttr::OMPNullMemAlloc;
3027   if (Allocator->isTypeDependent() || Allocator->isValueDependent() ||
3028       Allocator->isInstantiationDependent() ||
3029       Allocator->containsUnexpandedParameterPack())
3030     return OMPAllocateDeclAttr::OMPUserDefinedMemAlloc;
3031   auto AllocatorKindRes = OMPAllocateDeclAttr::OMPUserDefinedMemAlloc;
3032   const Expr *AE = Allocator->IgnoreParenImpCasts();
3033   for (int I = 0; I < OMPAllocateDeclAttr::OMPUserDefinedMemAlloc; ++I) {
3034     auto AllocatorKind = static_cast<OMPAllocateDeclAttr::AllocatorTypeTy>(I);
3035     const Expr *DefAllocator = Stack->getAllocator(AllocatorKind);
3036     llvm::FoldingSetNodeID AEId, DAEId;
3037     AE->Profile(AEId, S.getASTContext(), /*Canonical=*/true);
3038     DefAllocator->Profile(DAEId, S.getASTContext(), /*Canonical=*/true);
3039     if (AEId == DAEId) {
3040       AllocatorKindRes = AllocatorKind;
3041       break;
3042     }
3043   }
3044   return AllocatorKindRes;
3045 }
3046 
3047 static bool checkPreviousOMPAllocateAttribute(
3048     Sema &S, DSAStackTy *Stack, Expr *RefExpr, VarDecl *VD,
3049     OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind, Expr *Allocator) {
3050   if (!VD->hasAttr<OMPAllocateDeclAttr>())
3051     return false;
3052   const auto *A = VD->getAttr<OMPAllocateDeclAttr>();
3053   Expr *PrevAllocator = A->getAllocator();
3054   OMPAllocateDeclAttr::AllocatorTypeTy PrevAllocatorKind =
3055       getAllocatorKind(S, Stack, PrevAllocator);
3056   bool AllocatorsMatch = AllocatorKind == PrevAllocatorKind;
3057   if (AllocatorsMatch &&
3058       AllocatorKind == OMPAllocateDeclAttr::OMPUserDefinedMemAlloc &&
3059       Allocator && PrevAllocator) {
3060     const Expr *AE = Allocator->IgnoreParenImpCasts();
3061     const Expr *PAE = PrevAllocator->IgnoreParenImpCasts();
3062     llvm::FoldingSetNodeID AEId, PAEId;
3063     AE->Profile(AEId, S.Context, /*Canonical=*/true);
3064     PAE->Profile(PAEId, S.Context, /*Canonical=*/true);
3065     AllocatorsMatch = AEId == PAEId;
3066   }
3067   if (!AllocatorsMatch) {
3068     SmallString<256> AllocatorBuffer;
3069     llvm::raw_svector_ostream AllocatorStream(AllocatorBuffer);
3070     if (Allocator)
3071       Allocator->printPretty(AllocatorStream, nullptr, S.getPrintingPolicy());
3072     SmallString<256> PrevAllocatorBuffer;
3073     llvm::raw_svector_ostream PrevAllocatorStream(PrevAllocatorBuffer);
3074     if (PrevAllocator)
3075       PrevAllocator->printPretty(PrevAllocatorStream, nullptr,
3076                                  S.getPrintingPolicy());
3077 
3078     SourceLocation AllocatorLoc =
3079         Allocator ? Allocator->getExprLoc() : RefExpr->getExprLoc();
3080     SourceRange AllocatorRange =
3081         Allocator ? Allocator->getSourceRange() : RefExpr->getSourceRange();
3082     SourceLocation PrevAllocatorLoc =
3083         PrevAllocator ? PrevAllocator->getExprLoc() : A->getLocation();
3084     SourceRange PrevAllocatorRange =
3085         PrevAllocator ? PrevAllocator->getSourceRange() : A->getRange();
3086     S.Diag(AllocatorLoc, diag::warn_omp_used_different_allocator)
3087         << (Allocator ? 1 : 0) << AllocatorStream.str()
3088         << (PrevAllocator ? 1 : 0) << PrevAllocatorStream.str()
3089         << AllocatorRange;
3090     S.Diag(PrevAllocatorLoc, diag::note_omp_previous_allocator)
3091         << PrevAllocatorRange;
3092     return true;
3093   }
3094   return false;
3095 }
3096 
3097 static void
3098 applyOMPAllocateAttribute(Sema &S, VarDecl *VD,
3099                           OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind,
3100                           Expr *Allocator, SourceRange SR) {
3101   if (VD->hasAttr<OMPAllocateDeclAttr>())
3102     return;
3103   if (Allocator &&
3104       (Allocator->isTypeDependent() || Allocator->isValueDependent() ||
3105        Allocator->isInstantiationDependent() ||
3106        Allocator->containsUnexpandedParameterPack()))
3107     return;
3108   auto *A = OMPAllocateDeclAttr::CreateImplicit(S.Context, AllocatorKind,
3109                                                 Allocator, SR);
3110   VD->addAttr(A);
3111   if (ASTMutationListener *ML = S.Context.getASTMutationListener())
3112     ML->DeclarationMarkedOpenMPAllocate(VD, A);
3113 }
3114 
3115 Sema::DeclGroupPtrTy Sema::ActOnOpenMPAllocateDirective(
3116     SourceLocation Loc, ArrayRef<Expr *> VarList,
3117     ArrayRef<OMPClause *> Clauses, DeclContext *Owner) {
3118   assert(Clauses.size() <= 1 && "Expected at most one clause.");
3119   Expr *Allocator = nullptr;
3120   if (Clauses.empty()) {
3121     // OpenMP 5.0, 2.11.3 allocate Directive, Restrictions.
3122     // allocate directives that appear in a target region must specify an
3123     // allocator clause unless a requires directive with the dynamic_allocators
3124     // clause is present in the same compilation unit.
3125     if (LangOpts.OpenMPIsDevice &&
3126         !DSAStack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>())
3127       targetDiag(Loc, diag::err_expected_allocator_clause);
3128   } else {
3129     Allocator = cast<OMPAllocatorClause>(Clauses.back())->getAllocator();
3130   }
3131   OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind =
3132       getAllocatorKind(*this, DSAStack, Allocator);
3133   SmallVector<Expr *, 8> Vars;
3134   for (Expr *RefExpr : VarList) {
3135     auto *DE = cast<DeclRefExpr>(RefExpr);
3136     auto *VD = cast<VarDecl>(DE->getDecl());
3137 
3138     // Check if this is a TLS variable or global register.
3139     if (VD->getTLSKind() != VarDecl::TLS_None ||
3140         VD->hasAttr<OMPThreadPrivateDeclAttr>() ||
3141         (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
3142          !VD->isLocalVarDecl()))
3143       continue;
3144 
3145     // If the used several times in the allocate directive, the same allocator
3146     // must be used.
3147     if (checkPreviousOMPAllocateAttribute(*this, DSAStack, RefExpr, VD,
3148                                           AllocatorKind, Allocator))
3149       continue;
3150 
3151     // OpenMP, 2.11.3 allocate Directive, Restrictions, C / C++
3152     // If a list item has a static storage type, the allocator expression in the
3153     // allocator clause must be a constant expression that evaluates to one of
3154     // the predefined memory allocator values.
3155     if (Allocator && VD->hasGlobalStorage()) {
3156       if (AllocatorKind == OMPAllocateDeclAttr::OMPUserDefinedMemAlloc) {
3157         Diag(Allocator->getExprLoc(),
3158              diag::err_omp_expected_predefined_allocator)
3159             << Allocator->getSourceRange();
3160         bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
3161                       VarDecl::DeclarationOnly;
3162         Diag(VD->getLocation(),
3163              IsDecl ? diag::note_previous_decl : diag::note_defined_here)
3164             << VD;
3165         continue;
3166       }
3167     }
3168 
3169     Vars.push_back(RefExpr);
3170     applyOMPAllocateAttribute(*this, VD, AllocatorKind, Allocator,
3171                               DE->getSourceRange());
3172   }
3173   if (Vars.empty())
3174     return nullptr;
3175   if (!Owner)
3176     Owner = getCurLexicalContext();
3177   auto *D = OMPAllocateDecl::Create(Context, Owner, Loc, Vars, Clauses);
3178   D->setAccess(AS_public);
3179   Owner->addDecl(D);
3180   return DeclGroupPtrTy::make(DeclGroupRef(D));
3181 }
3182 
3183 Sema::DeclGroupPtrTy
3184 Sema::ActOnOpenMPRequiresDirective(SourceLocation Loc,
3185                                    ArrayRef<OMPClause *> ClauseList) {
3186   OMPRequiresDecl *D = nullptr;
3187   if (!CurContext->isFileContext()) {
3188     Diag(Loc, diag::err_omp_invalid_scope) << "requires";
3189   } else {
3190     D = CheckOMPRequiresDecl(Loc, ClauseList);
3191     if (D) {
3192       CurContext->addDecl(D);
3193       DSAStack->addRequiresDecl(D);
3194     }
3195   }
3196   return DeclGroupPtrTy::make(DeclGroupRef(D));
3197 }
3198 
3199 void Sema::ActOnOpenMPAssumesDirective(SourceLocation Loc,
3200                                        OpenMPDirectiveKind DKind,
3201                                        ArrayRef<StringRef> Assumptions,
3202                                        bool SkippedClauses) {
3203   if (!SkippedClauses && Assumptions.empty())
3204     Diag(Loc, diag::err_omp_no_clause_for_directive)
3205         << llvm::omp::getAllAssumeClauseOptions()
3206         << llvm::omp::getOpenMPDirectiveName(DKind);
3207 
3208   auto *AA = AssumptionAttr::Create(Context, llvm::join(Assumptions, ","), Loc);
3209   if (DKind == llvm::omp::Directive::OMPD_begin_assumes) {
3210     OMPAssumeScoped.push_back(AA);
3211     return;
3212   }
3213 
3214   // Global assumes without assumption clauses are ignored.
3215   if (Assumptions.empty())
3216     return;
3217 
3218   assert(DKind == llvm::omp::Directive::OMPD_assumes &&
3219          "Unexpected omp assumption directive!");
3220   OMPAssumeGlobal.push_back(AA);
3221 
3222   // The OMPAssumeGlobal scope above will take care of new declarations but
3223   // we also want to apply the assumption to existing ones, e.g., to
3224   // declarations in included headers. To this end, we traverse all existing
3225   // declaration contexts and annotate function declarations here.
3226   SmallVector<DeclContext *, 8> DeclContexts;
3227   auto *Ctx = CurContext;
3228   while (Ctx->getLexicalParent())
3229     Ctx = Ctx->getLexicalParent();
3230   DeclContexts.push_back(Ctx);
3231   while (!DeclContexts.empty()) {
3232     DeclContext *DC = DeclContexts.pop_back_val();
3233     for (auto *SubDC : DC->decls()) {
3234       if (SubDC->isInvalidDecl())
3235         continue;
3236       if (auto *CTD = dyn_cast<ClassTemplateDecl>(SubDC)) {
3237         DeclContexts.push_back(CTD->getTemplatedDecl());
3238         for (auto *S : CTD->specializations())
3239           DeclContexts.push_back(S);
3240         continue;
3241       }
3242       if (auto *DC = dyn_cast<DeclContext>(SubDC))
3243         DeclContexts.push_back(DC);
3244       if (auto *F = dyn_cast<FunctionDecl>(SubDC)) {
3245         F->addAttr(AA);
3246         continue;
3247       }
3248     }
3249   }
3250 }
3251 
3252 void Sema::ActOnOpenMPEndAssumesDirective() {
3253   assert(isInOpenMPAssumeScope() && "Not in OpenMP assumes scope!");
3254   OMPAssumeScoped.pop_back();
3255 }
3256 
3257 OMPRequiresDecl *Sema::CheckOMPRequiresDecl(SourceLocation Loc,
3258                                             ArrayRef<OMPClause *> ClauseList) {
3259   /// For target specific clauses, the requires directive cannot be
3260   /// specified after the handling of any of the target regions in the
3261   /// current compilation unit.
3262   ArrayRef<SourceLocation> TargetLocations =
3263       DSAStack->getEncounteredTargetLocs();
3264   SourceLocation AtomicLoc = DSAStack->getAtomicDirectiveLoc();
3265   if (!TargetLocations.empty() || !AtomicLoc.isInvalid()) {
3266     for (const OMPClause *CNew : ClauseList) {
3267       // Check if any of the requires clauses affect target regions.
3268       if (isa<OMPUnifiedSharedMemoryClause>(CNew) ||
3269           isa<OMPUnifiedAddressClause>(CNew) ||
3270           isa<OMPReverseOffloadClause>(CNew) ||
3271           isa<OMPDynamicAllocatorsClause>(CNew)) {
3272         Diag(Loc, diag::err_omp_directive_before_requires)
3273             << "target" << getOpenMPClauseName(CNew->getClauseKind());
3274         for (SourceLocation TargetLoc : TargetLocations) {
3275           Diag(TargetLoc, diag::note_omp_requires_encountered_directive)
3276               << "target";
3277         }
3278       } else if (!AtomicLoc.isInvalid() &&
3279                  isa<OMPAtomicDefaultMemOrderClause>(CNew)) {
3280         Diag(Loc, diag::err_omp_directive_before_requires)
3281             << "atomic" << getOpenMPClauseName(CNew->getClauseKind());
3282         Diag(AtomicLoc, diag::note_omp_requires_encountered_directive)
3283             << "atomic";
3284       }
3285     }
3286   }
3287 
3288   if (!DSAStack->hasDuplicateRequiresClause(ClauseList))
3289     return OMPRequiresDecl::Create(Context, getCurLexicalContext(), Loc,
3290                                    ClauseList);
3291   return nullptr;
3292 }
3293 
3294 static void reportOriginalDsa(Sema &SemaRef, const DSAStackTy *Stack,
3295                               const ValueDecl *D,
3296                               const DSAStackTy::DSAVarData &DVar,
3297                               bool IsLoopIterVar) {
3298   if (DVar.RefExpr) {
3299     SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
3300         << getOpenMPClauseName(DVar.CKind);
3301     return;
3302   }
3303   enum {
3304     PDSA_StaticMemberShared,
3305     PDSA_StaticLocalVarShared,
3306     PDSA_LoopIterVarPrivate,
3307     PDSA_LoopIterVarLinear,
3308     PDSA_LoopIterVarLastprivate,
3309     PDSA_ConstVarShared,
3310     PDSA_GlobalVarShared,
3311     PDSA_TaskVarFirstprivate,
3312     PDSA_LocalVarPrivate,
3313     PDSA_Implicit
3314   } Reason = PDSA_Implicit;
3315   bool ReportHint = false;
3316   auto ReportLoc = D->getLocation();
3317   auto *VD = dyn_cast<VarDecl>(D);
3318   if (IsLoopIterVar) {
3319     if (DVar.CKind == OMPC_private)
3320       Reason = PDSA_LoopIterVarPrivate;
3321     else if (DVar.CKind == OMPC_lastprivate)
3322       Reason = PDSA_LoopIterVarLastprivate;
3323     else
3324       Reason = PDSA_LoopIterVarLinear;
3325   } else if (isOpenMPTaskingDirective(DVar.DKind) &&
3326              DVar.CKind == OMPC_firstprivate) {
3327     Reason = PDSA_TaskVarFirstprivate;
3328     ReportLoc = DVar.ImplicitDSALoc;
3329   } else if (VD && VD->isStaticLocal())
3330     Reason = PDSA_StaticLocalVarShared;
3331   else if (VD && VD->isStaticDataMember())
3332     Reason = PDSA_StaticMemberShared;
3333   else if (VD && VD->isFileVarDecl())
3334     Reason = PDSA_GlobalVarShared;
3335   else if (D->getType().isConstant(SemaRef.getASTContext()))
3336     Reason = PDSA_ConstVarShared;
3337   else if (VD && VD->isLocalVarDecl() && DVar.CKind == OMPC_private) {
3338     ReportHint = true;
3339     Reason = PDSA_LocalVarPrivate;
3340   }
3341   if (Reason != PDSA_Implicit) {
3342     SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa)
3343         << Reason << ReportHint
3344         << getOpenMPDirectiveName(Stack->getCurrentDirective());
3345   } else if (DVar.ImplicitDSALoc.isValid()) {
3346     SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa)
3347         << getOpenMPClauseName(DVar.CKind);
3348   }
3349 }
3350 
3351 static OpenMPMapClauseKind
3352 getMapClauseKindFromModifier(OpenMPDefaultmapClauseModifier M,
3353                              bool IsAggregateOrDeclareTarget) {
3354   OpenMPMapClauseKind Kind = OMPC_MAP_unknown;
3355   switch (M) {
3356   case OMPC_DEFAULTMAP_MODIFIER_alloc:
3357     Kind = OMPC_MAP_alloc;
3358     break;
3359   case OMPC_DEFAULTMAP_MODIFIER_to:
3360     Kind = OMPC_MAP_to;
3361     break;
3362   case OMPC_DEFAULTMAP_MODIFIER_from:
3363     Kind = OMPC_MAP_from;
3364     break;
3365   case OMPC_DEFAULTMAP_MODIFIER_tofrom:
3366     Kind = OMPC_MAP_tofrom;
3367     break;
3368   case OMPC_DEFAULTMAP_MODIFIER_present:
3369     // OpenMP 5.1 [2.21.7.3] defaultmap clause, Description]
3370     // If implicit-behavior is present, each variable referenced in the
3371     // construct in the category specified by variable-category is treated as if
3372     // it had been listed in a map clause with the map-type of alloc and
3373     // map-type-modifier of present.
3374     Kind = OMPC_MAP_alloc;
3375     break;
3376   case OMPC_DEFAULTMAP_MODIFIER_firstprivate:
3377   case OMPC_DEFAULTMAP_MODIFIER_last:
3378     llvm_unreachable("Unexpected defaultmap implicit behavior");
3379   case OMPC_DEFAULTMAP_MODIFIER_none:
3380   case OMPC_DEFAULTMAP_MODIFIER_default:
3381   case OMPC_DEFAULTMAP_MODIFIER_unknown:
3382     // IsAggregateOrDeclareTarget could be true if:
3383     // 1. the implicit behavior for aggregate is tofrom
3384     // 2. it's a declare target link
3385     if (IsAggregateOrDeclareTarget) {
3386       Kind = OMPC_MAP_tofrom;
3387       break;
3388     }
3389     llvm_unreachable("Unexpected defaultmap implicit behavior");
3390   }
3391   assert(Kind != OMPC_MAP_unknown && "Expect map kind to be known");
3392   return Kind;
3393 }
3394 
3395 namespace {
3396 class DSAAttrChecker final : public StmtVisitor<DSAAttrChecker, void> {
3397   DSAStackTy *Stack;
3398   Sema &SemaRef;
3399   bool ErrorFound = false;
3400   bool TryCaptureCXXThisMembers = false;
3401   CapturedStmt *CS = nullptr;
3402   const static unsigned DefaultmapKindNum = OMPC_DEFAULTMAP_pointer + 1;
3403   llvm::SmallVector<Expr *, 4> ImplicitFirstprivate;
3404   llvm::SmallVector<Expr *, 4> ImplicitMap[DefaultmapKindNum][OMPC_MAP_delete];
3405   llvm::SmallVector<OpenMPMapModifierKind, NumberOfOMPMapClauseModifiers>
3406       ImplicitMapModifier[DefaultmapKindNum];
3407   Sema::VarsWithInheritedDSAType VarsWithInheritedDSA;
3408   llvm::SmallDenseSet<const ValueDecl *, 4> ImplicitDeclarations;
3409 
3410   void VisitSubCaptures(OMPExecutableDirective *S) {
3411     // Check implicitly captured variables.
3412     if (!S->hasAssociatedStmt() || !S->getAssociatedStmt())
3413       return;
3414     if (S->getDirectiveKind() == OMPD_atomic ||
3415         S->getDirectiveKind() == OMPD_critical ||
3416         S->getDirectiveKind() == OMPD_section ||
3417         S->getDirectiveKind() == OMPD_master) {
3418       Visit(S->getAssociatedStmt());
3419       return;
3420     }
3421     visitSubCaptures(S->getInnermostCapturedStmt());
3422     // Try to capture inner this->member references to generate correct mappings
3423     // and diagnostics.
3424     if (TryCaptureCXXThisMembers ||
3425         (isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()) &&
3426          llvm::any_of(S->getInnermostCapturedStmt()->captures(),
3427                       [](const CapturedStmt::Capture &C) {
3428                         return C.capturesThis();
3429                       }))) {
3430       bool SavedTryCaptureCXXThisMembers = TryCaptureCXXThisMembers;
3431       TryCaptureCXXThisMembers = true;
3432       Visit(S->getInnermostCapturedStmt()->getCapturedStmt());
3433       TryCaptureCXXThisMembers = SavedTryCaptureCXXThisMembers;
3434     }
3435     // In tasks firstprivates are not captured anymore, need to analyze them
3436     // explicitly.
3437     if (isOpenMPTaskingDirective(S->getDirectiveKind()) &&
3438         !isOpenMPTaskLoopDirective(S->getDirectiveKind())) {
3439       for (OMPClause *C : S->clauses())
3440         if (auto *FC = dyn_cast<OMPFirstprivateClause>(C)) {
3441           for (Expr *Ref : FC->varlists())
3442             Visit(Ref);
3443         }
3444     }
3445   }
3446 
3447 public:
3448   void VisitDeclRefExpr(DeclRefExpr *E) {
3449     if (TryCaptureCXXThisMembers || E->isTypeDependent() ||
3450         E->isValueDependent() || E->containsUnexpandedParameterPack() ||
3451         E->isInstantiationDependent())
3452       return;
3453     if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
3454       // Check the datasharing rules for the expressions in the clauses.
3455       if (!CS) {
3456         if (auto *CED = dyn_cast<OMPCapturedExprDecl>(VD))
3457           if (!CED->hasAttr<OMPCaptureNoInitAttr>()) {
3458             Visit(CED->getInit());
3459             return;
3460           }
3461       } else if (VD->isImplicit() || isa<OMPCapturedExprDecl>(VD))
3462         // Do not analyze internal variables and do not enclose them into
3463         // implicit clauses.
3464         return;
3465       VD = VD->getCanonicalDecl();
3466       // Skip internally declared variables.
3467       if (VD->hasLocalStorage() && CS && !CS->capturesVariable(VD) &&
3468           !Stack->isImplicitTaskFirstprivate(VD))
3469         return;
3470       // Skip allocators in uses_allocators clauses.
3471       if (Stack->isUsesAllocatorsDecl(VD).hasValue())
3472         return;
3473 
3474       DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, /*FromParent=*/false);
3475       // Check if the variable has explicit DSA set and stop analysis if it so.
3476       if (DVar.RefExpr || !ImplicitDeclarations.insert(VD).second)
3477         return;
3478 
3479       // Skip internally declared static variables.
3480       llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
3481           OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
3482       if (VD->hasGlobalStorage() && CS && !CS->capturesVariable(VD) &&
3483           (Stack->hasRequiresDeclWithClause<OMPUnifiedSharedMemoryClause>() ||
3484            !Res || *Res != OMPDeclareTargetDeclAttr::MT_Link) &&
3485           !Stack->isImplicitTaskFirstprivate(VD))
3486         return;
3487 
3488       SourceLocation ELoc = E->getExprLoc();
3489       OpenMPDirectiveKind DKind = Stack->getCurrentDirective();
3490       // The default(none) clause requires that each variable that is referenced
3491       // in the construct, and does not have a predetermined data-sharing
3492       // attribute, must have its data-sharing attribute explicitly determined
3493       // by being listed in a data-sharing attribute clause.
3494       if (DVar.CKind == OMPC_unknown &&
3495           (Stack->getDefaultDSA() == DSA_none ||
3496            Stack->getDefaultDSA() == DSA_firstprivate) &&
3497           isImplicitOrExplicitTaskingRegion(DKind) &&
3498           VarsWithInheritedDSA.count(VD) == 0) {
3499         bool InheritedDSA = Stack->getDefaultDSA() == DSA_none;
3500         if (!InheritedDSA && Stack->getDefaultDSA() == DSA_firstprivate) {
3501           DSAStackTy::DSAVarData DVar =
3502               Stack->getImplicitDSA(VD, /*FromParent=*/false);
3503           InheritedDSA = DVar.CKind == OMPC_unknown;
3504         }
3505         if (InheritedDSA)
3506           VarsWithInheritedDSA[VD] = E;
3507         return;
3508       }
3509 
3510       // OpenMP 5.0 [2.19.7.2, defaultmap clause, Description]
3511       // If implicit-behavior is none, each variable referenced in the
3512       // construct that does not have a predetermined data-sharing attribute
3513       // and does not appear in a to or link clause on a declare target
3514       // directive must be listed in a data-mapping attribute clause, a
3515       // data-haring attribute clause (including a data-sharing attribute
3516       // clause on a combined construct where target. is one of the
3517       // constituent constructs), or an is_device_ptr clause.
3518       OpenMPDefaultmapClauseKind ClauseKind =
3519           getVariableCategoryFromDecl(SemaRef.getLangOpts(), VD);
3520       if (SemaRef.getLangOpts().OpenMP >= 50) {
3521         bool IsModifierNone = Stack->getDefaultmapModifier(ClauseKind) ==
3522                               OMPC_DEFAULTMAP_MODIFIER_none;
3523         if (DVar.CKind == OMPC_unknown && IsModifierNone &&
3524             VarsWithInheritedDSA.count(VD) == 0 && !Res) {
3525           // Only check for data-mapping attribute and is_device_ptr here
3526           // since we have already make sure that the declaration does not
3527           // have a data-sharing attribute above
3528           if (!Stack->checkMappableExprComponentListsForDecl(
3529                   VD, /*CurrentRegionOnly=*/true,
3530                   [VD](OMPClauseMappableExprCommon::MappableExprComponentListRef
3531                            MapExprComponents,
3532                        OpenMPClauseKind) {
3533                     auto MI = MapExprComponents.rbegin();
3534                     auto ME = MapExprComponents.rend();
3535                     return MI != ME && MI->getAssociatedDeclaration() == VD;
3536                   })) {
3537             VarsWithInheritedDSA[VD] = E;
3538             return;
3539           }
3540         }
3541       }
3542       if (SemaRef.getLangOpts().OpenMP > 50) {
3543         bool IsModifierPresent = Stack->getDefaultmapModifier(ClauseKind) ==
3544                                  OMPC_DEFAULTMAP_MODIFIER_present;
3545         if (IsModifierPresent) {
3546           if (llvm::find(ImplicitMapModifier[ClauseKind],
3547                          OMPC_MAP_MODIFIER_present) ==
3548               std::end(ImplicitMapModifier[ClauseKind])) {
3549             ImplicitMapModifier[ClauseKind].push_back(
3550                 OMPC_MAP_MODIFIER_present);
3551           }
3552         }
3553       }
3554 
3555       if (isOpenMPTargetExecutionDirective(DKind) &&
3556           !Stack->isLoopControlVariable(VD).first) {
3557         if (!Stack->checkMappableExprComponentListsForDecl(
3558                 VD, /*CurrentRegionOnly=*/true,
3559                 [](OMPClauseMappableExprCommon::MappableExprComponentListRef
3560                        StackComponents,
3561                    OpenMPClauseKind) {
3562                   // Variable is used if it has been marked as an array, array
3563                   // section, array shaping or the variable iself.
3564                   return StackComponents.size() == 1 ||
3565                          std::all_of(
3566                              std::next(StackComponents.rbegin()),
3567                              StackComponents.rend(),
3568                              [](const OMPClauseMappableExprCommon::
3569                                     MappableComponent &MC) {
3570                                return MC.getAssociatedDeclaration() ==
3571                                           nullptr &&
3572                                       (isa<OMPArraySectionExpr>(
3573                                            MC.getAssociatedExpression()) ||
3574                                        isa<OMPArrayShapingExpr>(
3575                                            MC.getAssociatedExpression()) ||
3576                                        isa<ArraySubscriptExpr>(
3577                                            MC.getAssociatedExpression()));
3578                              });
3579                 })) {
3580           bool IsFirstprivate = false;
3581           // By default lambdas are captured as firstprivates.
3582           if (const auto *RD =
3583                   VD->getType().getNonReferenceType()->getAsCXXRecordDecl())
3584             IsFirstprivate = RD->isLambda();
3585           IsFirstprivate =
3586               IsFirstprivate || (Stack->mustBeFirstprivate(ClauseKind) && !Res);
3587           if (IsFirstprivate) {
3588             ImplicitFirstprivate.emplace_back(E);
3589           } else {
3590             OpenMPDefaultmapClauseModifier M =
3591                 Stack->getDefaultmapModifier(ClauseKind);
3592             OpenMPMapClauseKind Kind = getMapClauseKindFromModifier(
3593                 M, ClauseKind == OMPC_DEFAULTMAP_aggregate || Res);
3594             ImplicitMap[ClauseKind][Kind].emplace_back(E);
3595           }
3596           return;
3597         }
3598       }
3599 
3600       // OpenMP [2.9.3.6, Restrictions, p.2]
3601       //  A list item that appears in a reduction clause of the innermost
3602       //  enclosing worksharing or parallel construct may not be accessed in an
3603       //  explicit task.
3604       DVar = Stack->hasInnermostDSA(
3605           VD,
3606           [](OpenMPClauseKind C, bool AppliedToPointee) {
3607             return C == OMPC_reduction && !AppliedToPointee;
3608           },
3609           [](OpenMPDirectiveKind K) {
3610             return isOpenMPParallelDirective(K) ||
3611                    isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
3612           },
3613           /*FromParent=*/true);
3614       if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
3615         ErrorFound = true;
3616         SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
3617         reportOriginalDsa(SemaRef, Stack, VD, DVar);
3618         return;
3619       }
3620 
3621       // Define implicit data-sharing attributes for task.
3622       DVar = Stack->getImplicitDSA(VD, /*FromParent=*/false);
3623       if (((isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared) ||
3624            (Stack->getDefaultDSA() == DSA_firstprivate &&
3625             DVar.CKind == OMPC_firstprivate && !DVar.RefExpr)) &&
3626           !Stack->isLoopControlVariable(VD).first) {
3627         ImplicitFirstprivate.push_back(E);
3628         return;
3629       }
3630 
3631       // Store implicitly used globals with declare target link for parent
3632       // target.
3633       if (!isOpenMPTargetExecutionDirective(DKind) && Res &&
3634           *Res == OMPDeclareTargetDeclAttr::MT_Link) {
3635         Stack->addToParentTargetRegionLinkGlobals(E);
3636         return;
3637       }
3638     }
3639   }
3640   void VisitMemberExpr(MemberExpr *E) {
3641     if (E->isTypeDependent() || E->isValueDependent() ||
3642         E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
3643       return;
3644     auto *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
3645     OpenMPDirectiveKind DKind = Stack->getCurrentDirective();
3646     if (auto *TE = dyn_cast<CXXThisExpr>(E->getBase()->IgnoreParenCasts())) {
3647       if (!FD)
3648         return;
3649       DSAStackTy::DSAVarData DVar = Stack->getTopDSA(FD, /*FromParent=*/false);
3650       // Check if the variable has explicit DSA set and stop analysis if it
3651       // so.
3652       if (DVar.RefExpr || !ImplicitDeclarations.insert(FD).second)
3653         return;
3654 
3655       if (isOpenMPTargetExecutionDirective(DKind) &&
3656           !Stack->isLoopControlVariable(FD).first &&
3657           !Stack->checkMappableExprComponentListsForDecl(
3658               FD, /*CurrentRegionOnly=*/true,
3659               [](OMPClauseMappableExprCommon::MappableExprComponentListRef
3660                      StackComponents,
3661                  OpenMPClauseKind) {
3662                 return isa<CXXThisExpr>(
3663                     cast<MemberExpr>(
3664                         StackComponents.back().getAssociatedExpression())
3665                         ->getBase()
3666                         ->IgnoreParens());
3667               })) {
3668         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
3669         //  A bit-field cannot appear in a map clause.
3670         //
3671         if (FD->isBitField())
3672           return;
3673 
3674         // Check to see if the member expression is referencing a class that
3675         // has already been explicitly mapped
3676         if (Stack->isClassPreviouslyMapped(TE->getType()))
3677           return;
3678 
3679         OpenMPDefaultmapClauseModifier Modifier =
3680             Stack->getDefaultmapModifier(OMPC_DEFAULTMAP_aggregate);
3681         OpenMPDefaultmapClauseKind ClauseKind =
3682             getVariableCategoryFromDecl(SemaRef.getLangOpts(), FD);
3683         OpenMPMapClauseKind Kind = getMapClauseKindFromModifier(
3684             Modifier, /*IsAggregateOrDeclareTarget*/ true);
3685         ImplicitMap[ClauseKind][Kind].emplace_back(E);
3686         return;
3687       }
3688 
3689       SourceLocation ELoc = E->getExprLoc();
3690       // OpenMP [2.9.3.6, Restrictions, p.2]
3691       //  A list item that appears in a reduction clause of the innermost
3692       //  enclosing worksharing or parallel construct may not be accessed in
3693       //  an  explicit task.
3694       DVar = Stack->hasInnermostDSA(
3695           FD,
3696           [](OpenMPClauseKind C, bool AppliedToPointee) {
3697             return C == OMPC_reduction && !AppliedToPointee;
3698           },
3699           [](OpenMPDirectiveKind K) {
3700             return isOpenMPParallelDirective(K) ||
3701                    isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
3702           },
3703           /*FromParent=*/true);
3704       if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
3705         ErrorFound = true;
3706         SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
3707         reportOriginalDsa(SemaRef, Stack, FD, DVar);
3708         return;
3709       }
3710 
3711       // Define implicit data-sharing attributes for task.
3712       DVar = Stack->getImplicitDSA(FD, /*FromParent=*/false);
3713       if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
3714           !Stack->isLoopControlVariable(FD).first) {
3715         // Check if there is a captured expression for the current field in the
3716         // region. Do not mark it as firstprivate unless there is no captured
3717         // expression.
3718         // TODO: try to make it firstprivate.
3719         if (DVar.CKind != OMPC_unknown)
3720           ImplicitFirstprivate.push_back(E);
3721       }
3722       return;
3723     }
3724     if (isOpenMPTargetExecutionDirective(DKind)) {
3725       OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
3726       if (!checkMapClauseExpressionBase(SemaRef, E, CurComponents, OMPC_map,
3727                                         Stack->getCurrentDirective(),
3728                                         /*NoDiagnose=*/true))
3729         return;
3730       const auto *VD = cast<ValueDecl>(
3731           CurComponents.back().getAssociatedDeclaration()->getCanonicalDecl());
3732       if (!Stack->checkMappableExprComponentListsForDecl(
3733               VD, /*CurrentRegionOnly=*/true,
3734               [&CurComponents](
3735                   OMPClauseMappableExprCommon::MappableExprComponentListRef
3736                       StackComponents,
3737                   OpenMPClauseKind) {
3738                 auto CCI = CurComponents.rbegin();
3739                 auto CCE = CurComponents.rend();
3740                 for (const auto &SC : llvm::reverse(StackComponents)) {
3741                   // Do both expressions have the same kind?
3742                   if (CCI->getAssociatedExpression()->getStmtClass() !=
3743                       SC.getAssociatedExpression()->getStmtClass())
3744                     if (!((isa<OMPArraySectionExpr>(
3745                                SC.getAssociatedExpression()) ||
3746                            isa<OMPArrayShapingExpr>(
3747                                SC.getAssociatedExpression())) &&
3748                           isa<ArraySubscriptExpr>(
3749                               CCI->getAssociatedExpression())))
3750                       return false;
3751 
3752                   const Decl *CCD = CCI->getAssociatedDeclaration();
3753                   const Decl *SCD = SC.getAssociatedDeclaration();
3754                   CCD = CCD ? CCD->getCanonicalDecl() : nullptr;
3755                   SCD = SCD ? SCD->getCanonicalDecl() : nullptr;
3756                   if (SCD != CCD)
3757                     return false;
3758                   std::advance(CCI, 1);
3759                   if (CCI == CCE)
3760                     break;
3761                 }
3762                 return true;
3763               })) {
3764         Visit(E->getBase());
3765       }
3766     } else if (!TryCaptureCXXThisMembers) {
3767       Visit(E->getBase());
3768     }
3769   }
3770   void VisitOMPExecutableDirective(OMPExecutableDirective *S) {
3771     for (OMPClause *C : S->clauses()) {
3772       // Skip analysis of arguments of implicitly defined firstprivate clause
3773       // for task|target directives.
3774       // Skip analysis of arguments of implicitly defined map clause for target
3775       // directives.
3776       if (C && !((isa<OMPFirstprivateClause>(C) || isa<OMPMapClause>(C)) &&
3777                  C->isImplicit() &&
3778                  !isOpenMPTaskingDirective(Stack->getCurrentDirective()))) {
3779         for (Stmt *CC : C->children()) {
3780           if (CC)
3781             Visit(CC);
3782         }
3783       }
3784     }
3785     // Check implicitly captured variables.
3786     VisitSubCaptures(S);
3787   }
3788   void VisitStmt(Stmt *S) {
3789     for (Stmt *C : S->children()) {
3790       if (C) {
3791         // Check implicitly captured variables in the task-based directives to
3792         // check if they must be firstprivatized.
3793         Visit(C);
3794       }
3795     }
3796   }
3797 
3798   void visitSubCaptures(CapturedStmt *S) {
3799     for (const CapturedStmt::Capture &Cap : S->captures()) {
3800       if (!Cap.capturesVariable() && !Cap.capturesVariableByCopy())
3801         continue;
3802       VarDecl *VD = Cap.getCapturedVar();
3803       // Do not try to map the variable if it or its sub-component was mapped
3804       // already.
3805       if (isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()) &&
3806           Stack->checkMappableExprComponentListsForDecl(
3807               VD, /*CurrentRegionOnly=*/true,
3808               [](OMPClauseMappableExprCommon::MappableExprComponentListRef,
3809                  OpenMPClauseKind) { return true; }))
3810         continue;
3811       DeclRefExpr *DRE = buildDeclRefExpr(
3812           SemaRef, VD, VD->getType().getNonLValueExprType(SemaRef.Context),
3813           Cap.getLocation(), /*RefersToCapture=*/true);
3814       Visit(DRE);
3815     }
3816   }
3817   bool isErrorFound() const { return ErrorFound; }
3818   ArrayRef<Expr *> getImplicitFirstprivate() const {
3819     return ImplicitFirstprivate;
3820   }
3821   ArrayRef<Expr *> getImplicitMap(OpenMPDefaultmapClauseKind DK,
3822                                   OpenMPMapClauseKind MK) const {
3823     return ImplicitMap[DK][MK];
3824   }
3825   ArrayRef<OpenMPMapModifierKind>
3826   getImplicitMapModifier(OpenMPDefaultmapClauseKind Kind) const {
3827     return ImplicitMapModifier[Kind];
3828   }
3829   const Sema::VarsWithInheritedDSAType &getVarsWithInheritedDSA() const {
3830     return VarsWithInheritedDSA;
3831   }
3832 
3833   DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS)
3834       : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {
3835     // Process declare target link variables for the target directives.
3836     if (isOpenMPTargetExecutionDirective(S->getCurrentDirective())) {
3837       for (DeclRefExpr *E : Stack->getLinkGlobals())
3838         Visit(E);
3839     }
3840   }
3841 };
3842 } // namespace
3843 
3844 void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) {
3845   switch (DKind) {
3846   case OMPD_parallel:
3847   case OMPD_parallel_for:
3848   case OMPD_parallel_for_simd:
3849   case OMPD_parallel_sections:
3850   case OMPD_parallel_master:
3851   case OMPD_teams:
3852   case OMPD_teams_distribute:
3853   case OMPD_teams_distribute_simd: {
3854     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
3855     QualType KmpInt32PtrTy =
3856         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3857     Sema::CapturedParamNameType Params[] = {
3858         std::make_pair(".global_tid.", KmpInt32PtrTy),
3859         std::make_pair(".bound_tid.", KmpInt32PtrTy),
3860         std::make_pair(StringRef(), QualType()) // __context with shared vars
3861     };
3862     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3863                              Params);
3864     break;
3865   }
3866   case OMPD_target_teams:
3867   case OMPD_target_parallel:
3868   case OMPD_target_parallel_for:
3869   case OMPD_target_parallel_for_simd:
3870   case OMPD_target_teams_distribute:
3871   case OMPD_target_teams_distribute_simd: {
3872     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
3873     QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
3874     QualType KmpInt32PtrTy =
3875         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3876     QualType Args[] = {VoidPtrTy};
3877     FunctionProtoType::ExtProtoInfo EPI;
3878     EPI.Variadic = true;
3879     QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
3880     Sema::CapturedParamNameType Params[] = {
3881         std::make_pair(".global_tid.", KmpInt32Ty),
3882         std::make_pair(".part_id.", KmpInt32PtrTy),
3883         std::make_pair(".privates.", VoidPtrTy),
3884         std::make_pair(
3885             ".copy_fn.",
3886             Context.getPointerType(CopyFnType).withConst().withRestrict()),
3887         std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
3888         std::make_pair(StringRef(), QualType()) // __context with shared vars
3889     };
3890     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3891                              Params, /*OpenMPCaptureLevel=*/0);
3892     // Mark this captured region as inlined, because we don't use outlined
3893     // function directly.
3894     getCurCapturedRegion()->TheCapturedDecl->addAttr(
3895         AlwaysInlineAttr::CreateImplicit(
3896             Context, {}, AttributeCommonInfo::AS_Keyword,
3897             AlwaysInlineAttr::Keyword_forceinline));
3898     Sema::CapturedParamNameType ParamsTarget[] = {
3899         std::make_pair(StringRef(), QualType()) // __context with shared vars
3900     };
3901     // Start a captured region for 'target' with no implicit parameters.
3902     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3903                              ParamsTarget, /*OpenMPCaptureLevel=*/1);
3904     Sema::CapturedParamNameType ParamsTeamsOrParallel[] = {
3905         std::make_pair(".global_tid.", KmpInt32PtrTy),
3906         std::make_pair(".bound_tid.", KmpInt32PtrTy),
3907         std::make_pair(StringRef(), QualType()) // __context with shared vars
3908     };
3909     // Start a captured region for 'teams' or 'parallel'.  Both regions have
3910     // the same implicit parameters.
3911     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3912                              ParamsTeamsOrParallel, /*OpenMPCaptureLevel=*/2);
3913     break;
3914   }
3915   case OMPD_target:
3916   case OMPD_target_simd: {
3917     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
3918     QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
3919     QualType KmpInt32PtrTy =
3920         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
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     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3944                              std::make_pair(StringRef(), QualType()),
3945                              /*OpenMPCaptureLevel=*/1);
3946     break;
3947   }
3948   case OMPD_atomic:
3949   case OMPD_critical:
3950   case OMPD_section:
3951   case OMPD_master:
3952     break;
3953   case OMPD_simd:
3954   case OMPD_for:
3955   case OMPD_for_simd:
3956   case OMPD_sections:
3957   case OMPD_single:
3958   case OMPD_taskgroup:
3959   case OMPD_distribute:
3960   case OMPD_distribute_simd:
3961   case OMPD_ordered:
3962   case OMPD_target_data: {
3963     Sema::CapturedParamNameType Params[] = {
3964         std::make_pair(StringRef(), QualType()) // __context with shared vars
3965     };
3966     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3967                              Params);
3968     break;
3969   }
3970   case OMPD_task: {
3971     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
3972     QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
3973     QualType KmpInt32PtrTy =
3974         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3975     QualType Args[] = {VoidPtrTy};
3976     FunctionProtoType::ExtProtoInfo EPI;
3977     EPI.Variadic = true;
3978     QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
3979     Sema::CapturedParamNameType Params[] = {
3980         std::make_pair(".global_tid.", KmpInt32Ty),
3981         std::make_pair(".part_id.", KmpInt32PtrTy),
3982         std::make_pair(".privates.", VoidPtrTy),
3983         std::make_pair(
3984             ".copy_fn.",
3985             Context.getPointerType(CopyFnType).withConst().withRestrict()),
3986         std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
3987         std::make_pair(StringRef(), QualType()) // __context with shared vars
3988     };
3989     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3990                              Params);
3991     // Mark this captured region as inlined, because we don't use outlined
3992     // function directly.
3993     getCurCapturedRegion()->TheCapturedDecl->addAttr(
3994         AlwaysInlineAttr::CreateImplicit(
3995             Context, {}, AttributeCommonInfo::AS_Keyword,
3996             AlwaysInlineAttr::Keyword_forceinline));
3997     break;
3998   }
3999   case OMPD_taskloop:
4000   case OMPD_taskloop_simd:
4001   case OMPD_master_taskloop:
4002   case OMPD_master_taskloop_simd: {
4003     QualType KmpInt32Ty =
4004         Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1)
4005             .withConst();
4006     QualType KmpUInt64Ty =
4007         Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0)
4008             .withConst();
4009     QualType KmpInt64Ty =
4010         Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1)
4011             .withConst();
4012     QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
4013     QualType KmpInt32PtrTy =
4014         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
4015     QualType Args[] = {VoidPtrTy};
4016     FunctionProtoType::ExtProtoInfo EPI;
4017     EPI.Variadic = true;
4018     QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
4019     Sema::CapturedParamNameType Params[] = {
4020         std::make_pair(".global_tid.", KmpInt32Ty),
4021         std::make_pair(".part_id.", KmpInt32PtrTy),
4022         std::make_pair(".privates.", VoidPtrTy),
4023         std::make_pair(
4024             ".copy_fn.",
4025             Context.getPointerType(CopyFnType).withConst().withRestrict()),
4026         std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
4027         std::make_pair(".lb.", KmpUInt64Ty),
4028         std::make_pair(".ub.", KmpUInt64Ty),
4029         std::make_pair(".st.", KmpInt64Ty),
4030         std::make_pair(".liter.", KmpInt32Ty),
4031         std::make_pair(".reductions.", VoidPtrTy),
4032         std::make_pair(StringRef(), QualType()) // __context with shared vars
4033     };
4034     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
4035                              Params);
4036     // Mark this captured region as inlined, because we don't use outlined
4037     // function directly.
4038     getCurCapturedRegion()->TheCapturedDecl->addAttr(
4039         AlwaysInlineAttr::CreateImplicit(
4040             Context, {}, AttributeCommonInfo::AS_Keyword,
4041             AlwaysInlineAttr::Keyword_forceinline));
4042     break;
4043   }
4044   case OMPD_parallel_master_taskloop:
4045   case OMPD_parallel_master_taskloop_simd: {
4046     QualType KmpInt32Ty =
4047         Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1)
4048             .withConst();
4049     QualType KmpUInt64Ty =
4050         Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0)
4051             .withConst();
4052     QualType KmpInt64Ty =
4053         Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1)
4054             .withConst();
4055     QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
4056     QualType KmpInt32PtrTy =
4057         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
4058     Sema::CapturedParamNameType ParamsParallel[] = {
4059         std::make_pair(".global_tid.", KmpInt32PtrTy),
4060         std::make_pair(".bound_tid.", KmpInt32PtrTy),
4061         std::make_pair(StringRef(), QualType()) // __context with shared vars
4062     };
4063     // Start a captured region for 'parallel'.
4064     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
4065                              ParamsParallel, /*OpenMPCaptureLevel=*/0);
4066     QualType Args[] = {VoidPtrTy};
4067     FunctionProtoType::ExtProtoInfo EPI;
4068     EPI.Variadic = true;
4069     QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
4070     Sema::CapturedParamNameType Params[] = {
4071         std::make_pair(".global_tid.", KmpInt32Ty),
4072         std::make_pair(".part_id.", KmpInt32PtrTy),
4073         std::make_pair(".privates.", VoidPtrTy),
4074         std::make_pair(
4075             ".copy_fn.",
4076             Context.getPointerType(CopyFnType).withConst().withRestrict()),
4077         std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
4078         std::make_pair(".lb.", KmpUInt64Ty),
4079         std::make_pair(".ub.", KmpUInt64Ty),
4080         std::make_pair(".st.", KmpInt64Ty),
4081         std::make_pair(".liter.", KmpInt32Ty),
4082         std::make_pair(".reductions.", VoidPtrTy),
4083         std::make_pair(StringRef(), QualType()) // __context with shared vars
4084     };
4085     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
4086                              Params, /*OpenMPCaptureLevel=*/1);
4087     // Mark this captured region as inlined, because we don't use outlined
4088     // function directly.
4089     getCurCapturedRegion()->TheCapturedDecl->addAttr(
4090         AlwaysInlineAttr::CreateImplicit(
4091             Context, {}, AttributeCommonInfo::AS_Keyword,
4092             AlwaysInlineAttr::Keyword_forceinline));
4093     break;
4094   }
4095   case OMPD_distribute_parallel_for_simd:
4096   case OMPD_distribute_parallel_for: {
4097     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
4098     QualType KmpInt32PtrTy =
4099         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
4100     Sema::CapturedParamNameType Params[] = {
4101         std::make_pair(".global_tid.", KmpInt32PtrTy),
4102         std::make_pair(".bound_tid.", KmpInt32PtrTy),
4103         std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
4104         std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
4105         std::make_pair(StringRef(), QualType()) // __context with shared vars
4106     };
4107     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
4108                              Params);
4109     break;
4110   }
4111   case OMPD_target_teams_distribute_parallel_for:
4112   case OMPD_target_teams_distribute_parallel_for_simd: {
4113     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
4114     QualType KmpInt32PtrTy =
4115         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
4116     QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
4117 
4118     QualType Args[] = {VoidPtrTy};
4119     FunctionProtoType::ExtProtoInfo EPI;
4120     EPI.Variadic = true;
4121     QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
4122     Sema::CapturedParamNameType Params[] = {
4123         std::make_pair(".global_tid.", KmpInt32Ty),
4124         std::make_pair(".part_id.", KmpInt32PtrTy),
4125         std::make_pair(".privates.", VoidPtrTy),
4126         std::make_pair(
4127             ".copy_fn.",
4128             Context.getPointerType(CopyFnType).withConst().withRestrict()),
4129         std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
4130         std::make_pair(StringRef(), QualType()) // __context with shared vars
4131     };
4132     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
4133                              Params, /*OpenMPCaptureLevel=*/0);
4134     // Mark this captured region as inlined, because we don't use outlined
4135     // function directly.
4136     getCurCapturedRegion()->TheCapturedDecl->addAttr(
4137         AlwaysInlineAttr::CreateImplicit(
4138             Context, {}, AttributeCommonInfo::AS_Keyword,
4139             AlwaysInlineAttr::Keyword_forceinline));
4140     Sema::CapturedParamNameType ParamsTarget[] = {
4141         std::make_pair(StringRef(), QualType()) // __context with shared vars
4142     };
4143     // Start a captured region for 'target' with no implicit parameters.
4144     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
4145                              ParamsTarget, /*OpenMPCaptureLevel=*/1);
4146 
4147     Sema::CapturedParamNameType ParamsTeams[] = {
4148         std::make_pair(".global_tid.", KmpInt32PtrTy),
4149         std::make_pair(".bound_tid.", KmpInt32PtrTy),
4150         std::make_pair(StringRef(), QualType()) // __context with shared vars
4151     };
4152     // Start a captured region for 'target' with no implicit parameters.
4153     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
4154                              ParamsTeams, /*OpenMPCaptureLevel=*/2);
4155 
4156     Sema::CapturedParamNameType ParamsParallel[] = {
4157         std::make_pair(".global_tid.", KmpInt32PtrTy),
4158         std::make_pair(".bound_tid.", KmpInt32PtrTy),
4159         std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
4160         std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
4161         std::make_pair(StringRef(), QualType()) // __context with shared vars
4162     };
4163     // Start a captured region for 'teams' or 'parallel'.  Both regions have
4164     // the same implicit parameters.
4165     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
4166                              ParamsParallel, /*OpenMPCaptureLevel=*/3);
4167     break;
4168   }
4169 
4170   case OMPD_teams_distribute_parallel_for:
4171   case OMPD_teams_distribute_parallel_for_simd: {
4172     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
4173     QualType KmpInt32PtrTy =
4174         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
4175 
4176     Sema::CapturedParamNameType ParamsTeams[] = {
4177         std::make_pair(".global_tid.", KmpInt32PtrTy),
4178         std::make_pair(".bound_tid.", KmpInt32PtrTy),
4179         std::make_pair(StringRef(), QualType()) // __context with shared vars
4180     };
4181     // Start a captured region for 'target' with no implicit parameters.
4182     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
4183                              ParamsTeams, /*OpenMPCaptureLevel=*/0);
4184 
4185     Sema::CapturedParamNameType ParamsParallel[] = {
4186         std::make_pair(".global_tid.", KmpInt32PtrTy),
4187         std::make_pair(".bound_tid.", KmpInt32PtrTy),
4188         std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
4189         std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
4190         std::make_pair(StringRef(), QualType()) // __context with shared vars
4191     };
4192     // Start a captured region for 'teams' or 'parallel'.  Both regions have
4193     // the same implicit parameters.
4194     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
4195                              ParamsParallel, /*OpenMPCaptureLevel=*/1);
4196     break;
4197   }
4198   case OMPD_target_update:
4199   case OMPD_target_enter_data:
4200   case OMPD_target_exit_data: {
4201     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
4202     QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
4203     QualType KmpInt32PtrTy =
4204         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
4205     QualType Args[] = {VoidPtrTy};
4206     FunctionProtoType::ExtProtoInfo EPI;
4207     EPI.Variadic = true;
4208     QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
4209     Sema::CapturedParamNameType Params[] = {
4210         std::make_pair(".global_tid.", KmpInt32Ty),
4211         std::make_pair(".part_id.", KmpInt32PtrTy),
4212         std::make_pair(".privates.", VoidPtrTy),
4213         std::make_pair(
4214             ".copy_fn.",
4215             Context.getPointerType(CopyFnType).withConst().withRestrict()),
4216         std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
4217         std::make_pair(StringRef(), QualType()) // __context with shared vars
4218     };
4219     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
4220                              Params);
4221     // Mark this captured region as inlined, because we don't use outlined
4222     // function directly.
4223     getCurCapturedRegion()->TheCapturedDecl->addAttr(
4224         AlwaysInlineAttr::CreateImplicit(
4225             Context, {}, AttributeCommonInfo::AS_Keyword,
4226             AlwaysInlineAttr::Keyword_forceinline));
4227     break;
4228   }
4229   case OMPD_threadprivate:
4230   case OMPD_allocate:
4231   case OMPD_taskyield:
4232   case OMPD_barrier:
4233   case OMPD_taskwait:
4234   case OMPD_cancellation_point:
4235   case OMPD_cancel:
4236   case OMPD_flush:
4237   case OMPD_depobj:
4238   case OMPD_scan:
4239   case OMPD_declare_reduction:
4240   case OMPD_declare_mapper:
4241   case OMPD_declare_simd:
4242   case OMPD_declare_target:
4243   case OMPD_end_declare_target:
4244   case OMPD_requires:
4245   case OMPD_declare_variant:
4246   case OMPD_begin_declare_variant:
4247   case OMPD_end_declare_variant:
4248     llvm_unreachable("OpenMP Directive is not allowed");
4249   case OMPD_unknown:
4250   default:
4251     llvm_unreachable("Unknown OpenMP directive");
4252   }
4253   DSAStack->setContext(CurContext);
4254 }
4255 
4256 int Sema::getNumberOfConstructScopes(unsigned Level) const {
4257   return getOpenMPCaptureLevels(DSAStack->getDirective(Level));
4258 }
4259 
4260 int Sema::getOpenMPCaptureLevels(OpenMPDirectiveKind DKind) {
4261   SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
4262   getOpenMPCaptureRegions(CaptureRegions, DKind);
4263   return CaptureRegions.size();
4264 }
4265 
4266 static OMPCapturedExprDecl *buildCaptureDecl(Sema &S, IdentifierInfo *Id,
4267                                              Expr *CaptureExpr, bool WithInit,
4268                                              bool AsExpression) {
4269   assert(CaptureExpr);
4270   ASTContext &C = S.getASTContext();
4271   Expr *Init = AsExpression ? CaptureExpr : CaptureExpr->IgnoreImpCasts();
4272   QualType Ty = Init->getType();
4273   if (CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue()) {
4274     if (S.getLangOpts().CPlusPlus) {
4275       Ty = C.getLValueReferenceType(Ty);
4276     } else {
4277       Ty = C.getPointerType(Ty);
4278       ExprResult Res =
4279           S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_AddrOf, Init);
4280       if (!Res.isUsable())
4281         return nullptr;
4282       Init = Res.get();
4283     }
4284     WithInit = true;
4285   }
4286   auto *CED = OMPCapturedExprDecl::Create(C, S.CurContext, Id, Ty,
4287                                           CaptureExpr->getBeginLoc());
4288   if (!WithInit)
4289     CED->addAttr(OMPCaptureNoInitAttr::CreateImplicit(C));
4290   S.CurContext->addHiddenDecl(CED);
4291   Sema::TentativeAnalysisScope Trap(S);
4292   S.AddInitializerToDecl(CED, Init, /*DirectInit=*/false);
4293   return CED;
4294 }
4295 
4296 static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr,
4297                                  bool WithInit) {
4298   OMPCapturedExprDecl *CD;
4299   if (VarDecl *VD = S.isOpenMPCapturedDecl(D))
4300     CD = cast<OMPCapturedExprDecl>(VD);
4301   else
4302     CD = buildCaptureDecl(S, D->getIdentifier(), CaptureExpr, WithInit,
4303                           /*AsExpression=*/false);
4304   return buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
4305                           CaptureExpr->getExprLoc());
4306 }
4307 
4308 static ExprResult buildCapture(Sema &S, Expr *CaptureExpr, DeclRefExpr *&Ref) {
4309   CaptureExpr = S.DefaultLvalueConversion(CaptureExpr).get();
4310   if (!Ref) {
4311     OMPCapturedExprDecl *CD = buildCaptureDecl(
4312         S, &S.getASTContext().Idents.get(".capture_expr."), CaptureExpr,
4313         /*WithInit=*/true, /*AsExpression=*/true);
4314     Ref = buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
4315                            CaptureExpr->getExprLoc());
4316   }
4317   ExprResult Res = Ref;
4318   if (!S.getLangOpts().CPlusPlus &&
4319       CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue() &&
4320       Ref->getType()->isPointerType()) {
4321     Res = S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_Deref, Ref);
4322     if (!Res.isUsable())
4323       return ExprError();
4324   }
4325   return S.DefaultLvalueConversion(Res.get());
4326 }
4327 
4328 namespace {
4329 // OpenMP directives parsed in this section are represented as a
4330 // CapturedStatement with an associated statement.  If a syntax error
4331 // is detected during the parsing of the associated statement, the
4332 // compiler must abort processing and close the CapturedStatement.
4333 //
4334 // Combined directives such as 'target parallel' have more than one
4335 // nested CapturedStatements.  This RAII ensures that we unwind out
4336 // of all the nested CapturedStatements when an error is found.
4337 class CaptureRegionUnwinderRAII {
4338 private:
4339   Sema &S;
4340   bool &ErrorFound;
4341   OpenMPDirectiveKind DKind = OMPD_unknown;
4342 
4343 public:
4344   CaptureRegionUnwinderRAII(Sema &S, bool &ErrorFound,
4345                             OpenMPDirectiveKind DKind)
4346       : S(S), ErrorFound(ErrorFound), DKind(DKind) {}
4347   ~CaptureRegionUnwinderRAII() {
4348     if (ErrorFound) {
4349       int ThisCaptureLevel = S.getOpenMPCaptureLevels(DKind);
4350       while (--ThisCaptureLevel >= 0)
4351         S.ActOnCapturedRegionError();
4352     }
4353   }
4354 };
4355 } // namespace
4356 
4357 void Sema::tryCaptureOpenMPLambdas(ValueDecl *V) {
4358   // Capture variables captured by reference in lambdas for target-based
4359   // directives.
4360   if (!CurContext->isDependentContext() &&
4361       (isOpenMPTargetExecutionDirective(DSAStack->getCurrentDirective()) ||
4362        isOpenMPTargetDataManagementDirective(
4363            DSAStack->getCurrentDirective()))) {
4364     QualType Type = V->getType();
4365     if (const auto *RD = Type.getCanonicalType()
4366                              .getNonReferenceType()
4367                              ->getAsCXXRecordDecl()) {
4368       bool SavedForceCaptureByReferenceInTargetExecutable =
4369           DSAStack->isForceCaptureByReferenceInTargetExecutable();
4370       DSAStack->setForceCaptureByReferenceInTargetExecutable(
4371           /*V=*/true);
4372       if (RD->isLambda()) {
4373         llvm::DenseMap<const VarDecl *, FieldDecl *> Captures;
4374         FieldDecl *ThisCapture;
4375         RD->getCaptureFields(Captures, ThisCapture);
4376         for (const LambdaCapture &LC : RD->captures()) {
4377           if (LC.getCaptureKind() == LCK_ByRef) {
4378             VarDecl *VD = LC.getCapturedVar();
4379             DeclContext *VDC = VD->getDeclContext();
4380             if (!VDC->Encloses(CurContext))
4381               continue;
4382             MarkVariableReferenced(LC.getLocation(), VD);
4383           } else if (LC.getCaptureKind() == LCK_This) {
4384             QualType ThisTy = getCurrentThisType();
4385             if (!ThisTy.isNull() &&
4386                 Context.typesAreCompatible(ThisTy, ThisCapture->getType()))
4387               CheckCXXThisCapture(LC.getLocation());
4388           }
4389         }
4390       }
4391       DSAStack->setForceCaptureByReferenceInTargetExecutable(
4392           SavedForceCaptureByReferenceInTargetExecutable);
4393     }
4394   }
4395 }
4396 
4397 static bool checkOrderedOrderSpecified(Sema &S,
4398                                        const ArrayRef<OMPClause *> Clauses) {
4399   const OMPOrderedClause *Ordered = nullptr;
4400   const OMPOrderClause *Order = nullptr;
4401 
4402   for (const OMPClause *Clause : Clauses) {
4403     if (Clause->getClauseKind() == OMPC_ordered)
4404       Ordered = cast<OMPOrderedClause>(Clause);
4405     else if (Clause->getClauseKind() == OMPC_order) {
4406       Order = cast<OMPOrderClause>(Clause);
4407       if (Order->getKind() != OMPC_ORDER_concurrent)
4408         Order = nullptr;
4409     }
4410     if (Ordered && Order)
4411       break;
4412   }
4413 
4414   if (Ordered && Order) {
4415     S.Diag(Order->getKindKwLoc(),
4416            diag::err_omp_simple_clause_incompatible_with_ordered)
4417         << getOpenMPClauseName(OMPC_order)
4418         << getOpenMPSimpleClauseTypeName(OMPC_order, OMPC_ORDER_concurrent)
4419         << SourceRange(Order->getBeginLoc(), Order->getEndLoc());
4420     S.Diag(Ordered->getBeginLoc(), diag::note_omp_ordered_param)
4421         << 0 << SourceRange(Ordered->getBeginLoc(), Ordered->getEndLoc());
4422     return true;
4423   }
4424   return false;
4425 }
4426 
4427 StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S,
4428                                       ArrayRef<OMPClause *> Clauses) {
4429   if (DSAStack->getCurrentDirective() == OMPD_atomic ||
4430       DSAStack->getCurrentDirective() == OMPD_critical ||
4431       DSAStack->getCurrentDirective() == OMPD_section ||
4432       DSAStack->getCurrentDirective() == OMPD_master)
4433     return S;
4434 
4435   bool ErrorFound = false;
4436   CaptureRegionUnwinderRAII CaptureRegionUnwinder(
4437       *this, ErrorFound, DSAStack->getCurrentDirective());
4438   if (!S.isUsable()) {
4439     ErrorFound = true;
4440     return StmtError();
4441   }
4442 
4443   SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
4444   getOpenMPCaptureRegions(CaptureRegions, DSAStack->getCurrentDirective());
4445   OMPOrderedClause *OC = nullptr;
4446   OMPScheduleClause *SC = nullptr;
4447   SmallVector<const OMPLinearClause *, 4> LCs;
4448   SmallVector<const OMPClauseWithPreInit *, 4> PICs;
4449   // This is required for proper codegen.
4450   for (OMPClause *Clause : Clauses) {
4451     if (!LangOpts.OpenMPSimd &&
4452         isOpenMPTaskingDirective(DSAStack->getCurrentDirective()) &&
4453         Clause->getClauseKind() == OMPC_in_reduction) {
4454       // Capture taskgroup task_reduction descriptors inside the tasking regions
4455       // with the corresponding in_reduction items.
4456       auto *IRC = cast<OMPInReductionClause>(Clause);
4457       for (Expr *E : IRC->taskgroup_descriptors())
4458         if (E)
4459           MarkDeclarationsReferencedInExpr(E);
4460     }
4461     if (isOpenMPPrivate(Clause->getClauseKind()) ||
4462         Clause->getClauseKind() == OMPC_copyprivate ||
4463         (getLangOpts().OpenMPUseTLS &&
4464          getASTContext().getTargetInfo().isTLSSupported() &&
4465          Clause->getClauseKind() == OMPC_copyin)) {
4466       DSAStack->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin);
4467       // Mark all variables in private list clauses as used in inner region.
4468       for (Stmt *VarRef : Clause->children()) {
4469         if (auto *E = cast_or_null<Expr>(VarRef)) {
4470           MarkDeclarationsReferencedInExpr(E);
4471         }
4472       }
4473       DSAStack->setForceVarCapturing(/*V=*/false);
4474     } else if (CaptureRegions.size() > 1 ||
4475                CaptureRegions.back() != OMPD_unknown) {
4476       if (auto *C = OMPClauseWithPreInit::get(Clause))
4477         PICs.push_back(C);
4478       if (auto *C = OMPClauseWithPostUpdate::get(Clause)) {
4479         if (Expr *E = C->getPostUpdateExpr())
4480           MarkDeclarationsReferencedInExpr(E);
4481       }
4482     }
4483     if (Clause->getClauseKind() == OMPC_schedule)
4484       SC = cast<OMPScheduleClause>(Clause);
4485     else if (Clause->getClauseKind() == OMPC_ordered)
4486       OC = cast<OMPOrderedClause>(Clause);
4487     else if (Clause->getClauseKind() == OMPC_linear)
4488       LCs.push_back(cast<OMPLinearClause>(Clause));
4489   }
4490   // Capture allocator expressions if used.
4491   for (Expr *E : DSAStack->getInnerAllocators())
4492     MarkDeclarationsReferencedInExpr(E);
4493   // OpenMP, 2.7.1 Loop Construct, Restrictions
4494   // The nonmonotonic modifier cannot be specified if an ordered clause is
4495   // specified.
4496   if (SC &&
4497       (SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
4498        SC->getSecondScheduleModifier() ==
4499            OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
4500       OC) {
4501     Diag(SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic
4502              ? SC->getFirstScheduleModifierLoc()
4503              : SC->getSecondScheduleModifierLoc(),
4504          diag::err_omp_simple_clause_incompatible_with_ordered)
4505         << getOpenMPClauseName(OMPC_schedule)
4506         << getOpenMPSimpleClauseTypeName(OMPC_schedule,
4507                                          OMPC_SCHEDULE_MODIFIER_nonmonotonic)
4508         << SourceRange(OC->getBeginLoc(), OC->getEndLoc());
4509     ErrorFound = true;
4510   }
4511   // OpenMP 5.0, 2.9.2 Worksharing-Loop Construct, Restrictions.
4512   // If an order(concurrent) clause is present, an ordered clause may not appear
4513   // on the same directive.
4514   if (checkOrderedOrderSpecified(*this, Clauses))
4515     ErrorFound = true;
4516   if (!LCs.empty() && OC && OC->getNumForLoops()) {
4517     for (const OMPLinearClause *C : LCs) {
4518       Diag(C->getBeginLoc(), diag::err_omp_linear_ordered)
4519           << SourceRange(OC->getBeginLoc(), OC->getEndLoc());
4520     }
4521     ErrorFound = true;
4522   }
4523   if (isOpenMPWorksharingDirective(DSAStack->getCurrentDirective()) &&
4524       isOpenMPSimdDirective(DSAStack->getCurrentDirective()) && OC &&
4525       OC->getNumForLoops()) {
4526     Diag(OC->getBeginLoc(), diag::err_omp_ordered_simd)
4527         << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
4528     ErrorFound = true;
4529   }
4530   if (ErrorFound) {
4531     return StmtError();
4532   }
4533   StmtResult SR = S;
4534   unsigned CompletedRegions = 0;
4535   for (OpenMPDirectiveKind ThisCaptureRegion : llvm::reverse(CaptureRegions)) {
4536     // Mark all variables in private list clauses as used in inner region.
4537     // Required for proper codegen of combined directives.
4538     // TODO: add processing for other clauses.
4539     if (ThisCaptureRegion != OMPD_unknown) {
4540       for (const clang::OMPClauseWithPreInit *C : PICs) {
4541         OpenMPDirectiveKind CaptureRegion = C->getCaptureRegion();
4542         // Find the particular capture region for the clause if the
4543         // directive is a combined one with multiple capture regions.
4544         // If the directive is not a combined one, the capture region
4545         // associated with the clause is OMPD_unknown and is generated
4546         // only once.
4547         if (CaptureRegion == ThisCaptureRegion ||
4548             CaptureRegion == OMPD_unknown) {
4549           if (auto *DS = cast_or_null<DeclStmt>(C->getPreInitStmt())) {
4550             for (Decl *D : DS->decls())
4551               MarkVariableReferenced(D->getLocation(), cast<VarDecl>(D));
4552           }
4553         }
4554       }
4555     }
4556     if (ThisCaptureRegion == OMPD_target) {
4557       // Capture allocator traits in the target region. They are used implicitly
4558       // and, thus, are not captured by default.
4559       for (OMPClause *C : Clauses) {
4560         if (const auto *UAC = dyn_cast<OMPUsesAllocatorsClause>(C)) {
4561           for (unsigned I = 0, End = UAC->getNumberOfAllocators(); I < End;
4562                ++I) {
4563             OMPUsesAllocatorsClause::Data D = UAC->getAllocatorData(I);
4564             if (Expr *E = D.AllocatorTraits)
4565               MarkDeclarationsReferencedInExpr(E);
4566           }
4567           continue;
4568         }
4569       }
4570     }
4571     if (++CompletedRegions == CaptureRegions.size())
4572       DSAStack->setBodyComplete();
4573     SR = ActOnCapturedRegionEnd(SR.get());
4574   }
4575   return SR;
4576 }
4577 
4578 static bool checkCancelRegion(Sema &SemaRef, OpenMPDirectiveKind CurrentRegion,
4579                               OpenMPDirectiveKind CancelRegion,
4580                               SourceLocation StartLoc) {
4581   // CancelRegion is only needed for cancel and cancellation_point.
4582   if (CurrentRegion != OMPD_cancel && CurrentRegion != OMPD_cancellation_point)
4583     return false;
4584 
4585   if (CancelRegion == OMPD_parallel || CancelRegion == OMPD_for ||
4586       CancelRegion == OMPD_sections || CancelRegion == OMPD_taskgroup)
4587     return false;
4588 
4589   SemaRef.Diag(StartLoc, diag::err_omp_wrong_cancel_region)
4590       << getOpenMPDirectiveName(CancelRegion);
4591   return true;
4592 }
4593 
4594 static bool checkNestingOfRegions(Sema &SemaRef, const DSAStackTy *Stack,
4595                                   OpenMPDirectiveKind CurrentRegion,
4596                                   const DeclarationNameInfo &CurrentName,
4597                                   OpenMPDirectiveKind CancelRegion,
4598                                   SourceLocation StartLoc) {
4599   if (Stack->getCurScope()) {
4600     OpenMPDirectiveKind ParentRegion = Stack->getParentDirective();
4601     OpenMPDirectiveKind OffendingRegion = ParentRegion;
4602     bool NestingProhibited = false;
4603     bool CloseNesting = true;
4604     bool OrphanSeen = false;
4605     enum {
4606       NoRecommend,
4607       ShouldBeInParallelRegion,
4608       ShouldBeInOrderedRegion,
4609       ShouldBeInTargetRegion,
4610       ShouldBeInTeamsRegion,
4611       ShouldBeInLoopSimdRegion,
4612     } Recommend = NoRecommend;
4613     if (isOpenMPSimdDirective(ParentRegion) &&
4614         ((SemaRef.LangOpts.OpenMP <= 45 && CurrentRegion != OMPD_ordered) ||
4615          (SemaRef.LangOpts.OpenMP >= 50 && CurrentRegion != OMPD_ordered &&
4616           CurrentRegion != OMPD_simd && CurrentRegion != OMPD_atomic &&
4617           CurrentRegion != OMPD_scan))) {
4618       // OpenMP [2.16, Nesting of Regions]
4619       // OpenMP constructs may not be nested inside a simd region.
4620       // OpenMP [2.8.1,simd Construct, Restrictions]
4621       // An ordered construct with the simd clause is the only OpenMP
4622       // construct that can appear in the simd region.
4623       // Allowing a SIMD construct nested in another SIMD construct is an
4624       // extension. The OpenMP 4.5 spec does not allow it. Issue a warning
4625       // message.
4626       // OpenMP 5.0 [2.9.3.1, simd Construct, Restrictions]
4627       // The only OpenMP constructs that can be encountered during execution of
4628       // a simd region are the atomic construct, the loop construct, the simd
4629       // construct and the ordered construct with the simd clause.
4630       SemaRef.Diag(StartLoc, (CurrentRegion != OMPD_simd)
4631                                  ? diag::err_omp_prohibited_region_simd
4632                                  : diag::warn_omp_nesting_simd)
4633           << (SemaRef.LangOpts.OpenMP >= 50 ? 1 : 0);
4634       return CurrentRegion != OMPD_simd;
4635     }
4636     if (ParentRegion == OMPD_atomic) {
4637       // OpenMP [2.16, Nesting of Regions]
4638       // OpenMP constructs may not be nested inside an atomic region.
4639       SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic);
4640       return true;
4641     }
4642     if (CurrentRegion == OMPD_section) {
4643       // OpenMP [2.7.2, sections Construct, Restrictions]
4644       // Orphaned section directives are prohibited. That is, the section
4645       // directives must appear within the sections construct and must not be
4646       // encountered elsewhere in the sections region.
4647       if (ParentRegion != OMPD_sections &&
4648           ParentRegion != OMPD_parallel_sections) {
4649         SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive)
4650             << (ParentRegion != OMPD_unknown)
4651             << getOpenMPDirectiveName(ParentRegion);
4652         return true;
4653       }
4654       return false;
4655     }
4656     // Allow some constructs (except teams and cancellation constructs) to be
4657     // orphaned (they could be used in functions, called from OpenMP regions
4658     // with the required preconditions).
4659     if (ParentRegion == OMPD_unknown &&
4660         !isOpenMPNestingTeamsDirective(CurrentRegion) &&
4661         CurrentRegion != OMPD_cancellation_point &&
4662         CurrentRegion != OMPD_cancel && CurrentRegion != OMPD_scan)
4663       return false;
4664     if (CurrentRegion == OMPD_cancellation_point ||
4665         CurrentRegion == OMPD_cancel) {
4666       // OpenMP [2.16, Nesting of Regions]
4667       // A cancellation point construct for which construct-type-clause is
4668       // taskgroup must be nested inside a task construct. A cancellation
4669       // point construct for which construct-type-clause is not taskgroup must
4670       // be closely nested inside an OpenMP construct that matches the type
4671       // specified in construct-type-clause.
4672       // A cancel construct for which construct-type-clause is taskgroup must be
4673       // nested inside a task construct. A cancel construct for which
4674       // construct-type-clause is not taskgroup must be closely nested inside an
4675       // OpenMP construct that matches the type specified in
4676       // construct-type-clause.
4677       NestingProhibited =
4678           !((CancelRegion == OMPD_parallel &&
4679              (ParentRegion == OMPD_parallel ||
4680               ParentRegion == OMPD_target_parallel)) ||
4681             (CancelRegion == OMPD_for &&
4682              (ParentRegion == OMPD_for || ParentRegion == OMPD_parallel_for ||
4683               ParentRegion == OMPD_target_parallel_for ||
4684               ParentRegion == OMPD_distribute_parallel_for ||
4685               ParentRegion == OMPD_teams_distribute_parallel_for ||
4686               ParentRegion == OMPD_target_teams_distribute_parallel_for)) ||
4687             (CancelRegion == OMPD_taskgroup &&
4688              (ParentRegion == OMPD_task ||
4689               (SemaRef.getLangOpts().OpenMP >= 50 &&
4690                (ParentRegion == OMPD_taskloop ||
4691                 ParentRegion == OMPD_master_taskloop ||
4692                 ParentRegion == OMPD_parallel_master_taskloop)))) ||
4693             (CancelRegion == OMPD_sections &&
4694              (ParentRegion == OMPD_section || ParentRegion == OMPD_sections ||
4695               ParentRegion == OMPD_parallel_sections)));
4696       OrphanSeen = ParentRegion == OMPD_unknown;
4697     } else if (CurrentRegion == OMPD_master) {
4698       // OpenMP [2.16, Nesting of Regions]
4699       // A master region may not be closely nested inside a worksharing,
4700       // atomic, or explicit task region.
4701       NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
4702                           isOpenMPTaskingDirective(ParentRegion);
4703     } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) {
4704       // OpenMP [2.16, Nesting of Regions]
4705       // A critical region may not be nested (closely or otherwise) inside a
4706       // critical region with the same name. Note that this restriction is not
4707       // sufficient to prevent deadlock.
4708       SourceLocation PreviousCriticalLoc;
4709       bool DeadLock = Stack->hasDirective(
4710           [CurrentName, &PreviousCriticalLoc](OpenMPDirectiveKind K,
4711                                               const DeclarationNameInfo &DNI,
4712                                               SourceLocation Loc) {
4713             if (K == OMPD_critical && DNI.getName() == CurrentName.getName()) {
4714               PreviousCriticalLoc = Loc;
4715               return true;
4716             }
4717             return false;
4718           },
4719           false /* skip top directive */);
4720       if (DeadLock) {
4721         SemaRef.Diag(StartLoc,
4722                      diag::err_omp_prohibited_region_critical_same_name)
4723             << CurrentName.getName();
4724         if (PreviousCriticalLoc.isValid())
4725           SemaRef.Diag(PreviousCriticalLoc,
4726                        diag::note_omp_previous_critical_region);
4727         return true;
4728       }
4729     } else if (CurrentRegion == OMPD_barrier) {
4730       // OpenMP [2.16, Nesting of Regions]
4731       // A barrier region may not be closely nested inside a worksharing,
4732       // explicit task, critical, ordered, atomic, or master region.
4733       NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
4734                           isOpenMPTaskingDirective(ParentRegion) ||
4735                           ParentRegion == OMPD_master ||
4736                           ParentRegion == OMPD_parallel_master ||
4737                           ParentRegion == OMPD_critical ||
4738                           ParentRegion == OMPD_ordered;
4739     } else if (isOpenMPWorksharingDirective(CurrentRegion) &&
4740                !isOpenMPParallelDirective(CurrentRegion) &&
4741                !isOpenMPTeamsDirective(CurrentRegion)) {
4742       // OpenMP [2.16, Nesting of Regions]
4743       // A worksharing region may not be closely nested inside a worksharing,
4744       // explicit task, critical, ordered, atomic, or master region.
4745       NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
4746                           isOpenMPTaskingDirective(ParentRegion) ||
4747                           ParentRegion == OMPD_master ||
4748                           ParentRegion == OMPD_parallel_master ||
4749                           ParentRegion == OMPD_critical ||
4750                           ParentRegion == OMPD_ordered;
4751       Recommend = ShouldBeInParallelRegion;
4752     } else if (CurrentRegion == OMPD_ordered) {
4753       // OpenMP [2.16, Nesting of Regions]
4754       // An ordered region may not be closely nested inside a critical,
4755       // atomic, or explicit task region.
4756       // An ordered region must be closely nested inside a loop region (or
4757       // parallel loop region) with an ordered clause.
4758       // OpenMP [2.8.1,simd Construct, Restrictions]
4759       // An ordered construct with the simd clause is the only OpenMP construct
4760       // that can appear in the simd region.
4761       NestingProhibited = ParentRegion == OMPD_critical ||
4762                           isOpenMPTaskingDirective(ParentRegion) ||
4763                           !(isOpenMPSimdDirective(ParentRegion) ||
4764                             Stack->isParentOrderedRegion());
4765       Recommend = ShouldBeInOrderedRegion;
4766     } else if (isOpenMPNestingTeamsDirective(CurrentRegion)) {
4767       // OpenMP [2.16, Nesting of Regions]
4768       // If specified, a teams construct must be contained within a target
4769       // construct.
4770       NestingProhibited =
4771           (SemaRef.LangOpts.OpenMP <= 45 && ParentRegion != OMPD_target) ||
4772           (SemaRef.LangOpts.OpenMP >= 50 && ParentRegion != OMPD_unknown &&
4773            ParentRegion != OMPD_target);
4774       OrphanSeen = ParentRegion == OMPD_unknown;
4775       Recommend = ShouldBeInTargetRegion;
4776     } else if (CurrentRegion == OMPD_scan) {
4777       // OpenMP [2.16, Nesting of Regions]
4778       // If specified, a teams construct must be contained within a target
4779       // construct.
4780       NestingProhibited =
4781           SemaRef.LangOpts.OpenMP < 50 ||
4782           (ParentRegion != OMPD_simd && ParentRegion != OMPD_for &&
4783            ParentRegion != OMPD_for_simd && ParentRegion != OMPD_parallel_for &&
4784            ParentRegion != OMPD_parallel_for_simd);
4785       OrphanSeen = ParentRegion == OMPD_unknown;
4786       Recommend = ShouldBeInLoopSimdRegion;
4787     }
4788     if (!NestingProhibited &&
4789         !isOpenMPTargetExecutionDirective(CurrentRegion) &&
4790         !isOpenMPTargetDataManagementDirective(CurrentRegion) &&
4791         (ParentRegion == OMPD_teams || ParentRegion == OMPD_target_teams)) {
4792       // OpenMP [2.16, Nesting of Regions]
4793       // distribute, parallel, parallel sections, parallel workshare, and the
4794       // parallel loop and parallel loop SIMD constructs are the only OpenMP
4795       // constructs that can be closely nested in the teams region.
4796       NestingProhibited = !isOpenMPParallelDirective(CurrentRegion) &&
4797                           !isOpenMPDistributeDirective(CurrentRegion);
4798       Recommend = ShouldBeInParallelRegion;
4799     }
4800     if (!NestingProhibited &&
4801         isOpenMPNestingDistributeDirective(CurrentRegion)) {
4802       // OpenMP 4.5 [2.17 Nesting of Regions]
4803       // The region associated with the distribute construct must be strictly
4804       // nested inside a teams region
4805       NestingProhibited =
4806           (ParentRegion != OMPD_teams && ParentRegion != OMPD_target_teams);
4807       Recommend = ShouldBeInTeamsRegion;
4808     }
4809     if (!NestingProhibited &&
4810         (isOpenMPTargetExecutionDirective(CurrentRegion) ||
4811          isOpenMPTargetDataManagementDirective(CurrentRegion))) {
4812       // OpenMP 4.5 [2.17 Nesting of Regions]
4813       // If a target, target update, target data, target enter data, or
4814       // target exit data construct is encountered during execution of a
4815       // target region, the behavior is unspecified.
4816       NestingProhibited = Stack->hasDirective(
4817           [&OffendingRegion](OpenMPDirectiveKind K, const DeclarationNameInfo &,
4818                              SourceLocation) {
4819             if (isOpenMPTargetExecutionDirective(K)) {
4820               OffendingRegion = K;
4821               return true;
4822             }
4823             return false;
4824           },
4825           false /* don't skip top directive */);
4826       CloseNesting = false;
4827     }
4828     if (NestingProhibited) {
4829       if (OrphanSeen) {
4830         SemaRef.Diag(StartLoc, diag::err_omp_orphaned_device_directive)
4831             << getOpenMPDirectiveName(CurrentRegion) << Recommend;
4832       } else {
4833         SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region)
4834             << CloseNesting << getOpenMPDirectiveName(OffendingRegion)
4835             << Recommend << getOpenMPDirectiveName(CurrentRegion);
4836       }
4837       return true;
4838     }
4839   }
4840   return false;
4841 }
4842 
4843 struct Kind2Unsigned {
4844   using argument_type = OpenMPDirectiveKind;
4845   unsigned operator()(argument_type DK) { return unsigned(DK); }
4846 };
4847 static bool checkIfClauses(Sema &S, OpenMPDirectiveKind Kind,
4848                            ArrayRef<OMPClause *> Clauses,
4849                            ArrayRef<OpenMPDirectiveKind> AllowedNameModifiers) {
4850   bool ErrorFound = false;
4851   unsigned NamedModifiersNumber = 0;
4852   llvm::IndexedMap<const OMPIfClause *, Kind2Unsigned> FoundNameModifiers;
4853   FoundNameModifiers.resize(llvm::omp::Directive_enumSize + 1);
4854   SmallVector<SourceLocation, 4> NameModifierLoc;
4855   for (const OMPClause *C : Clauses) {
4856     if (const auto *IC = dyn_cast_or_null<OMPIfClause>(C)) {
4857       // At most one if clause without a directive-name-modifier can appear on
4858       // the directive.
4859       OpenMPDirectiveKind CurNM = IC->getNameModifier();
4860       if (FoundNameModifiers[CurNM]) {
4861         S.Diag(C->getBeginLoc(), diag::err_omp_more_one_clause)
4862             << getOpenMPDirectiveName(Kind) << getOpenMPClauseName(OMPC_if)
4863             << (CurNM != OMPD_unknown) << getOpenMPDirectiveName(CurNM);
4864         ErrorFound = true;
4865       } else if (CurNM != OMPD_unknown) {
4866         NameModifierLoc.push_back(IC->getNameModifierLoc());
4867         ++NamedModifiersNumber;
4868       }
4869       FoundNameModifiers[CurNM] = IC;
4870       if (CurNM == OMPD_unknown)
4871         continue;
4872       // Check if the specified name modifier is allowed for the current
4873       // directive.
4874       // At most one if clause with the particular directive-name-modifier can
4875       // appear on the directive.
4876       bool MatchFound = false;
4877       for (auto NM : AllowedNameModifiers) {
4878         if (CurNM == NM) {
4879           MatchFound = true;
4880           break;
4881         }
4882       }
4883       if (!MatchFound) {
4884         S.Diag(IC->getNameModifierLoc(),
4885                diag::err_omp_wrong_if_directive_name_modifier)
4886             << getOpenMPDirectiveName(CurNM) << getOpenMPDirectiveName(Kind);
4887         ErrorFound = true;
4888       }
4889     }
4890   }
4891   // If any if clause on the directive includes a directive-name-modifier then
4892   // all if clauses on the directive must include a directive-name-modifier.
4893   if (FoundNameModifiers[OMPD_unknown] && NamedModifiersNumber > 0) {
4894     if (NamedModifiersNumber == AllowedNameModifiers.size()) {
4895       S.Diag(FoundNameModifiers[OMPD_unknown]->getBeginLoc(),
4896              diag::err_omp_no_more_if_clause);
4897     } else {
4898       std::string Values;
4899       std::string Sep(", ");
4900       unsigned AllowedCnt = 0;
4901       unsigned TotalAllowedNum =
4902           AllowedNameModifiers.size() - NamedModifiersNumber;
4903       for (unsigned Cnt = 0, End = AllowedNameModifiers.size(); Cnt < End;
4904            ++Cnt) {
4905         OpenMPDirectiveKind NM = AllowedNameModifiers[Cnt];
4906         if (!FoundNameModifiers[NM]) {
4907           Values += "'";
4908           Values += getOpenMPDirectiveName(NM);
4909           Values += "'";
4910           if (AllowedCnt + 2 == TotalAllowedNum)
4911             Values += " or ";
4912           else if (AllowedCnt + 1 != TotalAllowedNum)
4913             Values += Sep;
4914           ++AllowedCnt;
4915         }
4916       }
4917       S.Diag(FoundNameModifiers[OMPD_unknown]->getCondition()->getBeginLoc(),
4918              diag::err_omp_unnamed_if_clause)
4919           << (TotalAllowedNum > 1) << Values;
4920     }
4921     for (SourceLocation Loc : NameModifierLoc) {
4922       S.Diag(Loc, diag::note_omp_previous_named_if_clause);
4923     }
4924     ErrorFound = true;
4925   }
4926   return ErrorFound;
4927 }
4928 
4929 static std::pair<ValueDecl *, bool> getPrivateItem(Sema &S, Expr *&RefExpr,
4930                                                    SourceLocation &ELoc,
4931                                                    SourceRange &ERange,
4932                                                    bool AllowArraySection) {
4933   if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() ||
4934       RefExpr->containsUnexpandedParameterPack())
4935     return std::make_pair(nullptr, true);
4936 
4937   // OpenMP [3.1, C/C++]
4938   //  A list item is a variable name.
4939   // OpenMP  [2.9.3.3, Restrictions, p.1]
4940   //  A variable that is part of another variable (as an array or
4941   //  structure element) cannot appear in a private clause.
4942   RefExpr = RefExpr->IgnoreParens();
4943   enum {
4944     NoArrayExpr = -1,
4945     ArraySubscript = 0,
4946     OMPArraySection = 1
4947   } IsArrayExpr = NoArrayExpr;
4948   if (AllowArraySection) {
4949     if (auto *ASE = dyn_cast_or_null<ArraySubscriptExpr>(RefExpr)) {
4950       Expr *Base = ASE->getBase()->IgnoreParenImpCasts();
4951       while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
4952         Base = TempASE->getBase()->IgnoreParenImpCasts();
4953       RefExpr = Base;
4954       IsArrayExpr = ArraySubscript;
4955     } else if (auto *OASE = dyn_cast_or_null<OMPArraySectionExpr>(RefExpr)) {
4956       Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
4957       while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
4958         Base = TempOASE->getBase()->IgnoreParenImpCasts();
4959       while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
4960         Base = TempASE->getBase()->IgnoreParenImpCasts();
4961       RefExpr = Base;
4962       IsArrayExpr = OMPArraySection;
4963     }
4964   }
4965   ELoc = RefExpr->getExprLoc();
4966   ERange = RefExpr->getSourceRange();
4967   RefExpr = RefExpr->IgnoreParenImpCasts();
4968   auto *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
4969   auto *ME = dyn_cast_or_null<MemberExpr>(RefExpr);
4970   if ((!DE || !isa<VarDecl>(DE->getDecl())) &&
4971       (S.getCurrentThisType().isNull() || !ME ||
4972        !isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()) ||
4973        !isa<FieldDecl>(ME->getMemberDecl()))) {
4974     if (IsArrayExpr != NoArrayExpr) {
4975       S.Diag(ELoc, diag::err_omp_expected_base_var_name) << IsArrayExpr
4976                                                          << ERange;
4977     } else {
4978       S.Diag(ELoc,
4979              AllowArraySection
4980                  ? diag::err_omp_expected_var_name_member_expr_or_array_item
4981                  : diag::err_omp_expected_var_name_member_expr)
4982           << (S.getCurrentThisType().isNull() ? 0 : 1) << ERange;
4983     }
4984     return std::make_pair(nullptr, false);
4985   }
4986   return std::make_pair(
4987       getCanonicalDecl(DE ? DE->getDecl() : ME->getMemberDecl()), false);
4988 }
4989 
4990 namespace {
4991 /// Checks if the allocator is used in uses_allocators clause to be allowed in
4992 /// target regions.
4993 class AllocatorChecker final : public ConstStmtVisitor<AllocatorChecker, bool> {
4994   DSAStackTy *S = nullptr;
4995 
4996 public:
4997   bool VisitDeclRefExpr(const DeclRefExpr *E) {
4998     return S->isUsesAllocatorsDecl(E->getDecl())
4999                .getValueOr(
5000                    DSAStackTy::UsesAllocatorsDeclKind::AllocatorTrait) ==
5001            DSAStackTy::UsesAllocatorsDeclKind::AllocatorTrait;
5002   }
5003   bool VisitStmt(const Stmt *S) {
5004     for (const Stmt *Child : S->children()) {
5005       if (Child && Visit(Child))
5006         return true;
5007     }
5008     return false;
5009   }
5010   explicit AllocatorChecker(DSAStackTy *S) : S(S) {}
5011 };
5012 } // namespace
5013 
5014 static void checkAllocateClauses(Sema &S, DSAStackTy *Stack,
5015                                  ArrayRef<OMPClause *> Clauses) {
5016   assert(!S.CurContext->isDependentContext() &&
5017          "Expected non-dependent context.");
5018   auto AllocateRange =
5019       llvm::make_filter_range(Clauses, OMPAllocateClause::classof);
5020   llvm::DenseMap<CanonicalDeclPtr<Decl>, CanonicalDeclPtr<VarDecl>>
5021       DeclToCopy;
5022   auto PrivateRange = llvm::make_filter_range(Clauses, [](const OMPClause *C) {
5023     return isOpenMPPrivate(C->getClauseKind());
5024   });
5025   for (OMPClause *Cl : PrivateRange) {
5026     MutableArrayRef<Expr *>::iterator I, It, Et;
5027     if (Cl->getClauseKind() == OMPC_private) {
5028       auto *PC = cast<OMPPrivateClause>(Cl);
5029       I = PC->private_copies().begin();
5030       It = PC->varlist_begin();
5031       Et = PC->varlist_end();
5032     } else if (Cl->getClauseKind() == OMPC_firstprivate) {
5033       auto *PC = cast<OMPFirstprivateClause>(Cl);
5034       I = PC->private_copies().begin();
5035       It = PC->varlist_begin();
5036       Et = PC->varlist_end();
5037     } else if (Cl->getClauseKind() == OMPC_lastprivate) {
5038       auto *PC = cast<OMPLastprivateClause>(Cl);
5039       I = PC->private_copies().begin();
5040       It = PC->varlist_begin();
5041       Et = PC->varlist_end();
5042     } else if (Cl->getClauseKind() == OMPC_linear) {
5043       auto *PC = cast<OMPLinearClause>(Cl);
5044       I = PC->privates().begin();
5045       It = PC->varlist_begin();
5046       Et = PC->varlist_end();
5047     } else if (Cl->getClauseKind() == OMPC_reduction) {
5048       auto *PC = cast<OMPReductionClause>(Cl);
5049       I = PC->privates().begin();
5050       It = PC->varlist_begin();
5051       Et = PC->varlist_end();
5052     } else if (Cl->getClauseKind() == OMPC_task_reduction) {
5053       auto *PC = cast<OMPTaskReductionClause>(Cl);
5054       I = PC->privates().begin();
5055       It = PC->varlist_begin();
5056       Et = PC->varlist_end();
5057     } else if (Cl->getClauseKind() == OMPC_in_reduction) {
5058       auto *PC = cast<OMPInReductionClause>(Cl);
5059       I = PC->privates().begin();
5060       It = PC->varlist_begin();
5061       Et = PC->varlist_end();
5062     } else {
5063       llvm_unreachable("Expected private clause.");
5064     }
5065     for (Expr *E : llvm::make_range(It, Et)) {
5066       if (!*I) {
5067         ++I;
5068         continue;
5069       }
5070       SourceLocation ELoc;
5071       SourceRange ERange;
5072       Expr *SimpleRefExpr = E;
5073       auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange,
5074                                 /*AllowArraySection=*/true);
5075       DeclToCopy.try_emplace(Res.first,
5076                              cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()));
5077       ++I;
5078     }
5079   }
5080   for (OMPClause *C : AllocateRange) {
5081     auto *AC = cast<OMPAllocateClause>(C);
5082     if (S.getLangOpts().OpenMP >= 50 &&
5083         !Stack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>() &&
5084         isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()) &&
5085         AC->getAllocator()) {
5086       Expr *Allocator = AC->getAllocator();
5087       // OpenMP, 2.12.5 target Construct
5088       // Memory allocators that do not appear in a uses_allocators clause cannot
5089       // appear as an allocator in an allocate clause or be used in the target
5090       // region unless a requires directive with the dynamic_allocators clause
5091       // is present in the same compilation unit.
5092       AllocatorChecker Checker(Stack);
5093       if (Checker.Visit(Allocator))
5094         S.Diag(Allocator->getExprLoc(),
5095                diag::err_omp_allocator_not_in_uses_allocators)
5096             << Allocator->getSourceRange();
5097     }
5098     OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind =
5099         getAllocatorKind(S, Stack, AC->getAllocator());
5100     // OpenMP, 2.11.4 allocate Clause, Restrictions.
5101     // For task, taskloop or target directives, allocation requests to memory
5102     // allocators with the trait access set to thread result in unspecified
5103     // behavior.
5104     if (AllocatorKind == OMPAllocateDeclAttr::OMPThreadMemAlloc &&
5105         (isOpenMPTaskingDirective(Stack->getCurrentDirective()) ||
5106          isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()))) {
5107       S.Diag(AC->getAllocator()->getExprLoc(),
5108              diag::warn_omp_allocate_thread_on_task_target_directive)
5109           << getOpenMPDirectiveName(Stack->getCurrentDirective());
5110     }
5111     for (Expr *E : AC->varlists()) {
5112       SourceLocation ELoc;
5113       SourceRange ERange;
5114       Expr *SimpleRefExpr = E;
5115       auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange);
5116       ValueDecl *VD = Res.first;
5117       DSAStackTy::DSAVarData Data = Stack->getTopDSA(VD, /*FromParent=*/false);
5118       if (!isOpenMPPrivate(Data.CKind)) {
5119         S.Diag(E->getExprLoc(),
5120                diag::err_omp_expected_private_copy_for_allocate);
5121         continue;
5122       }
5123       VarDecl *PrivateVD = DeclToCopy[VD];
5124       if (checkPreviousOMPAllocateAttribute(S, Stack, E, PrivateVD,
5125                                             AllocatorKind, AC->getAllocator()))
5126         continue;
5127       applyOMPAllocateAttribute(S, PrivateVD, AllocatorKind, AC->getAllocator(),
5128                                 E->getSourceRange());
5129     }
5130   }
5131 }
5132 
5133 StmtResult Sema::ActOnOpenMPExecutableDirective(
5134     OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
5135     OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
5136     Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
5137   StmtResult Res = StmtError();
5138   // First check CancelRegion which is then used in checkNestingOfRegions.
5139   if (checkCancelRegion(*this, Kind, CancelRegion, StartLoc) ||
5140       checkNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion,
5141                             StartLoc))
5142     return StmtError();
5143 
5144   llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit;
5145   VarsWithInheritedDSAType VarsWithInheritedDSA;
5146   bool ErrorFound = false;
5147   ClausesWithImplicit.append(Clauses.begin(), Clauses.end());
5148   if (AStmt && !CurContext->isDependentContext() && Kind != OMPD_atomic &&
5149       Kind != OMPD_critical && Kind != OMPD_section && Kind != OMPD_master) {
5150     assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5151 
5152     // Check default data sharing attributes for referenced variables.
5153     DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt));
5154     int ThisCaptureLevel = getOpenMPCaptureLevels(Kind);
5155     Stmt *S = AStmt;
5156     while (--ThisCaptureLevel >= 0)
5157       S = cast<CapturedStmt>(S)->getCapturedStmt();
5158     DSAChecker.Visit(S);
5159     if (!isOpenMPTargetDataManagementDirective(Kind) &&
5160         !isOpenMPTaskingDirective(Kind)) {
5161       // Visit subcaptures to generate implicit clauses for captured vars.
5162       auto *CS = cast<CapturedStmt>(AStmt);
5163       SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
5164       getOpenMPCaptureRegions(CaptureRegions, Kind);
5165       // Ignore outer tasking regions for target directives.
5166       if (CaptureRegions.size() > 1 && CaptureRegions.front() == OMPD_task)
5167         CS = cast<CapturedStmt>(CS->getCapturedStmt());
5168       DSAChecker.visitSubCaptures(CS);
5169     }
5170     if (DSAChecker.isErrorFound())
5171       return StmtError();
5172     // Generate list of implicitly defined firstprivate variables.
5173     VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA();
5174 
5175     SmallVector<Expr *, 4> ImplicitFirstprivates(
5176         DSAChecker.getImplicitFirstprivate().begin(),
5177         DSAChecker.getImplicitFirstprivate().end());
5178     const unsigned DefaultmapKindNum = OMPC_DEFAULTMAP_pointer + 1;
5179     SmallVector<Expr *, 4> ImplicitMaps[DefaultmapKindNum][OMPC_MAP_delete];
5180     SmallVector<OpenMPMapModifierKind, NumberOfOMPMapClauseModifiers>
5181         ImplicitMapModifiers[DefaultmapKindNum];
5182     SmallVector<SourceLocation, NumberOfOMPMapClauseModifiers>
5183         ImplicitMapModifiersLoc[DefaultmapKindNum];
5184     // Get the original location of present modifier from Defaultmap clause.
5185     SourceLocation PresentModifierLocs[DefaultmapKindNum];
5186     for (OMPClause *C : Clauses) {
5187       if (auto *DMC = dyn_cast<OMPDefaultmapClause>(C))
5188         if (DMC->getDefaultmapModifier() == OMPC_DEFAULTMAP_MODIFIER_present)
5189           PresentModifierLocs[DMC->getDefaultmapKind()] =
5190               DMC->getDefaultmapModifierLoc();
5191     }
5192     for (unsigned VC = 0; VC < DefaultmapKindNum; ++VC) {
5193       auto Kind = static_cast<OpenMPDefaultmapClauseKind>(VC);
5194       for (unsigned I = 0; I < OMPC_MAP_delete; ++I) {
5195         ArrayRef<Expr *> ImplicitMap = DSAChecker.getImplicitMap(
5196             Kind, static_cast<OpenMPMapClauseKind>(I));
5197         ImplicitMaps[VC][I].append(ImplicitMap.begin(), ImplicitMap.end());
5198       }
5199       ArrayRef<OpenMPMapModifierKind> ImplicitModifier =
5200           DSAChecker.getImplicitMapModifier(Kind);
5201       ImplicitMapModifiers[VC].append(ImplicitModifier.begin(),
5202                                       ImplicitModifier.end());
5203       std::fill_n(std::back_inserter(ImplicitMapModifiersLoc[VC]),
5204                   ImplicitModifier.size(), PresentModifierLocs[VC]);
5205     }
5206     // Mark taskgroup task_reduction descriptors as implicitly firstprivate.
5207     for (OMPClause *C : Clauses) {
5208       if (auto *IRC = dyn_cast<OMPInReductionClause>(C)) {
5209         for (Expr *E : IRC->taskgroup_descriptors())
5210           if (E)
5211             ImplicitFirstprivates.emplace_back(E);
5212       }
5213       // OpenMP 5.0, 2.10.1 task Construct
5214       // [detach clause]... The event-handle will be considered as if it was
5215       // specified on a firstprivate clause.
5216       if (auto *DC = dyn_cast<OMPDetachClause>(C))
5217         ImplicitFirstprivates.push_back(DC->getEventHandler());
5218     }
5219     if (!ImplicitFirstprivates.empty()) {
5220       if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause(
5221               ImplicitFirstprivates, SourceLocation(), SourceLocation(),
5222               SourceLocation())) {
5223         ClausesWithImplicit.push_back(Implicit);
5224         ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() !=
5225                      ImplicitFirstprivates.size();
5226       } else {
5227         ErrorFound = true;
5228       }
5229     }
5230     for (unsigned I = 0, E = DefaultmapKindNum; I < E; ++I) {
5231       int ClauseKindCnt = -1;
5232       for (ArrayRef<Expr *> ImplicitMap : ImplicitMaps[I]) {
5233         ++ClauseKindCnt;
5234         if (ImplicitMap.empty())
5235           continue;
5236         CXXScopeSpec MapperIdScopeSpec;
5237         DeclarationNameInfo MapperId;
5238         auto Kind = static_cast<OpenMPMapClauseKind>(ClauseKindCnt);
5239         if (OMPClause *Implicit = ActOnOpenMPMapClause(
5240                 ImplicitMapModifiers[I], ImplicitMapModifiersLoc[I],
5241                 MapperIdScopeSpec, MapperId, Kind, /*IsMapTypeImplicit=*/true,
5242                 SourceLocation(), SourceLocation(), ImplicitMap,
5243                 OMPVarListLocTy())) {
5244           ClausesWithImplicit.emplace_back(Implicit);
5245           ErrorFound |= cast<OMPMapClause>(Implicit)->varlist_size() !=
5246                         ImplicitMap.size();
5247         } else {
5248           ErrorFound = true;
5249         }
5250       }
5251     }
5252   }
5253 
5254   llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers;
5255   switch (Kind) {
5256   case OMPD_parallel:
5257     Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc,
5258                                        EndLoc);
5259     AllowedNameModifiers.push_back(OMPD_parallel);
5260     break;
5261   case OMPD_simd:
5262     Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
5263                                    VarsWithInheritedDSA);
5264     if (LangOpts.OpenMP >= 50)
5265       AllowedNameModifiers.push_back(OMPD_simd);
5266     break;
5267   case OMPD_for:
5268     Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
5269                                   VarsWithInheritedDSA);
5270     break;
5271   case OMPD_for_simd:
5272     Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
5273                                       EndLoc, VarsWithInheritedDSA);
5274     if (LangOpts.OpenMP >= 50)
5275       AllowedNameModifiers.push_back(OMPD_simd);
5276     break;
5277   case OMPD_sections:
5278     Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc,
5279                                        EndLoc);
5280     break;
5281   case OMPD_section:
5282     assert(ClausesWithImplicit.empty() &&
5283            "No clauses are allowed for 'omp section' directive");
5284     Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc);
5285     break;
5286   case OMPD_single:
5287     Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc,
5288                                      EndLoc);
5289     break;
5290   case OMPD_master:
5291     assert(ClausesWithImplicit.empty() &&
5292            "No clauses are allowed for 'omp master' directive");
5293     Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc);
5294     break;
5295   case OMPD_critical:
5296     Res = ActOnOpenMPCriticalDirective(DirName, ClausesWithImplicit, AStmt,
5297                                        StartLoc, EndLoc);
5298     break;
5299   case OMPD_parallel_for:
5300     Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc,
5301                                           EndLoc, VarsWithInheritedDSA);
5302     AllowedNameModifiers.push_back(OMPD_parallel);
5303     break;
5304   case OMPD_parallel_for_simd:
5305     Res = ActOnOpenMPParallelForSimdDirective(
5306         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
5307     AllowedNameModifiers.push_back(OMPD_parallel);
5308     if (LangOpts.OpenMP >= 50)
5309       AllowedNameModifiers.push_back(OMPD_simd);
5310     break;
5311   case OMPD_parallel_master:
5312     Res = ActOnOpenMPParallelMasterDirective(ClausesWithImplicit, AStmt,
5313                                                StartLoc, EndLoc);
5314     AllowedNameModifiers.push_back(OMPD_parallel);
5315     break;
5316   case OMPD_parallel_sections:
5317     Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt,
5318                                                StartLoc, EndLoc);
5319     AllowedNameModifiers.push_back(OMPD_parallel);
5320     break;
5321   case OMPD_task:
5322     Res =
5323         ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
5324     AllowedNameModifiers.push_back(OMPD_task);
5325     break;
5326   case OMPD_taskyield:
5327     assert(ClausesWithImplicit.empty() &&
5328            "No clauses are allowed for 'omp taskyield' directive");
5329     assert(AStmt == nullptr &&
5330            "No associated statement allowed for 'omp taskyield' directive");
5331     Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc);
5332     break;
5333   case OMPD_barrier:
5334     assert(ClausesWithImplicit.empty() &&
5335            "No clauses are allowed for 'omp barrier' directive");
5336     assert(AStmt == nullptr &&
5337            "No associated statement allowed for 'omp barrier' directive");
5338     Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc);
5339     break;
5340   case OMPD_taskwait:
5341     assert(ClausesWithImplicit.empty() &&
5342            "No clauses are allowed for 'omp taskwait' directive");
5343     assert(AStmt == nullptr &&
5344            "No associated statement allowed for 'omp taskwait' directive");
5345     Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc);
5346     break;
5347   case OMPD_taskgroup:
5348     Res = ActOnOpenMPTaskgroupDirective(ClausesWithImplicit, AStmt, StartLoc,
5349                                         EndLoc);
5350     break;
5351   case OMPD_flush:
5352     assert(AStmt == nullptr &&
5353            "No associated statement allowed for 'omp flush' directive");
5354     Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc);
5355     break;
5356   case OMPD_depobj:
5357     assert(AStmt == nullptr &&
5358            "No associated statement allowed for 'omp depobj' directive");
5359     Res = ActOnOpenMPDepobjDirective(ClausesWithImplicit, StartLoc, EndLoc);
5360     break;
5361   case OMPD_scan:
5362     assert(AStmt == nullptr &&
5363            "No associated statement allowed for 'omp scan' directive");
5364     Res = ActOnOpenMPScanDirective(ClausesWithImplicit, StartLoc, EndLoc);
5365     break;
5366   case OMPD_ordered:
5367     Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc,
5368                                       EndLoc);
5369     break;
5370   case OMPD_atomic:
5371     Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc,
5372                                      EndLoc);
5373     break;
5374   case OMPD_teams:
5375     Res =
5376         ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
5377     break;
5378   case OMPD_target:
5379     Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc,
5380                                      EndLoc);
5381     AllowedNameModifiers.push_back(OMPD_target);
5382     break;
5383   case OMPD_target_parallel:
5384     Res = ActOnOpenMPTargetParallelDirective(ClausesWithImplicit, AStmt,
5385                                              StartLoc, EndLoc);
5386     AllowedNameModifiers.push_back(OMPD_target);
5387     AllowedNameModifiers.push_back(OMPD_parallel);
5388     break;
5389   case OMPD_target_parallel_for:
5390     Res = ActOnOpenMPTargetParallelForDirective(
5391         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
5392     AllowedNameModifiers.push_back(OMPD_target);
5393     AllowedNameModifiers.push_back(OMPD_parallel);
5394     break;
5395   case OMPD_cancellation_point:
5396     assert(ClausesWithImplicit.empty() &&
5397            "No clauses are allowed for 'omp cancellation point' directive");
5398     assert(AStmt == nullptr && "No associated statement allowed for 'omp "
5399                                "cancellation point' directive");
5400     Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion);
5401     break;
5402   case OMPD_cancel:
5403     assert(AStmt == nullptr &&
5404            "No associated statement allowed for 'omp cancel' directive");
5405     Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc,
5406                                      CancelRegion);
5407     AllowedNameModifiers.push_back(OMPD_cancel);
5408     break;
5409   case OMPD_target_data:
5410     Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc,
5411                                          EndLoc);
5412     AllowedNameModifiers.push_back(OMPD_target_data);
5413     break;
5414   case OMPD_target_enter_data:
5415     Res = ActOnOpenMPTargetEnterDataDirective(ClausesWithImplicit, StartLoc,
5416                                               EndLoc, AStmt);
5417     AllowedNameModifiers.push_back(OMPD_target_enter_data);
5418     break;
5419   case OMPD_target_exit_data:
5420     Res = ActOnOpenMPTargetExitDataDirective(ClausesWithImplicit, StartLoc,
5421                                              EndLoc, AStmt);
5422     AllowedNameModifiers.push_back(OMPD_target_exit_data);
5423     break;
5424   case OMPD_taskloop:
5425     Res = ActOnOpenMPTaskLoopDirective(ClausesWithImplicit, AStmt, StartLoc,
5426                                        EndLoc, VarsWithInheritedDSA);
5427     AllowedNameModifiers.push_back(OMPD_taskloop);
5428     break;
5429   case OMPD_taskloop_simd:
5430     Res = ActOnOpenMPTaskLoopSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
5431                                            EndLoc, VarsWithInheritedDSA);
5432     AllowedNameModifiers.push_back(OMPD_taskloop);
5433     if (LangOpts.OpenMP >= 50)
5434       AllowedNameModifiers.push_back(OMPD_simd);
5435     break;
5436   case OMPD_master_taskloop:
5437     Res = ActOnOpenMPMasterTaskLoopDirective(
5438         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
5439     AllowedNameModifiers.push_back(OMPD_taskloop);
5440     break;
5441   case OMPD_master_taskloop_simd:
5442     Res = ActOnOpenMPMasterTaskLoopSimdDirective(
5443         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
5444     AllowedNameModifiers.push_back(OMPD_taskloop);
5445     if (LangOpts.OpenMP >= 50)
5446       AllowedNameModifiers.push_back(OMPD_simd);
5447     break;
5448   case OMPD_parallel_master_taskloop:
5449     Res = ActOnOpenMPParallelMasterTaskLoopDirective(
5450         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
5451     AllowedNameModifiers.push_back(OMPD_taskloop);
5452     AllowedNameModifiers.push_back(OMPD_parallel);
5453     break;
5454   case OMPD_parallel_master_taskloop_simd:
5455     Res = ActOnOpenMPParallelMasterTaskLoopSimdDirective(
5456         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
5457     AllowedNameModifiers.push_back(OMPD_taskloop);
5458     AllowedNameModifiers.push_back(OMPD_parallel);
5459     if (LangOpts.OpenMP >= 50)
5460       AllowedNameModifiers.push_back(OMPD_simd);
5461     break;
5462   case OMPD_distribute:
5463     Res = ActOnOpenMPDistributeDirective(ClausesWithImplicit, AStmt, StartLoc,
5464                                          EndLoc, VarsWithInheritedDSA);
5465     break;
5466   case OMPD_target_update:
5467     Res = ActOnOpenMPTargetUpdateDirective(ClausesWithImplicit, StartLoc,
5468                                            EndLoc, AStmt);
5469     AllowedNameModifiers.push_back(OMPD_target_update);
5470     break;
5471   case OMPD_distribute_parallel_for:
5472     Res = ActOnOpenMPDistributeParallelForDirective(
5473         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
5474     AllowedNameModifiers.push_back(OMPD_parallel);
5475     break;
5476   case OMPD_distribute_parallel_for_simd:
5477     Res = ActOnOpenMPDistributeParallelForSimdDirective(
5478         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
5479     AllowedNameModifiers.push_back(OMPD_parallel);
5480     if (LangOpts.OpenMP >= 50)
5481       AllowedNameModifiers.push_back(OMPD_simd);
5482     break;
5483   case OMPD_distribute_simd:
5484     Res = ActOnOpenMPDistributeSimdDirective(
5485         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
5486     if (LangOpts.OpenMP >= 50)
5487       AllowedNameModifiers.push_back(OMPD_simd);
5488     break;
5489   case OMPD_target_parallel_for_simd:
5490     Res = ActOnOpenMPTargetParallelForSimdDirective(
5491         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
5492     AllowedNameModifiers.push_back(OMPD_target);
5493     AllowedNameModifiers.push_back(OMPD_parallel);
5494     if (LangOpts.OpenMP >= 50)
5495       AllowedNameModifiers.push_back(OMPD_simd);
5496     break;
5497   case OMPD_target_simd:
5498     Res = ActOnOpenMPTargetSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
5499                                          EndLoc, VarsWithInheritedDSA);
5500     AllowedNameModifiers.push_back(OMPD_target);
5501     if (LangOpts.OpenMP >= 50)
5502       AllowedNameModifiers.push_back(OMPD_simd);
5503     break;
5504   case OMPD_teams_distribute:
5505     Res = ActOnOpenMPTeamsDistributeDirective(
5506         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
5507     break;
5508   case OMPD_teams_distribute_simd:
5509     Res = ActOnOpenMPTeamsDistributeSimdDirective(
5510         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
5511     if (LangOpts.OpenMP >= 50)
5512       AllowedNameModifiers.push_back(OMPD_simd);
5513     break;
5514   case OMPD_teams_distribute_parallel_for_simd:
5515     Res = ActOnOpenMPTeamsDistributeParallelForSimdDirective(
5516         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
5517     AllowedNameModifiers.push_back(OMPD_parallel);
5518     if (LangOpts.OpenMP >= 50)
5519       AllowedNameModifiers.push_back(OMPD_simd);
5520     break;
5521   case OMPD_teams_distribute_parallel_for:
5522     Res = ActOnOpenMPTeamsDistributeParallelForDirective(
5523         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
5524     AllowedNameModifiers.push_back(OMPD_parallel);
5525     break;
5526   case OMPD_target_teams:
5527     Res = ActOnOpenMPTargetTeamsDirective(ClausesWithImplicit, AStmt, StartLoc,
5528                                           EndLoc);
5529     AllowedNameModifiers.push_back(OMPD_target);
5530     break;
5531   case OMPD_target_teams_distribute:
5532     Res = ActOnOpenMPTargetTeamsDistributeDirective(
5533         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
5534     AllowedNameModifiers.push_back(OMPD_target);
5535     break;
5536   case OMPD_target_teams_distribute_parallel_for:
5537     Res = ActOnOpenMPTargetTeamsDistributeParallelForDirective(
5538         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
5539     AllowedNameModifiers.push_back(OMPD_target);
5540     AllowedNameModifiers.push_back(OMPD_parallel);
5541     break;
5542   case OMPD_target_teams_distribute_parallel_for_simd:
5543     Res = ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
5544         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
5545     AllowedNameModifiers.push_back(OMPD_target);
5546     AllowedNameModifiers.push_back(OMPD_parallel);
5547     if (LangOpts.OpenMP >= 50)
5548       AllowedNameModifiers.push_back(OMPD_simd);
5549     break;
5550   case OMPD_target_teams_distribute_simd:
5551     Res = ActOnOpenMPTargetTeamsDistributeSimdDirective(
5552         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
5553     AllowedNameModifiers.push_back(OMPD_target);
5554     if (LangOpts.OpenMP >= 50)
5555       AllowedNameModifiers.push_back(OMPD_simd);
5556     break;
5557   case OMPD_declare_target:
5558   case OMPD_end_declare_target:
5559   case OMPD_threadprivate:
5560   case OMPD_allocate:
5561   case OMPD_declare_reduction:
5562   case OMPD_declare_mapper:
5563   case OMPD_declare_simd:
5564   case OMPD_requires:
5565   case OMPD_declare_variant:
5566   case OMPD_begin_declare_variant:
5567   case OMPD_end_declare_variant:
5568     llvm_unreachable("OpenMP Directive is not allowed");
5569   case OMPD_unknown:
5570   default:
5571     llvm_unreachable("Unknown OpenMP directive");
5572   }
5573 
5574   ErrorFound = Res.isInvalid() || ErrorFound;
5575 
5576   // Check variables in the clauses if default(none) or
5577   // default(firstprivate) was specified.
5578   if (DSAStack->getDefaultDSA() == DSA_none ||
5579       DSAStack->getDefaultDSA() == DSA_firstprivate) {
5580     DSAAttrChecker DSAChecker(DSAStack, *this, nullptr);
5581     for (OMPClause *C : Clauses) {
5582       switch (C->getClauseKind()) {
5583       case OMPC_num_threads:
5584       case OMPC_dist_schedule:
5585         // Do not analyse if no parent teams directive.
5586         if (isOpenMPTeamsDirective(Kind))
5587           break;
5588         continue;
5589       case OMPC_if:
5590         if (isOpenMPTeamsDirective(Kind) &&
5591             cast<OMPIfClause>(C)->getNameModifier() != OMPD_target)
5592           break;
5593         if (isOpenMPParallelDirective(Kind) &&
5594             isOpenMPTaskLoopDirective(Kind) &&
5595             cast<OMPIfClause>(C)->getNameModifier() != OMPD_parallel)
5596           break;
5597         continue;
5598       case OMPC_schedule:
5599       case OMPC_detach:
5600         break;
5601       case OMPC_grainsize:
5602       case OMPC_num_tasks:
5603       case OMPC_final:
5604       case OMPC_priority:
5605         // Do not analyze if no parent parallel directive.
5606         if (isOpenMPParallelDirective(Kind))
5607           break;
5608         continue;
5609       case OMPC_ordered:
5610       case OMPC_device:
5611       case OMPC_num_teams:
5612       case OMPC_thread_limit:
5613       case OMPC_hint:
5614       case OMPC_collapse:
5615       case OMPC_safelen:
5616       case OMPC_simdlen:
5617       case OMPC_default:
5618       case OMPC_proc_bind:
5619       case OMPC_private:
5620       case OMPC_firstprivate:
5621       case OMPC_lastprivate:
5622       case OMPC_shared:
5623       case OMPC_reduction:
5624       case OMPC_task_reduction:
5625       case OMPC_in_reduction:
5626       case OMPC_linear:
5627       case OMPC_aligned:
5628       case OMPC_copyin:
5629       case OMPC_copyprivate:
5630       case OMPC_nowait:
5631       case OMPC_untied:
5632       case OMPC_mergeable:
5633       case OMPC_allocate:
5634       case OMPC_read:
5635       case OMPC_write:
5636       case OMPC_update:
5637       case OMPC_capture:
5638       case OMPC_seq_cst:
5639       case OMPC_acq_rel:
5640       case OMPC_acquire:
5641       case OMPC_release:
5642       case OMPC_relaxed:
5643       case OMPC_depend:
5644       case OMPC_threads:
5645       case OMPC_simd:
5646       case OMPC_map:
5647       case OMPC_nogroup:
5648       case OMPC_defaultmap:
5649       case OMPC_to:
5650       case OMPC_from:
5651       case OMPC_use_device_ptr:
5652       case OMPC_use_device_addr:
5653       case OMPC_is_device_ptr:
5654       case OMPC_nontemporal:
5655       case OMPC_order:
5656       case OMPC_destroy:
5657       case OMPC_inclusive:
5658       case OMPC_exclusive:
5659       case OMPC_uses_allocators:
5660       case OMPC_affinity:
5661         continue;
5662       case OMPC_allocator:
5663       case OMPC_flush:
5664       case OMPC_depobj:
5665       case OMPC_threadprivate:
5666       case OMPC_uniform:
5667       case OMPC_unknown:
5668       case OMPC_unified_address:
5669       case OMPC_unified_shared_memory:
5670       case OMPC_reverse_offload:
5671       case OMPC_dynamic_allocators:
5672       case OMPC_atomic_default_mem_order:
5673       case OMPC_device_type:
5674       case OMPC_match:
5675       default:
5676         llvm_unreachable("Unexpected clause");
5677       }
5678       for (Stmt *CC : C->children()) {
5679         if (CC)
5680           DSAChecker.Visit(CC);
5681       }
5682     }
5683     for (const auto &P : DSAChecker.getVarsWithInheritedDSA())
5684       VarsWithInheritedDSA[P.getFirst()] = P.getSecond();
5685   }
5686   for (const auto &P : VarsWithInheritedDSA) {
5687     if (P.getFirst()->isImplicit() || isa<OMPCapturedExprDecl>(P.getFirst()))
5688       continue;
5689     ErrorFound = true;
5690     if (DSAStack->getDefaultDSA() == DSA_none ||
5691         DSAStack->getDefaultDSA() == DSA_firstprivate) {
5692       Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable)
5693           << P.first << P.second->getSourceRange();
5694       Diag(DSAStack->getDefaultDSALocation(), diag::note_omp_default_dsa_none);
5695     } else if (getLangOpts().OpenMP >= 50) {
5696       Diag(P.second->getExprLoc(),
5697            diag::err_omp_defaultmap_no_attr_for_variable)
5698           << P.first << P.second->getSourceRange();
5699       Diag(DSAStack->getDefaultDSALocation(),
5700            diag::note_omp_defaultmap_attr_none);
5701     }
5702   }
5703 
5704   if (!AllowedNameModifiers.empty())
5705     ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) ||
5706                  ErrorFound;
5707 
5708   if (ErrorFound)
5709     return StmtError();
5710 
5711   if (!CurContext->isDependentContext() &&
5712       isOpenMPTargetExecutionDirective(Kind) &&
5713       !(DSAStack->hasRequiresDeclWithClause<OMPUnifiedSharedMemoryClause>() ||
5714         DSAStack->hasRequiresDeclWithClause<OMPUnifiedAddressClause>() ||
5715         DSAStack->hasRequiresDeclWithClause<OMPReverseOffloadClause>() ||
5716         DSAStack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>())) {
5717     // Register target to DSA Stack.
5718     DSAStack->addTargetDirLocation(StartLoc);
5719   }
5720 
5721   return Res;
5722 }
5723 
5724 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareSimdDirective(
5725     DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen,
5726     ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
5727     ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
5728     ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR) {
5729   assert(Aligneds.size() == Alignments.size());
5730   assert(Linears.size() == LinModifiers.size());
5731   assert(Linears.size() == Steps.size());
5732   if (!DG || DG.get().isNull())
5733     return DeclGroupPtrTy();
5734 
5735   const int SimdId = 0;
5736   if (!DG.get().isSingleDecl()) {
5737     Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd_variant)
5738         << SimdId;
5739     return DG;
5740   }
5741   Decl *ADecl = DG.get().getSingleDecl();
5742   if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
5743     ADecl = FTD->getTemplatedDecl();
5744 
5745   auto *FD = dyn_cast<FunctionDecl>(ADecl);
5746   if (!FD) {
5747     Diag(ADecl->getLocation(), diag::err_omp_function_expected) << SimdId;
5748     return DeclGroupPtrTy();
5749   }
5750 
5751   // OpenMP [2.8.2, declare simd construct, Description]
5752   // The parameter of the simdlen clause must be a constant positive integer
5753   // expression.
5754   ExprResult SL;
5755   if (Simdlen)
5756     SL = VerifyPositiveIntegerConstantInClause(Simdlen, OMPC_simdlen);
5757   // OpenMP [2.8.2, declare simd construct, Description]
5758   // The special this pointer can be used as if was one of the arguments to the
5759   // function in any of the linear, aligned, or uniform clauses.
5760   // The uniform clause declares one or more arguments to have an invariant
5761   // value for all concurrent invocations of the function in the execution of a
5762   // single SIMD loop.
5763   llvm::DenseMap<const Decl *, const Expr *> UniformedArgs;
5764   const Expr *UniformedLinearThis = nullptr;
5765   for (const Expr *E : Uniforms) {
5766     E = E->IgnoreParenImpCasts();
5767     if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
5768       if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
5769         if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
5770             FD->getParamDecl(PVD->getFunctionScopeIndex())
5771                     ->getCanonicalDecl() == PVD->getCanonicalDecl()) {
5772           UniformedArgs.try_emplace(PVD->getCanonicalDecl(), E);
5773           continue;
5774         }
5775     if (isa<CXXThisExpr>(E)) {
5776       UniformedLinearThis = E;
5777       continue;
5778     }
5779     Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
5780         << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
5781   }
5782   // OpenMP [2.8.2, declare simd construct, Description]
5783   // The aligned clause declares that the object to which each list item points
5784   // is aligned to the number of bytes expressed in the optional parameter of
5785   // the aligned clause.
5786   // The special this pointer can be used as if was one of the arguments to the
5787   // function in any of the linear, aligned, or uniform clauses.
5788   // The type of list items appearing in the aligned clause must be array,
5789   // pointer, reference to array, or reference to pointer.
5790   llvm::DenseMap<const Decl *, const Expr *> AlignedArgs;
5791   const Expr *AlignedThis = nullptr;
5792   for (const Expr *E : Aligneds) {
5793     E = E->IgnoreParenImpCasts();
5794     if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
5795       if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
5796         const VarDecl *CanonPVD = PVD->getCanonicalDecl();
5797         if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
5798             FD->getParamDecl(PVD->getFunctionScopeIndex())
5799                     ->getCanonicalDecl() == CanonPVD) {
5800           // OpenMP  [2.8.1, simd construct, Restrictions]
5801           // A list-item cannot appear in more than one aligned clause.
5802           if (AlignedArgs.count(CanonPVD) > 0) {
5803             Diag(E->getExprLoc(), diag::err_omp_used_in_clause_twice)
5804                 << 1 << getOpenMPClauseName(OMPC_aligned)
5805                 << E->getSourceRange();
5806             Diag(AlignedArgs[CanonPVD]->getExprLoc(),
5807                  diag::note_omp_explicit_dsa)
5808                 << getOpenMPClauseName(OMPC_aligned);
5809             continue;
5810           }
5811           AlignedArgs[CanonPVD] = E;
5812           QualType QTy = PVD->getType()
5813                              .getNonReferenceType()
5814                              .getUnqualifiedType()
5815                              .getCanonicalType();
5816           const Type *Ty = QTy.getTypePtrOrNull();
5817           if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
5818             Diag(E->getExprLoc(), diag::err_omp_aligned_expected_array_or_ptr)
5819                 << QTy << getLangOpts().CPlusPlus << E->getSourceRange();
5820             Diag(PVD->getLocation(), diag::note_previous_decl) << PVD;
5821           }
5822           continue;
5823         }
5824       }
5825     if (isa<CXXThisExpr>(E)) {
5826       if (AlignedThis) {
5827         Diag(E->getExprLoc(), diag::err_omp_used_in_clause_twice)
5828             << 2 << getOpenMPClauseName(OMPC_aligned) << E->getSourceRange();
5829         Diag(AlignedThis->getExprLoc(), diag::note_omp_explicit_dsa)
5830             << getOpenMPClauseName(OMPC_aligned);
5831       }
5832       AlignedThis = E;
5833       continue;
5834     }
5835     Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
5836         << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
5837   }
5838   // The optional parameter of the aligned clause, alignment, must be a constant
5839   // positive integer expression. If no optional parameter is specified,
5840   // implementation-defined default alignments for SIMD instructions on the
5841   // target platforms are assumed.
5842   SmallVector<const Expr *, 4> NewAligns;
5843   for (Expr *E : Alignments) {
5844     ExprResult Align;
5845     if (E)
5846       Align = VerifyPositiveIntegerConstantInClause(E, OMPC_aligned);
5847     NewAligns.push_back(Align.get());
5848   }
5849   // OpenMP [2.8.2, declare simd construct, Description]
5850   // The linear clause declares one or more list items to be private to a SIMD
5851   // lane and to have a linear relationship with respect to the iteration space
5852   // of a loop.
5853   // The special this pointer can be used as if was one of the arguments to the
5854   // function in any of the linear, aligned, or uniform clauses.
5855   // When a linear-step expression is specified in a linear clause it must be
5856   // either a constant integer expression or an integer-typed parameter that is
5857   // specified in a uniform clause on the directive.
5858   llvm::DenseMap<const Decl *, const Expr *> LinearArgs;
5859   const bool IsUniformedThis = UniformedLinearThis != nullptr;
5860   auto MI = LinModifiers.begin();
5861   for (const Expr *E : Linears) {
5862     auto LinKind = static_cast<OpenMPLinearClauseKind>(*MI);
5863     ++MI;
5864     E = E->IgnoreParenImpCasts();
5865     if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
5866       if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
5867         const VarDecl *CanonPVD = PVD->getCanonicalDecl();
5868         if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
5869             FD->getParamDecl(PVD->getFunctionScopeIndex())
5870                     ->getCanonicalDecl() == CanonPVD) {
5871           // OpenMP  [2.15.3.7, linear Clause, Restrictions]
5872           // A list-item cannot appear in more than one linear clause.
5873           if (LinearArgs.count(CanonPVD) > 0) {
5874             Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
5875                 << getOpenMPClauseName(OMPC_linear)
5876                 << getOpenMPClauseName(OMPC_linear) << E->getSourceRange();
5877             Diag(LinearArgs[CanonPVD]->getExprLoc(),
5878                  diag::note_omp_explicit_dsa)
5879                 << getOpenMPClauseName(OMPC_linear);
5880             continue;
5881           }
5882           // Each argument can appear in at most one uniform or linear clause.
5883           if (UniformedArgs.count(CanonPVD) > 0) {
5884             Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
5885                 << getOpenMPClauseName(OMPC_linear)
5886                 << getOpenMPClauseName(OMPC_uniform) << E->getSourceRange();
5887             Diag(UniformedArgs[CanonPVD]->getExprLoc(),
5888                  diag::note_omp_explicit_dsa)
5889                 << getOpenMPClauseName(OMPC_uniform);
5890             continue;
5891           }
5892           LinearArgs[CanonPVD] = E;
5893           if (E->isValueDependent() || E->isTypeDependent() ||
5894               E->isInstantiationDependent() ||
5895               E->containsUnexpandedParameterPack())
5896             continue;
5897           (void)CheckOpenMPLinearDecl(CanonPVD, E->getExprLoc(), LinKind,
5898                                       PVD->getOriginalType(),
5899                                       /*IsDeclareSimd=*/true);
5900           continue;
5901         }
5902       }
5903     if (isa<CXXThisExpr>(E)) {
5904       if (UniformedLinearThis) {
5905         Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
5906             << getOpenMPClauseName(OMPC_linear)
5907             << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform : OMPC_linear)
5908             << E->getSourceRange();
5909         Diag(UniformedLinearThis->getExprLoc(), diag::note_omp_explicit_dsa)
5910             << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform
5911                                                    : OMPC_linear);
5912         continue;
5913       }
5914       UniformedLinearThis = E;
5915       if (E->isValueDependent() || E->isTypeDependent() ||
5916           E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
5917         continue;
5918       (void)CheckOpenMPLinearDecl(/*D=*/nullptr, E->getExprLoc(), LinKind,
5919                                   E->getType(), /*IsDeclareSimd=*/true);
5920       continue;
5921     }
5922     Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
5923         << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
5924   }
5925   Expr *Step = nullptr;
5926   Expr *NewStep = nullptr;
5927   SmallVector<Expr *, 4> NewSteps;
5928   for (Expr *E : Steps) {
5929     // Skip the same step expression, it was checked already.
5930     if (Step == E || !E) {
5931       NewSteps.push_back(E ? NewStep : nullptr);
5932       continue;
5933     }
5934     Step = E;
5935     if (const auto *DRE = dyn_cast<DeclRefExpr>(Step))
5936       if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
5937         const VarDecl *CanonPVD = PVD->getCanonicalDecl();
5938         if (UniformedArgs.count(CanonPVD) == 0) {
5939           Diag(Step->getExprLoc(), diag::err_omp_expected_uniform_param)
5940               << Step->getSourceRange();
5941         } else if (E->isValueDependent() || E->isTypeDependent() ||
5942                    E->isInstantiationDependent() ||
5943                    E->containsUnexpandedParameterPack() ||
5944                    CanonPVD->getType()->hasIntegerRepresentation()) {
5945           NewSteps.push_back(Step);
5946         } else {
5947           Diag(Step->getExprLoc(), diag::err_omp_expected_int_param)
5948               << Step->getSourceRange();
5949         }
5950         continue;
5951       }
5952     NewStep = Step;
5953     if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
5954         !Step->isInstantiationDependent() &&
5955         !Step->containsUnexpandedParameterPack()) {
5956       NewStep = PerformOpenMPImplicitIntegerConversion(Step->getExprLoc(), Step)
5957                     .get();
5958       if (NewStep)
5959         NewStep =
5960             VerifyIntegerConstantExpression(NewStep, /*FIXME*/ AllowFold).get();
5961     }
5962     NewSteps.push_back(NewStep);
5963   }
5964   auto *NewAttr = OMPDeclareSimdDeclAttr::CreateImplicit(
5965       Context, BS, SL.get(), const_cast<Expr **>(Uniforms.data()),
5966       Uniforms.size(), const_cast<Expr **>(Aligneds.data()), Aligneds.size(),
5967       const_cast<Expr **>(NewAligns.data()), NewAligns.size(),
5968       const_cast<Expr **>(Linears.data()), Linears.size(),
5969       const_cast<unsigned *>(LinModifiers.data()), LinModifiers.size(),
5970       NewSteps.data(), NewSteps.size(), SR);
5971   ADecl->addAttr(NewAttr);
5972   return DG;
5973 }
5974 
5975 static void setPrototype(Sema &S, FunctionDecl *FD, FunctionDecl *FDWithProto,
5976                          QualType NewType) {
5977   assert(NewType->isFunctionProtoType() &&
5978          "Expected function type with prototype.");
5979   assert(FD->getType()->isFunctionNoProtoType() &&
5980          "Expected function with type with no prototype.");
5981   assert(FDWithProto->getType()->isFunctionProtoType() &&
5982          "Expected function with prototype.");
5983   // Synthesize parameters with the same types.
5984   FD->setType(NewType);
5985   SmallVector<ParmVarDecl *, 16> Params;
5986   for (const ParmVarDecl *P : FDWithProto->parameters()) {
5987     auto *Param = ParmVarDecl::Create(S.getASTContext(), FD, SourceLocation(),
5988                                       SourceLocation(), nullptr, P->getType(),
5989                                       /*TInfo=*/nullptr, SC_None, nullptr);
5990     Param->setScopeInfo(0, Params.size());
5991     Param->setImplicit();
5992     Params.push_back(Param);
5993   }
5994 
5995   FD->setParams(Params);
5996 }
5997 
5998 void Sema::ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(Decl *D) {
5999   if (D->isInvalidDecl())
6000     return;
6001   FunctionDecl *FD = nullptr;
6002   if (auto *UTemplDecl = dyn_cast<FunctionTemplateDecl>(D))
6003     FD = UTemplDecl->getTemplatedDecl();
6004   else
6005     FD = cast<FunctionDecl>(D);
6006   assert(FD && "Expected a function declaration!");
6007 
6008   // If we are intantiating templates we do *not* apply scoped assumptions but
6009   // only global ones. We apply scoped assumption to the template definition
6010   // though.
6011   if (!inTemplateInstantiation()) {
6012     for (AssumptionAttr *AA : OMPAssumeScoped)
6013       FD->addAttr(AA);
6014   }
6015   for (AssumptionAttr *AA : OMPAssumeGlobal)
6016     FD->addAttr(AA);
6017 }
6018 
6019 Sema::OMPDeclareVariantScope::OMPDeclareVariantScope(OMPTraitInfo &TI)
6020     : TI(&TI), NameSuffix(TI.getMangledName()) {}
6021 
6022 void Sema::ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(
6023     Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParamLists,
6024     SmallVectorImpl<FunctionDecl *> &Bases) {
6025   if (!D.getIdentifier())
6026     return;
6027 
6028   OMPDeclareVariantScope &DVScope = OMPDeclareVariantScopes.back();
6029 
6030   // Template specialization is an extension, check if we do it.
6031   bool IsTemplated = !TemplateParamLists.empty();
6032   if (IsTemplated &
6033       !DVScope.TI->isExtensionActive(
6034           llvm::omp::TraitProperty::implementation_extension_allow_templates))
6035     return;
6036 
6037   IdentifierInfo *BaseII = D.getIdentifier();
6038   LookupResult Lookup(*this, DeclarationName(BaseII), D.getIdentifierLoc(),
6039                       LookupOrdinaryName);
6040   LookupParsedName(Lookup, S, &D.getCXXScopeSpec());
6041 
6042   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
6043   QualType FType = TInfo->getType();
6044 
6045   bool IsConstexpr =
6046       D.getDeclSpec().getConstexprSpecifier() == ConstexprSpecKind::Constexpr;
6047   bool IsConsteval =
6048       D.getDeclSpec().getConstexprSpecifier() == ConstexprSpecKind::Consteval;
6049 
6050   for (auto *Candidate : Lookup) {
6051     auto *CandidateDecl = Candidate->getUnderlyingDecl();
6052     FunctionDecl *UDecl = nullptr;
6053     if (IsTemplated && isa<FunctionTemplateDecl>(CandidateDecl))
6054       UDecl = cast<FunctionTemplateDecl>(CandidateDecl)->getTemplatedDecl();
6055     else if (!IsTemplated)
6056       UDecl = dyn_cast<FunctionDecl>(CandidateDecl);
6057     if (!UDecl)
6058       continue;
6059 
6060     // Don't specialize constexpr/consteval functions with
6061     // non-constexpr/consteval functions.
6062     if (UDecl->isConstexpr() && !IsConstexpr)
6063       continue;
6064     if (UDecl->isConsteval() && !IsConsteval)
6065       continue;
6066 
6067     QualType UDeclTy = UDecl->getType();
6068     if (!UDeclTy->isDependentType()) {
6069       QualType NewType = Context.mergeFunctionTypes(
6070           FType, UDeclTy, /* OfBlockPointer */ false,
6071           /* Unqualified */ false, /* AllowCXX */ true);
6072       if (NewType.isNull())
6073         continue;
6074     }
6075 
6076     // Found a base!
6077     Bases.push_back(UDecl);
6078   }
6079 
6080   bool UseImplicitBase = !DVScope.TI->isExtensionActive(
6081       llvm::omp::TraitProperty::implementation_extension_disable_implicit_base);
6082   // If no base was found we create a declaration that we use as base.
6083   if (Bases.empty() && UseImplicitBase) {
6084     D.setFunctionDefinitionKind(FunctionDefinitionKind::Declaration);
6085     Decl *BaseD = HandleDeclarator(S, D, TemplateParamLists);
6086     BaseD->setImplicit(true);
6087     if (auto *BaseTemplD = dyn_cast<FunctionTemplateDecl>(BaseD))
6088       Bases.push_back(BaseTemplD->getTemplatedDecl());
6089     else
6090       Bases.push_back(cast<FunctionDecl>(BaseD));
6091   }
6092 
6093   std::string MangledName;
6094   MangledName += D.getIdentifier()->getName();
6095   MangledName += getOpenMPVariantManglingSeparatorStr();
6096   MangledName += DVScope.NameSuffix;
6097   IdentifierInfo &VariantII = Context.Idents.get(MangledName);
6098 
6099   VariantII.setMangledOpenMPVariantName(true);
6100   D.SetIdentifier(&VariantII, D.getBeginLoc());
6101 }
6102 
6103 void Sema::ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(
6104     Decl *D, SmallVectorImpl<FunctionDecl *> &Bases) {
6105   // Do not mark function as is used to prevent its emission if this is the
6106   // only place where it is used.
6107   EnterExpressionEvaluationContext Unevaluated(
6108       *this, Sema::ExpressionEvaluationContext::Unevaluated);
6109 
6110   FunctionDecl *FD = nullptr;
6111   if (auto *UTemplDecl = dyn_cast<FunctionTemplateDecl>(D))
6112     FD = UTemplDecl->getTemplatedDecl();
6113   else
6114     FD = cast<FunctionDecl>(D);
6115   auto *VariantFuncRef = DeclRefExpr::Create(
6116       Context, NestedNameSpecifierLoc(), SourceLocation(), FD,
6117       /* RefersToEnclosingVariableOrCapture */ false,
6118       /* NameLoc */ FD->getLocation(), FD->getType(), ExprValueKind::VK_RValue);
6119 
6120   OMPDeclareVariantScope &DVScope = OMPDeclareVariantScopes.back();
6121   auto *OMPDeclareVariantA = OMPDeclareVariantAttr::CreateImplicit(
6122       Context, VariantFuncRef, DVScope.TI);
6123   for (FunctionDecl *BaseFD : Bases)
6124     BaseFD->addAttr(OMPDeclareVariantA);
6125 }
6126 
6127 ExprResult Sema::ActOnOpenMPCall(ExprResult Call, Scope *Scope,
6128                                  SourceLocation LParenLoc,
6129                                  MultiExprArg ArgExprs,
6130                                  SourceLocation RParenLoc, Expr *ExecConfig) {
6131   // The common case is a regular call we do not want to specialize at all. Try
6132   // to make that case fast by bailing early.
6133   CallExpr *CE = dyn_cast<CallExpr>(Call.get());
6134   if (!CE)
6135     return Call;
6136 
6137   FunctionDecl *CalleeFnDecl = CE->getDirectCallee();
6138   if (!CalleeFnDecl)
6139     return Call;
6140 
6141   if (!CalleeFnDecl->hasAttr<OMPDeclareVariantAttr>())
6142     return Call;
6143 
6144   ASTContext &Context = getASTContext();
6145   std::function<void(StringRef)> DiagUnknownTrait = [this,
6146                                                      CE](StringRef ISATrait) {
6147     // TODO Track the selector locations in a way that is accessible here to
6148     // improve the diagnostic location.
6149     Diag(CE->getBeginLoc(), diag::warn_unknown_declare_variant_isa_trait)
6150         << ISATrait;
6151   };
6152   TargetOMPContext OMPCtx(Context, std::move(DiagUnknownTrait),
6153                           getCurFunctionDecl());
6154 
6155   QualType CalleeFnType = CalleeFnDecl->getType();
6156 
6157   SmallVector<Expr *, 4> Exprs;
6158   SmallVector<VariantMatchInfo, 4> VMIs;
6159   while (CalleeFnDecl) {
6160     for (OMPDeclareVariantAttr *A :
6161          CalleeFnDecl->specific_attrs<OMPDeclareVariantAttr>()) {
6162       Expr *VariantRef = A->getVariantFuncRef();
6163 
6164       VariantMatchInfo VMI;
6165       OMPTraitInfo &TI = A->getTraitInfo();
6166       TI.getAsVariantMatchInfo(Context, VMI);
6167       if (!isVariantApplicableInContext(VMI, OMPCtx,
6168                                         /* DeviceSetOnly */ false))
6169         continue;
6170 
6171       VMIs.push_back(VMI);
6172       Exprs.push_back(VariantRef);
6173     }
6174 
6175     CalleeFnDecl = CalleeFnDecl->getPreviousDecl();
6176   }
6177 
6178   ExprResult NewCall;
6179   do {
6180     int BestIdx = getBestVariantMatchForContext(VMIs, OMPCtx);
6181     if (BestIdx < 0)
6182       return Call;
6183     Expr *BestExpr = cast<DeclRefExpr>(Exprs[BestIdx]);
6184     Decl *BestDecl = cast<DeclRefExpr>(BestExpr)->getDecl();
6185 
6186     {
6187       // Try to build a (member) call expression for the current best applicable
6188       // variant expression. We allow this to fail in which case we continue
6189       // with the next best variant expression. The fail case is part of the
6190       // implementation defined behavior in the OpenMP standard when it talks
6191       // about what differences in the function prototypes: "Any differences
6192       // that the specific OpenMP context requires in the prototype of the
6193       // variant from the base function prototype are implementation defined."
6194       // This wording is there to allow the specialized variant to have a
6195       // different type than the base function. This is intended and OK but if
6196       // we cannot create a call the difference is not in the "implementation
6197       // defined range" we allow.
6198       Sema::TentativeAnalysisScope Trap(*this);
6199 
6200       if (auto *SpecializedMethod = dyn_cast<CXXMethodDecl>(BestDecl)) {
6201         auto *MemberCall = dyn_cast<CXXMemberCallExpr>(CE);
6202         BestExpr = MemberExpr::CreateImplicit(
6203             Context, MemberCall->getImplicitObjectArgument(),
6204             /* IsArrow */ false, SpecializedMethod, Context.BoundMemberTy,
6205             MemberCall->getValueKind(), MemberCall->getObjectKind());
6206       }
6207       NewCall = BuildCallExpr(Scope, BestExpr, LParenLoc, ArgExprs, RParenLoc,
6208                               ExecConfig);
6209       if (NewCall.isUsable()) {
6210         if (CallExpr *NCE = dyn_cast<CallExpr>(NewCall.get())) {
6211           FunctionDecl *NewCalleeFnDecl = NCE->getDirectCallee();
6212           QualType NewType = Context.mergeFunctionTypes(
6213               CalleeFnType, NewCalleeFnDecl->getType(),
6214               /* OfBlockPointer */ false,
6215               /* Unqualified */ false, /* AllowCXX */ true);
6216           if (!NewType.isNull())
6217             break;
6218           // Don't use the call if the function type was not compatible.
6219           NewCall = nullptr;
6220         }
6221       }
6222     }
6223 
6224     VMIs.erase(VMIs.begin() + BestIdx);
6225     Exprs.erase(Exprs.begin() + BestIdx);
6226   } while (!VMIs.empty());
6227 
6228   if (!NewCall.isUsable())
6229     return Call;
6230   return PseudoObjectExpr::Create(Context, CE, {NewCall.get()}, 0);
6231 }
6232 
6233 Optional<std::pair<FunctionDecl *, Expr *>>
6234 Sema::checkOpenMPDeclareVariantFunction(Sema::DeclGroupPtrTy DG,
6235                                         Expr *VariantRef, OMPTraitInfo &TI,
6236                                         SourceRange SR) {
6237   if (!DG || DG.get().isNull())
6238     return None;
6239 
6240   const int VariantId = 1;
6241   // Must be applied only to single decl.
6242   if (!DG.get().isSingleDecl()) {
6243     Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd_variant)
6244         << VariantId << SR;
6245     return None;
6246   }
6247   Decl *ADecl = DG.get().getSingleDecl();
6248   if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
6249     ADecl = FTD->getTemplatedDecl();
6250 
6251   // Decl must be a function.
6252   auto *FD = dyn_cast<FunctionDecl>(ADecl);
6253   if (!FD) {
6254     Diag(ADecl->getLocation(), diag::err_omp_function_expected)
6255         << VariantId << SR;
6256     return None;
6257   }
6258 
6259   auto &&HasMultiVersionAttributes = [](const FunctionDecl *FD) {
6260     return FD->hasAttrs() &&
6261            (FD->hasAttr<CPUDispatchAttr>() || FD->hasAttr<CPUSpecificAttr>() ||
6262             FD->hasAttr<TargetAttr>());
6263   };
6264   // OpenMP is not compatible with CPU-specific attributes.
6265   if (HasMultiVersionAttributes(FD)) {
6266     Diag(FD->getLocation(), diag::err_omp_declare_variant_incompat_attributes)
6267         << SR;
6268     return None;
6269   }
6270 
6271   // Allow #pragma omp declare variant only if the function is not used.
6272   if (FD->isUsed(false))
6273     Diag(SR.getBegin(), diag::warn_omp_declare_variant_after_used)
6274         << FD->getLocation();
6275 
6276   // Check if the function was emitted already.
6277   const FunctionDecl *Definition;
6278   if (!FD->isThisDeclarationADefinition() && FD->isDefined(Definition) &&
6279       (LangOpts.EmitAllDecls || Context.DeclMustBeEmitted(Definition)))
6280     Diag(SR.getBegin(), diag::warn_omp_declare_variant_after_emitted)
6281         << FD->getLocation();
6282 
6283   // The VariantRef must point to function.
6284   if (!VariantRef) {
6285     Diag(SR.getBegin(), diag::err_omp_function_expected) << VariantId;
6286     return None;
6287   }
6288 
6289   auto ShouldDelayChecks = [](Expr *&E, bool) {
6290     return E && (E->isTypeDependent() || E->isValueDependent() ||
6291                  E->containsUnexpandedParameterPack() ||
6292                  E->isInstantiationDependent());
6293   };
6294   // Do not check templates, wait until instantiation.
6295   if (FD->isDependentContext() || ShouldDelayChecks(VariantRef, false) ||
6296       TI.anyScoreOrCondition(ShouldDelayChecks))
6297     return std::make_pair(FD, VariantRef);
6298 
6299   // Deal with non-constant score and user condition expressions.
6300   auto HandleNonConstantScoresAndConditions = [this](Expr *&E,
6301                                                      bool IsScore) -> bool {
6302     if (!E || E->isIntegerConstantExpr(Context))
6303       return false;
6304 
6305     if (IsScore) {
6306       // We warn on non-constant scores and pretend they were not present.
6307       Diag(E->getExprLoc(), diag::warn_omp_declare_variant_score_not_constant)
6308           << E;
6309       E = nullptr;
6310     } else {
6311       // We could replace a non-constant user condition with "false" but we
6312       // will soon need to handle these anyway for the dynamic version of
6313       // OpenMP context selectors.
6314       Diag(E->getExprLoc(),
6315            diag::err_omp_declare_variant_user_condition_not_constant)
6316           << E;
6317     }
6318     return true;
6319   };
6320   if (TI.anyScoreOrCondition(HandleNonConstantScoresAndConditions))
6321     return None;
6322 
6323   // Convert VariantRef expression to the type of the original function to
6324   // resolve possible conflicts.
6325   ExprResult VariantRefCast = VariantRef;
6326   if (LangOpts.CPlusPlus) {
6327     QualType FnPtrType;
6328     auto *Method = dyn_cast<CXXMethodDecl>(FD);
6329     if (Method && !Method->isStatic()) {
6330       const Type *ClassType =
6331           Context.getTypeDeclType(Method->getParent()).getTypePtr();
6332       FnPtrType = Context.getMemberPointerType(FD->getType(), ClassType);
6333       ExprResult ER;
6334       {
6335         // Build adrr_of unary op to correctly handle type checks for member
6336         // functions.
6337         Sema::TentativeAnalysisScope Trap(*this);
6338         ER = CreateBuiltinUnaryOp(VariantRef->getBeginLoc(), UO_AddrOf,
6339                                   VariantRef);
6340       }
6341       if (!ER.isUsable()) {
6342         Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected)
6343             << VariantId << VariantRef->getSourceRange();
6344         return None;
6345       }
6346       VariantRef = ER.get();
6347     } else {
6348       FnPtrType = Context.getPointerType(FD->getType());
6349     }
6350     QualType VarianPtrType = Context.getPointerType(VariantRef->getType());
6351     if (VarianPtrType.getUnqualifiedType() != FnPtrType.getUnqualifiedType()) {
6352       ImplicitConversionSequence ICS = TryImplicitConversion(
6353           VariantRef, FnPtrType.getUnqualifiedType(),
6354           /*SuppressUserConversions=*/false, AllowedExplicit::None,
6355           /*InOverloadResolution=*/false,
6356           /*CStyle=*/false,
6357           /*AllowObjCWritebackConversion=*/false);
6358       if (ICS.isFailure()) {
6359         Diag(VariantRef->getExprLoc(),
6360              diag::err_omp_declare_variant_incompat_types)
6361             << VariantRef->getType()
6362             << ((Method && !Method->isStatic()) ? FnPtrType : FD->getType())
6363             << VariantRef->getSourceRange();
6364         return None;
6365       }
6366       VariantRefCast = PerformImplicitConversion(
6367           VariantRef, FnPtrType.getUnqualifiedType(), AA_Converting);
6368       if (!VariantRefCast.isUsable())
6369         return None;
6370     }
6371     // Drop previously built artificial addr_of unary op for member functions.
6372     if (Method && !Method->isStatic()) {
6373       Expr *PossibleAddrOfVariantRef = VariantRefCast.get();
6374       if (auto *UO = dyn_cast<UnaryOperator>(
6375               PossibleAddrOfVariantRef->IgnoreImplicit()))
6376         VariantRefCast = UO->getSubExpr();
6377     }
6378   }
6379 
6380   ExprResult ER = CheckPlaceholderExpr(VariantRefCast.get());
6381   if (!ER.isUsable() ||
6382       !ER.get()->IgnoreParenImpCasts()->getType()->isFunctionType()) {
6383     Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected)
6384         << VariantId << VariantRef->getSourceRange();
6385     return None;
6386   }
6387 
6388   // The VariantRef must point to function.
6389   auto *DRE = dyn_cast<DeclRefExpr>(ER.get()->IgnoreParenImpCasts());
6390   if (!DRE) {
6391     Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected)
6392         << VariantId << VariantRef->getSourceRange();
6393     return None;
6394   }
6395   auto *NewFD = dyn_cast_or_null<FunctionDecl>(DRE->getDecl());
6396   if (!NewFD) {
6397     Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected)
6398         << VariantId << VariantRef->getSourceRange();
6399     return None;
6400   }
6401 
6402   // Check if function types are compatible in C.
6403   if (!LangOpts.CPlusPlus) {
6404     QualType NewType =
6405         Context.mergeFunctionTypes(FD->getType(), NewFD->getType());
6406     if (NewType.isNull()) {
6407       Diag(VariantRef->getExprLoc(),
6408            diag::err_omp_declare_variant_incompat_types)
6409           << NewFD->getType() << FD->getType() << VariantRef->getSourceRange();
6410       return None;
6411     }
6412     if (NewType->isFunctionProtoType()) {
6413       if (FD->getType()->isFunctionNoProtoType())
6414         setPrototype(*this, FD, NewFD, NewType);
6415       else if (NewFD->getType()->isFunctionNoProtoType())
6416         setPrototype(*this, NewFD, FD, NewType);
6417     }
6418   }
6419 
6420   // Check if variant function is not marked with declare variant directive.
6421   if (NewFD->hasAttrs() && NewFD->hasAttr<OMPDeclareVariantAttr>()) {
6422     Diag(VariantRef->getExprLoc(),
6423          diag::warn_omp_declare_variant_marked_as_declare_variant)
6424         << VariantRef->getSourceRange();
6425     SourceRange SR =
6426         NewFD->specific_attr_begin<OMPDeclareVariantAttr>()->getRange();
6427     Diag(SR.getBegin(), diag::note_omp_marked_declare_variant_here) << SR;
6428     return None;
6429   }
6430 
6431   enum DoesntSupport {
6432     VirtFuncs = 1,
6433     Constructors = 3,
6434     Destructors = 4,
6435     DeletedFuncs = 5,
6436     DefaultedFuncs = 6,
6437     ConstexprFuncs = 7,
6438     ConstevalFuncs = 8,
6439   };
6440   if (const auto *CXXFD = dyn_cast<CXXMethodDecl>(FD)) {
6441     if (CXXFD->isVirtual()) {
6442       Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
6443           << VirtFuncs;
6444       return None;
6445     }
6446 
6447     if (isa<CXXConstructorDecl>(FD)) {
6448       Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
6449           << Constructors;
6450       return None;
6451     }
6452 
6453     if (isa<CXXDestructorDecl>(FD)) {
6454       Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
6455           << Destructors;
6456       return None;
6457     }
6458   }
6459 
6460   if (FD->isDeleted()) {
6461     Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
6462         << DeletedFuncs;
6463     return None;
6464   }
6465 
6466   if (FD->isDefaulted()) {
6467     Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
6468         << DefaultedFuncs;
6469     return None;
6470   }
6471 
6472   if (FD->isConstexpr()) {
6473     Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
6474         << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
6475     return None;
6476   }
6477 
6478   // Check general compatibility.
6479   if (areMultiversionVariantFunctionsCompatible(
6480           FD, NewFD, PartialDiagnostic::NullDiagnostic(),
6481           PartialDiagnosticAt(SourceLocation(),
6482                               PartialDiagnostic::NullDiagnostic()),
6483           PartialDiagnosticAt(
6484               VariantRef->getExprLoc(),
6485               PDiag(diag::err_omp_declare_variant_doesnt_support)),
6486           PartialDiagnosticAt(VariantRef->getExprLoc(),
6487                               PDiag(diag::err_omp_declare_variant_diff)
6488                                   << FD->getLocation()),
6489           /*TemplatesSupported=*/true, /*ConstexprSupported=*/false,
6490           /*CLinkageMayDiffer=*/true))
6491     return None;
6492   return std::make_pair(FD, cast<Expr>(DRE));
6493 }
6494 
6495 void Sema::ActOnOpenMPDeclareVariantDirective(FunctionDecl *FD,
6496                                               Expr *VariantRef,
6497                                               OMPTraitInfo &TI,
6498                                               SourceRange SR) {
6499   auto *NewAttr =
6500       OMPDeclareVariantAttr::CreateImplicit(Context, VariantRef, &TI, SR);
6501   FD->addAttr(NewAttr);
6502 }
6503 
6504 StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
6505                                               Stmt *AStmt,
6506                                               SourceLocation StartLoc,
6507                                               SourceLocation EndLoc) {
6508   if (!AStmt)
6509     return StmtError();
6510 
6511   auto *CS = cast<CapturedStmt>(AStmt);
6512   // 1.2.2 OpenMP Language Terminology
6513   // Structured block - An executable statement with a single entry at the
6514   // top and a single exit at the bottom.
6515   // The point of exit cannot be a branch out of the structured block.
6516   // longjmp() and throw() must not violate the entry/exit criteria.
6517   CS->getCapturedDecl()->setNothrow();
6518 
6519   setFunctionHasBranchProtectedScope();
6520 
6521   return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
6522                                       DSAStack->getTaskgroupReductionRef(),
6523                                       DSAStack->isCancelRegion());
6524 }
6525 
6526 namespace {
6527 /// Iteration space of a single for loop.
6528 struct LoopIterationSpace final {
6529   /// True if the condition operator is the strict compare operator (<, > or
6530   /// !=).
6531   bool IsStrictCompare = false;
6532   /// Condition of the loop.
6533   Expr *PreCond = nullptr;
6534   /// This expression calculates the number of iterations in the loop.
6535   /// It is always possible to calculate it before starting the loop.
6536   Expr *NumIterations = nullptr;
6537   /// The loop counter variable.
6538   Expr *CounterVar = nullptr;
6539   /// Private loop counter variable.
6540   Expr *PrivateCounterVar = nullptr;
6541   /// This is initializer for the initial value of #CounterVar.
6542   Expr *CounterInit = nullptr;
6543   /// This is step for the #CounterVar used to generate its update:
6544   /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration.
6545   Expr *CounterStep = nullptr;
6546   /// Should step be subtracted?
6547   bool Subtract = false;
6548   /// Source range of the loop init.
6549   SourceRange InitSrcRange;
6550   /// Source range of the loop condition.
6551   SourceRange CondSrcRange;
6552   /// Source range of the loop increment.
6553   SourceRange IncSrcRange;
6554   /// Minimum value that can have the loop control variable. Used to support
6555   /// non-rectangular loops. Applied only for LCV with the non-iterator types,
6556   /// since only such variables can be used in non-loop invariant expressions.
6557   Expr *MinValue = nullptr;
6558   /// Maximum value that can have the loop control variable. Used to support
6559   /// non-rectangular loops. Applied only for LCV with the non-iterator type,
6560   /// since only such variables can be used in non-loop invariant expressions.
6561   Expr *MaxValue = nullptr;
6562   /// true, if the lower bound depends on the outer loop control var.
6563   bool IsNonRectangularLB = false;
6564   /// true, if the upper bound depends on the outer loop control var.
6565   bool IsNonRectangularUB = false;
6566   /// Index of the loop this loop depends on and forms non-rectangular loop
6567   /// nest.
6568   unsigned LoopDependentIdx = 0;
6569   /// Final condition for the non-rectangular loop nest support. It is used to
6570   /// check that the number of iterations for this particular counter must be
6571   /// finished.
6572   Expr *FinalCondition = nullptr;
6573 };
6574 
6575 /// Helper class for checking canonical form of the OpenMP loops and
6576 /// extracting iteration space of each loop in the loop nest, that will be used
6577 /// for IR generation.
6578 class OpenMPIterationSpaceChecker {
6579   /// Reference to Sema.
6580   Sema &SemaRef;
6581   /// Data-sharing stack.
6582   DSAStackTy &Stack;
6583   /// A location for diagnostics (when there is no some better location).
6584   SourceLocation DefaultLoc;
6585   /// A location for diagnostics (when increment is not compatible).
6586   SourceLocation ConditionLoc;
6587   /// A source location for referring to loop init later.
6588   SourceRange InitSrcRange;
6589   /// A source location for referring to condition later.
6590   SourceRange ConditionSrcRange;
6591   /// A source location for referring to increment later.
6592   SourceRange IncrementSrcRange;
6593   /// Loop variable.
6594   ValueDecl *LCDecl = nullptr;
6595   /// Reference to loop variable.
6596   Expr *LCRef = nullptr;
6597   /// Lower bound (initializer for the var).
6598   Expr *LB = nullptr;
6599   /// Upper bound.
6600   Expr *UB = nullptr;
6601   /// Loop step (increment).
6602   Expr *Step = nullptr;
6603   /// This flag is true when condition is one of:
6604   ///   Var <  UB
6605   ///   Var <= UB
6606   ///   UB  >  Var
6607   ///   UB  >= Var
6608   /// This will have no value when the condition is !=
6609   llvm::Optional<bool> TestIsLessOp;
6610   /// This flag is true when condition is strict ( < or > ).
6611   bool TestIsStrictOp = false;
6612   /// This flag is true when step is subtracted on each iteration.
6613   bool SubtractStep = false;
6614   /// The outer loop counter this loop depends on (if any).
6615   const ValueDecl *DepDecl = nullptr;
6616   /// Contains number of loop (starts from 1) on which loop counter init
6617   /// expression of this loop depends on.
6618   Optional<unsigned> InitDependOnLC;
6619   /// Contains number of loop (starts from 1) on which loop counter condition
6620   /// expression of this loop depends on.
6621   Optional<unsigned> CondDependOnLC;
6622   /// Checks if the provide statement depends on the loop counter.
6623   Optional<unsigned> doesDependOnLoopCounter(const Stmt *S, bool IsInitializer);
6624   /// Original condition required for checking of the exit condition for
6625   /// non-rectangular loop.
6626   Expr *Condition = nullptr;
6627 
6628 public:
6629   OpenMPIterationSpaceChecker(Sema &SemaRef, DSAStackTy &Stack,
6630                               SourceLocation DefaultLoc)
6631       : SemaRef(SemaRef), Stack(Stack), DefaultLoc(DefaultLoc),
6632         ConditionLoc(DefaultLoc) {}
6633   /// Check init-expr for canonical loop form and save loop counter
6634   /// variable - #Var and its initialization value - #LB.
6635   bool checkAndSetInit(Stmt *S, bool EmitDiags = true);
6636   /// Check test-expr for canonical form, save upper-bound (#UB), flags
6637   /// for less/greater and for strict/non-strict comparison.
6638   bool checkAndSetCond(Expr *S);
6639   /// Check incr-expr for canonical loop form and return true if it
6640   /// does not conform, otherwise save loop step (#Step).
6641   bool checkAndSetInc(Expr *S);
6642   /// Return the loop counter variable.
6643   ValueDecl *getLoopDecl() const { return LCDecl; }
6644   /// Return the reference expression to loop counter variable.
6645   Expr *getLoopDeclRefExpr() const { return LCRef; }
6646   /// Source range of the loop init.
6647   SourceRange getInitSrcRange() const { return InitSrcRange; }
6648   /// Source range of the loop condition.
6649   SourceRange getConditionSrcRange() const { return ConditionSrcRange; }
6650   /// Source range of the loop increment.
6651   SourceRange getIncrementSrcRange() const { return IncrementSrcRange; }
6652   /// True if the step should be subtracted.
6653   bool shouldSubtractStep() const { return SubtractStep; }
6654   /// True, if the compare operator is strict (<, > or !=).
6655   bool isStrictTestOp() const { return TestIsStrictOp; }
6656   /// Build the expression to calculate the number of iterations.
6657   Expr *buildNumIterations(
6658       Scope *S, ArrayRef<LoopIterationSpace> ResultIterSpaces, bool LimitedType,
6659       llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
6660   /// Build the precondition expression for the loops.
6661   Expr *
6662   buildPreCond(Scope *S, Expr *Cond,
6663                llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
6664   /// Build reference expression to the counter be used for codegen.
6665   DeclRefExpr *
6666   buildCounterVar(llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
6667                   DSAStackTy &DSA) const;
6668   /// Build reference expression to the private counter be used for
6669   /// codegen.
6670   Expr *buildPrivateCounterVar() const;
6671   /// Build initialization of the counter be used for codegen.
6672   Expr *buildCounterInit() const;
6673   /// Build step of the counter be used for codegen.
6674   Expr *buildCounterStep() const;
6675   /// Build loop data with counter value for depend clauses in ordered
6676   /// directives.
6677   Expr *
6678   buildOrderedLoopData(Scope *S, Expr *Counter,
6679                        llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
6680                        SourceLocation Loc, Expr *Inc = nullptr,
6681                        OverloadedOperatorKind OOK = OO_Amp);
6682   /// Builds the minimum value for the loop counter.
6683   std::pair<Expr *, Expr *> buildMinMaxValues(
6684       Scope *S, llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
6685   /// Builds final condition for the non-rectangular loops.
6686   Expr *buildFinalCondition(Scope *S) const;
6687   /// Return true if any expression is dependent.
6688   bool dependent() const;
6689   /// Returns true if the initializer forms non-rectangular loop.
6690   bool doesInitDependOnLC() const { return InitDependOnLC.hasValue(); }
6691   /// Returns true if the condition forms non-rectangular loop.
6692   bool doesCondDependOnLC() const { return CondDependOnLC.hasValue(); }
6693   /// Returns index of the loop we depend on (starting from 1), or 0 otherwise.
6694   unsigned getLoopDependentIdx() const {
6695     return InitDependOnLC.getValueOr(CondDependOnLC.getValueOr(0));
6696   }
6697 
6698 private:
6699   /// Check the right-hand side of an assignment in the increment
6700   /// expression.
6701   bool checkAndSetIncRHS(Expr *RHS);
6702   /// Helper to set loop counter variable and its initializer.
6703   bool setLCDeclAndLB(ValueDecl *NewLCDecl, Expr *NewDeclRefExpr, Expr *NewLB,
6704                       bool EmitDiags);
6705   /// Helper to set upper bound.
6706   bool setUB(Expr *NewUB, llvm::Optional<bool> LessOp, bool StrictOp,
6707              SourceRange SR, SourceLocation SL);
6708   /// Helper to set loop increment.
6709   bool setStep(Expr *NewStep, bool Subtract);
6710 };
6711 
6712 bool OpenMPIterationSpaceChecker::dependent() const {
6713   if (!LCDecl) {
6714     assert(!LB && !UB && !Step);
6715     return false;
6716   }
6717   return LCDecl->getType()->isDependentType() ||
6718          (LB && LB->isValueDependent()) || (UB && UB->isValueDependent()) ||
6719          (Step && Step->isValueDependent());
6720 }
6721 
6722 bool OpenMPIterationSpaceChecker::setLCDeclAndLB(ValueDecl *NewLCDecl,
6723                                                  Expr *NewLCRefExpr,
6724                                                  Expr *NewLB, bool EmitDiags) {
6725   // State consistency checking to ensure correct usage.
6726   assert(LCDecl == nullptr && LB == nullptr && LCRef == nullptr &&
6727          UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
6728   if (!NewLCDecl || !NewLB)
6729     return true;
6730   LCDecl = getCanonicalDecl(NewLCDecl);
6731   LCRef = NewLCRefExpr;
6732   if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB))
6733     if (const CXXConstructorDecl *Ctor = CE->getConstructor())
6734       if ((Ctor->isCopyOrMoveConstructor() ||
6735            Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
6736           CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
6737         NewLB = CE->getArg(0)->IgnoreParenImpCasts();
6738   LB = NewLB;
6739   if (EmitDiags)
6740     InitDependOnLC = doesDependOnLoopCounter(LB, /*IsInitializer=*/true);
6741   return false;
6742 }
6743 
6744 bool OpenMPIterationSpaceChecker::setUB(Expr *NewUB,
6745                                         llvm::Optional<bool> LessOp,
6746                                         bool StrictOp, SourceRange SR,
6747                                         SourceLocation SL) {
6748   // State consistency checking to ensure correct usage.
6749   assert(LCDecl != nullptr && LB != nullptr && UB == nullptr &&
6750          Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
6751   if (!NewUB)
6752     return true;
6753   UB = NewUB;
6754   if (LessOp)
6755     TestIsLessOp = LessOp;
6756   TestIsStrictOp = StrictOp;
6757   ConditionSrcRange = SR;
6758   ConditionLoc = SL;
6759   CondDependOnLC = doesDependOnLoopCounter(UB, /*IsInitializer=*/false);
6760   return false;
6761 }
6762 
6763 bool OpenMPIterationSpaceChecker::setStep(Expr *NewStep, bool Subtract) {
6764   // State consistency checking to ensure correct usage.
6765   assert(LCDecl != nullptr && LB != nullptr && Step == nullptr);
6766   if (!NewStep)
6767     return true;
6768   if (!NewStep->isValueDependent()) {
6769     // Check that the step is integer expression.
6770     SourceLocation StepLoc = NewStep->getBeginLoc();
6771     ExprResult Val = SemaRef.PerformOpenMPImplicitIntegerConversion(
6772         StepLoc, getExprAsWritten(NewStep));
6773     if (Val.isInvalid())
6774       return true;
6775     NewStep = Val.get();
6776 
6777     // OpenMP [2.6, Canonical Loop Form, Restrictions]
6778     //  If test-expr is of form var relational-op b and relational-op is < or
6779     //  <= then incr-expr must cause var to increase on each iteration of the
6780     //  loop. If test-expr is of form var relational-op b and relational-op is
6781     //  > or >= then incr-expr must cause var to decrease on each iteration of
6782     //  the loop.
6783     //  If test-expr is of form b relational-op var and relational-op is < or
6784     //  <= then incr-expr must cause var to decrease on each iteration of the
6785     //  loop. If test-expr is of form b relational-op var and relational-op is
6786     //  > or >= then incr-expr must cause var to increase on each iteration of
6787     //  the loop.
6788     Optional<llvm::APSInt> Result =
6789         NewStep->getIntegerConstantExpr(SemaRef.Context);
6790     bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation();
6791     bool IsConstNeg =
6792         Result && Result->isSigned() && (Subtract != Result->isNegative());
6793     bool IsConstPos =
6794         Result && Result->isSigned() && (Subtract == Result->isNegative());
6795     bool IsConstZero = Result && !Result->getBoolValue();
6796 
6797     // != with increment is treated as <; != with decrement is treated as >
6798     if (!TestIsLessOp.hasValue())
6799       TestIsLessOp = IsConstPos || (IsUnsigned && !Subtract);
6800     if (UB && (IsConstZero ||
6801                (TestIsLessOp.getValue() ?
6802                   (IsConstNeg || (IsUnsigned && Subtract)) :
6803                   (IsConstPos || (IsUnsigned && !Subtract))))) {
6804       SemaRef.Diag(NewStep->getExprLoc(),
6805                    diag::err_omp_loop_incr_not_compatible)
6806           << LCDecl << TestIsLessOp.getValue() << NewStep->getSourceRange();
6807       SemaRef.Diag(ConditionLoc,
6808                    diag::note_omp_loop_cond_requres_compatible_incr)
6809           << TestIsLessOp.getValue() << ConditionSrcRange;
6810       return true;
6811     }
6812     if (TestIsLessOp.getValue() == Subtract) {
6813       NewStep =
6814           SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus, NewStep)
6815               .get();
6816       Subtract = !Subtract;
6817     }
6818   }
6819 
6820   Step = NewStep;
6821   SubtractStep = Subtract;
6822   return false;
6823 }
6824 
6825 namespace {
6826 /// Checker for the non-rectangular loops. Checks if the initializer or
6827 /// condition expression references loop counter variable.
6828 class LoopCounterRefChecker final
6829     : public ConstStmtVisitor<LoopCounterRefChecker, bool> {
6830   Sema &SemaRef;
6831   DSAStackTy &Stack;
6832   const ValueDecl *CurLCDecl = nullptr;
6833   const ValueDecl *DepDecl = nullptr;
6834   const ValueDecl *PrevDepDecl = nullptr;
6835   bool IsInitializer = true;
6836   unsigned BaseLoopId = 0;
6837   bool checkDecl(const Expr *E, const ValueDecl *VD) {
6838     if (getCanonicalDecl(VD) == getCanonicalDecl(CurLCDecl)) {
6839       SemaRef.Diag(E->getExprLoc(), diag::err_omp_stmt_depends_on_loop_counter)
6840           << (IsInitializer ? 0 : 1);
6841       return false;
6842     }
6843     const auto &&Data = Stack.isLoopControlVariable(VD);
6844     // OpenMP, 2.9.1 Canonical Loop Form, Restrictions.
6845     // The type of the loop iterator on which we depend may not have a random
6846     // access iterator type.
6847     if (Data.first && VD->getType()->isRecordType()) {
6848       SmallString<128> Name;
6849       llvm::raw_svector_ostream OS(Name);
6850       VD->getNameForDiagnostic(OS, SemaRef.getPrintingPolicy(),
6851                                /*Qualified=*/true);
6852       SemaRef.Diag(E->getExprLoc(),
6853                    diag::err_omp_wrong_dependency_iterator_type)
6854           << OS.str();
6855       SemaRef.Diag(VD->getLocation(), diag::note_previous_decl) << VD;
6856       return false;
6857     }
6858     if (Data.first &&
6859         (DepDecl || (PrevDepDecl &&
6860                      getCanonicalDecl(VD) != getCanonicalDecl(PrevDepDecl)))) {
6861       if (!DepDecl && PrevDepDecl)
6862         DepDecl = PrevDepDecl;
6863       SmallString<128> Name;
6864       llvm::raw_svector_ostream OS(Name);
6865       DepDecl->getNameForDiagnostic(OS, SemaRef.getPrintingPolicy(),
6866                                     /*Qualified=*/true);
6867       SemaRef.Diag(E->getExprLoc(),
6868                    diag::err_omp_invariant_or_linear_dependency)
6869           << OS.str();
6870       return false;
6871     }
6872     if (Data.first) {
6873       DepDecl = VD;
6874       BaseLoopId = Data.first;
6875     }
6876     return Data.first;
6877   }
6878 
6879 public:
6880   bool VisitDeclRefExpr(const DeclRefExpr *E) {
6881     const ValueDecl *VD = E->getDecl();
6882     if (isa<VarDecl>(VD))
6883       return checkDecl(E, VD);
6884     return false;
6885   }
6886   bool VisitMemberExpr(const MemberExpr *E) {
6887     if (isa<CXXThisExpr>(E->getBase()->IgnoreParens())) {
6888       const ValueDecl *VD = E->getMemberDecl();
6889       if (isa<VarDecl>(VD) || isa<FieldDecl>(VD))
6890         return checkDecl(E, VD);
6891     }
6892     return false;
6893   }
6894   bool VisitStmt(const Stmt *S) {
6895     bool Res = false;
6896     for (const Stmt *Child : S->children())
6897       Res = (Child && Visit(Child)) || Res;
6898     return Res;
6899   }
6900   explicit LoopCounterRefChecker(Sema &SemaRef, DSAStackTy &Stack,
6901                                  const ValueDecl *CurLCDecl, bool IsInitializer,
6902                                  const ValueDecl *PrevDepDecl = nullptr)
6903       : SemaRef(SemaRef), Stack(Stack), CurLCDecl(CurLCDecl),
6904         PrevDepDecl(PrevDepDecl), IsInitializer(IsInitializer) {}
6905   unsigned getBaseLoopId() const {
6906     assert(CurLCDecl && "Expected loop dependency.");
6907     return BaseLoopId;
6908   }
6909   const ValueDecl *getDepDecl() const {
6910     assert(CurLCDecl && "Expected loop dependency.");
6911     return DepDecl;
6912   }
6913 };
6914 } // namespace
6915 
6916 Optional<unsigned>
6917 OpenMPIterationSpaceChecker::doesDependOnLoopCounter(const Stmt *S,
6918                                                      bool IsInitializer) {
6919   // Check for the non-rectangular loops.
6920   LoopCounterRefChecker LoopStmtChecker(SemaRef, Stack, LCDecl, IsInitializer,
6921                                         DepDecl);
6922   if (LoopStmtChecker.Visit(S)) {
6923     DepDecl = LoopStmtChecker.getDepDecl();
6924     return LoopStmtChecker.getBaseLoopId();
6925   }
6926   return llvm::None;
6927 }
6928 
6929 bool OpenMPIterationSpaceChecker::checkAndSetInit(Stmt *S, bool EmitDiags) {
6930   // Check init-expr for canonical loop form and save loop counter
6931   // variable - #Var and its initialization value - #LB.
6932   // OpenMP [2.6] Canonical loop form. init-expr may be one of the following:
6933   //   var = lb
6934   //   integer-type var = lb
6935   //   random-access-iterator-type var = lb
6936   //   pointer-type var = lb
6937   //
6938   if (!S) {
6939     if (EmitDiags) {
6940       SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init);
6941     }
6942     return true;
6943   }
6944   if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
6945     if (!ExprTemp->cleanupsHaveSideEffects())
6946       S = ExprTemp->getSubExpr();
6947 
6948   InitSrcRange = S->getSourceRange();
6949   if (Expr *E = dyn_cast<Expr>(S))
6950     S = E->IgnoreParens();
6951   if (auto *BO = dyn_cast<BinaryOperator>(S)) {
6952     if (BO->getOpcode() == BO_Assign) {
6953       Expr *LHS = BO->getLHS()->IgnoreParens();
6954       if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
6955         if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
6956           if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
6957             return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
6958                                   EmitDiags);
6959         return setLCDeclAndLB(DRE->getDecl(), DRE, BO->getRHS(), EmitDiags);
6960       }
6961       if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
6962         if (ME->isArrow() &&
6963             isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
6964           return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
6965                                 EmitDiags);
6966       }
6967     }
6968   } else if (auto *DS = dyn_cast<DeclStmt>(S)) {
6969     if (DS->isSingleDecl()) {
6970       if (auto *Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) {
6971         if (Var->hasInit() && !Var->getType()->isReferenceType()) {
6972           // Accept non-canonical init form here but emit ext. warning.
6973           if (Var->getInitStyle() != VarDecl::CInit && EmitDiags)
6974             SemaRef.Diag(S->getBeginLoc(),
6975                          diag::ext_omp_loop_not_canonical_init)
6976                 << S->getSourceRange();
6977           return setLCDeclAndLB(
6978               Var,
6979               buildDeclRefExpr(SemaRef, Var,
6980                                Var->getType().getNonReferenceType(),
6981                                DS->getBeginLoc()),
6982               Var->getInit(), EmitDiags);
6983         }
6984       }
6985     }
6986   } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
6987     if (CE->getOperator() == OO_Equal) {
6988       Expr *LHS = CE->getArg(0);
6989       if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
6990         if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
6991           if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
6992             return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
6993                                   EmitDiags);
6994         return setLCDeclAndLB(DRE->getDecl(), DRE, CE->getArg(1), EmitDiags);
6995       }
6996       if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
6997         if (ME->isArrow() &&
6998             isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
6999           return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
7000                                 EmitDiags);
7001       }
7002     }
7003   }
7004 
7005   if (dependent() || SemaRef.CurContext->isDependentContext())
7006     return false;
7007   if (EmitDiags) {
7008     SemaRef.Diag(S->getBeginLoc(), diag::err_omp_loop_not_canonical_init)
7009         << S->getSourceRange();
7010   }
7011   return true;
7012 }
7013 
7014 /// Ignore parenthesizes, implicit casts, copy constructor and return the
7015 /// variable (which may be the loop variable) if possible.
7016 static const ValueDecl *getInitLCDecl(const Expr *E) {
7017   if (!E)
7018     return nullptr;
7019   E = getExprAsWritten(E);
7020   if (const auto *CE = dyn_cast_or_null<CXXConstructExpr>(E))
7021     if (const CXXConstructorDecl *Ctor = CE->getConstructor())
7022       if ((Ctor->isCopyOrMoveConstructor() ||
7023            Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
7024           CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
7025         E = CE->getArg(0)->IgnoreParenImpCasts();
7026   if (const auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) {
7027     if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
7028       return getCanonicalDecl(VD);
7029   }
7030   if (const auto *ME = dyn_cast_or_null<MemberExpr>(E))
7031     if (ME->isArrow() && isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
7032       return getCanonicalDecl(ME->getMemberDecl());
7033   return nullptr;
7034 }
7035 
7036 bool OpenMPIterationSpaceChecker::checkAndSetCond(Expr *S) {
7037   // Check test-expr for canonical form, save upper-bound UB, flags for
7038   // less/greater and for strict/non-strict comparison.
7039   // OpenMP [2.9] Canonical loop form. Test-expr may be one of the following:
7040   //   var relational-op b
7041   //   b relational-op var
7042   //
7043   bool IneqCondIsCanonical = SemaRef.getLangOpts().OpenMP >= 50;
7044   if (!S) {
7045     SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond)
7046         << (IneqCondIsCanonical ? 1 : 0) << LCDecl;
7047     return true;
7048   }
7049   Condition = S;
7050   S = getExprAsWritten(S);
7051   SourceLocation CondLoc = S->getBeginLoc();
7052   if (auto *BO = dyn_cast<BinaryOperator>(S)) {
7053     if (BO->isRelationalOp()) {
7054       if (getInitLCDecl(BO->getLHS()) == LCDecl)
7055         return setUB(BO->getRHS(),
7056                      (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE),
7057                      (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
7058                      BO->getSourceRange(), BO->getOperatorLoc());
7059       if (getInitLCDecl(BO->getRHS()) == LCDecl)
7060         return setUB(BO->getLHS(),
7061                      (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE),
7062                      (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
7063                      BO->getSourceRange(), BO->getOperatorLoc());
7064     } else if (IneqCondIsCanonical && BO->getOpcode() == BO_NE)
7065       return setUB(
7066           getInitLCDecl(BO->getLHS()) == LCDecl ? BO->getRHS() : BO->getLHS(),
7067           /*LessOp=*/llvm::None,
7068           /*StrictOp=*/true, BO->getSourceRange(), BO->getOperatorLoc());
7069   } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
7070     if (CE->getNumArgs() == 2) {
7071       auto Op = CE->getOperator();
7072       switch (Op) {
7073       case OO_Greater:
7074       case OO_GreaterEqual:
7075       case OO_Less:
7076       case OO_LessEqual:
7077         if (getInitLCDecl(CE->getArg(0)) == LCDecl)
7078           return setUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual,
7079                        Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
7080                        CE->getOperatorLoc());
7081         if (getInitLCDecl(CE->getArg(1)) == LCDecl)
7082           return setUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual,
7083                        Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
7084                        CE->getOperatorLoc());
7085         break;
7086       case OO_ExclaimEqual:
7087         if (IneqCondIsCanonical)
7088           return setUB(getInitLCDecl(CE->getArg(0)) == LCDecl ? CE->getArg(1)
7089                                                               : CE->getArg(0),
7090                        /*LessOp=*/llvm::None,
7091                        /*StrictOp=*/true, CE->getSourceRange(),
7092                        CE->getOperatorLoc());
7093         break;
7094       default:
7095         break;
7096       }
7097     }
7098   }
7099   if (dependent() || SemaRef.CurContext->isDependentContext())
7100     return false;
7101   SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond)
7102       << (IneqCondIsCanonical ? 1 : 0) << S->getSourceRange() << LCDecl;
7103   return true;
7104 }
7105 
7106 bool OpenMPIterationSpaceChecker::checkAndSetIncRHS(Expr *RHS) {
7107   // RHS of canonical loop form increment can be:
7108   //   var + incr
7109   //   incr + var
7110   //   var - incr
7111   //
7112   RHS = RHS->IgnoreParenImpCasts();
7113   if (auto *BO = dyn_cast<BinaryOperator>(RHS)) {
7114     if (BO->isAdditiveOp()) {
7115       bool IsAdd = BO->getOpcode() == BO_Add;
7116       if (getInitLCDecl(BO->getLHS()) == LCDecl)
7117         return setStep(BO->getRHS(), !IsAdd);
7118       if (IsAdd && getInitLCDecl(BO->getRHS()) == LCDecl)
7119         return setStep(BO->getLHS(), /*Subtract=*/false);
7120     }
7121   } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(RHS)) {
7122     bool IsAdd = CE->getOperator() == OO_Plus;
7123     if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) {
7124       if (getInitLCDecl(CE->getArg(0)) == LCDecl)
7125         return setStep(CE->getArg(1), !IsAdd);
7126       if (IsAdd && getInitLCDecl(CE->getArg(1)) == LCDecl)
7127         return setStep(CE->getArg(0), /*Subtract=*/false);
7128     }
7129   }
7130   if (dependent() || SemaRef.CurContext->isDependentContext())
7131     return false;
7132   SemaRef.Diag(RHS->getBeginLoc(), diag::err_omp_loop_not_canonical_incr)
7133       << RHS->getSourceRange() << LCDecl;
7134   return true;
7135 }
7136 
7137 bool OpenMPIterationSpaceChecker::checkAndSetInc(Expr *S) {
7138   // Check incr-expr for canonical loop form and return true if it
7139   // does not conform.
7140   // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
7141   //   ++var
7142   //   var++
7143   //   --var
7144   //   var--
7145   //   var += incr
7146   //   var -= incr
7147   //   var = var + incr
7148   //   var = incr + var
7149   //   var = var - incr
7150   //
7151   if (!S) {
7152     SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << LCDecl;
7153     return true;
7154   }
7155   if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
7156     if (!ExprTemp->cleanupsHaveSideEffects())
7157       S = ExprTemp->getSubExpr();
7158 
7159   IncrementSrcRange = S->getSourceRange();
7160   S = S->IgnoreParens();
7161   if (auto *UO = dyn_cast<UnaryOperator>(S)) {
7162     if (UO->isIncrementDecrementOp() &&
7163         getInitLCDecl(UO->getSubExpr()) == LCDecl)
7164       return setStep(SemaRef
7165                          .ActOnIntegerConstant(UO->getBeginLoc(),
7166                                                (UO->isDecrementOp() ? -1 : 1))
7167                          .get(),
7168                      /*Subtract=*/false);
7169   } else if (auto *BO = dyn_cast<BinaryOperator>(S)) {
7170     switch (BO->getOpcode()) {
7171     case BO_AddAssign:
7172     case BO_SubAssign:
7173       if (getInitLCDecl(BO->getLHS()) == LCDecl)
7174         return setStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign);
7175       break;
7176     case BO_Assign:
7177       if (getInitLCDecl(BO->getLHS()) == LCDecl)
7178         return checkAndSetIncRHS(BO->getRHS());
7179       break;
7180     default:
7181       break;
7182     }
7183   } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
7184     switch (CE->getOperator()) {
7185     case OO_PlusPlus:
7186     case OO_MinusMinus:
7187       if (getInitLCDecl(CE->getArg(0)) == LCDecl)
7188         return setStep(SemaRef
7189                            .ActOnIntegerConstant(
7190                                CE->getBeginLoc(),
7191                                ((CE->getOperator() == OO_MinusMinus) ? -1 : 1))
7192                            .get(),
7193                        /*Subtract=*/false);
7194       break;
7195     case OO_PlusEqual:
7196     case OO_MinusEqual:
7197       if (getInitLCDecl(CE->getArg(0)) == LCDecl)
7198         return setStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual);
7199       break;
7200     case OO_Equal:
7201       if (getInitLCDecl(CE->getArg(0)) == LCDecl)
7202         return checkAndSetIncRHS(CE->getArg(1));
7203       break;
7204     default:
7205       break;
7206     }
7207   }
7208   if (dependent() || SemaRef.CurContext->isDependentContext())
7209     return false;
7210   SemaRef.Diag(S->getBeginLoc(), diag::err_omp_loop_not_canonical_incr)
7211       << S->getSourceRange() << LCDecl;
7212   return true;
7213 }
7214 
7215 static ExprResult
7216 tryBuildCapture(Sema &SemaRef, Expr *Capture,
7217                 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
7218   if (SemaRef.CurContext->isDependentContext() || Capture->containsErrors())
7219     return Capture;
7220   if (Capture->isEvaluatable(SemaRef.Context, Expr::SE_AllowSideEffects))
7221     return SemaRef.PerformImplicitConversion(
7222         Capture->IgnoreImpCasts(), Capture->getType(), Sema::AA_Converting,
7223         /*AllowExplicit=*/true);
7224   auto I = Captures.find(Capture);
7225   if (I != Captures.end())
7226     return buildCapture(SemaRef, Capture, I->second);
7227   DeclRefExpr *Ref = nullptr;
7228   ExprResult Res = buildCapture(SemaRef, Capture, Ref);
7229   Captures[Capture] = Ref;
7230   return Res;
7231 }
7232 
7233 /// Calculate number of iterations, transforming to unsigned, if number of
7234 /// iterations may be larger than the original type.
7235 static Expr *
7236 calculateNumIters(Sema &SemaRef, Scope *S, SourceLocation DefaultLoc,
7237                   Expr *Lower, Expr *Upper, Expr *Step, QualType LCTy,
7238                   bool TestIsStrictOp, bool RoundToStep,
7239                   llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
7240   ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures);
7241   if (!NewStep.isUsable())
7242     return nullptr;
7243   llvm::APSInt LRes, SRes;
7244   bool IsLowerConst = false, IsStepConst = false;
7245   if (Optional<llvm::APSInt> Res = Lower->getIntegerConstantExpr(SemaRef.Context)) {
7246     LRes = *Res;
7247     IsLowerConst = true;
7248   }
7249   if (Optional<llvm::APSInt> Res = Step->getIntegerConstantExpr(SemaRef.Context)) {
7250     SRes = *Res;
7251     IsStepConst = true;
7252   }
7253   bool NoNeedToConvert = IsLowerConst && !RoundToStep &&
7254                          ((!TestIsStrictOp && LRes.isNonNegative()) ||
7255                           (TestIsStrictOp && LRes.isStrictlyPositive()));
7256   bool NeedToReorganize = false;
7257   // Check if any subexpressions in Lower -Step [+ 1] lead to overflow.
7258   if (!NoNeedToConvert && IsLowerConst &&
7259       (TestIsStrictOp || (RoundToStep && IsStepConst))) {
7260     NoNeedToConvert = true;
7261     if (RoundToStep) {
7262       unsigned BW = LRes.getBitWidth() > SRes.getBitWidth()
7263                         ? LRes.getBitWidth()
7264                         : SRes.getBitWidth();
7265       LRes = LRes.extend(BW + 1);
7266       LRes.setIsSigned(true);
7267       SRes = SRes.extend(BW + 1);
7268       SRes.setIsSigned(true);
7269       LRes -= SRes;
7270       NoNeedToConvert = LRes.trunc(BW).extend(BW + 1) == LRes;
7271       LRes = LRes.trunc(BW);
7272     }
7273     if (TestIsStrictOp) {
7274       unsigned BW = LRes.getBitWidth();
7275       LRes = LRes.extend(BW + 1);
7276       LRes.setIsSigned(true);
7277       ++LRes;
7278       NoNeedToConvert =
7279           NoNeedToConvert && LRes.trunc(BW).extend(BW + 1) == LRes;
7280       // truncate to the original bitwidth.
7281       LRes = LRes.trunc(BW);
7282     }
7283     NeedToReorganize = NoNeedToConvert;
7284   }
7285   llvm::APSInt URes;
7286   bool IsUpperConst = false;
7287   if (Optional<llvm::APSInt> Res = Upper->getIntegerConstantExpr(SemaRef.Context)) {
7288     URes = *Res;
7289     IsUpperConst = true;
7290   }
7291   if (NoNeedToConvert && IsLowerConst && IsUpperConst &&
7292       (!RoundToStep || IsStepConst)) {
7293     unsigned BW = LRes.getBitWidth() > URes.getBitWidth() ? LRes.getBitWidth()
7294                                                           : URes.getBitWidth();
7295     LRes = LRes.extend(BW + 1);
7296     LRes.setIsSigned(true);
7297     URes = URes.extend(BW + 1);
7298     URes.setIsSigned(true);
7299     URes -= LRes;
7300     NoNeedToConvert = URes.trunc(BW).extend(BW + 1) == URes;
7301     NeedToReorganize = NoNeedToConvert;
7302   }
7303   // If the boundaries are not constant or (Lower - Step [+ 1]) is not constant
7304   // or less than zero (Upper - (Lower - Step [+ 1]) may overflow) - promote to
7305   // unsigned.
7306   if ((!NoNeedToConvert || (LRes.isNegative() && !IsUpperConst)) &&
7307       !LCTy->isDependentType() && LCTy->isIntegerType()) {
7308     QualType LowerTy = Lower->getType();
7309     QualType UpperTy = Upper->getType();
7310     uint64_t LowerSize = SemaRef.Context.getTypeSize(LowerTy);
7311     uint64_t UpperSize = SemaRef.Context.getTypeSize(UpperTy);
7312     if ((LowerSize <= UpperSize && UpperTy->hasSignedIntegerRepresentation()) ||
7313         (LowerSize > UpperSize && LowerTy->hasSignedIntegerRepresentation())) {
7314       QualType CastType = SemaRef.Context.getIntTypeForBitwidth(
7315           LowerSize > UpperSize ? LowerSize : UpperSize, /*Signed=*/0);
7316       Upper =
7317           SemaRef
7318               .PerformImplicitConversion(
7319                   SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Upper).get(),
7320                   CastType, Sema::AA_Converting)
7321               .get();
7322       Lower = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Lower).get();
7323       NewStep = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, NewStep.get());
7324     }
7325   }
7326   if (!Lower || !Upper || NewStep.isInvalid())
7327     return nullptr;
7328 
7329   ExprResult Diff;
7330   // If need to reorganize, then calculate the form as Upper - (Lower - Step [+
7331   // 1]).
7332   if (NeedToReorganize) {
7333     Diff = Lower;
7334 
7335     if (RoundToStep) {
7336       // Lower - Step
7337       Diff =
7338           SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Diff.get(), NewStep.get());
7339       if (!Diff.isUsable())
7340         return nullptr;
7341     }
7342 
7343     // Lower - Step [+ 1]
7344     if (TestIsStrictOp)
7345       Diff = SemaRef.BuildBinOp(
7346           S, DefaultLoc, BO_Add, Diff.get(),
7347           SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
7348     if (!Diff.isUsable())
7349       return nullptr;
7350 
7351     Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
7352     if (!Diff.isUsable())
7353       return nullptr;
7354 
7355     // Upper - (Lower - Step [+ 1]).
7356     Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Diff.get());
7357     if (!Diff.isUsable())
7358       return nullptr;
7359   } else {
7360     Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
7361 
7362     if (!Diff.isUsable() && LCTy->getAsCXXRecordDecl()) {
7363       // BuildBinOp already emitted error, this one is to point user to upper
7364       // and lower bound, and to tell what is passed to 'operator-'.
7365       SemaRef.Diag(Upper->getBeginLoc(), diag::err_omp_loop_diff_cxx)
7366           << Upper->getSourceRange() << Lower->getSourceRange();
7367       return nullptr;
7368     }
7369 
7370     if (!Diff.isUsable())
7371       return nullptr;
7372 
7373     // Upper - Lower [- 1]
7374     if (TestIsStrictOp)
7375       Diff = SemaRef.BuildBinOp(
7376           S, DefaultLoc, BO_Sub, Diff.get(),
7377           SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
7378     if (!Diff.isUsable())
7379       return nullptr;
7380 
7381     if (RoundToStep) {
7382       // Upper - Lower [- 1] + Step
7383       Diff =
7384           SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get());
7385       if (!Diff.isUsable())
7386         return nullptr;
7387     }
7388   }
7389 
7390   // Parentheses (for dumping/debugging purposes only).
7391   Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
7392   if (!Diff.isUsable())
7393     return nullptr;
7394 
7395   // (Upper - Lower [- 1] + Step) / Step or (Upper - Lower) / Step
7396   Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
7397   if (!Diff.isUsable())
7398     return nullptr;
7399 
7400   return Diff.get();
7401 }
7402 
7403 /// Build the expression to calculate the number of iterations.
7404 Expr *OpenMPIterationSpaceChecker::buildNumIterations(
7405     Scope *S, ArrayRef<LoopIterationSpace> ResultIterSpaces, bool LimitedType,
7406     llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
7407   QualType VarType = LCDecl->getType().getNonReferenceType();
7408   if (!VarType->isIntegerType() && !VarType->isPointerType() &&
7409       !SemaRef.getLangOpts().CPlusPlus)
7410     return nullptr;
7411   Expr *LBVal = LB;
7412   Expr *UBVal = UB;
7413   // LB = TestIsLessOp.getValue() ? min(LB(MinVal), LB(MaxVal)) :
7414   // max(LB(MinVal), LB(MaxVal))
7415   if (InitDependOnLC) {
7416     const LoopIterationSpace &IS =
7417         ResultIterSpaces[ResultIterSpaces.size() - 1 -
7418                          InitDependOnLC.getValueOr(
7419                              CondDependOnLC.getValueOr(0))];
7420     if (!IS.MinValue || !IS.MaxValue)
7421       return nullptr;
7422     // OuterVar = Min
7423     ExprResult MinValue =
7424         SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MinValue);
7425     if (!MinValue.isUsable())
7426       return nullptr;
7427 
7428     ExprResult LBMinVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign,
7429                                              IS.CounterVar, MinValue.get());
7430     if (!LBMinVal.isUsable())
7431       return nullptr;
7432     // OuterVar = Min, LBVal
7433     LBMinVal =
7434         SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, LBMinVal.get(), LBVal);
7435     if (!LBMinVal.isUsable())
7436       return nullptr;
7437     // (OuterVar = Min, LBVal)
7438     LBMinVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, LBMinVal.get());
7439     if (!LBMinVal.isUsable())
7440       return nullptr;
7441 
7442     // OuterVar = Max
7443     ExprResult MaxValue =
7444         SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MaxValue);
7445     if (!MaxValue.isUsable())
7446       return nullptr;
7447 
7448     ExprResult LBMaxVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign,
7449                                              IS.CounterVar, MaxValue.get());
7450     if (!LBMaxVal.isUsable())
7451       return nullptr;
7452     // OuterVar = Max, LBVal
7453     LBMaxVal =
7454         SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, LBMaxVal.get(), LBVal);
7455     if (!LBMaxVal.isUsable())
7456       return nullptr;
7457     // (OuterVar = Max, LBVal)
7458     LBMaxVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, LBMaxVal.get());
7459     if (!LBMaxVal.isUsable())
7460       return nullptr;
7461 
7462     Expr *LBMin = tryBuildCapture(SemaRef, LBMinVal.get(), Captures).get();
7463     Expr *LBMax = tryBuildCapture(SemaRef, LBMaxVal.get(), Captures).get();
7464     if (!LBMin || !LBMax)
7465       return nullptr;
7466     // LB(MinVal) < LB(MaxVal)
7467     ExprResult MinLessMaxRes =
7468         SemaRef.BuildBinOp(S, DefaultLoc, BO_LT, LBMin, LBMax);
7469     if (!MinLessMaxRes.isUsable())
7470       return nullptr;
7471     Expr *MinLessMax =
7472         tryBuildCapture(SemaRef, MinLessMaxRes.get(), Captures).get();
7473     if (!MinLessMax)
7474       return nullptr;
7475     if (TestIsLessOp.getValue()) {
7476       // LB(MinVal) < LB(MaxVal) ? LB(MinVal) : LB(MaxVal) - min(LB(MinVal),
7477       // LB(MaxVal))
7478       ExprResult MinLB = SemaRef.ActOnConditionalOp(DefaultLoc, DefaultLoc,
7479                                                     MinLessMax, LBMin, LBMax);
7480       if (!MinLB.isUsable())
7481         return nullptr;
7482       LBVal = MinLB.get();
7483     } else {
7484       // LB(MinVal) < LB(MaxVal) ? LB(MaxVal) : LB(MinVal) - max(LB(MinVal),
7485       // LB(MaxVal))
7486       ExprResult MaxLB = SemaRef.ActOnConditionalOp(DefaultLoc, DefaultLoc,
7487                                                     MinLessMax, LBMax, LBMin);
7488       if (!MaxLB.isUsable())
7489         return nullptr;
7490       LBVal = MaxLB.get();
7491     }
7492   }
7493   // UB = TestIsLessOp.getValue() ? max(UB(MinVal), UB(MaxVal)) :
7494   // min(UB(MinVal), UB(MaxVal))
7495   if (CondDependOnLC) {
7496     const LoopIterationSpace &IS =
7497         ResultIterSpaces[ResultIterSpaces.size() - 1 -
7498                          InitDependOnLC.getValueOr(
7499                              CondDependOnLC.getValueOr(0))];
7500     if (!IS.MinValue || !IS.MaxValue)
7501       return nullptr;
7502     // OuterVar = Min
7503     ExprResult MinValue =
7504         SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MinValue);
7505     if (!MinValue.isUsable())
7506       return nullptr;
7507 
7508     ExprResult UBMinVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign,
7509                                              IS.CounterVar, MinValue.get());
7510     if (!UBMinVal.isUsable())
7511       return nullptr;
7512     // OuterVar = Min, UBVal
7513     UBMinVal =
7514         SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, UBMinVal.get(), UBVal);
7515     if (!UBMinVal.isUsable())
7516       return nullptr;
7517     // (OuterVar = Min, UBVal)
7518     UBMinVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, UBMinVal.get());
7519     if (!UBMinVal.isUsable())
7520       return nullptr;
7521 
7522     // OuterVar = Max
7523     ExprResult MaxValue =
7524         SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MaxValue);
7525     if (!MaxValue.isUsable())
7526       return nullptr;
7527 
7528     ExprResult UBMaxVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign,
7529                                              IS.CounterVar, MaxValue.get());
7530     if (!UBMaxVal.isUsable())
7531       return nullptr;
7532     // OuterVar = Max, UBVal
7533     UBMaxVal =
7534         SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, UBMaxVal.get(), UBVal);
7535     if (!UBMaxVal.isUsable())
7536       return nullptr;
7537     // (OuterVar = Max, UBVal)
7538     UBMaxVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, UBMaxVal.get());
7539     if (!UBMaxVal.isUsable())
7540       return nullptr;
7541 
7542     Expr *UBMin = tryBuildCapture(SemaRef, UBMinVal.get(), Captures).get();
7543     Expr *UBMax = tryBuildCapture(SemaRef, UBMaxVal.get(), Captures).get();
7544     if (!UBMin || !UBMax)
7545       return nullptr;
7546     // UB(MinVal) > UB(MaxVal)
7547     ExprResult MinGreaterMaxRes =
7548         SemaRef.BuildBinOp(S, DefaultLoc, BO_GT, UBMin, UBMax);
7549     if (!MinGreaterMaxRes.isUsable())
7550       return nullptr;
7551     Expr *MinGreaterMax =
7552         tryBuildCapture(SemaRef, MinGreaterMaxRes.get(), Captures).get();
7553     if (!MinGreaterMax)
7554       return nullptr;
7555     if (TestIsLessOp.getValue()) {
7556       // UB(MinVal) > UB(MaxVal) ? UB(MinVal) : UB(MaxVal) - max(UB(MinVal),
7557       // UB(MaxVal))
7558       ExprResult MaxUB = SemaRef.ActOnConditionalOp(
7559           DefaultLoc, DefaultLoc, MinGreaterMax, UBMin, UBMax);
7560       if (!MaxUB.isUsable())
7561         return nullptr;
7562       UBVal = MaxUB.get();
7563     } else {
7564       // UB(MinVal) > UB(MaxVal) ? UB(MaxVal) : UB(MinVal) - min(UB(MinVal),
7565       // UB(MaxVal))
7566       ExprResult MinUB = SemaRef.ActOnConditionalOp(
7567           DefaultLoc, DefaultLoc, MinGreaterMax, UBMax, UBMin);
7568       if (!MinUB.isUsable())
7569         return nullptr;
7570       UBVal = MinUB.get();
7571     }
7572   }
7573   Expr *UBExpr = TestIsLessOp.getValue() ? UBVal : LBVal;
7574   Expr *LBExpr = TestIsLessOp.getValue() ? LBVal : UBVal;
7575   Expr *Upper = tryBuildCapture(SemaRef, UBExpr, Captures).get();
7576   Expr *Lower = tryBuildCapture(SemaRef, LBExpr, Captures).get();
7577   if (!Upper || !Lower)
7578     return nullptr;
7579 
7580   ExprResult Diff =
7581       calculateNumIters(SemaRef, S, DefaultLoc, Lower, Upper, Step, VarType,
7582                         TestIsStrictOp, /*RoundToStep=*/true, Captures);
7583   if (!Diff.isUsable())
7584     return nullptr;
7585 
7586   // OpenMP runtime requires 32-bit or 64-bit loop variables.
7587   QualType Type = Diff.get()->getType();
7588   ASTContext &C = SemaRef.Context;
7589   bool UseVarType = VarType->hasIntegerRepresentation() &&
7590                     C.getTypeSize(Type) > C.getTypeSize(VarType);
7591   if (!Type->isIntegerType() || UseVarType) {
7592     unsigned NewSize =
7593         UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type);
7594     bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation()
7595                                : Type->hasSignedIntegerRepresentation();
7596     Type = C.getIntTypeForBitwidth(NewSize, IsSigned);
7597     if (!SemaRef.Context.hasSameType(Diff.get()->getType(), Type)) {
7598       Diff = SemaRef.PerformImplicitConversion(
7599           Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true);
7600       if (!Diff.isUsable())
7601         return nullptr;
7602     }
7603   }
7604   if (LimitedType) {
7605     unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32;
7606     if (NewSize != C.getTypeSize(Type)) {
7607       if (NewSize < C.getTypeSize(Type)) {
7608         assert(NewSize == 64 && "incorrect loop var size");
7609         SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var)
7610             << InitSrcRange << ConditionSrcRange;
7611       }
7612       QualType NewType = C.getIntTypeForBitwidth(
7613           NewSize, Type->hasSignedIntegerRepresentation() ||
7614                        C.getTypeSize(Type) < NewSize);
7615       if (!SemaRef.Context.hasSameType(Diff.get()->getType(), NewType)) {
7616         Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType,
7617                                                  Sema::AA_Converting, true);
7618         if (!Diff.isUsable())
7619           return nullptr;
7620       }
7621     }
7622   }
7623 
7624   return Diff.get();
7625 }
7626 
7627 std::pair<Expr *, Expr *> OpenMPIterationSpaceChecker::buildMinMaxValues(
7628     Scope *S, llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
7629   // Do not build for iterators, they cannot be used in non-rectangular loop
7630   // nests.
7631   if (LCDecl->getType()->isRecordType())
7632     return std::make_pair(nullptr, nullptr);
7633   // If we subtract, the min is in the condition, otherwise the min is in the
7634   // init value.
7635   Expr *MinExpr = nullptr;
7636   Expr *MaxExpr = nullptr;
7637   Expr *LBExpr = TestIsLessOp.getValue() ? LB : UB;
7638   Expr *UBExpr = TestIsLessOp.getValue() ? UB : LB;
7639   bool LBNonRect = TestIsLessOp.getValue() ? InitDependOnLC.hasValue()
7640                                            : CondDependOnLC.hasValue();
7641   bool UBNonRect = TestIsLessOp.getValue() ? CondDependOnLC.hasValue()
7642                                            : InitDependOnLC.hasValue();
7643   Expr *Lower =
7644       LBNonRect ? LBExpr : tryBuildCapture(SemaRef, LBExpr, Captures).get();
7645   Expr *Upper =
7646       UBNonRect ? UBExpr : tryBuildCapture(SemaRef, UBExpr, Captures).get();
7647   if (!Upper || !Lower)
7648     return std::make_pair(nullptr, nullptr);
7649 
7650   if (TestIsLessOp.getValue())
7651     MinExpr = Lower;
7652   else
7653     MaxExpr = Upper;
7654 
7655   // Build minimum/maximum value based on number of iterations.
7656   QualType VarType = LCDecl->getType().getNonReferenceType();
7657 
7658   ExprResult Diff =
7659       calculateNumIters(SemaRef, S, DefaultLoc, Lower, Upper, Step, VarType,
7660                         TestIsStrictOp, /*RoundToStep=*/false, Captures);
7661   if (!Diff.isUsable())
7662     return std::make_pair(nullptr, nullptr);
7663 
7664   // ((Upper - Lower [- 1]) / Step) * Step
7665   // Parentheses (for dumping/debugging purposes only).
7666   Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
7667   if (!Diff.isUsable())
7668     return std::make_pair(nullptr, nullptr);
7669 
7670   ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures);
7671   if (!NewStep.isUsable())
7672     return std::make_pair(nullptr, nullptr);
7673   Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Mul, Diff.get(), NewStep.get());
7674   if (!Diff.isUsable())
7675     return std::make_pair(nullptr, nullptr);
7676 
7677   // Parentheses (for dumping/debugging purposes only).
7678   Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
7679   if (!Diff.isUsable())
7680     return std::make_pair(nullptr, nullptr);
7681 
7682   // Convert to the ptrdiff_t, if original type is pointer.
7683   if (VarType->isAnyPointerType() &&
7684       !SemaRef.Context.hasSameType(
7685           Diff.get()->getType(),
7686           SemaRef.Context.getUnsignedPointerDiffType())) {
7687     Diff = SemaRef.PerformImplicitConversion(
7688         Diff.get(), SemaRef.Context.getUnsignedPointerDiffType(),
7689         Sema::AA_Converting, /*AllowExplicit=*/true);
7690   }
7691   if (!Diff.isUsable())
7692     return std::make_pair(nullptr, nullptr);
7693 
7694   if (TestIsLessOp.getValue()) {
7695     // MinExpr = Lower;
7696     // MaxExpr = Lower + (((Upper - Lower [- 1]) / Step) * Step)
7697     Diff = SemaRef.BuildBinOp(
7698         S, DefaultLoc, BO_Add,
7699         SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Lower).get(),
7700         Diff.get());
7701     if (!Diff.isUsable())
7702       return std::make_pair(nullptr, nullptr);
7703   } else {
7704     // MaxExpr = Upper;
7705     // MinExpr = Upper - (((Upper - Lower [- 1]) / Step) * Step)
7706     Diff = SemaRef.BuildBinOp(
7707         S, DefaultLoc, BO_Sub,
7708         SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Upper).get(),
7709         Diff.get());
7710     if (!Diff.isUsable())
7711       return std::make_pair(nullptr, nullptr);
7712   }
7713 
7714   // Convert to the original type.
7715   if (SemaRef.Context.hasSameType(Diff.get()->getType(), VarType))
7716     Diff = SemaRef.PerformImplicitConversion(Diff.get(), VarType,
7717                                              Sema::AA_Converting,
7718                                              /*AllowExplicit=*/true);
7719   if (!Diff.isUsable())
7720     return std::make_pair(nullptr, nullptr);
7721 
7722   Sema::TentativeAnalysisScope Trap(SemaRef);
7723   Diff = SemaRef.ActOnFinishFullExpr(Diff.get(), /*DiscardedValue=*/false);
7724   if (!Diff.isUsable())
7725     return std::make_pair(nullptr, nullptr);
7726 
7727   if (TestIsLessOp.getValue())
7728     MaxExpr = Diff.get();
7729   else
7730     MinExpr = Diff.get();
7731 
7732   return std::make_pair(MinExpr, MaxExpr);
7733 }
7734 
7735 Expr *OpenMPIterationSpaceChecker::buildFinalCondition(Scope *S) const {
7736   if (InitDependOnLC || CondDependOnLC)
7737     return Condition;
7738   return nullptr;
7739 }
7740 
7741 Expr *OpenMPIterationSpaceChecker::buildPreCond(
7742     Scope *S, Expr *Cond,
7743     llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
7744   // Do not build a precondition when the condition/initialization is dependent
7745   // to prevent pessimistic early loop exit.
7746   // TODO: this can be improved by calculating min/max values but not sure that
7747   // it will be very effective.
7748   if (CondDependOnLC || InitDependOnLC)
7749     return SemaRef.PerformImplicitConversion(
7750         SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get(),
7751         SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
7752         /*AllowExplicit=*/true).get();
7753 
7754   // Try to build LB <op> UB, where <op> is <, >, <=, or >=.
7755   Sema::TentativeAnalysisScope Trap(SemaRef);
7756 
7757   ExprResult NewLB = tryBuildCapture(SemaRef, LB, Captures);
7758   ExprResult NewUB = tryBuildCapture(SemaRef, UB, Captures);
7759   if (!NewLB.isUsable() || !NewUB.isUsable())
7760     return nullptr;
7761 
7762   ExprResult CondExpr =
7763       SemaRef.BuildBinOp(S, DefaultLoc,
7764                          TestIsLessOp.getValue() ?
7765                            (TestIsStrictOp ? BO_LT : BO_LE) :
7766                            (TestIsStrictOp ? BO_GT : BO_GE),
7767                          NewLB.get(), NewUB.get());
7768   if (CondExpr.isUsable()) {
7769     if (!SemaRef.Context.hasSameUnqualifiedType(CondExpr.get()->getType(),
7770                                                 SemaRef.Context.BoolTy))
7771       CondExpr = SemaRef.PerformImplicitConversion(
7772           CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
7773           /*AllowExplicit=*/true);
7774   }
7775 
7776   // Otherwise use original loop condition and evaluate it in runtime.
7777   return CondExpr.isUsable() ? CondExpr.get() : Cond;
7778 }
7779 
7780 /// Build reference expression to the counter be used for codegen.
7781 DeclRefExpr *OpenMPIterationSpaceChecker::buildCounterVar(
7782     llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
7783     DSAStackTy &DSA) const {
7784   auto *VD = dyn_cast<VarDecl>(LCDecl);
7785   if (!VD) {
7786     VD = SemaRef.isOpenMPCapturedDecl(LCDecl);
7787     DeclRefExpr *Ref = buildDeclRefExpr(
7788         SemaRef, VD, VD->getType().getNonReferenceType(), DefaultLoc);
7789     const DSAStackTy::DSAVarData Data =
7790         DSA.getTopDSA(LCDecl, /*FromParent=*/false);
7791     // If the loop control decl is explicitly marked as private, do not mark it
7792     // as captured again.
7793     if (!isOpenMPPrivate(Data.CKind) || !Data.RefExpr)
7794       Captures.insert(std::make_pair(LCRef, Ref));
7795     return Ref;
7796   }
7797   return cast<DeclRefExpr>(LCRef);
7798 }
7799 
7800 Expr *OpenMPIterationSpaceChecker::buildPrivateCounterVar() const {
7801   if (LCDecl && !LCDecl->isInvalidDecl()) {
7802     QualType Type = LCDecl->getType().getNonReferenceType();
7803     VarDecl *PrivateVar = buildVarDecl(
7804         SemaRef, DefaultLoc, Type, LCDecl->getName(),
7805         LCDecl->hasAttrs() ? &LCDecl->getAttrs() : nullptr,
7806         isa<VarDecl>(LCDecl)
7807             ? buildDeclRefExpr(SemaRef, cast<VarDecl>(LCDecl), Type, DefaultLoc)
7808             : nullptr);
7809     if (PrivateVar->isInvalidDecl())
7810       return nullptr;
7811     return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc);
7812   }
7813   return nullptr;
7814 }
7815 
7816 /// Build initialization of the counter to be used for codegen.
7817 Expr *OpenMPIterationSpaceChecker::buildCounterInit() const { return LB; }
7818 
7819 /// Build step of the counter be used for codegen.
7820 Expr *OpenMPIterationSpaceChecker::buildCounterStep() const { return Step; }
7821 
7822 Expr *OpenMPIterationSpaceChecker::buildOrderedLoopData(
7823     Scope *S, Expr *Counter,
7824     llvm::MapVector<const Expr *, DeclRefExpr *> &Captures, SourceLocation Loc,
7825     Expr *Inc, OverloadedOperatorKind OOK) {
7826   Expr *Cnt = SemaRef.DefaultLvalueConversion(Counter).get();
7827   if (!Cnt)
7828     return nullptr;
7829   if (Inc) {
7830     assert((OOK == OO_Plus || OOK == OO_Minus) &&
7831            "Expected only + or - operations for depend clauses.");
7832     BinaryOperatorKind BOK = (OOK == OO_Plus) ? BO_Add : BO_Sub;
7833     Cnt = SemaRef.BuildBinOp(S, Loc, BOK, Cnt, Inc).get();
7834     if (!Cnt)
7835       return nullptr;
7836   }
7837   QualType VarType = LCDecl->getType().getNonReferenceType();
7838   if (!VarType->isIntegerType() && !VarType->isPointerType() &&
7839       !SemaRef.getLangOpts().CPlusPlus)
7840     return nullptr;
7841   // Upper - Lower
7842   Expr *Upper = TestIsLessOp.getValue()
7843                     ? Cnt
7844                     : tryBuildCapture(SemaRef, LB, Captures).get();
7845   Expr *Lower = TestIsLessOp.getValue()
7846                     ? tryBuildCapture(SemaRef, LB, Captures).get()
7847                     : Cnt;
7848   if (!Upper || !Lower)
7849     return nullptr;
7850 
7851   ExprResult Diff = calculateNumIters(SemaRef, S, DefaultLoc, Lower, Upper,
7852                                       Step, VarType, /*TestIsStrictOp=*/false,
7853                                       /*RoundToStep=*/false, Captures);
7854   if (!Diff.isUsable())
7855     return nullptr;
7856 
7857   return Diff.get();
7858 }
7859 } // namespace
7860 
7861 void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) {
7862   assert(getLangOpts().OpenMP && "OpenMP is not active.");
7863   assert(Init && "Expected loop in canonical form.");
7864   unsigned AssociatedLoops = DSAStack->getAssociatedLoops();
7865   if (AssociatedLoops > 0 &&
7866       isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
7867     DSAStack->loopStart();
7868     OpenMPIterationSpaceChecker ISC(*this, *DSAStack, ForLoc);
7869     if (!ISC.checkAndSetInit(Init, /*EmitDiags=*/false)) {
7870       if (ValueDecl *D = ISC.getLoopDecl()) {
7871         auto *VD = dyn_cast<VarDecl>(D);
7872         DeclRefExpr *PrivateRef = nullptr;
7873         if (!VD) {
7874           if (VarDecl *Private = isOpenMPCapturedDecl(D)) {
7875             VD = Private;
7876           } else {
7877             PrivateRef = buildCapture(*this, D, ISC.getLoopDeclRefExpr(),
7878                                       /*WithInit=*/false);
7879             VD = cast<VarDecl>(PrivateRef->getDecl());
7880           }
7881         }
7882         DSAStack->addLoopControlVariable(D, VD);
7883         const Decl *LD = DSAStack->getPossiblyLoopCunter();
7884         if (LD != D->getCanonicalDecl()) {
7885           DSAStack->resetPossibleLoopCounter();
7886           if (auto *Var = dyn_cast_or_null<VarDecl>(LD))
7887             MarkDeclarationsReferencedInExpr(
7888                 buildDeclRefExpr(*this, const_cast<VarDecl *>(Var),
7889                                  Var->getType().getNonLValueExprType(Context),
7890                                  ForLoc, /*RefersToCapture=*/true));
7891         }
7892         OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
7893         // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables
7894         // Referenced in a Construct, C/C++]. The loop iteration variable in the
7895         // associated for-loop of a simd construct with just one associated
7896         // for-loop may be listed in a linear clause with a constant-linear-step
7897         // that is the increment of the associated for-loop. The loop iteration
7898         // variable(s) in the associated for-loop(s) of a for or parallel for
7899         // construct may be listed in a private or lastprivate clause.
7900         DSAStackTy::DSAVarData DVar =
7901             DSAStack->getTopDSA(D, /*FromParent=*/false);
7902         // If LoopVarRefExpr is nullptr it means the corresponding loop variable
7903         // is declared in the loop and it is predetermined as a private.
7904         Expr *LoopDeclRefExpr = ISC.getLoopDeclRefExpr();
7905         OpenMPClauseKind PredeterminedCKind =
7906             isOpenMPSimdDirective(DKind)
7907                 ? (DSAStack->hasMutipleLoops() ? OMPC_lastprivate : OMPC_linear)
7908                 : OMPC_private;
7909         if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
7910               DVar.CKind != PredeterminedCKind && DVar.RefExpr &&
7911               (LangOpts.OpenMP <= 45 || (DVar.CKind != OMPC_lastprivate &&
7912                                          DVar.CKind != OMPC_private))) ||
7913              ((isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop ||
7914                DKind == OMPD_master_taskloop ||
7915                DKind == OMPD_parallel_master_taskloop ||
7916                isOpenMPDistributeDirective(DKind)) &&
7917               !isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
7918               DVar.CKind != OMPC_private && DVar.CKind != OMPC_lastprivate)) &&
7919             (DVar.CKind != OMPC_private || DVar.RefExpr)) {
7920           Diag(Init->getBeginLoc(), diag::err_omp_loop_var_dsa)
7921               << getOpenMPClauseName(DVar.CKind)
7922               << getOpenMPDirectiveName(DKind)
7923               << getOpenMPClauseName(PredeterminedCKind);
7924           if (DVar.RefExpr == nullptr)
7925             DVar.CKind = PredeterminedCKind;
7926           reportOriginalDsa(*this, DSAStack, D, DVar,
7927                             /*IsLoopIterVar=*/true);
7928         } else if (LoopDeclRefExpr) {
7929           // Make the loop iteration variable private (for worksharing
7930           // constructs), linear (for simd directives with the only one
7931           // associated loop) or lastprivate (for simd directives with several
7932           // collapsed or ordered loops).
7933           if (DVar.CKind == OMPC_unknown)
7934             DSAStack->addDSA(D, LoopDeclRefExpr, PredeterminedCKind,
7935                              PrivateRef);
7936         }
7937       }
7938     }
7939     DSAStack->setAssociatedLoops(AssociatedLoops - 1);
7940   }
7941 }
7942 
7943 /// Called on a for stmt to check and extract its iteration space
7944 /// for further processing (such as collapsing).
7945 static bool checkOpenMPIterationSpace(
7946     OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA,
7947     unsigned CurrentNestedLoopCount, unsigned NestedLoopCount,
7948     unsigned TotalNestedLoopCount, Expr *CollapseLoopCountExpr,
7949     Expr *OrderedLoopCountExpr,
7950     Sema::VarsWithInheritedDSAType &VarsWithImplicitDSA,
7951     llvm::MutableArrayRef<LoopIterationSpace> ResultIterSpaces,
7952     llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
7953   // OpenMP [2.9.1, Canonical Loop Form]
7954   //   for (init-expr; test-expr; incr-expr) structured-block
7955   //   for (range-decl: range-expr) structured-block
7956   auto *For = dyn_cast_or_null<ForStmt>(S);
7957   auto *CXXFor = dyn_cast_or_null<CXXForRangeStmt>(S);
7958   // Ranged for is supported only in OpenMP 5.0.
7959   if (!For && (SemaRef.LangOpts.OpenMP <= 45 || !CXXFor)) {
7960     SemaRef.Diag(S->getBeginLoc(), diag::err_omp_not_for)
7961         << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr)
7962         << getOpenMPDirectiveName(DKind) << TotalNestedLoopCount
7963         << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount;
7964     if (TotalNestedLoopCount > 1) {
7965       if (CollapseLoopCountExpr && OrderedLoopCountExpr)
7966         SemaRef.Diag(DSA.getConstructLoc(),
7967                      diag::note_omp_collapse_ordered_expr)
7968             << 2 << CollapseLoopCountExpr->getSourceRange()
7969             << OrderedLoopCountExpr->getSourceRange();
7970       else if (CollapseLoopCountExpr)
7971         SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
7972                      diag::note_omp_collapse_ordered_expr)
7973             << 0 << CollapseLoopCountExpr->getSourceRange();
7974       else
7975         SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
7976                      diag::note_omp_collapse_ordered_expr)
7977             << 1 << OrderedLoopCountExpr->getSourceRange();
7978     }
7979     return true;
7980   }
7981   assert(((For && For->getBody()) || (CXXFor && CXXFor->getBody())) &&
7982          "No loop body.");
7983 
7984   OpenMPIterationSpaceChecker ISC(SemaRef, DSA,
7985                                   For ? For->getForLoc() : CXXFor->getForLoc());
7986 
7987   // Check init.
7988   Stmt *Init = For ? For->getInit() : CXXFor->getBeginStmt();
7989   if (ISC.checkAndSetInit(Init))
7990     return true;
7991 
7992   bool HasErrors = false;
7993 
7994   // Check loop variable's type.
7995   if (ValueDecl *LCDecl = ISC.getLoopDecl()) {
7996     // OpenMP [2.6, Canonical Loop Form]
7997     // Var is one of the following:
7998     //   A variable of signed or unsigned integer type.
7999     //   For C++, a variable of a random access iterator type.
8000     //   For C, a variable of a pointer type.
8001     QualType VarType = LCDecl->getType().getNonReferenceType();
8002     if (!VarType->isDependentType() && !VarType->isIntegerType() &&
8003         !VarType->isPointerType() &&
8004         !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) {
8005       SemaRef.Diag(Init->getBeginLoc(), diag::err_omp_loop_variable_type)
8006           << SemaRef.getLangOpts().CPlusPlus;
8007       HasErrors = true;
8008     }
8009 
8010     // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in
8011     // a Construct
8012     // The loop iteration variable(s) in the associated for-loop(s) of a for or
8013     // parallel for construct is (are) private.
8014     // The loop iteration variable in the associated for-loop of a simd
8015     // construct with just one associated for-loop is linear with a
8016     // constant-linear-step that is the increment of the associated for-loop.
8017     // Exclude loop var from the list of variables with implicitly defined data
8018     // sharing attributes.
8019     VarsWithImplicitDSA.erase(LCDecl);
8020 
8021     assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars");
8022 
8023     // Check test-expr.
8024     HasErrors |= ISC.checkAndSetCond(For ? For->getCond() : CXXFor->getCond());
8025 
8026     // Check incr-expr.
8027     HasErrors |= ISC.checkAndSetInc(For ? For->getInc() : CXXFor->getInc());
8028   }
8029 
8030   if (ISC.dependent() || SemaRef.CurContext->isDependentContext() || HasErrors)
8031     return HasErrors;
8032 
8033   // Build the loop's iteration space representation.
8034   ResultIterSpaces[CurrentNestedLoopCount].PreCond = ISC.buildPreCond(
8035       DSA.getCurScope(), For ? For->getCond() : CXXFor->getCond(), Captures);
8036   ResultIterSpaces[CurrentNestedLoopCount].NumIterations =
8037       ISC.buildNumIterations(DSA.getCurScope(), ResultIterSpaces,
8038                              (isOpenMPWorksharingDirective(DKind) ||
8039                               isOpenMPTaskLoopDirective(DKind) ||
8040                               isOpenMPDistributeDirective(DKind)),
8041                              Captures);
8042   ResultIterSpaces[CurrentNestedLoopCount].CounterVar =
8043       ISC.buildCounterVar(Captures, DSA);
8044   ResultIterSpaces[CurrentNestedLoopCount].PrivateCounterVar =
8045       ISC.buildPrivateCounterVar();
8046   ResultIterSpaces[CurrentNestedLoopCount].CounterInit = ISC.buildCounterInit();
8047   ResultIterSpaces[CurrentNestedLoopCount].CounterStep = ISC.buildCounterStep();
8048   ResultIterSpaces[CurrentNestedLoopCount].InitSrcRange = ISC.getInitSrcRange();
8049   ResultIterSpaces[CurrentNestedLoopCount].CondSrcRange =
8050       ISC.getConditionSrcRange();
8051   ResultIterSpaces[CurrentNestedLoopCount].IncSrcRange =
8052       ISC.getIncrementSrcRange();
8053   ResultIterSpaces[CurrentNestedLoopCount].Subtract = ISC.shouldSubtractStep();
8054   ResultIterSpaces[CurrentNestedLoopCount].IsStrictCompare =
8055       ISC.isStrictTestOp();
8056   std::tie(ResultIterSpaces[CurrentNestedLoopCount].MinValue,
8057            ResultIterSpaces[CurrentNestedLoopCount].MaxValue) =
8058       ISC.buildMinMaxValues(DSA.getCurScope(), Captures);
8059   ResultIterSpaces[CurrentNestedLoopCount].FinalCondition =
8060       ISC.buildFinalCondition(DSA.getCurScope());
8061   ResultIterSpaces[CurrentNestedLoopCount].IsNonRectangularLB =
8062       ISC.doesInitDependOnLC();
8063   ResultIterSpaces[CurrentNestedLoopCount].IsNonRectangularUB =
8064       ISC.doesCondDependOnLC();
8065   ResultIterSpaces[CurrentNestedLoopCount].LoopDependentIdx =
8066       ISC.getLoopDependentIdx();
8067 
8068   HasErrors |=
8069       (ResultIterSpaces[CurrentNestedLoopCount].PreCond == nullptr ||
8070        ResultIterSpaces[CurrentNestedLoopCount].NumIterations == nullptr ||
8071        ResultIterSpaces[CurrentNestedLoopCount].CounterVar == nullptr ||
8072        ResultIterSpaces[CurrentNestedLoopCount].PrivateCounterVar == nullptr ||
8073        ResultIterSpaces[CurrentNestedLoopCount].CounterInit == nullptr ||
8074        ResultIterSpaces[CurrentNestedLoopCount].CounterStep == nullptr);
8075   if (!HasErrors && DSA.isOrderedRegion()) {
8076     if (DSA.getOrderedRegionParam().second->getNumForLoops()) {
8077       if (CurrentNestedLoopCount <
8078           DSA.getOrderedRegionParam().second->getLoopNumIterations().size()) {
8079         DSA.getOrderedRegionParam().second->setLoopNumIterations(
8080             CurrentNestedLoopCount,
8081             ResultIterSpaces[CurrentNestedLoopCount].NumIterations);
8082         DSA.getOrderedRegionParam().second->setLoopCounter(
8083             CurrentNestedLoopCount,
8084             ResultIterSpaces[CurrentNestedLoopCount].CounterVar);
8085       }
8086     }
8087     for (auto &Pair : DSA.getDoacrossDependClauses()) {
8088       if (CurrentNestedLoopCount >= Pair.first->getNumLoops()) {
8089         // Erroneous case - clause has some problems.
8090         continue;
8091       }
8092       if (Pair.first->getDependencyKind() == OMPC_DEPEND_sink &&
8093           Pair.second.size() <= CurrentNestedLoopCount) {
8094         // Erroneous case - clause has some problems.
8095         Pair.first->setLoopData(CurrentNestedLoopCount, nullptr);
8096         continue;
8097       }
8098       Expr *CntValue;
8099       if (Pair.first->getDependencyKind() == OMPC_DEPEND_source)
8100         CntValue = ISC.buildOrderedLoopData(
8101             DSA.getCurScope(),
8102             ResultIterSpaces[CurrentNestedLoopCount].CounterVar, Captures,
8103             Pair.first->getDependencyLoc());
8104       else
8105         CntValue = ISC.buildOrderedLoopData(
8106             DSA.getCurScope(),
8107             ResultIterSpaces[CurrentNestedLoopCount].CounterVar, Captures,
8108             Pair.first->getDependencyLoc(),
8109             Pair.second[CurrentNestedLoopCount].first,
8110             Pair.second[CurrentNestedLoopCount].second);
8111       Pair.first->setLoopData(CurrentNestedLoopCount, CntValue);
8112     }
8113   }
8114 
8115   return HasErrors;
8116 }
8117 
8118 /// Build 'VarRef = Start.
8119 static ExprResult
8120 buildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
8121                  ExprResult Start, bool IsNonRectangularLB,
8122                  llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
8123   // Build 'VarRef = Start.
8124   ExprResult NewStart = IsNonRectangularLB
8125                             ? Start.get()
8126                             : tryBuildCapture(SemaRef, Start.get(), Captures);
8127   if (!NewStart.isUsable())
8128     return ExprError();
8129   if (!SemaRef.Context.hasSameType(NewStart.get()->getType(),
8130                                    VarRef.get()->getType())) {
8131     NewStart = SemaRef.PerformImplicitConversion(
8132         NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting,
8133         /*AllowExplicit=*/true);
8134     if (!NewStart.isUsable())
8135       return ExprError();
8136   }
8137 
8138   ExprResult Init =
8139       SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
8140   return Init;
8141 }
8142 
8143 /// Build 'VarRef = Start + Iter * Step'.
8144 static ExprResult buildCounterUpdate(
8145     Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
8146     ExprResult Start, ExprResult Iter, ExprResult Step, bool Subtract,
8147     bool IsNonRectangularLB,
8148     llvm::MapVector<const Expr *, DeclRefExpr *> *Captures = nullptr) {
8149   // Add parentheses (for debugging purposes only).
8150   Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get());
8151   if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() ||
8152       !Step.isUsable())
8153     return ExprError();
8154 
8155   ExprResult NewStep = Step;
8156   if (Captures)
8157     NewStep = tryBuildCapture(SemaRef, Step.get(), *Captures);
8158   if (NewStep.isInvalid())
8159     return ExprError();
8160   ExprResult Update =
8161       SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get());
8162   if (!Update.isUsable())
8163     return ExprError();
8164 
8165   // Try to build 'VarRef = Start, VarRef (+|-)= Iter * Step' or
8166   // 'VarRef = Start (+|-) Iter * Step'.
8167   if (!Start.isUsable())
8168     return ExprError();
8169   ExprResult NewStart = SemaRef.ActOnParenExpr(Loc, Loc, Start.get());
8170   if (!NewStart.isUsable())
8171     return ExprError();
8172   if (Captures && !IsNonRectangularLB)
8173     NewStart = tryBuildCapture(SemaRef, Start.get(), *Captures);
8174   if (NewStart.isInvalid())
8175     return ExprError();
8176 
8177   // First attempt: try to build 'VarRef = Start, VarRef += Iter * Step'.
8178   ExprResult SavedUpdate = Update;
8179   ExprResult UpdateVal;
8180   if (VarRef.get()->getType()->isOverloadableType() ||
8181       NewStart.get()->getType()->isOverloadableType() ||
8182       Update.get()->getType()->isOverloadableType()) {
8183     Sema::TentativeAnalysisScope Trap(SemaRef);
8184 
8185     Update =
8186         SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
8187     if (Update.isUsable()) {
8188       UpdateVal =
8189           SemaRef.BuildBinOp(S, Loc, Subtract ? BO_SubAssign : BO_AddAssign,
8190                              VarRef.get(), SavedUpdate.get());
8191       if (UpdateVal.isUsable()) {
8192         Update = SemaRef.CreateBuiltinBinOp(Loc, BO_Comma, Update.get(),
8193                                             UpdateVal.get());
8194       }
8195     }
8196   }
8197 
8198   // Second attempt: try to build 'VarRef = Start (+|-) Iter * Step'.
8199   if (!Update.isUsable() || !UpdateVal.isUsable()) {
8200     Update = SemaRef.BuildBinOp(S, Loc, Subtract ? BO_Sub : BO_Add,
8201                                 NewStart.get(), SavedUpdate.get());
8202     if (!Update.isUsable())
8203       return ExprError();
8204 
8205     if (!SemaRef.Context.hasSameType(Update.get()->getType(),
8206                                      VarRef.get()->getType())) {
8207       Update = SemaRef.PerformImplicitConversion(
8208           Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true);
8209       if (!Update.isUsable())
8210         return ExprError();
8211     }
8212 
8213     Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get());
8214   }
8215   return Update;
8216 }
8217 
8218 /// Convert integer expression \a E to make it have at least \a Bits
8219 /// bits.
8220 static ExprResult widenIterationCount(unsigned Bits, Expr *E, Sema &SemaRef) {
8221   if (E == nullptr)
8222     return ExprError();
8223   ASTContext &C = SemaRef.Context;
8224   QualType OldType = E->getType();
8225   unsigned HasBits = C.getTypeSize(OldType);
8226   if (HasBits >= Bits)
8227     return ExprResult(E);
8228   // OK to convert to signed, because new type has more bits than old.
8229   QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true);
8230   return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting,
8231                                            true);
8232 }
8233 
8234 /// Check if the given expression \a E is a constant integer that fits
8235 /// into \a Bits bits.
8236 static bool fitsInto(unsigned Bits, bool Signed, const Expr *E, Sema &SemaRef) {
8237   if (E == nullptr)
8238     return false;
8239   if (Optional<llvm::APSInt> Result =
8240           E->getIntegerConstantExpr(SemaRef.Context))
8241     return Signed ? Result->isSignedIntN(Bits) : Result->isIntN(Bits);
8242   return false;
8243 }
8244 
8245 /// Build preinits statement for the given declarations.
8246 static Stmt *buildPreInits(ASTContext &Context,
8247                            MutableArrayRef<Decl *> PreInits) {
8248   if (!PreInits.empty()) {
8249     return new (Context) DeclStmt(
8250         DeclGroupRef::Create(Context, PreInits.begin(), PreInits.size()),
8251         SourceLocation(), SourceLocation());
8252   }
8253   return nullptr;
8254 }
8255 
8256 /// Build preinits statement for the given declarations.
8257 static Stmt *
8258 buildPreInits(ASTContext &Context,
8259               const llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
8260   if (!Captures.empty()) {
8261     SmallVector<Decl *, 16> PreInits;
8262     for (const auto &Pair : Captures)
8263       PreInits.push_back(Pair.second->getDecl());
8264     return buildPreInits(Context, PreInits);
8265   }
8266   return nullptr;
8267 }
8268 
8269 /// Build postupdate expression for the given list of postupdates expressions.
8270 static Expr *buildPostUpdate(Sema &S, ArrayRef<Expr *> PostUpdates) {
8271   Expr *PostUpdate = nullptr;
8272   if (!PostUpdates.empty()) {
8273     for (Expr *E : PostUpdates) {
8274       Expr *ConvE = S.BuildCStyleCastExpr(
8275                          E->getExprLoc(),
8276                          S.Context.getTrivialTypeSourceInfo(S.Context.VoidTy),
8277                          E->getExprLoc(), E)
8278                         .get();
8279       PostUpdate = PostUpdate
8280                        ? S.CreateBuiltinBinOp(ConvE->getExprLoc(), BO_Comma,
8281                                               PostUpdate, ConvE)
8282                              .get()
8283                        : ConvE;
8284     }
8285   }
8286   return PostUpdate;
8287 }
8288 
8289 /// Called on a for stmt to check itself and nested loops (if any).
8290 /// \return Returns 0 if one of the collapsed stmts is not canonical for loop,
8291 /// number of collapsed loops otherwise.
8292 static unsigned
8293 checkOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr,
8294                 Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef,
8295                 DSAStackTy &DSA,
8296                 Sema::VarsWithInheritedDSAType &VarsWithImplicitDSA,
8297                 OMPLoopDirective::HelperExprs &Built) {
8298   unsigned NestedLoopCount = 1;
8299   if (CollapseLoopCountExpr) {
8300     // Found 'collapse' clause - calculate collapse number.
8301     Expr::EvalResult Result;
8302     if (!CollapseLoopCountExpr->isValueDependent() &&
8303         CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext())) {
8304       NestedLoopCount = Result.Val.getInt().getLimitedValue();
8305     } else {
8306       Built.clear(/*Size=*/1);
8307       return 1;
8308     }
8309   }
8310   unsigned OrderedLoopCount = 1;
8311   if (OrderedLoopCountExpr) {
8312     // Found 'ordered' clause - calculate collapse number.
8313     Expr::EvalResult EVResult;
8314     if (!OrderedLoopCountExpr->isValueDependent() &&
8315         OrderedLoopCountExpr->EvaluateAsInt(EVResult,
8316                                             SemaRef.getASTContext())) {
8317       llvm::APSInt Result = EVResult.Val.getInt();
8318       if (Result.getLimitedValue() < NestedLoopCount) {
8319         SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
8320                      diag::err_omp_wrong_ordered_loop_count)
8321             << OrderedLoopCountExpr->getSourceRange();
8322         SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
8323                      diag::note_collapse_loop_count)
8324             << CollapseLoopCountExpr->getSourceRange();
8325       }
8326       OrderedLoopCount = Result.getLimitedValue();
8327     } else {
8328       Built.clear(/*Size=*/1);
8329       return 1;
8330     }
8331   }
8332   // This is helper routine for loop directives (e.g., 'for', 'simd',
8333   // 'for simd', etc.).
8334   llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
8335   SmallVector<LoopIterationSpace, 4> IterSpaces(
8336       std::max(OrderedLoopCount, NestedLoopCount));
8337   Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true);
8338   for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
8339     if (checkOpenMPIterationSpace(
8340             DKind, CurStmt, SemaRef, DSA, Cnt, NestedLoopCount,
8341             std::max(OrderedLoopCount, NestedLoopCount), CollapseLoopCountExpr,
8342             OrderedLoopCountExpr, VarsWithImplicitDSA, IterSpaces, Captures))
8343       return 0;
8344     // Move on to the next nested for loop, or to the loop body.
8345     // OpenMP [2.8.1, simd construct, Restrictions]
8346     // All loops associated with the construct must be perfectly nested; that
8347     // is, there must be no intervening code nor any OpenMP directive between
8348     // any two loops.
8349     if (auto *For = dyn_cast<ForStmt>(CurStmt)) {
8350       CurStmt = For->getBody();
8351     } else {
8352       assert(isa<CXXForRangeStmt>(CurStmt) &&
8353              "Expected canonical for or range-based for loops.");
8354       CurStmt = cast<CXXForRangeStmt>(CurStmt)->getBody();
8355     }
8356     CurStmt = OMPLoopDirective::tryToFindNextInnerLoop(
8357         CurStmt, SemaRef.LangOpts.OpenMP >= 50);
8358   }
8359   for (unsigned Cnt = NestedLoopCount; Cnt < OrderedLoopCount; ++Cnt) {
8360     if (checkOpenMPIterationSpace(
8361             DKind, CurStmt, SemaRef, DSA, Cnt, NestedLoopCount,
8362             std::max(OrderedLoopCount, NestedLoopCount), CollapseLoopCountExpr,
8363             OrderedLoopCountExpr, VarsWithImplicitDSA, IterSpaces, Captures))
8364       return 0;
8365     if (Cnt > 0 && IterSpaces[Cnt].CounterVar) {
8366       // Handle initialization of captured loop iterator variables.
8367       auto *DRE = cast<DeclRefExpr>(IterSpaces[Cnt].CounterVar);
8368       if (isa<OMPCapturedExprDecl>(DRE->getDecl())) {
8369         Captures[DRE] = DRE;
8370       }
8371     }
8372     // Move on to the next nested for loop, or to the loop body.
8373     // OpenMP [2.8.1, simd construct, Restrictions]
8374     // All loops associated with the construct must be perfectly nested; that
8375     // is, there must be no intervening code nor any OpenMP directive between
8376     // any two loops.
8377     if (auto *For = dyn_cast<ForStmt>(CurStmt)) {
8378       CurStmt = For->getBody();
8379     } else {
8380       assert(isa<CXXForRangeStmt>(CurStmt) &&
8381              "Expected canonical for or range-based for loops.");
8382       CurStmt = cast<CXXForRangeStmt>(CurStmt)->getBody();
8383     }
8384     CurStmt = OMPLoopDirective::tryToFindNextInnerLoop(
8385         CurStmt, SemaRef.LangOpts.OpenMP >= 50);
8386   }
8387 
8388   Built.clear(/* size */ NestedLoopCount);
8389 
8390   if (SemaRef.CurContext->isDependentContext())
8391     return NestedLoopCount;
8392 
8393   // An example of what is generated for the following code:
8394   //
8395   //   #pragma omp simd collapse(2) ordered(2)
8396   //   for (i = 0; i < NI; ++i)
8397   //     for (k = 0; k < NK; ++k)
8398   //       for (j = J0; j < NJ; j+=2) {
8399   //         <loop body>
8400   //       }
8401   //
8402   // We generate the code below.
8403   // Note: the loop body may be outlined in CodeGen.
8404   // Note: some counters may be C++ classes, operator- is used to find number of
8405   // iterations and operator+= to calculate counter value.
8406   // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32
8407   // or i64 is currently supported).
8408   //
8409   //   #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2))
8410   //   for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) {
8411   //     .local.i = IV / ((NJ - J0 - 1 + 2) / 2);
8412   //     .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2;
8413   //     // similar updates for vars in clauses (e.g. 'linear')
8414   //     <loop body (using local i and j)>
8415   //   }
8416   //   i = NI; // assign final values of counters
8417   //   j = NJ;
8418   //
8419 
8420   // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are
8421   // the iteration counts of the collapsed for loops.
8422   // Precondition tests if there is at least one iteration (all conditions are
8423   // true).
8424   auto PreCond = ExprResult(IterSpaces[0].PreCond);
8425   Expr *N0 = IterSpaces[0].NumIterations;
8426   ExprResult LastIteration32 =
8427       widenIterationCount(/*Bits=*/32,
8428                           SemaRef
8429                               .PerformImplicitConversion(
8430                                   N0->IgnoreImpCasts(), N0->getType(),
8431                                   Sema::AA_Converting, /*AllowExplicit=*/true)
8432                               .get(),
8433                           SemaRef);
8434   ExprResult LastIteration64 = widenIterationCount(
8435       /*Bits=*/64,
8436       SemaRef
8437           .PerformImplicitConversion(N0->IgnoreImpCasts(), N0->getType(),
8438                                      Sema::AA_Converting,
8439                                      /*AllowExplicit=*/true)
8440           .get(),
8441       SemaRef);
8442 
8443   if (!LastIteration32.isUsable() || !LastIteration64.isUsable())
8444     return NestedLoopCount;
8445 
8446   ASTContext &C = SemaRef.Context;
8447   bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32;
8448 
8449   Scope *CurScope = DSA.getCurScope();
8450   for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) {
8451     if (PreCond.isUsable()) {
8452       PreCond =
8453           SemaRef.BuildBinOp(CurScope, PreCond.get()->getExprLoc(), BO_LAnd,
8454                              PreCond.get(), IterSpaces[Cnt].PreCond);
8455     }
8456     Expr *N = IterSpaces[Cnt].NumIterations;
8457     SourceLocation Loc = N->getExprLoc();
8458     AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32;
8459     if (LastIteration32.isUsable())
8460       LastIteration32 = SemaRef.BuildBinOp(
8461           CurScope, Loc, BO_Mul, LastIteration32.get(),
8462           SemaRef
8463               .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
8464                                          Sema::AA_Converting,
8465                                          /*AllowExplicit=*/true)
8466               .get());
8467     if (LastIteration64.isUsable())
8468       LastIteration64 = SemaRef.BuildBinOp(
8469           CurScope, Loc, BO_Mul, LastIteration64.get(),
8470           SemaRef
8471               .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
8472                                          Sema::AA_Converting,
8473                                          /*AllowExplicit=*/true)
8474               .get());
8475   }
8476 
8477   // Choose either the 32-bit or 64-bit version.
8478   ExprResult LastIteration = LastIteration64;
8479   if (SemaRef.getLangOpts().OpenMPOptimisticCollapse ||
8480       (LastIteration32.isUsable() &&
8481        C.getTypeSize(LastIteration32.get()->getType()) == 32 &&
8482        (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 ||
8483         fitsInto(
8484             /*Bits=*/32,
8485             LastIteration32.get()->getType()->hasSignedIntegerRepresentation(),
8486             LastIteration64.get(), SemaRef))))
8487     LastIteration = LastIteration32;
8488   QualType VType = LastIteration.get()->getType();
8489   QualType RealVType = VType;
8490   QualType StrideVType = VType;
8491   if (isOpenMPTaskLoopDirective(DKind)) {
8492     VType =
8493         SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
8494     StrideVType =
8495         SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
8496   }
8497 
8498   if (!LastIteration.isUsable())
8499     return 0;
8500 
8501   // Save the number of iterations.
8502   ExprResult NumIterations = LastIteration;
8503   {
8504     LastIteration = SemaRef.BuildBinOp(
8505         CurScope, LastIteration.get()->getExprLoc(), BO_Sub,
8506         LastIteration.get(),
8507         SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
8508     if (!LastIteration.isUsable())
8509       return 0;
8510   }
8511 
8512   // Calculate the last iteration number beforehand instead of doing this on
8513   // each iteration. Do not do this if the number of iterations may be kfold-ed.
8514   bool IsConstant = LastIteration.get()->isIntegerConstantExpr(SemaRef.Context);
8515   ExprResult CalcLastIteration;
8516   if (!IsConstant) {
8517     ExprResult SaveRef =
8518         tryBuildCapture(SemaRef, LastIteration.get(), Captures);
8519     LastIteration = SaveRef;
8520 
8521     // Prepare SaveRef + 1.
8522     NumIterations = SemaRef.BuildBinOp(
8523         CurScope, SaveRef.get()->getExprLoc(), BO_Add, SaveRef.get(),
8524         SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
8525     if (!NumIterations.isUsable())
8526       return 0;
8527   }
8528 
8529   SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin();
8530 
8531   // Build variables passed into runtime, necessary for worksharing directives.
8532   ExprResult LB, UB, IL, ST, EUB, CombLB, CombUB, PrevLB, PrevUB, CombEUB;
8533   if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
8534       isOpenMPDistributeDirective(DKind)) {
8535     // Lower bound variable, initialized with zero.
8536     VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb");
8537     LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc);
8538     SemaRef.AddInitializerToDecl(LBDecl,
8539                                  SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
8540                                  /*DirectInit*/ false);
8541 
8542     // Upper bound variable, initialized with last iteration number.
8543     VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub");
8544     UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc);
8545     SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(),
8546                                  /*DirectInit*/ false);
8547 
8548     // A 32-bit variable-flag where runtime returns 1 for the last iteration.
8549     // This will be used to implement clause 'lastprivate'.
8550     QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true);
8551     VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last");
8552     IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc);
8553     SemaRef.AddInitializerToDecl(ILDecl,
8554                                  SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
8555                                  /*DirectInit*/ false);
8556 
8557     // Stride variable returned by runtime (we initialize it to 1 by default).
8558     VarDecl *STDecl =
8559         buildVarDecl(SemaRef, InitLoc, StrideVType, ".omp.stride");
8560     ST = buildDeclRefExpr(SemaRef, STDecl, StrideVType, InitLoc);
8561     SemaRef.AddInitializerToDecl(STDecl,
8562                                  SemaRef.ActOnIntegerConstant(InitLoc, 1).get(),
8563                                  /*DirectInit*/ false);
8564 
8565     // Build expression: UB = min(UB, LastIteration)
8566     // It is necessary for CodeGen of directives with static scheduling.
8567     ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT,
8568                                                 UB.get(), LastIteration.get());
8569     ExprResult CondOp = SemaRef.ActOnConditionalOp(
8570         LastIteration.get()->getExprLoc(), InitLoc, IsUBGreater.get(),
8571         LastIteration.get(), UB.get());
8572     EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(),
8573                              CondOp.get());
8574     EUB = SemaRef.ActOnFinishFullExpr(EUB.get(), /*DiscardedValue*/ false);
8575 
8576     // If we have a combined directive that combines 'distribute', 'for' or
8577     // 'simd' we need to be able to access the bounds of the schedule of the
8578     // enclosing region. E.g. in 'distribute parallel for' the bounds obtained
8579     // by scheduling 'distribute' have to be passed to the schedule of 'for'.
8580     if (isOpenMPLoopBoundSharingDirective(DKind)) {
8581       // Lower bound variable, initialized with zero.
8582       VarDecl *CombLBDecl =
8583           buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.lb");
8584       CombLB = buildDeclRefExpr(SemaRef, CombLBDecl, VType, InitLoc);
8585       SemaRef.AddInitializerToDecl(
8586           CombLBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
8587           /*DirectInit*/ false);
8588 
8589       // Upper bound variable, initialized with last iteration number.
8590       VarDecl *CombUBDecl =
8591           buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.ub");
8592       CombUB = buildDeclRefExpr(SemaRef, CombUBDecl, VType, InitLoc);
8593       SemaRef.AddInitializerToDecl(CombUBDecl, LastIteration.get(),
8594                                    /*DirectInit*/ false);
8595 
8596       ExprResult CombIsUBGreater = SemaRef.BuildBinOp(
8597           CurScope, InitLoc, BO_GT, CombUB.get(), LastIteration.get());
8598       ExprResult CombCondOp =
8599           SemaRef.ActOnConditionalOp(InitLoc, InitLoc, CombIsUBGreater.get(),
8600                                      LastIteration.get(), CombUB.get());
8601       CombEUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, CombUB.get(),
8602                                    CombCondOp.get());
8603       CombEUB =
8604           SemaRef.ActOnFinishFullExpr(CombEUB.get(), /*DiscardedValue*/ false);
8605 
8606       const CapturedDecl *CD = cast<CapturedStmt>(AStmt)->getCapturedDecl();
8607       // We expect to have at least 2 more parameters than the 'parallel'
8608       // directive does - the lower and upper bounds of the previous schedule.
8609       assert(CD->getNumParams() >= 4 &&
8610              "Unexpected number of parameters in loop combined directive");
8611 
8612       // Set the proper type for the bounds given what we learned from the
8613       // enclosed loops.
8614       ImplicitParamDecl *PrevLBDecl = CD->getParam(/*PrevLB=*/2);
8615       ImplicitParamDecl *PrevUBDecl = CD->getParam(/*PrevUB=*/3);
8616 
8617       // Previous lower and upper bounds are obtained from the region
8618       // parameters.
8619       PrevLB =
8620           buildDeclRefExpr(SemaRef, PrevLBDecl, PrevLBDecl->getType(), InitLoc);
8621       PrevUB =
8622           buildDeclRefExpr(SemaRef, PrevUBDecl, PrevUBDecl->getType(), InitLoc);
8623     }
8624   }
8625 
8626   // Build the iteration variable and its initialization before loop.
8627   ExprResult IV;
8628   ExprResult Init, CombInit;
8629   {
8630     VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, RealVType, ".omp.iv");
8631     IV = buildDeclRefExpr(SemaRef, IVDecl, RealVType, InitLoc);
8632     Expr *RHS =
8633         (isOpenMPWorksharingDirective(DKind) ||
8634          isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
8635             ? LB.get()
8636             : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
8637     Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS);
8638     Init = SemaRef.ActOnFinishFullExpr(Init.get(), /*DiscardedValue*/ false);
8639 
8640     if (isOpenMPLoopBoundSharingDirective(DKind)) {
8641       Expr *CombRHS =
8642           (isOpenMPWorksharingDirective(DKind) ||
8643            isOpenMPTaskLoopDirective(DKind) ||
8644            isOpenMPDistributeDirective(DKind))
8645               ? CombLB.get()
8646               : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
8647       CombInit =
8648           SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), CombRHS);
8649       CombInit =
8650           SemaRef.ActOnFinishFullExpr(CombInit.get(), /*DiscardedValue*/ false);
8651     }
8652   }
8653 
8654   bool UseStrictCompare =
8655       RealVType->hasUnsignedIntegerRepresentation() &&
8656       llvm::all_of(IterSpaces, [](const LoopIterationSpace &LIS) {
8657         return LIS.IsStrictCompare;
8658       });
8659   // Loop condition (IV < NumIterations) or (IV <= UB or IV < UB + 1 (for
8660   // unsigned IV)) for worksharing loops.
8661   SourceLocation CondLoc = AStmt->getBeginLoc();
8662   Expr *BoundUB = UB.get();
8663   if (UseStrictCompare) {
8664     BoundUB =
8665         SemaRef
8666             .BuildBinOp(CurScope, CondLoc, BO_Add, BoundUB,
8667                         SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
8668             .get();
8669     BoundUB =
8670         SemaRef.ActOnFinishFullExpr(BoundUB, /*DiscardedValue*/ false).get();
8671   }
8672   ExprResult Cond =
8673       (isOpenMPWorksharingDirective(DKind) ||
8674        isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
8675           ? SemaRef.BuildBinOp(CurScope, CondLoc,
8676                                UseStrictCompare ? BO_LT : BO_LE, IV.get(),
8677                                BoundUB)
8678           : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
8679                                NumIterations.get());
8680   ExprResult CombDistCond;
8681   if (isOpenMPLoopBoundSharingDirective(DKind)) {
8682     CombDistCond = SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
8683                                       NumIterations.get());
8684   }
8685 
8686   ExprResult CombCond;
8687   if (isOpenMPLoopBoundSharingDirective(DKind)) {
8688     Expr *BoundCombUB = CombUB.get();
8689     if (UseStrictCompare) {
8690       BoundCombUB =
8691           SemaRef
8692               .BuildBinOp(
8693                   CurScope, CondLoc, BO_Add, BoundCombUB,
8694                   SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
8695               .get();
8696       BoundCombUB =
8697           SemaRef.ActOnFinishFullExpr(BoundCombUB, /*DiscardedValue*/ false)
8698               .get();
8699     }
8700     CombCond =
8701         SemaRef.BuildBinOp(CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE,
8702                            IV.get(), BoundCombUB);
8703   }
8704   // Loop increment (IV = IV + 1)
8705   SourceLocation IncLoc = AStmt->getBeginLoc();
8706   ExprResult Inc =
8707       SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(),
8708                          SemaRef.ActOnIntegerConstant(IncLoc, 1).get());
8709   if (!Inc.isUsable())
8710     return 0;
8711   Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get());
8712   Inc = SemaRef.ActOnFinishFullExpr(Inc.get(), /*DiscardedValue*/ false);
8713   if (!Inc.isUsable())
8714     return 0;
8715 
8716   // Increments for worksharing loops (LB = LB + ST; UB = UB + ST).
8717   // Used for directives with static scheduling.
8718   // In combined construct, add combined version that use CombLB and CombUB
8719   // base variables for the update
8720   ExprResult NextLB, NextUB, CombNextLB, CombNextUB;
8721   if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
8722       isOpenMPDistributeDirective(DKind)) {
8723     // LB + ST
8724     NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get());
8725     if (!NextLB.isUsable())
8726       return 0;
8727     // LB = LB + ST
8728     NextLB =
8729         SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get());
8730     NextLB =
8731         SemaRef.ActOnFinishFullExpr(NextLB.get(), /*DiscardedValue*/ false);
8732     if (!NextLB.isUsable())
8733       return 0;
8734     // UB + ST
8735     NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get());
8736     if (!NextUB.isUsable())
8737       return 0;
8738     // UB = UB + ST
8739     NextUB =
8740         SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get());
8741     NextUB =
8742         SemaRef.ActOnFinishFullExpr(NextUB.get(), /*DiscardedValue*/ false);
8743     if (!NextUB.isUsable())
8744       return 0;
8745     if (isOpenMPLoopBoundSharingDirective(DKind)) {
8746       CombNextLB =
8747           SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombLB.get(), ST.get());
8748       if (!NextLB.isUsable())
8749         return 0;
8750       // LB = LB + ST
8751       CombNextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombLB.get(),
8752                                       CombNextLB.get());
8753       CombNextLB = SemaRef.ActOnFinishFullExpr(CombNextLB.get(),
8754                                                /*DiscardedValue*/ false);
8755       if (!CombNextLB.isUsable())
8756         return 0;
8757       // UB + ST
8758       CombNextUB =
8759           SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombUB.get(), ST.get());
8760       if (!CombNextUB.isUsable())
8761         return 0;
8762       // UB = UB + ST
8763       CombNextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombUB.get(),
8764                                       CombNextUB.get());
8765       CombNextUB = SemaRef.ActOnFinishFullExpr(CombNextUB.get(),
8766                                                /*DiscardedValue*/ false);
8767       if (!CombNextUB.isUsable())
8768         return 0;
8769     }
8770   }
8771 
8772   // Create increment expression for distribute loop when combined in a same
8773   // directive with for as IV = IV + ST; ensure upper bound expression based
8774   // on PrevUB instead of NumIterations - used to implement 'for' when found
8775   // in combination with 'distribute', like in 'distribute parallel for'
8776   SourceLocation DistIncLoc = AStmt->getBeginLoc();
8777   ExprResult DistCond, DistInc, PrevEUB, ParForInDistCond;
8778   if (isOpenMPLoopBoundSharingDirective(DKind)) {
8779     DistCond = SemaRef.BuildBinOp(
8780         CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE, IV.get(), BoundUB);
8781     assert(DistCond.isUsable() && "distribute cond expr was not built");
8782 
8783     DistInc =
8784         SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Add, IV.get(), ST.get());
8785     assert(DistInc.isUsable() && "distribute inc expr was not built");
8786     DistInc = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, IV.get(),
8787                                  DistInc.get());
8788     DistInc =
8789         SemaRef.ActOnFinishFullExpr(DistInc.get(), /*DiscardedValue*/ false);
8790     assert(DistInc.isUsable() && "distribute inc expr was not built");
8791 
8792     // Build expression: UB = min(UB, prevUB) for #for in composite or combined
8793     // construct
8794     SourceLocation DistEUBLoc = AStmt->getBeginLoc();
8795     ExprResult IsUBGreater =
8796         SemaRef.BuildBinOp(CurScope, DistEUBLoc, BO_GT, UB.get(), PrevUB.get());
8797     ExprResult CondOp = SemaRef.ActOnConditionalOp(
8798         DistEUBLoc, DistEUBLoc, IsUBGreater.get(), PrevUB.get(), UB.get());
8799     PrevEUB = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, UB.get(),
8800                                  CondOp.get());
8801     PrevEUB =
8802         SemaRef.ActOnFinishFullExpr(PrevEUB.get(), /*DiscardedValue*/ false);
8803 
8804     // Build IV <= PrevUB or IV < PrevUB + 1 for unsigned IV to be used in
8805     // parallel for is in combination with a distribute directive with
8806     // schedule(static, 1)
8807     Expr *BoundPrevUB = PrevUB.get();
8808     if (UseStrictCompare) {
8809       BoundPrevUB =
8810           SemaRef
8811               .BuildBinOp(
8812                   CurScope, CondLoc, BO_Add, BoundPrevUB,
8813                   SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
8814               .get();
8815       BoundPrevUB =
8816           SemaRef.ActOnFinishFullExpr(BoundPrevUB, /*DiscardedValue*/ false)
8817               .get();
8818     }
8819     ParForInDistCond =
8820         SemaRef.BuildBinOp(CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE,
8821                            IV.get(), BoundPrevUB);
8822   }
8823 
8824   // Build updates and final values of the loop counters.
8825   bool HasErrors = false;
8826   Built.Counters.resize(NestedLoopCount);
8827   Built.Inits.resize(NestedLoopCount);
8828   Built.Updates.resize(NestedLoopCount);
8829   Built.Finals.resize(NestedLoopCount);
8830   Built.DependentCounters.resize(NestedLoopCount);
8831   Built.DependentInits.resize(NestedLoopCount);
8832   Built.FinalsConditions.resize(NestedLoopCount);
8833   {
8834     // We implement the following algorithm for obtaining the
8835     // original loop iteration variable values based on the
8836     // value of the collapsed loop iteration variable IV.
8837     //
8838     // Let n+1 be the number of collapsed loops in the nest.
8839     // Iteration variables (I0, I1, .... In)
8840     // Iteration counts (N0, N1, ... Nn)
8841     //
8842     // Acc = IV;
8843     //
8844     // To compute Ik for loop k, 0 <= k <= n, generate:
8845     //    Prod = N(k+1) * N(k+2) * ... * Nn;
8846     //    Ik = Acc / Prod;
8847     //    Acc -= Ik * Prod;
8848     //
8849     ExprResult Acc = IV;
8850     for (unsigned int Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
8851       LoopIterationSpace &IS = IterSpaces[Cnt];
8852       SourceLocation UpdLoc = IS.IncSrcRange.getBegin();
8853       ExprResult Iter;
8854 
8855       // Compute prod
8856       ExprResult Prod =
8857           SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
8858       for (unsigned int K = Cnt+1; K < NestedLoopCount; ++K)
8859         Prod = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Prod.get(),
8860                                   IterSpaces[K].NumIterations);
8861 
8862       // Iter = Acc / Prod
8863       // If there is at least one more inner loop to avoid
8864       // multiplication by 1.
8865       if (Cnt + 1 < NestedLoopCount)
8866         Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div,
8867                                   Acc.get(), Prod.get());
8868       else
8869         Iter = Acc;
8870       if (!Iter.isUsable()) {
8871         HasErrors = true;
8872         break;
8873       }
8874 
8875       // Update Acc:
8876       // Acc -= Iter * Prod
8877       // Check if there is at least one more inner loop to avoid
8878       // multiplication by 1.
8879       if (Cnt + 1 < NestedLoopCount)
8880         Prod = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul,
8881                                   Iter.get(), Prod.get());
8882       else
8883         Prod = Iter;
8884       Acc = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Sub,
8885                                Acc.get(), Prod.get());
8886 
8887       // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step
8888       auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl());
8889       DeclRefExpr *CounterVar = buildDeclRefExpr(
8890           SemaRef, VD, IS.CounterVar->getType(), IS.CounterVar->getExprLoc(),
8891           /*RefersToCapture=*/true);
8892       ExprResult Init =
8893           buildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar,
8894                            IS.CounterInit, IS.IsNonRectangularLB, Captures);
8895       if (!Init.isUsable()) {
8896         HasErrors = true;
8897         break;
8898       }
8899       ExprResult Update = buildCounterUpdate(
8900           SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, Iter,
8901           IS.CounterStep, IS.Subtract, IS.IsNonRectangularLB, &Captures);
8902       if (!Update.isUsable()) {
8903         HasErrors = true;
8904         break;
8905       }
8906 
8907       // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step
8908       ExprResult Final =
8909           buildCounterUpdate(SemaRef, CurScope, UpdLoc, CounterVar,
8910                              IS.CounterInit, IS.NumIterations, IS.CounterStep,
8911                              IS.Subtract, IS.IsNonRectangularLB, &Captures);
8912       if (!Final.isUsable()) {
8913         HasErrors = true;
8914         break;
8915       }
8916 
8917       if (!Update.isUsable() || !Final.isUsable()) {
8918         HasErrors = true;
8919         break;
8920       }
8921       // Save results
8922       Built.Counters[Cnt] = IS.CounterVar;
8923       Built.PrivateCounters[Cnt] = IS.PrivateCounterVar;
8924       Built.Inits[Cnt] = Init.get();
8925       Built.Updates[Cnt] = Update.get();
8926       Built.Finals[Cnt] = Final.get();
8927       Built.DependentCounters[Cnt] = nullptr;
8928       Built.DependentInits[Cnt] = nullptr;
8929       Built.FinalsConditions[Cnt] = nullptr;
8930       if (IS.IsNonRectangularLB || IS.IsNonRectangularUB) {
8931         Built.DependentCounters[Cnt] =
8932             Built.Counters[NestedLoopCount - 1 - IS.LoopDependentIdx];
8933         Built.DependentInits[Cnt] =
8934             Built.Inits[NestedLoopCount - 1 - IS.LoopDependentIdx];
8935         Built.FinalsConditions[Cnt] = IS.FinalCondition;
8936       }
8937     }
8938   }
8939 
8940   if (HasErrors)
8941     return 0;
8942 
8943   // Save results
8944   Built.IterationVarRef = IV.get();
8945   Built.LastIteration = LastIteration.get();
8946   Built.NumIterations = NumIterations.get();
8947   Built.CalcLastIteration = SemaRef
8948                                 .ActOnFinishFullExpr(CalcLastIteration.get(),
8949                                                      /*DiscardedValue=*/false)
8950                                 .get();
8951   Built.PreCond = PreCond.get();
8952   Built.PreInits = buildPreInits(C, Captures);
8953   Built.Cond = Cond.get();
8954   Built.Init = Init.get();
8955   Built.Inc = Inc.get();
8956   Built.LB = LB.get();
8957   Built.UB = UB.get();
8958   Built.IL = IL.get();
8959   Built.ST = ST.get();
8960   Built.EUB = EUB.get();
8961   Built.NLB = NextLB.get();
8962   Built.NUB = NextUB.get();
8963   Built.PrevLB = PrevLB.get();
8964   Built.PrevUB = PrevUB.get();
8965   Built.DistInc = DistInc.get();
8966   Built.PrevEUB = PrevEUB.get();
8967   Built.DistCombinedFields.LB = CombLB.get();
8968   Built.DistCombinedFields.UB = CombUB.get();
8969   Built.DistCombinedFields.EUB = CombEUB.get();
8970   Built.DistCombinedFields.Init = CombInit.get();
8971   Built.DistCombinedFields.Cond = CombCond.get();
8972   Built.DistCombinedFields.NLB = CombNextLB.get();
8973   Built.DistCombinedFields.NUB = CombNextUB.get();
8974   Built.DistCombinedFields.DistCond = CombDistCond.get();
8975   Built.DistCombinedFields.ParForInDistCond = ParForInDistCond.get();
8976 
8977   return NestedLoopCount;
8978 }
8979 
8980 static Expr *getCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) {
8981   auto CollapseClauses =
8982       OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses);
8983   if (CollapseClauses.begin() != CollapseClauses.end())
8984     return (*CollapseClauses.begin())->getNumForLoops();
8985   return nullptr;
8986 }
8987 
8988 static Expr *getOrderedNumberExpr(ArrayRef<OMPClause *> Clauses) {
8989   auto OrderedClauses =
8990       OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses);
8991   if (OrderedClauses.begin() != OrderedClauses.end())
8992     return (*OrderedClauses.begin())->getNumForLoops();
8993   return nullptr;
8994 }
8995 
8996 static bool checkSimdlenSafelenSpecified(Sema &S,
8997                                          const ArrayRef<OMPClause *> Clauses) {
8998   const OMPSafelenClause *Safelen = nullptr;
8999   const OMPSimdlenClause *Simdlen = nullptr;
9000 
9001   for (const OMPClause *Clause : Clauses) {
9002     if (Clause->getClauseKind() == OMPC_safelen)
9003       Safelen = cast<OMPSafelenClause>(Clause);
9004     else if (Clause->getClauseKind() == OMPC_simdlen)
9005       Simdlen = cast<OMPSimdlenClause>(Clause);
9006     if (Safelen && Simdlen)
9007       break;
9008   }
9009 
9010   if (Simdlen && Safelen) {
9011     const Expr *SimdlenLength = Simdlen->getSimdlen();
9012     const Expr *SafelenLength = Safelen->getSafelen();
9013     if (SimdlenLength->isValueDependent() || SimdlenLength->isTypeDependent() ||
9014         SimdlenLength->isInstantiationDependent() ||
9015         SimdlenLength->containsUnexpandedParameterPack())
9016       return false;
9017     if (SafelenLength->isValueDependent() || SafelenLength->isTypeDependent() ||
9018         SafelenLength->isInstantiationDependent() ||
9019         SafelenLength->containsUnexpandedParameterPack())
9020       return false;
9021     Expr::EvalResult SimdlenResult, SafelenResult;
9022     SimdlenLength->EvaluateAsInt(SimdlenResult, S.Context);
9023     SafelenLength->EvaluateAsInt(SafelenResult, S.Context);
9024     llvm::APSInt SimdlenRes = SimdlenResult.Val.getInt();
9025     llvm::APSInt SafelenRes = SafelenResult.Val.getInt();
9026     // OpenMP 4.5 [2.8.1, simd Construct, Restrictions]
9027     // If both simdlen and safelen clauses are specified, the value of the
9028     // simdlen parameter must be less than or equal to the value of the safelen
9029     // parameter.
9030     if (SimdlenRes > SafelenRes) {
9031       S.Diag(SimdlenLength->getExprLoc(),
9032              diag::err_omp_wrong_simdlen_safelen_values)
9033           << SimdlenLength->getSourceRange() << SafelenLength->getSourceRange();
9034       return true;
9035     }
9036   }
9037   return false;
9038 }
9039 
9040 StmtResult
9041 Sema::ActOnOpenMPSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
9042                                SourceLocation StartLoc, SourceLocation EndLoc,
9043                                VarsWithInheritedDSAType &VarsWithImplicitDSA) {
9044   if (!AStmt)
9045     return StmtError();
9046 
9047   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
9048   OMPLoopDirective::HelperExprs B;
9049   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
9050   // define the nested loops number.
9051   unsigned NestedLoopCount = checkOpenMPLoop(
9052       OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
9053       AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
9054   if (NestedLoopCount == 0)
9055     return StmtError();
9056 
9057   assert((CurContext->isDependentContext() || B.builtAll()) &&
9058          "omp simd loop exprs were not built");
9059 
9060   if (!CurContext->isDependentContext()) {
9061     // Finalize the clauses that need pre-built expressions for CodeGen.
9062     for (OMPClause *C : Clauses) {
9063       if (auto *LC = dyn_cast<OMPLinearClause>(C))
9064         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
9065                                      B.NumIterations, *this, CurScope,
9066                                      DSAStack))
9067           return StmtError();
9068     }
9069   }
9070 
9071   if (checkSimdlenSafelenSpecified(*this, Clauses))
9072     return StmtError();
9073 
9074   setFunctionHasBranchProtectedScope();
9075   return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
9076                                   Clauses, AStmt, B);
9077 }
9078 
9079 StmtResult
9080 Sema::ActOnOpenMPForDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
9081                               SourceLocation StartLoc, SourceLocation EndLoc,
9082                               VarsWithInheritedDSAType &VarsWithImplicitDSA) {
9083   if (!AStmt)
9084     return StmtError();
9085 
9086   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
9087   OMPLoopDirective::HelperExprs B;
9088   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
9089   // define the nested loops number.
9090   unsigned NestedLoopCount = checkOpenMPLoop(
9091       OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
9092       AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
9093   if (NestedLoopCount == 0)
9094     return StmtError();
9095 
9096   assert((CurContext->isDependentContext() || B.builtAll()) &&
9097          "omp for loop exprs were not built");
9098 
9099   if (!CurContext->isDependentContext()) {
9100     // Finalize the clauses that need pre-built expressions for CodeGen.
9101     for (OMPClause *C : Clauses) {
9102       if (auto *LC = dyn_cast<OMPLinearClause>(C))
9103         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
9104                                      B.NumIterations, *this, CurScope,
9105                                      DSAStack))
9106           return StmtError();
9107     }
9108   }
9109 
9110   setFunctionHasBranchProtectedScope();
9111   return OMPForDirective::Create(
9112       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
9113       DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion());
9114 }
9115 
9116 StmtResult Sema::ActOnOpenMPForSimdDirective(
9117     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
9118     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
9119   if (!AStmt)
9120     return StmtError();
9121 
9122   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
9123   OMPLoopDirective::HelperExprs B;
9124   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
9125   // define the nested loops number.
9126   unsigned NestedLoopCount =
9127       checkOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses),
9128                       getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
9129                       VarsWithImplicitDSA, B);
9130   if (NestedLoopCount == 0)
9131     return StmtError();
9132 
9133   assert((CurContext->isDependentContext() || B.builtAll()) &&
9134          "omp for simd loop exprs were not built");
9135 
9136   if (!CurContext->isDependentContext()) {
9137     // Finalize the clauses that need pre-built expressions for CodeGen.
9138     for (OMPClause *C : Clauses) {
9139       if (auto *LC = dyn_cast<OMPLinearClause>(C))
9140         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
9141                                      B.NumIterations, *this, CurScope,
9142                                      DSAStack))
9143           return StmtError();
9144     }
9145   }
9146 
9147   if (checkSimdlenSafelenSpecified(*this, Clauses))
9148     return StmtError();
9149 
9150   setFunctionHasBranchProtectedScope();
9151   return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
9152                                      Clauses, AStmt, B);
9153 }
9154 
9155 StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
9156                                               Stmt *AStmt,
9157                                               SourceLocation StartLoc,
9158                                               SourceLocation EndLoc) {
9159   if (!AStmt)
9160     return StmtError();
9161 
9162   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
9163   auto BaseStmt = AStmt;
9164   while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
9165     BaseStmt = CS->getCapturedStmt();
9166   if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
9167     auto S = C->children();
9168     if (S.begin() == S.end())
9169       return StmtError();
9170     // All associated statements must be '#pragma omp section' except for
9171     // the first one.
9172     for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
9173       if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
9174         if (SectionStmt)
9175           Diag(SectionStmt->getBeginLoc(),
9176                diag::err_omp_sections_substmt_not_section);
9177         return StmtError();
9178       }
9179       cast<OMPSectionDirective>(SectionStmt)
9180           ->setHasCancel(DSAStack->isCancelRegion());
9181     }
9182   } else {
9183     Diag(AStmt->getBeginLoc(), diag::err_omp_sections_not_compound_stmt);
9184     return StmtError();
9185   }
9186 
9187   setFunctionHasBranchProtectedScope();
9188 
9189   return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
9190                                       DSAStack->getTaskgroupReductionRef(),
9191                                       DSAStack->isCancelRegion());
9192 }
9193 
9194 StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt,
9195                                              SourceLocation StartLoc,
9196                                              SourceLocation EndLoc) {
9197   if (!AStmt)
9198     return StmtError();
9199 
9200   setFunctionHasBranchProtectedScope();
9201   DSAStack->setParentCancelRegion(DSAStack->isCancelRegion());
9202 
9203   return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt,
9204                                      DSAStack->isCancelRegion());
9205 }
9206 
9207 StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
9208                                             Stmt *AStmt,
9209                                             SourceLocation StartLoc,
9210                                             SourceLocation EndLoc) {
9211   if (!AStmt)
9212     return StmtError();
9213 
9214   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
9215 
9216   setFunctionHasBranchProtectedScope();
9217 
9218   // OpenMP [2.7.3, single Construct, Restrictions]
9219   // The copyprivate clause must not be used with the nowait clause.
9220   const OMPClause *Nowait = nullptr;
9221   const OMPClause *Copyprivate = nullptr;
9222   for (const OMPClause *Clause : Clauses) {
9223     if (Clause->getClauseKind() == OMPC_nowait)
9224       Nowait = Clause;
9225     else if (Clause->getClauseKind() == OMPC_copyprivate)
9226       Copyprivate = Clause;
9227     if (Copyprivate && Nowait) {
9228       Diag(Copyprivate->getBeginLoc(),
9229            diag::err_omp_single_copyprivate_with_nowait);
9230       Diag(Nowait->getBeginLoc(), diag::note_omp_nowait_clause_here);
9231       return StmtError();
9232     }
9233   }
9234 
9235   return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
9236 }
9237 
9238 StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt,
9239                                             SourceLocation StartLoc,
9240                                             SourceLocation EndLoc) {
9241   if (!AStmt)
9242     return StmtError();
9243 
9244   setFunctionHasBranchProtectedScope();
9245 
9246   return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt);
9247 }
9248 
9249 StmtResult Sema::ActOnOpenMPCriticalDirective(
9250     const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses,
9251     Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
9252   if (!AStmt)
9253     return StmtError();
9254 
9255   bool ErrorFound = false;
9256   llvm::APSInt Hint;
9257   SourceLocation HintLoc;
9258   bool DependentHint = false;
9259   for (const OMPClause *C : Clauses) {
9260     if (C->getClauseKind() == OMPC_hint) {
9261       if (!DirName.getName()) {
9262         Diag(C->getBeginLoc(), diag::err_omp_hint_clause_no_name);
9263         ErrorFound = true;
9264       }
9265       Expr *E = cast<OMPHintClause>(C)->getHint();
9266       if (E->isTypeDependent() || E->isValueDependent() ||
9267           E->isInstantiationDependent()) {
9268         DependentHint = true;
9269       } else {
9270         Hint = E->EvaluateKnownConstInt(Context);
9271         HintLoc = C->getBeginLoc();
9272       }
9273     }
9274   }
9275   if (ErrorFound)
9276     return StmtError();
9277   const auto Pair = DSAStack->getCriticalWithHint(DirName);
9278   if (Pair.first && DirName.getName() && !DependentHint) {
9279     if (llvm::APSInt::compareValues(Hint, Pair.second) != 0) {
9280       Diag(StartLoc, diag::err_omp_critical_with_hint);
9281       if (HintLoc.isValid())
9282         Diag(HintLoc, diag::note_omp_critical_hint_here)
9283             << 0 << Hint.toString(/*Radix=*/10, /*Signed=*/false);
9284       else
9285         Diag(StartLoc, diag::note_omp_critical_no_hint) << 0;
9286       if (const auto *C = Pair.first->getSingleClause<OMPHintClause>()) {
9287         Diag(C->getBeginLoc(), diag::note_omp_critical_hint_here)
9288             << 1
9289             << C->getHint()->EvaluateKnownConstInt(Context).toString(
9290                    /*Radix=*/10, /*Signed=*/false);
9291       } else {
9292         Diag(Pair.first->getBeginLoc(), diag::note_omp_critical_no_hint) << 1;
9293       }
9294     }
9295   }
9296 
9297   setFunctionHasBranchProtectedScope();
9298 
9299   auto *Dir = OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc,
9300                                            Clauses, AStmt);
9301   if (!Pair.first && DirName.getName() && !DependentHint)
9302     DSAStack->addCriticalWithHint(Dir, Hint);
9303   return Dir;
9304 }
9305 
9306 StmtResult Sema::ActOnOpenMPParallelForDirective(
9307     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
9308     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
9309   if (!AStmt)
9310     return StmtError();
9311 
9312   auto *CS = cast<CapturedStmt>(AStmt);
9313   // 1.2.2 OpenMP Language Terminology
9314   // Structured block - An executable statement with a single entry at the
9315   // top and a single exit at the bottom.
9316   // The point of exit cannot be a branch out of the structured block.
9317   // longjmp() and throw() must not violate the entry/exit criteria.
9318   CS->getCapturedDecl()->setNothrow();
9319 
9320   OMPLoopDirective::HelperExprs B;
9321   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
9322   // define the nested loops number.
9323   unsigned NestedLoopCount =
9324       checkOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses),
9325                       getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
9326                       VarsWithImplicitDSA, B);
9327   if (NestedLoopCount == 0)
9328     return StmtError();
9329 
9330   assert((CurContext->isDependentContext() || B.builtAll()) &&
9331          "omp parallel for loop exprs were not built");
9332 
9333   if (!CurContext->isDependentContext()) {
9334     // Finalize the clauses that need pre-built expressions for CodeGen.
9335     for (OMPClause *C : Clauses) {
9336       if (auto *LC = dyn_cast<OMPLinearClause>(C))
9337         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
9338                                      B.NumIterations, *this, CurScope,
9339                                      DSAStack))
9340           return StmtError();
9341     }
9342   }
9343 
9344   setFunctionHasBranchProtectedScope();
9345   return OMPParallelForDirective::Create(
9346       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
9347       DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion());
9348 }
9349 
9350 StmtResult Sema::ActOnOpenMPParallelForSimdDirective(
9351     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
9352     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
9353   if (!AStmt)
9354     return StmtError();
9355 
9356   auto *CS = cast<CapturedStmt>(AStmt);
9357   // 1.2.2 OpenMP Language Terminology
9358   // Structured block - An executable statement with a single entry at the
9359   // top and a single exit at the bottom.
9360   // The point of exit cannot be a branch out of the structured block.
9361   // longjmp() and throw() must not violate the entry/exit criteria.
9362   CS->getCapturedDecl()->setNothrow();
9363 
9364   OMPLoopDirective::HelperExprs B;
9365   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
9366   // define the nested loops number.
9367   unsigned NestedLoopCount =
9368       checkOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses),
9369                       getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
9370                       VarsWithImplicitDSA, B);
9371   if (NestedLoopCount == 0)
9372     return StmtError();
9373 
9374   if (!CurContext->isDependentContext()) {
9375     // Finalize the clauses that need pre-built expressions for CodeGen.
9376     for (OMPClause *C : Clauses) {
9377       if (auto *LC = dyn_cast<OMPLinearClause>(C))
9378         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
9379                                      B.NumIterations, *this, CurScope,
9380                                      DSAStack))
9381           return StmtError();
9382     }
9383   }
9384 
9385   if (checkSimdlenSafelenSpecified(*this, Clauses))
9386     return StmtError();
9387 
9388   setFunctionHasBranchProtectedScope();
9389   return OMPParallelForSimdDirective::Create(
9390       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
9391 }
9392 
9393 StmtResult
9394 Sema::ActOnOpenMPParallelMasterDirective(ArrayRef<OMPClause *> Clauses,
9395                                          Stmt *AStmt, SourceLocation StartLoc,
9396                                          SourceLocation EndLoc) {
9397   if (!AStmt)
9398     return StmtError();
9399 
9400   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
9401   auto *CS = cast<CapturedStmt>(AStmt);
9402   // 1.2.2 OpenMP Language Terminology
9403   // Structured block - An executable statement with a single entry at the
9404   // top and a single exit at the bottom.
9405   // The point of exit cannot be a branch out of the structured block.
9406   // longjmp() and throw() must not violate the entry/exit criteria.
9407   CS->getCapturedDecl()->setNothrow();
9408 
9409   setFunctionHasBranchProtectedScope();
9410 
9411   return OMPParallelMasterDirective::Create(
9412       Context, StartLoc, EndLoc, Clauses, AStmt,
9413       DSAStack->getTaskgroupReductionRef());
9414 }
9415 
9416 StmtResult
9417 Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
9418                                            Stmt *AStmt, SourceLocation StartLoc,
9419                                            SourceLocation EndLoc) {
9420   if (!AStmt)
9421     return StmtError();
9422 
9423   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
9424   auto BaseStmt = AStmt;
9425   while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
9426     BaseStmt = CS->getCapturedStmt();
9427   if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
9428     auto S = C->children();
9429     if (S.begin() == S.end())
9430       return StmtError();
9431     // All associated statements must be '#pragma omp section' except for
9432     // the first one.
9433     for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
9434       if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
9435         if (SectionStmt)
9436           Diag(SectionStmt->getBeginLoc(),
9437                diag::err_omp_parallel_sections_substmt_not_section);
9438         return StmtError();
9439       }
9440       cast<OMPSectionDirective>(SectionStmt)
9441           ->setHasCancel(DSAStack->isCancelRegion());
9442     }
9443   } else {
9444     Diag(AStmt->getBeginLoc(),
9445          diag::err_omp_parallel_sections_not_compound_stmt);
9446     return StmtError();
9447   }
9448 
9449   setFunctionHasBranchProtectedScope();
9450 
9451   return OMPParallelSectionsDirective::Create(
9452       Context, StartLoc, EndLoc, Clauses, AStmt,
9453       DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion());
9454 }
9455 
9456 /// detach and mergeable clauses are mutially exclusive, check for it.
9457 static bool checkDetachMergeableClauses(Sema &S,
9458                                         ArrayRef<OMPClause *> Clauses) {
9459   const OMPClause *PrevClause = nullptr;
9460   bool ErrorFound = false;
9461   for (const OMPClause *C : Clauses) {
9462     if (C->getClauseKind() == OMPC_detach ||
9463         C->getClauseKind() == OMPC_mergeable) {
9464       if (!PrevClause) {
9465         PrevClause = C;
9466       } else if (PrevClause->getClauseKind() != C->getClauseKind()) {
9467         S.Diag(C->getBeginLoc(), diag::err_omp_clauses_mutually_exclusive)
9468             << getOpenMPClauseName(C->getClauseKind())
9469             << getOpenMPClauseName(PrevClause->getClauseKind());
9470         S.Diag(PrevClause->getBeginLoc(), diag::note_omp_previous_clause)
9471             << getOpenMPClauseName(PrevClause->getClauseKind());
9472         ErrorFound = true;
9473       }
9474     }
9475   }
9476   return ErrorFound;
9477 }
9478 
9479 StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
9480                                           Stmt *AStmt, SourceLocation StartLoc,
9481                                           SourceLocation EndLoc) {
9482   if (!AStmt)
9483     return StmtError();
9484 
9485   // OpenMP 5.0, 2.10.1 task Construct
9486   // If a detach clause appears on the directive, then a mergeable clause cannot
9487   // appear on the same directive.
9488   if (checkDetachMergeableClauses(*this, Clauses))
9489     return StmtError();
9490 
9491   auto *CS = cast<CapturedStmt>(AStmt);
9492   // 1.2.2 OpenMP Language Terminology
9493   // Structured block - An executable statement with a single entry at the
9494   // top and a single exit at the bottom.
9495   // The point of exit cannot be a branch out of the structured block.
9496   // longjmp() and throw() must not violate the entry/exit criteria.
9497   CS->getCapturedDecl()->setNothrow();
9498 
9499   setFunctionHasBranchProtectedScope();
9500 
9501   return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
9502                                   DSAStack->isCancelRegion());
9503 }
9504 
9505 StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
9506                                                SourceLocation EndLoc) {
9507   return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc);
9508 }
9509 
9510 StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
9511                                              SourceLocation EndLoc) {
9512   return OMPBarrierDirective::Create(Context, StartLoc, EndLoc);
9513 }
9514 
9515 StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
9516                                               SourceLocation EndLoc) {
9517   return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc);
9518 }
9519 
9520 StmtResult Sema::ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses,
9521                                                Stmt *AStmt,
9522                                                SourceLocation StartLoc,
9523                                                SourceLocation EndLoc) {
9524   if (!AStmt)
9525     return StmtError();
9526 
9527   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
9528 
9529   setFunctionHasBranchProtectedScope();
9530 
9531   return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, Clauses,
9532                                        AStmt,
9533                                        DSAStack->getTaskgroupReductionRef());
9534 }
9535 
9536 StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
9537                                            SourceLocation StartLoc,
9538                                            SourceLocation EndLoc) {
9539   OMPFlushClause *FC = nullptr;
9540   OMPClause *OrderClause = nullptr;
9541   for (OMPClause *C : Clauses) {
9542     if (C->getClauseKind() == OMPC_flush)
9543       FC = cast<OMPFlushClause>(C);
9544     else
9545       OrderClause = C;
9546   }
9547   OpenMPClauseKind MemOrderKind = OMPC_unknown;
9548   SourceLocation MemOrderLoc;
9549   for (const OMPClause *C : Clauses) {
9550     if (C->getClauseKind() == OMPC_acq_rel ||
9551         C->getClauseKind() == OMPC_acquire ||
9552         C->getClauseKind() == OMPC_release) {
9553       if (MemOrderKind != OMPC_unknown) {
9554         Diag(C->getBeginLoc(), diag::err_omp_several_mem_order_clauses)
9555             << getOpenMPDirectiveName(OMPD_flush) << 1
9556             << SourceRange(C->getBeginLoc(), C->getEndLoc());
9557         Diag(MemOrderLoc, diag::note_omp_previous_mem_order_clause)
9558             << getOpenMPClauseName(MemOrderKind);
9559       } else {
9560         MemOrderKind = C->getClauseKind();
9561         MemOrderLoc = C->getBeginLoc();
9562       }
9563     }
9564   }
9565   if (FC && OrderClause) {
9566     Diag(FC->getLParenLoc(), diag::err_omp_flush_order_clause_and_list)
9567         << getOpenMPClauseName(OrderClause->getClauseKind());
9568     Diag(OrderClause->getBeginLoc(), diag::note_omp_flush_order_clause_here)
9569         << getOpenMPClauseName(OrderClause->getClauseKind());
9570     return StmtError();
9571   }
9572   return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses);
9573 }
9574 
9575 StmtResult Sema::ActOnOpenMPDepobjDirective(ArrayRef<OMPClause *> Clauses,
9576                                             SourceLocation StartLoc,
9577                                             SourceLocation EndLoc) {
9578   if (Clauses.empty()) {
9579     Diag(StartLoc, diag::err_omp_depobj_expected);
9580     return StmtError();
9581   } else if (Clauses[0]->getClauseKind() != OMPC_depobj) {
9582     Diag(Clauses[0]->getBeginLoc(), diag::err_omp_depobj_expected);
9583     return StmtError();
9584   }
9585   // Only depobj expression and another single clause is allowed.
9586   if (Clauses.size() > 2) {
9587     Diag(Clauses[2]->getBeginLoc(),
9588          diag::err_omp_depobj_single_clause_expected);
9589     return StmtError();
9590   } else if (Clauses.size() < 1) {
9591     Diag(Clauses[0]->getEndLoc(), diag::err_omp_depobj_single_clause_expected);
9592     return StmtError();
9593   }
9594   return OMPDepobjDirective::Create(Context, StartLoc, EndLoc, Clauses);
9595 }
9596 
9597 StmtResult Sema::ActOnOpenMPScanDirective(ArrayRef<OMPClause *> Clauses,
9598                                           SourceLocation StartLoc,
9599                                           SourceLocation EndLoc) {
9600   // Check that exactly one clause is specified.
9601   if (Clauses.size() != 1) {
9602     Diag(Clauses.empty() ? EndLoc : Clauses[1]->getBeginLoc(),
9603          diag::err_omp_scan_single_clause_expected);
9604     return StmtError();
9605   }
9606   // Check that scan directive is used in the scopeof the OpenMP loop body.
9607   if (Scope *S = DSAStack->getCurScope()) {
9608     Scope *ParentS = S->getParent();
9609     if (!ParentS || ParentS->getParent() != ParentS->getBreakParent() ||
9610         !ParentS->getBreakParent()->isOpenMPLoopScope())
9611       return StmtError(Diag(StartLoc, diag::err_omp_orphaned_device_directive)
9612                        << getOpenMPDirectiveName(OMPD_scan) << 5);
9613   }
9614   // Check that only one instance of scan directives is used in the same outer
9615   // region.
9616   if (DSAStack->doesParentHasScanDirective()) {
9617     Diag(StartLoc, diag::err_omp_several_directives_in_region) << "scan";
9618     Diag(DSAStack->getParentScanDirectiveLoc(),
9619          diag::note_omp_previous_directive)
9620         << "scan";
9621     return StmtError();
9622   }
9623   DSAStack->setParentHasScanDirective(StartLoc);
9624   return OMPScanDirective::Create(Context, StartLoc, EndLoc, Clauses);
9625 }
9626 
9627 StmtResult Sema::ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
9628                                              Stmt *AStmt,
9629                                              SourceLocation StartLoc,
9630                                              SourceLocation EndLoc) {
9631   const OMPClause *DependFound = nullptr;
9632   const OMPClause *DependSourceClause = nullptr;
9633   const OMPClause *DependSinkClause = nullptr;
9634   bool ErrorFound = false;
9635   const OMPThreadsClause *TC = nullptr;
9636   const OMPSIMDClause *SC = nullptr;
9637   for (const OMPClause *C : Clauses) {
9638     if (auto *DC = dyn_cast<OMPDependClause>(C)) {
9639       DependFound = C;
9640       if (DC->getDependencyKind() == OMPC_DEPEND_source) {
9641         if (DependSourceClause) {
9642           Diag(C->getBeginLoc(), diag::err_omp_more_one_clause)
9643               << getOpenMPDirectiveName(OMPD_ordered)
9644               << getOpenMPClauseName(OMPC_depend) << 2;
9645           ErrorFound = true;
9646         } else {
9647           DependSourceClause = C;
9648         }
9649         if (DependSinkClause) {
9650           Diag(C->getBeginLoc(), diag::err_omp_depend_sink_source_not_allowed)
9651               << 0;
9652           ErrorFound = true;
9653         }
9654       } else if (DC->getDependencyKind() == OMPC_DEPEND_sink) {
9655         if (DependSourceClause) {
9656           Diag(C->getBeginLoc(), diag::err_omp_depend_sink_source_not_allowed)
9657               << 1;
9658           ErrorFound = true;
9659         }
9660         DependSinkClause = C;
9661       }
9662     } else if (C->getClauseKind() == OMPC_threads) {
9663       TC = cast<OMPThreadsClause>(C);
9664     } else if (C->getClauseKind() == OMPC_simd) {
9665       SC = cast<OMPSIMDClause>(C);
9666     }
9667   }
9668   if (!ErrorFound && !SC &&
9669       isOpenMPSimdDirective(DSAStack->getParentDirective())) {
9670     // OpenMP [2.8.1,simd Construct, Restrictions]
9671     // An ordered construct with the simd clause is the only OpenMP construct
9672     // that can appear in the simd region.
9673     Diag(StartLoc, diag::err_omp_prohibited_region_simd)
9674         << (LangOpts.OpenMP >= 50 ? 1 : 0);
9675     ErrorFound = true;
9676   } else if (DependFound && (TC || SC)) {
9677     Diag(DependFound->getBeginLoc(), diag::err_omp_depend_clause_thread_simd)
9678         << getOpenMPClauseName(TC ? TC->getClauseKind() : SC->getClauseKind());
9679     ErrorFound = true;
9680   } else if (DependFound && !DSAStack->getParentOrderedRegionParam().first) {
9681     Diag(DependFound->getBeginLoc(),
9682          diag::err_omp_ordered_directive_without_param);
9683     ErrorFound = true;
9684   } else if (TC || Clauses.empty()) {
9685     if (const Expr *Param = DSAStack->getParentOrderedRegionParam().first) {
9686       SourceLocation ErrLoc = TC ? TC->getBeginLoc() : StartLoc;
9687       Diag(ErrLoc, diag::err_omp_ordered_directive_with_param)
9688           << (TC != nullptr);
9689       Diag(Param->getBeginLoc(), diag::note_omp_ordered_param) << 1;
9690       ErrorFound = true;
9691     }
9692   }
9693   if ((!AStmt && !DependFound) || ErrorFound)
9694     return StmtError();
9695 
9696   // OpenMP 5.0, 2.17.9, ordered Construct, Restrictions.
9697   // During execution of an iteration of a worksharing-loop or a loop nest
9698   // within a worksharing-loop, simd, or worksharing-loop SIMD region, a thread
9699   // must not execute more than one ordered region corresponding to an ordered
9700   // construct without a depend clause.
9701   if (!DependFound) {
9702     if (DSAStack->doesParentHasOrderedDirective()) {
9703       Diag(StartLoc, diag::err_omp_several_directives_in_region) << "ordered";
9704       Diag(DSAStack->getParentOrderedDirectiveLoc(),
9705            diag::note_omp_previous_directive)
9706           << "ordered";
9707       return StmtError();
9708     }
9709     DSAStack->setParentHasOrderedDirective(StartLoc);
9710   }
9711 
9712   if (AStmt) {
9713     assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
9714 
9715     setFunctionHasBranchProtectedScope();
9716   }
9717 
9718   return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
9719 }
9720 
9721 namespace {
9722 /// Helper class for checking expression in 'omp atomic [update]'
9723 /// construct.
9724 class OpenMPAtomicUpdateChecker {
9725   /// Error results for atomic update expressions.
9726   enum ExprAnalysisErrorCode {
9727     /// A statement is not an expression statement.
9728     NotAnExpression,
9729     /// Expression is not builtin binary or unary operation.
9730     NotABinaryOrUnaryExpression,
9731     /// Unary operation is not post-/pre- increment/decrement operation.
9732     NotAnUnaryIncDecExpression,
9733     /// An expression is not of scalar type.
9734     NotAScalarType,
9735     /// A binary operation is not an assignment operation.
9736     NotAnAssignmentOp,
9737     /// RHS part of the binary operation is not a binary expression.
9738     NotABinaryExpression,
9739     /// RHS part is not additive/multiplicative/shift/biwise binary
9740     /// expression.
9741     NotABinaryOperator,
9742     /// RHS binary operation does not have reference to the updated LHS
9743     /// part.
9744     NotAnUpdateExpression,
9745     /// No errors is found.
9746     NoError
9747   };
9748   /// Reference to Sema.
9749   Sema &SemaRef;
9750   /// A location for note diagnostics (when error is found).
9751   SourceLocation NoteLoc;
9752   /// 'x' lvalue part of the source atomic expression.
9753   Expr *X;
9754   /// 'expr' rvalue part of the source atomic expression.
9755   Expr *E;
9756   /// Helper expression of the form
9757   /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
9758   /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
9759   Expr *UpdateExpr;
9760   /// Is 'x' a LHS in a RHS part of full update expression. It is
9761   /// important for non-associative operations.
9762   bool IsXLHSInRHSPart;
9763   BinaryOperatorKind Op;
9764   SourceLocation OpLoc;
9765   /// true if the source expression is a postfix unary operation, false
9766   /// if it is a prefix unary operation.
9767   bool IsPostfixUpdate;
9768 
9769 public:
9770   OpenMPAtomicUpdateChecker(Sema &SemaRef)
9771       : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr),
9772         IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {}
9773   /// Check specified statement that it is suitable for 'atomic update'
9774   /// constructs and extract 'x', 'expr' and Operation from the original
9775   /// expression. If DiagId and NoteId == 0, then only check is performed
9776   /// without error notification.
9777   /// \param DiagId Diagnostic which should be emitted if error is found.
9778   /// \param NoteId Diagnostic note for the main error message.
9779   /// \return true if statement is not an update expression, false otherwise.
9780   bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0);
9781   /// Return the 'x' lvalue part of the source atomic expression.
9782   Expr *getX() const { return X; }
9783   /// Return the 'expr' rvalue part of the source atomic expression.
9784   Expr *getExpr() const { return E; }
9785   /// Return the update expression used in calculation of the updated
9786   /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
9787   /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
9788   Expr *getUpdateExpr() const { return UpdateExpr; }
9789   /// Return true if 'x' is LHS in RHS part of full update expression,
9790   /// false otherwise.
9791   bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; }
9792 
9793   /// true if the source expression is a postfix unary operation, false
9794   /// if it is a prefix unary operation.
9795   bool isPostfixUpdate() const { return IsPostfixUpdate; }
9796 
9797 private:
9798   bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0,
9799                             unsigned NoteId = 0);
9800 };
9801 } // namespace
9802 
9803 bool OpenMPAtomicUpdateChecker::checkBinaryOperation(
9804     BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) {
9805   ExprAnalysisErrorCode ErrorFound = NoError;
9806   SourceLocation ErrorLoc, NoteLoc;
9807   SourceRange ErrorRange, NoteRange;
9808   // Allowed constructs are:
9809   //  x = x binop expr;
9810   //  x = expr binop x;
9811   if (AtomicBinOp->getOpcode() == BO_Assign) {
9812     X = AtomicBinOp->getLHS();
9813     if (const auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>(
9814             AtomicBinOp->getRHS()->IgnoreParenImpCasts())) {
9815       if (AtomicInnerBinOp->isMultiplicativeOp() ||
9816           AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() ||
9817           AtomicInnerBinOp->isBitwiseOp()) {
9818         Op = AtomicInnerBinOp->getOpcode();
9819         OpLoc = AtomicInnerBinOp->getOperatorLoc();
9820         Expr *LHS = AtomicInnerBinOp->getLHS();
9821         Expr *RHS = AtomicInnerBinOp->getRHS();
9822         llvm::FoldingSetNodeID XId, LHSId, RHSId;
9823         X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(),
9824                                           /*Canonical=*/true);
9825         LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(),
9826                                             /*Canonical=*/true);
9827         RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(),
9828                                             /*Canonical=*/true);
9829         if (XId == LHSId) {
9830           E = RHS;
9831           IsXLHSInRHSPart = true;
9832         } else if (XId == RHSId) {
9833           E = LHS;
9834           IsXLHSInRHSPart = false;
9835         } else {
9836           ErrorLoc = AtomicInnerBinOp->getExprLoc();
9837           ErrorRange = AtomicInnerBinOp->getSourceRange();
9838           NoteLoc = X->getExprLoc();
9839           NoteRange = X->getSourceRange();
9840           ErrorFound = NotAnUpdateExpression;
9841         }
9842       } else {
9843         ErrorLoc = AtomicInnerBinOp->getExprLoc();
9844         ErrorRange = AtomicInnerBinOp->getSourceRange();
9845         NoteLoc = AtomicInnerBinOp->getOperatorLoc();
9846         NoteRange = SourceRange(NoteLoc, NoteLoc);
9847         ErrorFound = NotABinaryOperator;
9848       }
9849     } else {
9850       NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc();
9851       NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange();
9852       ErrorFound = NotABinaryExpression;
9853     }
9854   } else {
9855     ErrorLoc = AtomicBinOp->getExprLoc();
9856     ErrorRange = AtomicBinOp->getSourceRange();
9857     NoteLoc = AtomicBinOp->getOperatorLoc();
9858     NoteRange = SourceRange(NoteLoc, NoteLoc);
9859     ErrorFound = NotAnAssignmentOp;
9860   }
9861   if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
9862     SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
9863     SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
9864     return true;
9865   }
9866   if (SemaRef.CurContext->isDependentContext())
9867     E = X = UpdateExpr = nullptr;
9868   return ErrorFound != NoError;
9869 }
9870 
9871 bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId,
9872                                                unsigned NoteId) {
9873   ExprAnalysisErrorCode ErrorFound = NoError;
9874   SourceLocation ErrorLoc, NoteLoc;
9875   SourceRange ErrorRange, NoteRange;
9876   // Allowed constructs are:
9877   //  x++;
9878   //  x--;
9879   //  ++x;
9880   //  --x;
9881   //  x binop= expr;
9882   //  x = x binop expr;
9883   //  x = expr binop x;
9884   if (auto *AtomicBody = dyn_cast<Expr>(S)) {
9885     AtomicBody = AtomicBody->IgnoreParenImpCasts();
9886     if (AtomicBody->getType()->isScalarType() ||
9887         AtomicBody->isInstantiationDependent()) {
9888       if (const auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>(
9889               AtomicBody->IgnoreParenImpCasts())) {
9890         // Check for Compound Assignment Operation
9891         Op = BinaryOperator::getOpForCompoundAssignment(
9892             AtomicCompAssignOp->getOpcode());
9893         OpLoc = AtomicCompAssignOp->getOperatorLoc();
9894         E = AtomicCompAssignOp->getRHS();
9895         X = AtomicCompAssignOp->getLHS()->IgnoreParens();
9896         IsXLHSInRHSPart = true;
9897       } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>(
9898                      AtomicBody->IgnoreParenImpCasts())) {
9899         // Check for Binary Operation
9900         if (checkBinaryOperation(AtomicBinOp, DiagId, NoteId))
9901           return true;
9902       } else if (const auto *AtomicUnaryOp = dyn_cast<UnaryOperator>(
9903                      AtomicBody->IgnoreParenImpCasts())) {
9904         // Check for Unary Operation
9905         if (AtomicUnaryOp->isIncrementDecrementOp()) {
9906           IsPostfixUpdate = AtomicUnaryOp->isPostfix();
9907           Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub;
9908           OpLoc = AtomicUnaryOp->getOperatorLoc();
9909           X = AtomicUnaryOp->getSubExpr()->IgnoreParens();
9910           E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get();
9911           IsXLHSInRHSPart = true;
9912         } else {
9913           ErrorFound = NotAnUnaryIncDecExpression;
9914           ErrorLoc = AtomicUnaryOp->getExprLoc();
9915           ErrorRange = AtomicUnaryOp->getSourceRange();
9916           NoteLoc = AtomicUnaryOp->getOperatorLoc();
9917           NoteRange = SourceRange(NoteLoc, NoteLoc);
9918         }
9919       } else if (!AtomicBody->isInstantiationDependent()) {
9920         ErrorFound = NotABinaryOrUnaryExpression;
9921         NoteLoc = ErrorLoc = AtomicBody->getExprLoc();
9922         NoteRange = ErrorRange = AtomicBody->getSourceRange();
9923       }
9924     } else {
9925       ErrorFound = NotAScalarType;
9926       NoteLoc = ErrorLoc = AtomicBody->getBeginLoc();
9927       NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
9928     }
9929   } else {
9930     ErrorFound = NotAnExpression;
9931     NoteLoc = ErrorLoc = S->getBeginLoc();
9932     NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
9933   }
9934   if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
9935     SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
9936     SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
9937     return true;
9938   }
9939   if (SemaRef.CurContext->isDependentContext())
9940     E = X = UpdateExpr = nullptr;
9941   if (ErrorFound == NoError && E && X) {
9942     // Build an update expression of form 'OpaqueValueExpr(x) binop
9943     // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop
9944     // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression.
9945     auto *OVEX = new (SemaRef.getASTContext())
9946         OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue);
9947     auto *OVEExpr = new (SemaRef.getASTContext())
9948         OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue);
9949     ExprResult Update =
9950         SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr,
9951                                    IsXLHSInRHSPart ? OVEExpr : OVEX);
9952     if (Update.isInvalid())
9953       return true;
9954     Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(),
9955                                                Sema::AA_Casting);
9956     if (Update.isInvalid())
9957       return true;
9958     UpdateExpr = Update.get();
9959   }
9960   return ErrorFound != NoError;
9961 }
9962 
9963 StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
9964                                             Stmt *AStmt,
9965                                             SourceLocation StartLoc,
9966                                             SourceLocation EndLoc) {
9967   // Register location of the first atomic directive.
9968   DSAStack->addAtomicDirectiveLoc(StartLoc);
9969   if (!AStmt)
9970     return StmtError();
9971 
9972   // 1.2.2 OpenMP Language Terminology
9973   // Structured block - An executable statement with a single entry at the
9974   // top and a single exit at the bottom.
9975   // The point of exit cannot be a branch out of the structured block.
9976   // longjmp() and throw() must not violate the entry/exit criteria.
9977   OpenMPClauseKind AtomicKind = OMPC_unknown;
9978   SourceLocation AtomicKindLoc;
9979   OpenMPClauseKind MemOrderKind = OMPC_unknown;
9980   SourceLocation MemOrderLoc;
9981   for (const OMPClause *C : Clauses) {
9982     if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write ||
9983         C->getClauseKind() == OMPC_update ||
9984         C->getClauseKind() == OMPC_capture) {
9985       if (AtomicKind != OMPC_unknown) {
9986         Diag(C->getBeginLoc(), diag::err_omp_atomic_several_clauses)
9987             << SourceRange(C->getBeginLoc(), C->getEndLoc());
9988         Diag(AtomicKindLoc, diag::note_omp_previous_mem_order_clause)
9989             << getOpenMPClauseName(AtomicKind);
9990       } else {
9991         AtomicKind = C->getClauseKind();
9992         AtomicKindLoc = C->getBeginLoc();
9993       }
9994     }
9995     if (C->getClauseKind() == OMPC_seq_cst ||
9996         C->getClauseKind() == OMPC_acq_rel ||
9997         C->getClauseKind() == OMPC_acquire ||
9998         C->getClauseKind() == OMPC_release ||
9999         C->getClauseKind() == OMPC_relaxed) {
10000       if (MemOrderKind != OMPC_unknown) {
10001         Diag(C->getBeginLoc(), diag::err_omp_several_mem_order_clauses)
10002             << getOpenMPDirectiveName(OMPD_atomic) << 0
10003             << SourceRange(C->getBeginLoc(), C->getEndLoc());
10004         Diag(MemOrderLoc, diag::note_omp_previous_mem_order_clause)
10005             << getOpenMPClauseName(MemOrderKind);
10006       } else {
10007         MemOrderKind = C->getClauseKind();
10008         MemOrderLoc = C->getBeginLoc();
10009       }
10010     }
10011   }
10012   // OpenMP 5.0, 2.17.7 atomic Construct, Restrictions
10013   // If atomic-clause is read then memory-order-clause must not be acq_rel or
10014   // release.
10015   // If atomic-clause is write then memory-order-clause must not be acq_rel or
10016   // acquire.
10017   // If atomic-clause is update or not present then memory-order-clause must not
10018   // be acq_rel or acquire.
10019   if ((AtomicKind == OMPC_read &&
10020        (MemOrderKind == OMPC_acq_rel || MemOrderKind == OMPC_release)) ||
10021       ((AtomicKind == OMPC_write || AtomicKind == OMPC_update ||
10022         AtomicKind == OMPC_unknown) &&
10023        (MemOrderKind == OMPC_acq_rel || MemOrderKind == OMPC_acquire))) {
10024     SourceLocation Loc = AtomicKindLoc;
10025     if (AtomicKind == OMPC_unknown)
10026       Loc = StartLoc;
10027     Diag(Loc, diag::err_omp_atomic_incompatible_mem_order_clause)
10028         << getOpenMPClauseName(AtomicKind)
10029         << (AtomicKind == OMPC_unknown ? 1 : 0)
10030         << getOpenMPClauseName(MemOrderKind);
10031     Diag(MemOrderLoc, diag::note_omp_previous_mem_order_clause)
10032         << getOpenMPClauseName(MemOrderKind);
10033   }
10034 
10035   Stmt *Body = AStmt;
10036   if (auto *EWC = dyn_cast<ExprWithCleanups>(Body))
10037     Body = EWC->getSubExpr();
10038 
10039   Expr *X = nullptr;
10040   Expr *V = nullptr;
10041   Expr *E = nullptr;
10042   Expr *UE = nullptr;
10043   bool IsXLHSInRHSPart = false;
10044   bool IsPostfixUpdate = false;
10045   // OpenMP [2.12.6, atomic Construct]
10046   // In the next expressions:
10047   // * x and v (as applicable) are both l-value expressions with scalar type.
10048   // * During the execution of an atomic region, multiple syntactic
10049   // occurrences of x must designate the same storage location.
10050   // * Neither of v and expr (as applicable) may access the storage location
10051   // designated by x.
10052   // * Neither of x and expr (as applicable) may access the storage location
10053   // designated by v.
10054   // * expr is an expression with scalar type.
10055   // * binop is one of +, *, -, /, &, ^, |, <<, or >>.
10056   // * binop, binop=, ++, and -- are not overloaded operators.
10057   // * The expression x binop expr must be numerically equivalent to x binop
10058   // (expr). This requirement is satisfied if the operators in expr have
10059   // precedence greater than binop, or by using parentheses around expr or
10060   // subexpressions of expr.
10061   // * The expression expr binop x must be numerically equivalent to (expr)
10062   // binop x. This requirement is satisfied if the operators in expr have
10063   // precedence equal to or greater than binop, or by using parentheses around
10064   // expr or subexpressions of expr.
10065   // * For forms that allow multiple occurrences of x, the number of times
10066   // that x is evaluated is unspecified.
10067   if (AtomicKind == OMPC_read) {
10068     enum {
10069       NotAnExpression,
10070       NotAnAssignmentOp,
10071       NotAScalarType,
10072       NotAnLValue,
10073       NoError
10074     } ErrorFound = NoError;
10075     SourceLocation ErrorLoc, NoteLoc;
10076     SourceRange ErrorRange, NoteRange;
10077     // If clause is read:
10078     //  v = x;
10079     if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
10080       const auto *AtomicBinOp =
10081           dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
10082       if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
10083         X = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
10084         V = AtomicBinOp->getLHS()->IgnoreParenImpCasts();
10085         if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
10086             (V->isInstantiationDependent() || V->getType()->isScalarType())) {
10087           if (!X->isLValue() || !V->isLValue()) {
10088             const Expr *NotLValueExpr = X->isLValue() ? V : X;
10089             ErrorFound = NotAnLValue;
10090             ErrorLoc = AtomicBinOp->getExprLoc();
10091             ErrorRange = AtomicBinOp->getSourceRange();
10092             NoteLoc = NotLValueExpr->getExprLoc();
10093             NoteRange = NotLValueExpr->getSourceRange();
10094           }
10095         } else if (!X->isInstantiationDependent() ||
10096                    !V->isInstantiationDependent()) {
10097           const Expr *NotScalarExpr =
10098               (X->isInstantiationDependent() || X->getType()->isScalarType())
10099                   ? V
10100                   : X;
10101           ErrorFound = NotAScalarType;
10102           ErrorLoc = AtomicBinOp->getExprLoc();
10103           ErrorRange = AtomicBinOp->getSourceRange();
10104           NoteLoc = NotScalarExpr->getExprLoc();
10105           NoteRange = NotScalarExpr->getSourceRange();
10106         }
10107       } else if (!AtomicBody->isInstantiationDependent()) {
10108         ErrorFound = NotAnAssignmentOp;
10109         ErrorLoc = AtomicBody->getExprLoc();
10110         ErrorRange = AtomicBody->getSourceRange();
10111         NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
10112                               : AtomicBody->getExprLoc();
10113         NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
10114                                 : AtomicBody->getSourceRange();
10115       }
10116     } else {
10117       ErrorFound = NotAnExpression;
10118       NoteLoc = ErrorLoc = Body->getBeginLoc();
10119       NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
10120     }
10121     if (ErrorFound != NoError) {
10122       Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement)
10123           << ErrorRange;
10124       Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
10125                                                       << NoteRange;
10126       return StmtError();
10127     }
10128     if (CurContext->isDependentContext())
10129       V = X = nullptr;
10130   } else if (AtomicKind == OMPC_write) {
10131     enum {
10132       NotAnExpression,
10133       NotAnAssignmentOp,
10134       NotAScalarType,
10135       NotAnLValue,
10136       NoError
10137     } ErrorFound = NoError;
10138     SourceLocation ErrorLoc, NoteLoc;
10139     SourceRange ErrorRange, NoteRange;
10140     // If clause is write:
10141     //  x = expr;
10142     if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
10143       const auto *AtomicBinOp =
10144           dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
10145       if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
10146         X = AtomicBinOp->getLHS();
10147         E = AtomicBinOp->getRHS();
10148         if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
10149             (E->isInstantiationDependent() || E->getType()->isScalarType())) {
10150           if (!X->isLValue()) {
10151             ErrorFound = NotAnLValue;
10152             ErrorLoc = AtomicBinOp->getExprLoc();
10153             ErrorRange = AtomicBinOp->getSourceRange();
10154             NoteLoc = X->getExprLoc();
10155             NoteRange = X->getSourceRange();
10156           }
10157         } else if (!X->isInstantiationDependent() ||
10158                    !E->isInstantiationDependent()) {
10159           const Expr *NotScalarExpr =
10160               (X->isInstantiationDependent() || X->getType()->isScalarType())
10161                   ? E
10162                   : X;
10163           ErrorFound = NotAScalarType;
10164           ErrorLoc = AtomicBinOp->getExprLoc();
10165           ErrorRange = AtomicBinOp->getSourceRange();
10166           NoteLoc = NotScalarExpr->getExprLoc();
10167           NoteRange = NotScalarExpr->getSourceRange();
10168         }
10169       } else if (!AtomicBody->isInstantiationDependent()) {
10170         ErrorFound = NotAnAssignmentOp;
10171         ErrorLoc = AtomicBody->getExprLoc();
10172         ErrorRange = AtomicBody->getSourceRange();
10173         NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
10174                               : AtomicBody->getExprLoc();
10175         NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
10176                                 : AtomicBody->getSourceRange();
10177       }
10178     } else {
10179       ErrorFound = NotAnExpression;
10180       NoteLoc = ErrorLoc = Body->getBeginLoc();
10181       NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
10182     }
10183     if (ErrorFound != NoError) {
10184       Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement)
10185           << ErrorRange;
10186       Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
10187                                                       << NoteRange;
10188       return StmtError();
10189     }
10190     if (CurContext->isDependentContext())
10191       E = X = nullptr;
10192   } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) {
10193     // If clause is update:
10194     //  x++;
10195     //  x--;
10196     //  ++x;
10197     //  --x;
10198     //  x binop= expr;
10199     //  x = x binop expr;
10200     //  x = expr binop x;
10201     OpenMPAtomicUpdateChecker Checker(*this);
10202     if (Checker.checkStatement(
10203             Body, (AtomicKind == OMPC_update)
10204                       ? diag::err_omp_atomic_update_not_expression_statement
10205                       : diag::err_omp_atomic_not_expression_statement,
10206             diag::note_omp_atomic_update))
10207       return StmtError();
10208     if (!CurContext->isDependentContext()) {
10209       E = Checker.getExpr();
10210       X = Checker.getX();
10211       UE = Checker.getUpdateExpr();
10212       IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
10213     }
10214   } else if (AtomicKind == OMPC_capture) {
10215     enum {
10216       NotAnAssignmentOp,
10217       NotACompoundStatement,
10218       NotTwoSubstatements,
10219       NotASpecificExpression,
10220       NoError
10221     } ErrorFound = NoError;
10222     SourceLocation ErrorLoc, NoteLoc;
10223     SourceRange ErrorRange, NoteRange;
10224     if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
10225       // If clause is a capture:
10226       //  v = x++;
10227       //  v = x--;
10228       //  v = ++x;
10229       //  v = --x;
10230       //  v = x binop= expr;
10231       //  v = x = x binop expr;
10232       //  v = x = expr binop x;
10233       const auto *AtomicBinOp =
10234           dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
10235       if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
10236         V = AtomicBinOp->getLHS();
10237         Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
10238         OpenMPAtomicUpdateChecker Checker(*this);
10239         if (Checker.checkStatement(
10240                 Body, diag::err_omp_atomic_capture_not_expression_statement,
10241                 diag::note_omp_atomic_update))
10242           return StmtError();
10243         E = Checker.getExpr();
10244         X = Checker.getX();
10245         UE = Checker.getUpdateExpr();
10246         IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
10247         IsPostfixUpdate = Checker.isPostfixUpdate();
10248       } else if (!AtomicBody->isInstantiationDependent()) {
10249         ErrorLoc = AtomicBody->getExprLoc();
10250         ErrorRange = AtomicBody->getSourceRange();
10251         NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
10252                               : AtomicBody->getExprLoc();
10253         NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
10254                                 : AtomicBody->getSourceRange();
10255         ErrorFound = NotAnAssignmentOp;
10256       }
10257       if (ErrorFound != NoError) {
10258         Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement)
10259             << ErrorRange;
10260         Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
10261         return StmtError();
10262       }
10263       if (CurContext->isDependentContext())
10264         UE = V = E = X = nullptr;
10265     } else {
10266       // If clause is a capture:
10267       //  { v = x; x = expr; }
10268       //  { v = x; x++; }
10269       //  { v = x; x--; }
10270       //  { v = x; ++x; }
10271       //  { v = x; --x; }
10272       //  { v = x; x binop= expr; }
10273       //  { v = x; x = x binop expr; }
10274       //  { v = x; x = expr binop x; }
10275       //  { x++; v = x; }
10276       //  { x--; v = x; }
10277       //  { ++x; v = x; }
10278       //  { --x; v = x; }
10279       //  { x binop= expr; v = x; }
10280       //  { x = x binop expr; v = x; }
10281       //  { x = expr binop x; v = x; }
10282       if (auto *CS = dyn_cast<CompoundStmt>(Body)) {
10283         // Check that this is { expr1; expr2; }
10284         if (CS->size() == 2) {
10285           Stmt *First = CS->body_front();
10286           Stmt *Second = CS->body_back();
10287           if (auto *EWC = dyn_cast<ExprWithCleanups>(First))
10288             First = EWC->getSubExpr()->IgnoreParenImpCasts();
10289           if (auto *EWC = dyn_cast<ExprWithCleanups>(Second))
10290             Second = EWC->getSubExpr()->IgnoreParenImpCasts();
10291           // Need to find what subexpression is 'v' and what is 'x'.
10292           OpenMPAtomicUpdateChecker Checker(*this);
10293           bool IsUpdateExprFound = !Checker.checkStatement(Second);
10294           BinaryOperator *BinOp = nullptr;
10295           if (IsUpdateExprFound) {
10296             BinOp = dyn_cast<BinaryOperator>(First);
10297             IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
10298           }
10299           if (IsUpdateExprFound && !CurContext->isDependentContext()) {
10300             //  { v = x; x++; }
10301             //  { v = x; x--; }
10302             //  { v = x; ++x; }
10303             //  { v = x; --x; }
10304             //  { v = x; x binop= expr; }
10305             //  { v = x; x = x binop expr; }
10306             //  { v = x; x = expr binop x; }
10307             // Check that the first expression has form v = x.
10308             Expr *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
10309             llvm::FoldingSetNodeID XId, PossibleXId;
10310             Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
10311             PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
10312             IsUpdateExprFound = XId == PossibleXId;
10313             if (IsUpdateExprFound) {
10314               V = BinOp->getLHS();
10315               X = Checker.getX();
10316               E = Checker.getExpr();
10317               UE = Checker.getUpdateExpr();
10318               IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
10319               IsPostfixUpdate = true;
10320             }
10321           }
10322           if (!IsUpdateExprFound) {
10323             IsUpdateExprFound = !Checker.checkStatement(First);
10324             BinOp = nullptr;
10325             if (IsUpdateExprFound) {
10326               BinOp = dyn_cast<BinaryOperator>(Second);
10327               IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
10328             }
10329             if (IsUpdateExprFound && !CurContext->isDependentContext()) {
10330               //  { x++; v = x; }
10331               //  { x--; v = x; }
10332               //  { ++x; v = x; }
10333               //  { --x; v = x; }
10334               //  { x binop= expr; v = x; }
10335               //  { x = x binop expr; v = x; }
10336               //  { x = expr binop x; v = x; }
10337               // Check that the second expression has form v = x.
10338               Expr *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
10339               llvm::FoldingSetNodeID XId, PossibleXId;
10340               Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
10341               PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
10342               IsUpdateExprFound = XId == PossibleXId;
10343               if (IsUpdateExprFound) {
10344                 V = BinOp->getLHS();
10345                 X = Checker.getX();
10346                 E = Checker.getExpr();
10347                 UE = Checker.getUpdateExpr();
10348                 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
10349                 IsPostfixUpdate = false;
10350               }
10351             }
10352           }
10353           if (!IsUpdateExprFound) {
10354             //  { v = x; x = expr; }
10355             auto *FirstExpr = dyn_cast<Expr>(First);
10356             auto *SecondExpr = dyn_cast<Expr>(Second);
10357             if (!FirstExpr || !SecondExpr ||
10358                 !(FirstExpr->isInstantiationDependent() ||
10359                   SecondExpr->isInstantiationDependent())) {
10360               auto *FirstBinOp = dyn_cast<BinaryOperator>(First);
10361               if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) {
10362                 ErrorFound = NotAnAssignmentOp;
10363                 NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc()
10364                                                 : First->getBeginLoc();
10365                 NoteRange = ErrorRange = FirstBinOp
10366                                              ? FirstBinOp->getSourceRange()
10367                                              : SourceRange(ErrorLoc, ErrorLoc);
10368               } else {
10369                 auto *SecondBinOp = dyn_cast<BinaryOperator>(Second);
10370                 if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) {
10371                   ErrorFound = NotAnAssignmentOp;
10372                   NoteLoc = ErrorLoc = SecondBinOp
10373                                            ? SecondBinOp->getOperatorLoc()
10374                                            : Second->getBeginLoc();
10375                   NoteRange = ErrorRange =
10376                       SecondBinOp ? SecondBinOp->getSourceRange()
10377                                   : SourceRange(ErrorLoc, ErrorLoc);
10378                 } else {
10379                   Expr *PossibleXRHSInFirst =
10380                       FirstBinOp->getRHS()->IgnoreParenImpCasts();
10381                   Expr *PossibleXLHSInSecond =
10382                       SecondBinOp->getLHS()->IgnoreParenImpCasts();
10383                   llvm::FoldingSetNodeID X1Id, X2Id;
10384                   PossibleXRHSInFirst->Profile(X1Id, Context,
10385                                                /*Canonical=*/true);
10386                   PossibleXLHSInSecond->Profile(X2Id, Context,
10387                                                 /*Canonical=*/true);
10388                   IsUpdateExprFound = X1Id == X2Id;
10389                   if (IsUpdateExprFound) {
10390                     V = FirstBinOp->getLHS();
10391                     X = SecondBinOp->getLHS();
10392                     E = SecondBinOp->getRHS();
10393                     UE = nullptr;
10394                     IsXLHSInRHSPart = false;
10395                     IsPostfixUpdate = true;
10396                   } else {
10397                     ErrorFound = NotASpecificExpression;
10398                     ErrorLoc = FirstBinOp->getExprLoc();
10399                     ErrorRange = FirstBinOp->getSourceRange();
10400                     NoteLoc = SecondBinOp->getLHS()->getExprLoc();
10401                     NoteRange = SecondBinOp->getRHS()->getSourceRange();
10402                   }
10403                 }
10404               }
10405             }
10406           }
10407         } else {
10408           NoteLoc = ErrorLoc = Body->getBeginLoc();
10409           NoteRange = ErrorRange =
10410               SourceRange(Body->getBeginLoc(), Body->getBeginLoc());
10411           ErrorFound = NotTwoSubstatements;
10412         }
10413       } else {
10414         NoteLoc = ErrorLoc = Body->getBeginLoc();
10415         NoteRange = ErrorRange =
10416             SourceRange(Body->getBeginLoc(), Body->getBeginLoc());
10417         ErrorFound = NotACompoundStatement;
10418       }
10419       if (ErrorFound != NoError) {
10420         Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement)
10421             << ErrorRange;
10422         Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
10423         return StmtError();
10424       }
10425       if (CurContext->isDependentContext())
10426         UE = V = E = X = nullptr;
10427     }
10428   }
10429 
10430   setFunctionHasBranchProtectedScope();
10431 
10432   return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
10433                                     X, V, E, UE, IsXLHSInRHSPart,
10434                                     IsPostfixUpdate);
10435 }
10436 
10437 StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
10438                                             Stmt *AStmt,
10439                                             SourceLocation StartLoc,
10440                                             SourceLocation EndLoc) {
10441   if (!AStmt)
10442     return StmtError();
10443 
10444   auto *CS = cast<CapturedStmt>(AStmt);
10445   // 1.2.2 OpenMP Language Terminology
10446   // Structured block - An executable statement with a single entry at the
10447   // top and a single exit at the bottom.
10448   // The point of exit cannot be a branch out of the structured block.
10449   // longjmp() and throw() must not violate the entry/exit criteria.
10450   CS->getCapturedDecl()->setNothrow();
10451   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target);
10452        ThisCaptureLevel > 1; --ThisCaptureLevel) {
10453     CS = cast<CapturedStmt>(CS->getCapturedStmt());
10454     // 1.2.2 OpenMP Language Terminology
10455     // Structured block - An executable statement with a single entry at the
10456     // top and a single exit at the bottom.
10457     // The point of exit cannot be a branch out of the structured block.
10458     // longjmp() and throw() must not violate the entry/exit criteria.
10459     CS->getCapturedDecl()->setNothrow();
10460   }
10461 
10462   // OpenMP [2.16, Nesting of Regions]
10463   // If specified, a teams construct must be contained within a target
10464   // construct. That target construct must contain no statements or directives
10465   // outside of the teams construct.
10466   if (DSAStack->hasInnerTeamsRegion()) {
10467     const Stmt *S = CS->IgnoreContainers(/*IgnoreCaptured=*/true);
10468     bool OMPTeamsFound = true;
10469     if (const auto *CS = dyn_cast<CompoundStmt>(S)) {
10470       auto I = CS->body_begin();
10471       while (I != CS->body_end()) {
10472         const auto *OED = dyn_cast<OMPExecutableDirective>(*I);
10473         if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind()) ||
10474             OMPTeamsFound) {
10475 
10476           OMPTeamsFound = false;
10477           break;
10478         }
10479         ++I;
10480       }
10481       assert(I != CS->body_end() && "Not found statement");
10482       S = *I;
10483     } else {
10484       const auto *OED = dyn_cast<OMPExecutableDirective>(S);
10485       OMPTeamsFound = OED && isOpenMPTeamsDirective(OED->getDirectiveKind());
10486     }
10487     if (!OMPTeamsFound) {
10488       Diag(StartLoc, diag::err_omp_target_contains_not_only_teams);
10489       Diag(DSAStack->getInnerTeamsRegionLoc(),
10490            diag::note_omp_nested_teams_construct_here);
10491       Diag(S->getBeginLoc(), diag::note_omp_nested_statement_here)
10492           << isa<OMPExecutableDirective>(S);
10493       return StmtError();
10494     }
10495   }
10496 
10497   setFunctionHasBranchProtectedScope();
10498 
10499   return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
10500 }
10501 
10502 StmtResult
10503 Sema::ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
10504                                          Stmt *AStmt, SourceLocation StartLoc,
10505                                          SourceLocation EndLoc) {
10506   if (!AStmt)
10507     return StmtError();
10508 
10509   auto *CS = cast<CapturedStmt>(AStmt);
10510   // 1.2.2 OpenMP Language Terminology
10511   // Structured block - An executable statement with a single entry at the
10512   // top and a single exit at the bottom.
10513   // The point of exit cannot be a branch out of the structured block.
10514   // longjmp() and throw() must not violate the entry/exit criteria.
10515   CS->getCapturedDecl()->setNothrow();
10516   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel);
10517        ThisCaptureLevel > 1; --ThisCaptureLevel) {
10518     CS = cast<CapturedStmt>(CS->getCapturedStmt());
10519     // 1.2.2 OpenMP Language Terminology
10520     // Structured block - An executable statement with a single entry at the
10521     // top and a single exit at the bottom.
10522     // The point of exit cannot be a branch out of the structured block.
10523     // longjmp() and throw() must not violate the entry/exit criteria.
10524     CS->getCapturedDecl()->setNothrow();
10525   }
10526 
10527   setFunctionHasBranchProtectedScope();
10528 
10529   return OMPTargetParallelDirective::Create(
10530       Context, StartLoc, EndLoc, Clauses, AStmt,
10531       DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion());
10532 }
10533 
10534 StmtResult Sema::ActOnOpenMPTargetParallelForDirective(
10535     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10536     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
10537   if (!AStmt)
10538     return StmtError();
10539 
10540   auto *CS = cast<CapturedStmt>(AStmt);
10541   // 1.2.2 OpenMP Language Terminology
10542   // Structured block - An executable statement with a single entry at the
10543   // top and a single exit at the bottom.
10544   // The point of exit cannot be a branch out of the structured block.
10545   // longjmp() and throw() must not violate the entry/exit criteria.
10546   CS->getCapturedDecl()->setNothrow();
10547   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
10548        ThisCaptureLevel > 1; --ThisCaptureLevel) {
10549     CS = cast<CapturedStmt>(CS->getCapturedStmt());
10550     // 1.2.2 OpenMP Language Terminology
10551     // Structured block - An executable statement with a single entry at the
10552     // top and a single exit at the bottom.
10553     // The point of exit cannot be a branch out of the structured block.
10554     // longjmp() and throw() must not violate the entry/exit criteria.
10555     CS->getCapturedDecl()->setNothrow();
10556   }
10557 
10558   OMPLoopDirective::HelperExprs B;
10559   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
10560   // define the nested loops number.
10561   unsigned NestedLoopCount =
10562       checkOpenMPLoop(OMPD_target_parallel_for, getCollapseNumberExpr(Clauses),
10563                       getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
10564                       VarsWithImplicitDSA, B);
10565   if (NestedLoopCount == 0)
10566     return StmtError();
10567 
10568   assert((CurContext->isDependentContext() || B.builtAll()) &&
10569          "omp target parallel for loop exprs were not built");
10570 
10571   if (!CurContext->isDependentContext()) {
10572     // Finalize the clauses that need pre-built expressions for CodeGen.
10573     for (OMPClause *C : Clauses) {
10574       if (auto *LC = dyn_cast<OMPLinearClause>(C))
10575         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
10576                                      B.NumIterations, *this, CurScope,
10577                                      DSAStack))
10578           return StmtError();
10579     }
10580   }
10581 
10582   setFunctionHasBranchProtectedScope();
10583   return OMPTargetParallelForDirective::Create(
10584       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
10585       DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion());
10586 }
10587 
10588 /// Check for existence of a map clause in the list of clauses.
10589 static bool hasClauses(ArrayRef<OMPClause *> Clauses,
10590                        const OpenMPClauseKind K) {
10591   return llvm::any_of(
10592       Clauses, [K](const OMPClause *C) { return C->getClauseKind() == K; });
10593 }
10594 
10595 template <typename... Params>
10596 static bool hasClauses(ArrayRef<OMPClause *> Clauses, const OpenMPClauseKind K,
10597                        const Params... ClauseTypes) {
10598   return hasClauses(Clauses, K) || hasClauses(Clauses, ClauseTypes...);
10599 }
10600 
10601 StmtResult Sema::ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
10602                                                 Stmt *AStmt,
10603                                                 SourceLocation StartLoc,
10604                                                 SourceLocation EndLoc) {
10605   if (!AStmt)
10606     return StmtError();
10607 
10608   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
10609 
10610   // OpenMP [2.12.2, target data Construct, Restrictions]
10611   // At least one map, use_device_addr or use_device_ptr clause must appear on
10612   // the directive.
10613   if (!hasClauses(Clauses, OMPC_map, OMPC_use_device_ptr) &&
10614       (LangOpts.OpenMP < 50 || !hasClauses(Clauses, OMPC_use_device_addr))) {
10615     StringRef Expected;
10616     if (LangOpts.OpenMP < 50)
10617       Expected = "'map' or 'use_device_ptr'";
10618     else
10619       Expected = "'map', 'use_device_ptr', or 'use_device_addr'";
10620     Diag(StartLoc, diag::err_omp_no_clause_for_directive)
10621         << Expected << getOpenMPDirectiveName(OMPD_target_data);
10622     return StmtError();
10623   }
10624 
10625   setFunctionHasBranchProtectedScope();
10626 
10627   return OMPTargetDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
10628                                         AStmt);
10629 }
10630 
10631 StmtResult
10632 Sema::ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
10633                                           SourceLocation StartLoc,
10634                                           SourceLocation EndLoc, Stmt *AStmt) {
10635   if (!AStmt)
10636     return StmtError();
10637 
10638   auto *CS = cast<CapturedStmt>(AStmt);
10639   // 1.2.2 OpenMP Language Terminology
10640   // Structured block - An executable statement with a single entry at the
10641   // top and a single exit at the bottom.
10642   // The point of exit cannot be a branch out of the structured block.
10643   // longjmp() and throw() must not violate the entry/exit criteria.
10644   CS->getCapturedDecl()->setNothrow();
10645   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_enter_data);
10646        ThisCaptureLevel > 1; --ThisCaptureLevel) {
10647     CS = cast<CapturedStmt>(CS->getCapturedStmt());
10648     // 1.2.2 OpenMP Language Terminology
10649     // Structured block - An executable statement with a single entry at the
10650     // top and a single exit at the bottom.
10651     // The point of exit cannot be a branch out of the structured block.
10652     // longjmp() and throw() must not violate the entry/exit criteria.
10653     CS->getCapturedDecl()->setNothrow();
10654   }
10655 
10656   // OpenMP [2.10.2, Restrictions, p. 99]
10657   // At least one map clause must appear on the directive.
10658   if (!hasClauses(Clauses, OMPC_map)) {
10659     Diag(StartLoc, diag::err_omp_no_clause_for_directive)
10660         << "'map'" << getOpenMPDirectiveName(OMPD_target_enter_data);
10661     return StmtError();
10662   }
10663 
10664   return OMPTargetEnterDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
10665                                              AStmt);
10666 }
10667 
10668 StmtResult
10669 Sema::ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
10670                                          SourceLocation StartLoc,
10671                                          SourceLocation EndLoc, Stmt *AStmt) {
10672   if (!AStmt)
10673     return StmtError();
10674 
10675   auto *CS = cast<CapturedStmt>(AStmt);
10676   // 1.2.2 OpenMP Language Terminology
10677   // Structured block - An executable statement with a single entry at the
10678   // top and a single exit at the bottom.
10679   // The point of exit cannot be a branch out of the structured block.
10680   // longjmp() and throw() must not violate the entry/exit criteria.
10681   CS->getCapturedDecl()->setNothrow();
10682   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_exit_data);
10683        ThisCaptureLevel > 1; --ThisCaptureLevel) {
10684     CS = cast<CapturedStmt>(CS->getCapturedStmt());
10685     // 1.2.2 OpenMP Language Terminology
10686     // Structured block - An executable statement with a single entry at the
10687     // top and a single exit at the bottom.
10688     // The point of exit cannot be a branch out of the structured block.
10689     // longjmp() and throw() must not violate the entry/exit criteria.
10690     CS->getCapturedDecl()->setNothrow();
10691   }
10692 
10693   // OpenMP [2.10.3, Restrictions, p. 102]
10694   // At least one map clause must appear on the directive.
10695   if (!hasClauses(Clauses, OMPC_map)) {
10696     Diag(StartLoc, diag::err_omp_no_clause_for_directive)
10697         << "'map'" << getOpenMPDirectiveName(OMPD_target_exit_data);
10698     return StmtError();
10699   }
10700 
10701   return OMPTargetExitDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
10702                                             AStmt);
10703 }
10704 
10705 StmtResult Sema::ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
10706                                                   SourceLocation StartLoc,
10707                                                   SourceLocation EndLoc,
10708                                                   Stmt *AStmt) {
10709   if (!AStmt)
10710     return StmtError();
10711 
10712   auto *CS = cast<CapturedStmt>(AStmt);
10713   // 1.2.2 OpenMP Language Terminology
10714   // Structured block - An executable statement with a single entry at the
10715   // top and a single exit at the bottom.
10716   // The point of exit cannot be a branch out of the structured block.
10717   // longjmp() and throw() must not violate the entry/exit criteria.
10718   CS->getCapturedDecl()->setNothrow();
10719   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_update);
10720        ThisCaptureLevel > 1; --ThisCaptureLevel) {
10721     CS = cast<CapturedStmt>(CS->getCapturedStmt());
10722     // 1.2.2 OpenMP Language Terminology
10723     // Structured block - An executable statement with a single entry at the
10724     // top and a single exit at the bottom.
10725     // The point of exit cannot be a branch out of the structured block.
10726     // longjmp() and throw() must not violate the entry/exit criteria.
10727     CS->getCapturedDecl()->setNothrow();
10728   }
10729 
10730   if (!hasClauses(Clauses, OMPC_to, OMPC_from)) {
10731     Diag(StartLoc, diag::err_omp_at_least_one_motion_clause_required);
10732     return StmtError();
10733   }
10734   return OMPTargetUpdateDirective::Create(Context, StartLoc, EndLoc, Clauses,
10735                                           AStmt);
10736 }
10737 
10738 StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
10739                                            Stmt *AStmt, SourceLocation StartLoc,
10740                                            SourceLocation EndLoc) {
10741   if (!AStmt)
10742     return StmtError();
10743 
10744   auto *CS = cast<CapturedStmt>(AStmt);
10745   // 1.2.2 OpenMP Language Terminology
10746   // Structured block - An executable statement with a single entry at the
10747   // top and a single exit at the bottom.
10748   // The point of exit cannot be a branch out of the structured block.
10749   // longjmp() and throw() must not violate the entry/exit criteria.
10750   CS->getCapturedDecl()->setNothrow();
10751 
10752   setFunctionHasBranchProtectedScope();
10753 
10754   DSAStack->setParentTeamsRegionLoc(StartLoc);
10755 
10756   return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
10757 }
10758 
10759 StmtResult
10760 Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
10761                                             SourceLocation EndLoc,
10762                                             OpenMPDirectiveKind CancelRegion) {
10763   if (DSAStack->isParentNowaitRegion()) {
10764     Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0;
10765     return StmtError();
10766   }
10767   if (DSAStack->isParentOrderedRegion()) {
10768     Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0;
10769     return StmtError();
10770   }
10771   return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc,
10772                                                CancelRegion);
10773 }
10774 
10775 StmtResult Sema::ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
10776                                             SourceLocation StartLoc,
10777                                             SourceLocation EndLoc,
10778                                             OpenMPDirectiveKind CancelRegion) {
10779   if (DSAStack->isParentNowaitRegion()) {
10780     Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1;
10781     return StmtError();
10782   }
10783   if (DSAStack->isParentOrderedRegion()) {
10784     Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1;
10785     return StmtError();
10786   }
10787   DSAStack->setParentCancelRegion(/*Cancel=*/true);
10788   return OMPCancelDirective::Create(Context, StartLoc, EndLoc, Clauses,
10789                                     CancelRegion);
10790 }
10791 
10792 static bool checkGrainsizeNumTasksClauses(Sema &S,
10793                                           ArrayRef<OMPClause *> Clauses) {
10794   const OMPClause *PrevClause = nullptr;
10795   bool ErrorFound = false;
10796   for (const OMPClause *C : Clauses) {
10797     if (C->getClauseKind() == OMPC_grainsize ||
10798         C->getClauseKind() == OMPC_num_tasks) {
10799       if (!PrevClause)
10800         PrevClause = C;
10801       else if (PrevClause->getClauseKind() != C->getClauseKind()) {
10802         S.Diag(C->getBeginLoc(), diag::err_omp_clauses_mutually_exclusive)
10803             << getOpenMPClauseName(C->getClauseKind())
10804             << getOpenMPClauseName(PrevClause->getClauseKind());
10805         S.Diag(PrevClause->getBeginLoc(), diag::note_omp_previous_clause)
10806             << getOpenMPClauseName(PrevClause->getClauseKind());
10807         ErrorFound = true;
10808       }
10809     }
10810   }
10811   return ErrorFound;
10812 }
10813 
10814 static bool checkReductionClauseWithNogroup(Sema &S,
10815                                             ArrayRef<OMPClause *> Clauses) {
10816   const OMPClause *ReductionClause = nullptr;
10817   const OMPClause *NogroupClause = nullptr;
10818   for (const OMPClause *C : Clauses) {
10819     if (C->getClauseKind() == OMPC_reduction) {
10820       ReductionClause = C;
10821       if (NogroupClause)
10822         break;
10823       continue;
10824     }
10825     if (C->getClauseKind() == OMPC_nogroup) {
10826       NogroupClause = C;
10827       if (ReductionClause)
10828         break;
10829       continue;
10830     }
10831   }
10832   if (ReductionClause && NogroupClause) {
10833     S.Diag(ReductionClause->getBeginLoc(), diag::err_omp_reduction_with_nogroup)
10834         << SourceRange(NogroupClause->getBeginLoc(),
10835                        NogroupClause->getEndLoc());
10836     return true;
10837   }
10838   return false;
10839 }
10840 
10841 StmtResult Sema::ActOnOpenMPTaskLoopDirective(
10842     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10843     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
10844   if (!AStmt)
10845     return StmtError();
10846 
10847   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
10848   OMPLoopDirective::HelperExprs B;
10849   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
10850   // define the nested loops number.
10851   unsigned NestedLoopCount =
10852       checkOpenMPLoop(OMPD_taskloop, getCollapseNumberExpr(Clauses),
10853                       /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
10854                       VarsWithImplicitDSA, B);
10855   if (NestedLoopCount == 0)
10856     return StmtError();
10857 
10858   assert((CurContext->isDependentContext() || B.builtAll()) &&
10859          "omp for loop exprs were not built");
10860 
10861   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
10862   // The grainsize clause and num_tasks clause are mutually exclusive and may
10863   // not appear on the same taskloop directive.
10864   if (checkGrainsizeNumTasksClauses(*this, Clauses))
10865     return StmtError();
10866   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
10867   // If a reduction clause is present on the taskloop directive, the nogroup
10868   // clause must not be specified.
10869   if (checkReductionClauseWithNogroup(*this, Clauses))
10870     return StmtError();
10871 
10872   setFunctionHasBranchProtectedScope();
10873   return OMPTaskLoopDirective::Create(Context, StartLoc, EndLoc,
10874                                       NestedLoopCount, Clauses, AStmt, B,
10875                                       DSAStack->isCancelRegion());
10876 }
10877 
10878 StmtResult Sema::ActOnOpenMPTaskLoopSimdDirective(
10879     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10880     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
10881   if (!AStmt)
10882     return StmtError();
10883 
10884   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
10885   OMPLoopDirective::HelperExprs B;
10886   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
10887   // define the nested loops number.
10888   unsigned NestedLoopCount =
10889       checkOpenMPLoop(OMPD_taskloop_simd, getCollapseNumberExpr(Clauses),
10890                       /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
10891                       VarsWithImplicitDSA, B);
10892   if (NestedLoopCount == 0)
10893     return StmtError();
10894 
10895   assert((CurContext->isDependentContext() || B.builtAll()) &&
10896          "omp for loop exprs were not built");
10897 
10898   if (!CurContext->isDependentContext()) {
10899     // Finalize the clauses that need pre-built expressions for CodeGen.
10900     for (OMPClause *C : Clauses) {
10901       if (auto *LC = dyn_cast<OMPLinearClause>(C))
10902         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
10903                                      B.NumIterations, *this, CurScope,
10904                                      DSAStack))
10905           return StmtError();
10906     }
10907   }
10908 
10909   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
10910   // The grainsize clause and num_tasks clause are mutually exclusive and may
10911   // not appear on the same taskloop directive.
10912   if (checkGrainsizeNumTasksClauses(*this, Clauses))
10913     return StmtError();
10914   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
10915   // If a reduction clause is present on the taskloop directive, the nogroup
10916   // clause must not be specified.
10917   if (checkReductionClauseWithNogroup(*this, Clauses))
10918     return StmtError();
10919   if (checkSimdlenSafelenSpecified(*this, Clauses))
10920     return StmtError();
10921 
10922   setFunctionHasBranchProtectedScope();
10923   return OMPTaskLoopSimdDirective::Create(Context, StartLoc, EndLoc,
10924                                           NestedLoopCount, Clauses, AStmt, B);
10925 }
10926 
10927 StmtResult Sema::ActOnOpenMPMasterTaskLoopDirective(
10928     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10929     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
10930   if (!AStmt)
10931     return StmtError();
10932 
10933   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
10934   OMPLoopDirective::HelperExprs B;
10935   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
10936   // define the nested loops number.
10937   unsigned NestedLoopCount =
10938       checkOpenMPLoop(OMPD_master_taskloop, getCollapseNumberExpr(Clauses),
10939                       /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
10940                       VarsWithImplicitDSA, B);
10941   if (NestedLoopCount == 0)
10942     return StmtError();
10943 
10944   assert((CurContext->isDependentContext() || B.builtAll()) &&
10945          "omp for loop exprs were not built");
10946 
10947   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
10948   // The grainsize clause and num_tasks clause are mutually exclusive and may
10949   // not appear on the same taskloop directive.
10950   if (checkGrainsizeNumTasksClauses(*this, Clauses))
10951     return StmtError();
10952   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
10953   // If a reduction clause is present on the taskloop directive, the nogroup
10954   // clause must not be specified.
10955   if (checkReductionClauseWithNogroup(*this, Clauses))
10956     return StmtError();
10957 
10958   setFunctionHasBranchProtectedScope();
10959   return OMPMasterTaskLoopDirective::Create(Context, StartLoc, EndLoc,
10960                                             NestedLoopCount, Clauses, AStmt, B,
10961                                             DSAStack->isCancelRegion());
10962 }
10963 
10964 StmtResult Sema::ActOnOpenMPMasterTaskLoopSimdDirective(
10965     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10966     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
10967   if (!AStmt)
10968     return StmtError();
10969 
10970   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
10971   OMPLoopDirective::HelperExprs B;
10972   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
10973   // define the nested loops number.
10974   unsigned NestedLoopCount =
10975       checkOpenMPLoop(OMPD_master_taskloop_simd, getCollapseNumberExpr(Clauses),
10976                       /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
10977                       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   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
10996   // The grainsize clause and num_tasks clause are mutually exclusive and may
10997   // not appear on the same taskloop directive.
10998   if (checkGrainsizeNumTasksClauses(*this, Clauses))
10999     return StmtError();
11000   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
11001   // If a reduction clause is present on the taskloop directive, the nogroup
11002   // clause must not be specified.
11003   if (checkReductionClauseWithNogroup(*this, Clauses))
11004     return StmtError();
11005   if (checkSimdlenSafelenSpecified(*this, Clauses))
11006     return StmtError();
11007 
11008   setFunctionHasBranchProtectedScope();
11009   return OMPMasterTaskLoopSimdDirective::Create(
11010       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
11011 }
11012 
11013 StmtResult Sema::ActOnOpenMPParallelMasterTaskLoopDirective(
11014     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11015     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
11016   if (!AStmt)
11017     return StmtError();
11018 
11019   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
11020   auto *CS = cast<CapturedStmt>(AStmt);
11021   // 1.2.2 OpenMP Language Terminology
11022   // Structured block - An executable statement with a single entry at the
11023   // top and a single exit at the bottom.
11024   // The point of exit cannot be a branch out of the structured block.
11025   // longjmp() and throw() must not violate the entry/exit criteria.
11026   CS->getCapturedDecl()->setNothrow();
11027   for (int ThisCaptureLevel =
11028            getOpenMPCaptureLevels(OMPD_parallel_master_taskloop);
11029        ThisCaptureLevel > 1; --ThisCaptureLevel) {
11030     CS = cast<CapturedStmt>(CS->getCapturedStmt());
11031     // 1.2.2 OpenMP Language Terminology
11032     // Structured block - An executable statement with a single entry at the
11033     // top and a single exit at the bottom.
11034     // The point of exit cannot be a branch out of the structured block.
11035     // longjmp() and throw() must not violate the entry/exit criteria.
11036     CS->getCapturedDecl()->setNothrow();
11037   }
11038 
11039   OMPLoopDirective::HelperExprs B;
11040   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
11041   // define the nested loops number.
11042   unsigned NestedLoopCount = checkOpenMPLoop(
11043       OMPD_parallel_master_taskloop, getCollapseNumberExpr(Clauses),
11044       /*OrderedLoopCountExpr=*/nullptr, CS, *this, *DSAStack,
11045       VarsWithImplicitDSA, B);
11046   if (NestedLoopCount == 0)
11047     return StmtError();
11048 
11049   assert((CurContext->isDependentContext() || B.builtAll()) &&
11050          "omp for loop exprs were not built");
11051 
11052   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
11053   // The grainsize clause and num_tasks clause are mutually exclusive and may
11054   // not appear on the same taskloop directive.
11055   if (checkGrainsizeNumTasksClauses(*this, Clauses))
11056     return StmtError();
11057   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
11058   // If a reduction clause is present on the taskloop directive, the nogroup
11059   // clause must not be specified.
11060   if (checkReductionClauseWithNogroup(*this, Clauses))
11061     return StmtError();
11062 
11063   setFunctionHasBranchProtectedScope();
11064   return OMPParallelMasterTaskLoopDirective::Create(
11065       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
11066       DSAStack->isCancelRegion());
11067 }
11068 
11069 StmtResult Sema::ActOnOpenMPParallelMasterTaskLoopSimdDirective(
11070     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11071     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
11072   if (!AStmt)
11073     return StmtError();
11074 
11075   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
11076   auto *CS = cast<CapturedStmt>(AStmt);
11077   // 1.2.2 OpenMP Language Terminology
11078   // Structured block - An executable statement with a single entry at the
11079   // top and a single exit at the bottom.
11080   // The point of exit cannot be a branch out of the structured block.
11081   // longjmp() and throw() must not violate the entry/exit criteria.
11082   CS->getCapturedDecl()->setNothrow();
11083   for (int ThisCaptureLevel =
11084            getOpenMPCaptureLevels(OMPD_parallel_master_taskloop_simd);
11085        ThisCaptureLevel > 1; --ThisCaptureLevel) {
11086     CS = cast<CapturedStmt>(CS->getCapturedStmt());
11087     // 1.2.2 OpenMP Language Terminology
11088     // Structured block - An executable statement with a single entry at the
11089     // top and a single exit at the bottom.
11090     // The point of exit cannot be a branch out of the structured block.
11091     // longjmp() and throw() must not violate the entry/exit criteria.
11092     CS->getCapturedDecl()->setNothrow();
11093   }
11094 
11095   OMPLoopDirective::HelperExprs B;
11096   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
11097   // define the nested loops number.
11098   unsigned NestedLoopCount = checkOpenMPLoop(
11099       OMPD_parallel_master_taskloop_simd, getCollapseNumberExpr(Clauses),
11100       /*OrderedLoopCountExpr=*/nullptr, CS, *this, *DSAStack,
11101       VarsWithImplicitDSA, B);
11102   if (NestedLoopCount == 0)
11103     return StmtError();
11104 
11105   assert((CurContext->isDependentContext() || B.builtAll()) &&
11106          "omp for loop exprs were not built");
11107 
11108   if (!CurContext->isDependentContext()) {
11109     // Finalize the clauses that need pre-built expressions for CodeGen.
11110     for (OMPClause *C : Clauses) {
11111       if (auto *LC = dyn_cast<OMPLinearClause>(C))
11112         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
11113                                      B.NumIterations, *this, CurScope,
11114                                      DSAStack))
11115           return StmtError();
11116     }
11117   }
11118 
11119   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
11120   // The grainsize clause and num_tasks clause are mutually exclusive and may
11121   // not appear on the same taskloop directive.
11122   if (checkGrainsizeNumTasksClauses(*this, Clauses))
11123     return StmtError();
11124   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
11125   // If a reduction clause is present on the taskloop directive, the nogroup
11126   // clause must not be specified.
11127   if (checkReductionClauseWithNogroup(*this, Clauses))
11128     return StmtError();
11129   if (checkSimdlenSafelenSpecified(*this, Clauses))
11130     return StmtError();
11131 
11132   setFunctionHasBranchProtectedScope();
11133   return OMPParallelMasterTaskLoopSimdDirective::Create(
11134       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
11135 }
11136 
11137 StmtResult Sema::ActOnOpenMPDistributeDirective(
11138     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11139     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
11140   if (!AStmt)
11141     return StmtError();
11142 
11143   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
11144   OMPLoopDirective::HelperExprs B;
11145   // In presence of clause 'collapse' with number of loops, it will
11146   // define the nested loops number.
11147   unsigned NestedLoopCount =
11148       checkOpenMPLoop(OMPD_distribute, getCollapseNumberExpr(Clauses),
11149                       nullptr /*ordered not a clause on distribute*/, AStmt,
11150                       *this, *DSAStack, VarsWithImplicitDSA, B);
11151   if (NestedLoopCount == 0)
11152     return StmtError();
11153 
11154   assert((CurContext->isDependentContext() || B.builtAll()) &&
11155          "omp for loop exprs were not built");
11156 
11157   setFunctionHasBranchProtectedScope();
11158   return OMPDistributeDirective::Create(Context, StartLoc, EndLoc,
11159                                         NestedLoopCount, Clauses, AStmt, B);
11160 }
11161 
11162 StmtResult Sema::ActOnOpenMPDistributeParallelForDirective(
11163     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11164     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
11165   if (!AStmt)
11166     return StmtError();
11167 
11168   auto *CS = cast<CapturedStmt>(AStmt);
11169   // 1.2.2 OpenMP Language Terminology
11170   // Structured block - An executable statement with a single entry at the
11171   // top and a single exit at the bottom.
11172   // The point of exit cannot be a branch out of the structured block.
11173   // longjmp() and throw() must not violate the entry/exit criteria.
11174   CS->getCapturedDecl()->setNothrow();
11175   for (int ThisCaptureLevel =
11176            getOpenMPCaptureLevels(OMPD_distribute_parallel_for);
11177        ThisCaptureLevel > 1; --ThisCaptureLevel) {
11178     CS = cast<CapturedStmt>(CS->getCapturedStmt());
11179     // 1.2.2 OpenMP Language Terminology
11180     // Structured block - An executable statement with a single entry at the
11181     // top and a single exit at the bottom.
11182     // The point of exit cannot be a branch out of the structured block.
11183     // longjmp() and throw() must not violate the entry/exit criteria.
11184     CS->getCapturedDecl()->setNothrow();
11185   }
11186 
11187   OMPLoopDirective::HelperExprs B;
11188   // In presence of clause 'collapse' with number of loops, it will
11189   // define the nested loops number.
11190   unsigned NestedLoopCount = checkOpenMPLoop(
11191       OMPD_distribute_parallel_for, getCollapseNumberExpr(Clauses),
11192       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
11193       VarsWithImplicitDSA, B);
11194   if (NestedLoopCount == 0)
11195     return StmtError();
11196 
11197   assert((CurContext->isDependentContext() || B.builtAll()) &&
11198          "omp for loop exprs were not built");
11199 
11200   setFunctionHasBranchProtectedScope();
11201   return OMPDistributeParallelForDirective::Create(
11202       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
11203       DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion());
11204 }
11205 
11206 StmtResult Sema::ActOnOpenMPDistributeParallelForSimdDirective(
11207     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11208     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
11209   if (!AStmt)
11210     return StmtError();
11211 
11212   auto *CS = cast<CapturedStmt>(AStmt);
11213   // 1.2.2 OpenMP Language Terminology
11214   // Structured block - An executable statement with a single entry at the
11215   // top and a single exit at the bottom.
11216   // The point of exit cannot be a branch out of the structured block.
11217   // longjmp() and throw() must not violate the entry/exit criteria.
11218   CS->getCapturedDecl()->setNothrow();
11219   for (int ThisCaptureLevel =
11220            getOpenMPCaptureLevels(OMPD_distribute_parallel_for_simd);
11221        ThisCaptureLevel > 1; --ThisCaptureLevel) {
11222     CS = cast<CapturedStmt>(CS->getCapturedStmt());
11223     // 1.2.2 OpenMP Language Terminology
11224     // Structured block - An executable statement with a single entry at the
11225     // top and a single exit at the bottom.
11226     // The point of exit cannot be a branch out of the structured block.
11227     // longjmp() and throw() must not violate the entry/exit criteria.
11228     CS->getCapturedDecl()->setNothrow();
11229   }
11230 
11231   OMPLoopDirective::HelperExprs B;
11232   // In presence of clause 'collapse' with number of loops, it will
11233   // define the nested loops number.
11234   unsigned NestedLoopCount = checkOpenMPLoop(
11235       OMPD_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
11236       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
11237       VarsWithImplicitDSA, B);
11238   if (NestedLoopCount == 0)
11239     return StmtError();
11240 
11241   assert((CurContext->isDependentContext() || B.builtAll()) &&
11242          "omp for loop exprs were not built");
11243 
11244   if (!CurContext->isDependentContext()) {
11245     // Finalize the clauses that need pre-built expressions for CodeGen.
11246     for (OMPClause *C : Clauses) {
11247       if (auto *LC = dyn_cast<OMPLinearClause>(C))
11248         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
11249                                      B.NumIterations, *this, CurScope,
11250                                      DSAStack))
11251           return StmtError();
11252     }
11253   }
11254 
11255   if (checkSimdlenSafelenSpecified(*this, Clauses))
11256     return StmtError();
11257 
11258   setFunctionHasBranchProtectedScope();
11259   return OMPDistributeParallelForSimdDirective::Create(
11260       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
11261 }
11262 
11263 StmtResult Sema::ActOnOpenMPDistributeSimdDirective(
11264     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11265     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
11266   if (!AStmt)
11267     return StmtError();
11268 
11269   auto *CS = cast<CapturedStmt>(AStmt);
11270   // 1.2.2 OpenMP Language Terminology
11271   // Structured block - An executable statement with a single entry at the
11272   // top and a single exit at the bottom.
11273   // The point of exit cannot be a branch out of the structured block.
11274   // longjmp() and throw() must not violate the entry/exit criteria.
11275   CS->getCapturedDecl()->setNothrow();
11276   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_distribute_simd);
11277        ThisCaptureLevel > 1; --ThisCaptureLevel) {
11278     CS = cast<CapturedStmt>(CS->getCapturedStmt());
11279     // 1.2.2 OpenMP Language Terminology
11280     // Structured block - An executable statement with a single entry at the
11281     // top and a single exit at the bottom.
11282     // The point of exit cannot be a branch out of the structured block.
11283     // longjmp() and throw() must not violate the entry/exit criteria.
11284     CS->getCapturedDecl()->setNothrow();
11285   }
11286 
11287   OMPLoopDirective::HelperExprs B;
11288   // In presence of clause 'collapse' with number of loops, it will
11289   // define the nested loops number.
11290   unsigned NestedLoopCount =
11291       checkOpenMPLoop(OMPD_distribute_simd, getCollapseNumberExpr(Clauses),
11292                       nullptr /*ordered not a clause on distribute*/, CS, *this,
11293                       *DSAStack, VarsWithImplicitDSA, B);
11294   if (NestedLoopCount == 0)
11295     return StmtError();
11296 
11297   assert((CurContext->isDependentContext() || B.builtAll()) &&
11298          "omp for loop exprs were not built");
11299 
11300   if (!CurContext->isDependentContext()) {
11301     // Finalize the clauses that need pre-built expressions for CodeGen.
11302     for (OMPClause *C : Clauses) {
11303       if (auto *LC = dyn_cast<OMPLinearClause>(C))
11304         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
11305                                      B.NumIterations, *this, CurScope,
11306                                      DSAStack))
11307           return StmtError();
11308     }
11309   }
11310 
11311   if (checkSimdlenSafelenSpecified(*this, Clauses))
11312     return StmtError();
11313 
11314   setFunctionHasBranchProtectedScope();
11315   return OMPDistributeSimdDirective::Create(Context, StartLoc, EndLoc,
11316                                             NestedLoopCount, Clauses, AStmt, B);
11317 }
11318 
11319 StmtResult Sema::ActOnOpenMPTargetParallelForSimdDirective(
11320     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11321     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
11322   if (!AStmt)
11323     return StmtError();
11324 
11325   auto *CS = cast<CapturedStmt>(AStmt);
11326   // 1.2.2 OpenMP Language Terminology
11327   // Structured block - An executable statement with a single entry at the
11328   // top and a single exit at the bottom.
11329   // The point of exit cannot be a branch out of the structured block.
11330   // longjmp() and throw() must not violate the entry/exit criteria.
11331   CS->getCapturedDecl()->setNothrow();
11332   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
11333        ThisCaptureLevel > 1; --ThisCaptureLevel) {
11334     CS = cast<CapturedStmt>(CS->getCapturedStmt());
11335     // 1.2.2 OpenMP Language Terminology
11336     // Structured block - An executable statement with a single entry at the
11337     // top and a single exit at the bottom.
11338     // The point of exit cannot be a branch out of the structured block.
11339     // longjmp() and throw() must not violate the entry/exit criteria.
11340     CS->getCapturedDecl()->setNothrow();
11341   }
11342 
11343   OMPLoopDirective::HelperExprs B;
11344   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
11345   // define the nested loops number.
11346   unsigned NestedLoopCount = checkOpenMPLoop(
11347       OMPD_target_parallel_for_simd, getCollapseNumberExpr(Clauses),
11348       getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
11349       VarsWithImplicitDSA, B);
11350   if (NestedLoopCount == 0)
11351     return StmtError();
11352 
11353   assert((CurContext->isDependentContext() || B.builtAll()) &&
11354          "omp target parallel for simd loop exprs were not built");
11355 
11356   if (!CurContext->isDependentContext()) {
11357     // Finalize the clauses that need pre-built expressions for CodeGen.
11358     for (OMPClause *C : Clauses) {
11359       if (auto *LC = dyn_cast<OMPLinearClause>(C))
11360         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
11361                                      B.NumIterations, *this, CurScope,
11362                                      DSAStack))
11363           return StmtError();
11364     }
11365   }
11366   if (checkSimdlenSafelenSpecified(*this, Clauses))
11367     return StmtError();
11368 
11369   setFunctionHasBranchProtectedScope();
11370   return OMPTargetParallelForSimdDirective::Create(
11371       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
11372 }
11373 
11374 StmtResult Sema::ActOnOpenMPTargetSimdDirective(
11375     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11376     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
11377   if (!AStmt)
11378     return StmtError();
11379 
11380   auto *CS = cast<CapturedStmt>(AStmt);
11381   // 1.2.2 OpenMP Language Terminology
11382   // Structured block - An executable statement with a single entry at the
11383   // top and a single exit at the bottom.
11384   // The point of exit cannot be a branch out of the structured block.
11385   // longjmp() and throw() must not violate the entry/exit criteria.
11386   CS->getCapturedDecl()->setNothrow();
11387   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_simd);
11388        ThisCaptureLevel > 1; --ThisCaptureLevel) {
11389     CS = cast<CapturedStmt>(CS->getCapturedStmt());
11390     // 1.2.2 OpenMP Language Terminology
11391     // Structured block - An executable statement with a single entry at the
11392     // top and a single exit at the bottom.
11393     // The point of exit cannot be a branch out of the structured block.
11394     // longjmp() and throw() must not violate the entry/exit criteria.
11395     CS->getCapturedDecl()->setNothrow();
11396   }
11397 
11398   OMPLoopDirective::HelperExprs B;
11399   // In presence of clause 'collapse' with number of loops, it will define the
11400   // nested loops number.
11401   unsigned NestedLoopCount =
11402       checkOpenMPLoop(OMPD_target_simd, getCollapseNumberExpr(Clauses),
11403                       getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
11404                       VarsWithImplicitDSA, B);
11405   if (NestedLoopCount == 0)
11406     return StmtError();
11407 
11408   assert((CurContext->isDependentContext() || B.builtAll()) &&
11409          "omp target simd loop exprs were not built");
11410 
11411   if (!CurContext->isDependentContext()) {
11412     // Finalize the clauses that need pre-built expressions for CodeGen.
11413     for (OMPClause *C : Clauses) {
11414       if (auto *LC = dyn_cast<OMPLinearClause>(C))
11415         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
11416                                      B.NumIterations, *this, CurScope,
11417                                      DSAStack))
11418           return StmtError();
11419     }
11420   }
11421 
11422   if (checkSimdlenSafelenSpecified(*this, Clauses))
11423     return StmtError();
11424 
11425   setFunctionHasBranchProtectedScope();
11426   return OMPTargetSimdDirective::Create(Context, StartLoc, EndLoc,
11427                                         NestedLoopCount, Clauses, AStmt, B);
11428 }
11429 
11430 StmtResult Sema::ActOnOpenMPTeamsDistributeDirective(
11431     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11432     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
11433   if (!AStmt)
11434     return StmtError();
11435 
11436   auto *CS = cast<CapturedStmt>(AStmt);
11437   // 1.2.2 OpenMP Language Terminology
11438   // Structured block - An executable statement with a single entry at the
11439   // top and a single exit at the bottom.
11440   // The point of exit cannot be a branch out of the structured block.
11441   // longjmp() and throw() must not violate the entry/exit criteria.
11442   CS->getCapturedDecl()->setNothrow();
11443   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_teams_distribute);
11444        ThisCaptureLevel > 1; --ThisCaptureLevel) {
11445     CS = cast<CapturedStmt>(CS->getCapturedStmt());
11446     // 1.2.2 OpenMP Language Terminology
11447     // Structured block - An executable statement with a single entry at the
11448     // top and a single exit at the bottom.
11449     // The point of exit cannot be a branch out of the structured block.
11450     // longjmp() and throw() must not violate the entry/exit criteria.
11451     CS->getCapturedDecl()->setNothrow();
11452   }
11453 
11454   OMPLoopDirective::HelperExprs B;
11455   // In presence of clause 'collapse' with number of loops, it will
11456   // define the nested loops number.
11457   unsigned NestedLoopCount =
11458       checkOpenMPLoop(OMPD_teams_distribute, getCollapseNumberExpr(Clauses),
11459                       nullptr /*ordered not a clause on distribute*/, CS, *this,
11460                       *DSAStack, VarsWithImplicitDSA, B);
11461   if (NestedLoopCount == 0)
11462     return StmtError();
11463 
11464   assert((CurContext->isDependentContext() || B.builtAll()) &&
11465          "omp teams distribute loop exprs were not built");
11466 
11467   setFunctionHasBranchProtectedScope();
11468 
11469   DSAStack->setParentTeamsRegionLoc(StartLoc);
11470 
11471   return OMPTeamsDistributeDirective::Create(
11472       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
11473 }
11474 
11475 StmtResult Sema::ActOnOpenMPTeamsDistributeSimdDirective(
11476     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11477     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
11478   if (!AStmt)
11479     return StmtError();
11480 
11481   auto *CS = cast<CapturedStmt>(AStmt);
11482   // 1.2.2 OpenMP Language Terminology
11483   // Structured block - An executable statement with a single entry at the
11484   // top and a single exit at the bottom.
11485   // The point of exit cannot be a branch out of the structured block.
11486   // longjmp() and throw() must not violate the entry/exit criteria.
11487   CS->getCapturedDecl()->setNothrow();
11488   for (int ThisCaptureLevel =
11489            getOpenMPCaptureLevels(OMPD_teams_distribute_simd);
11490        ThisCaptureLevel > 1; --ThisCaptureLevel) {
11491     CS = cast<CapturedStmt>(CS->getCapturedStmt());
11492     // 1.2.2 OpenMP Language Terminology
11493     // Structured block - An executable statement with a single entry at the
11494     // top and a single exit at the bottom.
11495     // The point of exit cannot be a branch out of the structured block.
11496     // longjmp() and throw() must not violate the entry/exit criteria.
11497     CS->getCapturedDecl()->setNothrow();
11498   }
11499 
11500   OMPLoopDirective::HelperExprs B;
11501   // In presence of clause 'collapse' with number of loops, it will
11502   // define the nested loops number.
11503   unsigned NestedLoopCount = checkOpenMPLoop(
11504       OMPD_teams_distribute_simd, getCollapseNumberExpr(Clauses),
11505       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
11506       VarsWithImplicitDSA, B);
11507 
11508   if (NestedLoopCount == 0)
11509     return StmtError();
11510 
11511   assert((CurContext->isDependentContext() || B.builtAll()) &&
11512          "omp teams distribute simd loop exprs were not built");
11513 
11514   if (!CurContext->isDependentContext()) {
11515     // Finalize the clauses that need pre-built expressions for CodeGen.
11516     for (OMPClause *C : Clauses) {
11517       if (auto *LC = dyn_cast<OMPLinearClause>(C))
11518         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
11519                                      B.NumIterations, *this, CurScope,
11520                                      DSAStack))
11521           return StmtError();
11522     }
11523   }
11524 
11525   if (checkSimdlenSafelenSpecified(*this, Clauses))
11526     return StmtError();
11527 
11528   setFunctionHasBranchProtectedScope();
11529 
11530   DSAStack->setParentTeamsRegionLoc(StartLoc);
11531 
11532   return OMPTeamsDistributeSimdDirective::Create(
11533       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
11534 }
11535 
11536 StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForSimdDirective(
11537     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11538     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
11539   if (!AStmt)
11540     return StmtError();
11541 
11542   auto *CS = cast<CapturedStmt>(AStmt);
11543   // 1.2.2 OpenMP Language Terminology
11544   // Structured block - An executable statement with a single entry at the
11545   // top and a single exit at the bottom.
11546   // The point of exit cannot be a branch out of the structured block.
11547   // longjmp() and throw() must not violate the entry/exit criteria.
11548   CS->getCapturedDecl()->setNothrow();
11549 
11550   for (int ThisCaptureLevel =
11551            getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for_simd);
11552        ThisCaptureLevel > 1; --ThisCaptureLevel) {
11553     CS = cast<CapturedStmt>(CS->getCapturedStmt());
11554     // 1.2.2 OpenMP Language Terminology
11555     // Structured block - An executable statement with a single entry at the
11556     // top and a single exit at the bottom.
11557     // The point of exit cannot be a branch out of the structured block.
11558     // longjmp() and throw() must not violate the entry/exit criteria.
11559     CS->getCapturedDecl()->setNothrow();
11560   }
11561 
11562   OMPLoopDirective::HelperExprs B;
11563   // In presence of clause 'collapse' with number of loops, it will
11564   // define the nested loops number.
11565   unsigned NestedLoopCount = checkOpenMPLoop(
11566       OMPD_teams_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
11567       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
11568       VarsWithImplicitDSA, B);
11569 
11570   if (NestedLoopCount == 0)
11571     return StmtError();
11572 
11573   assert((CurContext->isDependentContext() || B.builtAll()) &&
11574          "omp for loop exprs were not built");
11575 
11576   if (!CurContext->isDependentContext()) {
11577     // Finalize the clauses that need pre-built expressions for CodeGen.
11578     for (OMPClause *C : Clauses) {
11579       if (auto *LC = dyn_cast<OMPLinearClause>(C))
11580         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
11581                                      B.NumIterations, *this, CurScope,
11582                                      DSAStack))
11583           return StmtError();
11584     }
11585   }
11586 
11587   if (checkSimdlenSafelenSpecified(*this, Clauses))
11588     return StmtError();
11589 
11590   setFunctionHasBranchProtectedScope();
11591 
11592   DSAStack->setParentTeamsRegionLoc(StartLoc);
11593 
11594   return OMPTeamsDistributeParallelForSimdDirective::Create(
11595       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
11596 }
11597 
11598 StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForDirective(
11599     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11600     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
11601   if (!AStmt)
11602     return StmtError();
11603 
11604   auto *CS = cast<CapturedStmt>(AStmt);
11605   // 1.2.2 OpenMP Language Terminology
11606   // Structured block - An executable statement with a single entry at the
11607   // top and a single exit at the bottom.
11608   // The point of exit cannot be a branch out of the structured block.
11609   // longjmp() and throw() must not violate the entry/exit criteria.
11610   CS->getCapturedDecl()->setNothrow();
11611 
11612   for (int ThisCaptureLevel =
11613            getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for);
11614        ThisCaptureLevel > 1; --ThisCaptureLevel) {
11615     CS = cast<CapturedStmt>(CS->getCapturedStmt());
11616     // 1.2.2 OpenMP Language Terminology
11617     // Structured block - An executable statement with a single entry at the
11618     // top and a single exit at the bottom.
11619     // The point of exit cannot be a branch out of the structured block.
11620     // longjmp() and throw() must not violate the entry/exit criteria.
11621     CS->getCapturedDecl()->setNothrow();
11622   }
11623 
11624   OMPLoopDirective::HelperExprs B;
11625   // In presence of clause 'collapse' with number of loops, it will
11626   // define the nested loops number.
11627   unsigned NestedLoopCount = checkOpenMPLoop(
11628       OMPD_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
11629       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
11630       VarsWithImplicitDSA, B);
11631 
11632   if (NestedLoopCount == 0)
11633     return StmtError();
11634 
11635   assert((CurContext->isDependentContext() || B.builtAll()) &&
11636          "omp for loop exprs were not built");
11637 
11638   setFunctionHasBranchProtectedScope();
11639 
11640   DSAStack->setParentTeamsRegionLoc(StartLoc);
11641 
11642   return OMPTeamsDistributeParallelForDirective::Create(
11643       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
11644       DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion());
11645 }
11646 
11647 StmtResult Sema::ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses,
11648                                                  Stmt *AStmt,
11649                                                  SourceLocation StartLoc,
11650                                                  SourceLocation EndLoc) {
11651   if (!AStmt)
11652     return StmtError();
11653 
11654   auto *CS = cast<CapturedStmt>(AStmt);
11655   // 1.2.2 OpenMP Language Terminology
11656   // Structured block - An executable statement with a single entry at the
11657   // top and a single exit at the bottom.
11658   // The point of exit cannot be a branch out of the structured block.
11659   // longjmp() and throw() must not violate the entry/exit criteria.
11660   CS->getCapturedDecl()->setNothrow();
11661 
11662   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_teams);
11663        ThisCaptureLevel > 1; --ThisCaptureLevel) {
11664     CS = cast<CapturedStmt>(CS->getCapturedStmt());
11665     // 1.2.2 OpenMP Language Terminology
11666     // Structured block - An executable statement with a single entry at the
11667     // top and a single exit at the bottom.
11668     // The point of exit cannot be a branch out of the structured block.
11669     // longjmp() and throw() must not violate the entry/exit criteria.
11670     CS->getCapturedDecl()->setNothrow();
11671   }
11672   setFunctionHasBranchProtectedScope();
11673 
11674   return OMPTargetTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses,
11675                                          AStmt);
11676 }
11677 
11678 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeDirective(
11679     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11680     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
11681   if (!AStmt)
11682     return StmtError();
11683 
11684   auto *CS = cast<CapturedStmt>(AStmt);
11685   // 1.2.2 OpenMP Language Terminology
11686   // Structured block - An executable statement with a single entry at the
11687   // top and a single exit at the bottom.
11688   // The point of exit cannot be a branch out of the structured block.
11689   // longjmp() and throw() must not violate the entry/exit criteria.
11690   CS->getCapturedDecl()->setNothrow();
11691   for (int ThisCaptureLevel =
11692            getOpenMPCaptureLevels(OMPD_target_teams_distribute);
11693        ThisCaptureLevel > 1; --ThisCaptureLevel) {
11694     CS = cast<CapturedStmt>(CS->getCapturedStmt());
11695     // 1.2.2 OpenMP Language Terminology
11696     // Structured block - An executable statement with a single entry at the
11697     // top and a single exit at the bottom.
11698     // The point of exit cannot be a branch out of the structured block.
11699     // longjmp() and throw() must not violate the entry/exit criteria.
11700     CS->getCapturedDecl()->setNothrow();
11701   }
11702 
11703   OMPLoopDirective::HelperExprs B;
11704   // In presence of clause 'collapse' with number of loops, it will
11705   // define the nested loops number.
11706   unsigned NestedLoopCount = checkOpenMPLoop(
11707       OMPD_target_teams_distribute, getCollapseNumberExpr(Clauses),
11708       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
11709       VarsWithImplicitDSA, B);
11710   if (NestedLoopCount == 0)
11711     return StmtError();
11712 
11713   assert((CurContext->isDependentContext() || B.builtAll()) &&
11714          "omp target teams distribute loop exprs were not built");
11715 
11716   setFunctionHasBranchProtectedScope();
11717   return OMPTargetTeamsDistributeDirective::Create(
11718       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
11719 }
11720 
11721 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForDirective(
11722     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11723     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
11724   if (!AStmt)
11725     return StmtError();
11726 
11727   auto *CS = cast<CapturedStmt>(AStmt);
11728   // 1.2.2 OpenMP Language Terminology
11729   // Structured block - An executable statement with a single entry at the
11730   // top and a single exit at the bottom.
11731   // The point of exit cannot be a branch out of the structured block.
11732   // longjmp() and throw() must not violate the entry/exit criteria.
11733   CS->getCapturedDecl()->setNothrow();
11734   for (int ThisCaptureLevel =
11735            getOpenMPCaptureLevels(OMPD_target_teams_distribute_parallel_for);
11736        ThisCaptureLevel > 1; --ThisCaptureLevel) {
11737     CS = cast<CapturedStmt>(CS->getCapturedStmt());
11738     // 1.2.2 OpenMP Language Terminology
11739     // Structured block - An executable statement with a single entry at the
11740     // top and a single exit at the bottom.
11741     // The point of exit cannot be a branch out of the structured block.
11742     // longjmp() and throw() must not violate the entry/exit criteria.
11743     CS->getCapturedDecl()->setNothrow();
11744   }
11745 
11746   OMPLoopDirective::HelperExprs B;
11747   // In presence of clause 'collapse' with number of loops, it will
11748   // define the nested loops number.
11749   unsigned NestedLoopCount = checkOpenMPLoop(
11750       OMPD_target_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
11751       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
11752       VarsWithImplicitDSA, B);
11753   if (NestedLoopCount == 0)
11754     return StmtError();
11755 
11756   assert((CurContext->isDependentContext() || B.builtAll()) &&
11757          "omp target teams distribute parallel for loop exprs were not built");
11758 
11759   if (!CurContext->isDependentContext()) {
11760     // Finalize the clauses that need pre-built expressions for CodeGen.
11761     for (OMPClause *C : Clauses) {
11762       if (auto *LC = dyn_cast<OMPLinearClause>(C))
11763         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
11764                                      B.NumIterations, *this, CurScope,
11765                                      DSAStack))
11766           return StmtError();
11767     }
11768   }
11769 
11770   setFunctionHasBranchProtectedScope();
11771   return OMPTargetTeamsDistributeParallelForDirective::Create(
11772       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
11773       DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion());
11774 }
11775 
11776 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
11777     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11778     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
11779   if (!AStmt)
11780     return StmtError();
11781 
11782   auto *CS = cast<CapturedStmt>(AStmt);
11783   // 1.2.2 OpenMP Language Terminology
11784   // Structured block - An executable statement with a single entry at the
11785   // top and a single exit at the bottom.
11786   // The point of exit cannot be a branch out of the structured block.
11787   // longjmp() and throw() must not violate the entry/exit criteria.
11788   CS->getCapturedDecl()->setNothrow();
11789   for (int ThisCaptureLevel = getOpenMPCaptureLevels(
11790            OMPD_target_teams_distribute_parallel_for_simd);
11791        ThisCaptureLevel > 1; --ThisCaptureLevel) {
11792     CS = cast<CapturedStmt>(CS->getCapturedStmt());
11793     // 1.2.2 OpenMP Language Terminology
11794     // Structured block - An executable statement with a single entry at the
11795     // top and a single exit at the bottom.
11796     // The point of exit cannot be a branch out of the structured block.
11797     // longjmp() and throw() must not violate the entry/exit criteria.
11798     CS->getCapturedDecl()->setNothrow();
11799   }
11800 
11801   OMPLoopDirective::HelperExprs B;
11802   // In presence of clause 'collapse' with number of loops, it will
11803   // define the nested loops number.
11804   unsigned NestedLoopCount =
11805       checkOpenMPLoop(OMPD_target_teams_distribute_parallel_for_simd,
11806                       getCollapseNumberExpr(Clauses),
11807                       nullptr /*ordered not a clause on distribute*/, CS, *this,
11808                       *DSAStack, VarsWithImplicitDSA, B);
11809   if (NestedLoopCount == 0)
11810     return StmtError();
11811 
11812   assert((CurContext->isDependentContext() || B.builtAll()) &&
11813          "omp target teams distribute parallel for simd loop exprs were not "
11814          "built");
11815 
11816   if (!CurContext->isDependentContext()) {
11817     // Finalize the clauses that need pre-built expressions for CodeGen.
11818     for (OMPClause *C : Clauses) {
11819       if (auto *LC = dyn_cast<OMPLinearClause>(C))
11820         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
11821                                      B.NumIterations, *this, CurScope,
11822                                      DSAStack))
11823           return StmtError();
11824     }
11825   }
11826 
11827   if (checkSimdlenSafelenSpecified(*this, Clauses))
11828     return StmtError();
11829 
11830   setFunctionHasBranchProtectedScope();
11831   return OMPTargetTeamsDistributeParallelForSimdDirective::Create(
11832       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
11833 }
11834 
11835 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeSimdDirective(
11836     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11837     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
11838   if (!AStmt)
11839     return StmtError();
11840 
11841   auto *CS = cast<CapturedStmt>(AStmt);
11842   // 1.2.2 OpenMP Language Terminology
11843   // Structured block - An executable statement with a single entry at the
11844   // top and a single exit at the bottom.
11845   // The point of exit cannot be a branch out of the structured block.
11846   // longjmp() and throw() must not violate the entry/exit criteria.
11847   CS->getCapturedDecl()->setNothrow();
11848   for (int ThisCaptureLevel =
11849            getOpenMPCaptureLevels(OMPD_target_teams_distribute_simd);
11850        ThisCaptureLevel > 1; --ThisCaptureLevel) {
11851     CS = cast<CapturedStmt>(CS->getCapturedStmt());
11852     // 1.2.2 OpenMP Language Terminology
11853     // Structured block - An executable statement with a single entry at the
11854     // top and a single exit at the bottom.
11855     // The point of exit cannot be a branch out of the structured block.
11856     // longjmp() and throw() must not violate the entry/exit criteria.
11857     CS->getCapturedDecl()->setNothrow();
11858   }
11859 
11860   OMPLoopDirective::HelperExprs B;
11861   // In presence of clause 'collapse' with number of loops, it will
11862   // define the nested loops number.
11863   unsigned NestedLoopCount = checkOpenMPLoop(
11864       OMPD_target_teams_distribute_simd, getCollapseNumberExpr(Clauses),
11865       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
11866       VarsWithImplicitDSA, B);
11867   if (NestedLoopCount == 0)
11868     return StmtError();
11869 
11870   assert((CurContext->isDependentContext() || B.builtAll()) &&
11871          "omp target teams distribute simd loop exprs were not built");
11872 
11873   if (!CurContext->isDependentContext()) {
11874     // Finalize the clauses that need pre-built expressions for CodeGen.
11875     for (OMPClause *C : Clauses) {
11876       if (auto *LC = dyn_cast<OMPLinearClause>(C))
11877         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
11878                                      B.NumIterations, *this, CurScope,
11879                                      DSAStack))
11880           return StmtError();
11881     }
11882   }
11883 
11884   if (checkSimdlenSafelenSpecified(*this, Clauses))
11885     return StmtError();
11886 
11887   setFunctionHasBranchProtectedScope();
11888   return OMPTargetTeamsDistributeSimdDirective::Create(
11889       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
11890 }
11891 
11892 OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
11893                                              SourceLocation StartLoc,
11894                                              SourceLocation LParenLoc,
11895                                              SourceLocation EndLoc) {
11896   OMPClause *Res = nullptr;
11897   switch (Kind) {
11898   case OMPC_final:
11899     Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc);
11900     break;
11901   case OMPC_num_threads:
11902     Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc);
11903     break;
11904   case OMPC_safelen:
11905     Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
11906     break;
11907   case OMPC_simdlen:
11908     Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc);
11909     break;
11910   case OMPC_allocator:
11911     Res = ActOnOpenMPAllocatorClause(Expr, StartLoc, LParenLoc, EndLoc);
11912     break;
11913   case OMPC_collapse:
11914     Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc);
11915     break;
11916   case OMPC_ordered:
11917     Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr);
11918     break;
11919   case OMPC_num_teams:
11920     Res = ActOnOpenMPNumTeamsClause(Expr, StartLoc, LParenLoc, EndLoc);
11921     break;
11922   case OMPC_thread_limit:
11923     Res = ActOnOpenMPThreadLimitClause(Expr, StartLoc, LParenLoc, EndLoc);
11924     break;
11925   case OMPC_priority:
11926     Res = ActOnOpenMPPriorityClause(Expr, StartLoc, LParenLoc, EndLoc);
11927     break;
11928   case OMPC_grainsize:
11929     Res = ActOnOpenMPGrainsizeClause(Expr, StartLoc, LParenLoc, EndLoc);
11930     break;
11931   case OMPC_num_tasks:
11932     Res = ActOnOpenMPNumTasksClause(Expr, StartLoc, LParenLoc, EndLoc);
11933     break;
11934   case OMPC_hint:
11935     Res = ActOnOpenMPHintClause(Expr, StartLoc, LParenLoc, EndLoc);
11936     break;
11937   case OMPC_depobj:
11938     Res = ActOnOpenMPDepobjClause(Expr, StartLoc, LParenLoc, EndLoc);
11939     break;
11940   case OMPC_detach:
11941     Res = ActOnOpenMPDetachClause(Expr, StartLoc, LParenLoc, EndLoc);
11942     break;
11943   case OMPC_device:
11944   case OMPC_if:
11945   case OMPC_default:
11946   case OMPC_proc_bind:
11947   case OMPC_schedule:
11948   case OMPC_private:
11949   case OMPC_firstprivate:
11950   case OMPC_lastprivate:
11951   case OMPC_shared:
11952   case OMPC_reduction:
11953   case OMPC_task_reduction:
11954   case OMPC_in_reduction:
11955   case OMPC_linear:
11956   case OMPC_aligned:
11957   case OMPC_copyin:
11958   case OMPC_copyprivate:
11959   case OMPC_nowait:
11960   case OMPC_untied:
11961   case OMPC_mergeable:
11962   case OMPC_threadprivate:
11963   case OMPC_allocate:
11964   case OMPC_flush:
11965   case OMPC_read:
11966   case OMPC_write:
11967   case OMPC_update:
11968   case OMPC_capture:
11969   case OMPC_seq_cst:
11970   case OMPC_acq_rel:
11971   case OMPC_acquire:
11972   case OMPC_release:
11973   case OMPC_relaxed:
11974   case OMPC_depend:
11975   case OMPC_threads:
11976   case OMPC_simd:
11977   case OMPC_map:
11978   case OMPC_nogroup:
11979   case OMPC_dist_schedule:
11980   case OMPC_defaultmap:
11981   case OMPC_unknown:
11982   case OMPC_uniform:
11983   case OMPC_to:
11984   case OMPC_from:
11985   case OMPC_use_device_ptr:
11986   case OMPC_use_device_addr:
11987   case OMPC_is_device_ptr:
11988   case OMPC_unified_address:
11989   case OMPC_unified_shared_memory:
11990   case OMPC_reverse_offload:
11991   case OMPC_dynamic_allocators:
11992   case OMPC_atomic_default_mem_order:
11993   case OMPC_device_type:
11994   case OMPC_match:
11995   case OMPC_nontemporal:
11996   case OMPC_order:
11997   case OMPC_destroy:
11998   case OMPC_inclusive:
11999   case OMPC_exclusive:
12000   case OMPC_uses_allocators:
12001   case OMPC_affinity:
12002   default:
12003     llvm_unreachable("Clause is not allowed.");
12004   }
12005   return Res;
12006 }
12007 
12008 // An OpenMP directive such as 'target parallel' has two captured regions:
12009 // for the 'target' and 'parallel' respectively.  This function returns
12010 // the region in which to capture expressions associated with a clause.
12011 // A return value of OMPD_unknown signifies that the expression should not
12012 // be captured.
12013 static OpenMPDirectiveKind getOpenMPCaptureRegionForClause(
12014     OpenMPDirectiveKind DKind, OpenMPClauseKind CKind, unsigned OpenMPVersion,
12015     OpenMPDirectiveKind NameModifier = OMPD_unknown) {
12016   OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
12017   switch (CKind) {
12018   case OMPC_if:
12019     switch (DKind) {
12020     case OMPD_target_parallel_for_simd:
12021       if (OpenMPVersion >= 50 &&
12022           (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)) {
12023         CaptureRegion = OMPD_parallel;
12024         break;
12025       }
12026       LLVM_FALLTHROUGH;
12027     case OMPD_target_parallel:
12028     case OMPD_target_parallel_for:
12029       // If this clause applies to the nested 'parallel' region, capture within
12030       // the 'target' region, otherwise do not capture.
12031       if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
12032         CaptureRegion = OMPD_target;
12033       break;
12034     case OMPD_target_teams_distribute_parallel_for_simd:
12035       if (OpenMPVersion >= 50 &&
12036           (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)) {
12037         CaptureRegion = OMPD_parallel;
12038         break;
12039       }
12040       LLVM_FALLTHROUGH;
12041     case OMPD_target_teams_distribute_parallel_for:
12042       // If this clause applies to the nested 'parallel' region, capture within
12043       // the 'teams' region, otherwise do not capture.
12044       if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
12045         CaptureRegion = OMPD_teams;
12046       break;
12047     case OMPD_teams_distribute_parallel_for_simd:
12048       if (OpenMPVersion >= 50 &&
12049           (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)) {
12050         CaptureRegion = OMPD_parallel;
12051         break;
12052       }
12053       LLVM_FALLTHROUGH;
12054     case OMPD_teams_distribute_parallel_for:
12055       CaptureRegion = OMPD_teams;
12056       break;
12057     case OMPD_target_update:
12058     case OMPD_target_enter_data:
12059     case OMPD_target_exit_data:
12060       CaptureRegion = OMPD_task;
12061       break;
12062     case OMPD_parallel_master_taskloop:
12063       if (NameModifier == OMPD_unknown || NameModifier == OMPD_taskloop)
12064         CaptureRegion = OMPD_parallel;
12065       break;
12066     case OMPD_parallel_master_taskloop_simd:
12067       if ((OpenMPVersion <= 45 && NameModifier == OMPD_unknown) ||
12068           NameModifier == OMPD_taskloop) {
12069         CaptureRegion = OMPD_parallel;
12070         break;
12071       }
12072       if (OpenMPVersion <= 45)
12073         break;
12074       if (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)
12075         CaptureRegion = OMPD_taskloop;
12076       break;
12077     case OMPD_parallel_for_simd:
12078       if (OpenMPVersion <= 45)
12079         break;
12080       if (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)
12081         CaptureRegion = OMPD_parallel;
12082       break;
12083     case OMPD_taskloop_simd:
12084     case OMPD_master_taskloop_simd:
12085       if (OpenMPVersion <= 45)
12086         break;
12087       if (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)
12088         CaptureRegion = OMPD_taskloop;
12089       break;
12090     case OMPD_distribute_parallel_for_simd:
12091       if (OpenMPVersion <= 45)
12092         break;
12093       if (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)
12094         CaptureRegion = OMPD_parallel;
12095       break;
12096     case OMPD_target_simd:
12097       if (OpenMPVersion >= 50 &&
12098           (NameModifier == OMPD_unknown || NameModifier == OMPD_simd))
12099         CaptureRegion = OMPD_target;
12100       break;
12101     case OMPD_teams_distribute_simd:
12102     case OMPD_target_teams_distribute_simd:
12103       if (OpenMPVersion >= 50 &&
12104           (NameModifier == OMPD_unknown || NameModifier == OMPD_simd))
12105         CaptureRegion = OMPD_teams;
12106       break;
12107     case OMPD_cancel:
12108     case OMPD_parallel:
12109     case OMPD_parallel_master:
12110     case OMPD_parallel_sections:
12111     case OMPD_parallel_for:
12112     case OMPD_target:
12113     case OMPD_target_teams:
12114     case OMPD_target_teams_distribute:
12115     case OMPD_distribute_parallel_for:
12116     case OMPD_task:
12117     case OMPD_taskloop:
12118     case OMPD_master_taskloop:
12119     case OMPD_target_data:
12120     case OMPD_simd:
12121     case OMPD_for_simd:
12122     case OMPD_distribute_simd:
12123       // Do not capture if-clause expressions.
12124       break;
12125     case OMPD_threadprivate:
12126     case OMPD_allocate:
12127     case OMPD_taskyield:
12128     case OMPD_barrier:
12129     case OMPD_taskwait:
12130     case OMPD_cancellation_point:
12131     case OMPD_flush:
12132     case OMPD_depobj:
12133     case OMPD_scan:
12134     case OMPD_declare_reduction:
12135     case OMPD_declare_mapper:
12136     case OMPD_declare_simd:
12137     case OMPD_declare_variant:
12138     case OMPD_begin_declare_variant:
12139     case OMPD_end_declare_variant:
12140     case OMPD_declare_target:
12141     case OMPD_end_declare_target:
12142     case OMPD_teams:
12143     case OMPD_for:
12144     case OMPD_sections:
12145     case OMPD_section:
12146     case OMPD_single:
12147     case OMPD_master:
12148     case OMPD_critical:
12149     case OMPD_taskgroup:
12150     case OMPD_distribute:
12151     case OMPD_ordered:
12152     case OMPD_atomic:
12153     case OMPD_teams_distribute:
12154     case OMPD_requires:
12155       llvm_unreachable("Unexpected OpenMP directive with if-clause");
12156     case OMPD_unknown:
12157     default:
12158       llvm_unreachable("Unknown OpenMP directive");
12159     }
12160     break;
12161   case OMPC_num_threads:
12162     switch (DKind) {
12163     case OMPD_target_parallel:
12164     case OMPD_target_parallel_for:
12165     case OMPD_target_parallel_for_simd:
12166       CaptureRegion = OMPD_target;
12167       break;
12168     case OMPD_teams_distribute_parallel_for:
12169     case OMPD_teams_distribute_parallel_for_simd:
12170     case OMPD_target_teams_distribute_parallel_for:
12171     case OMPD_target_teams_distribute_parallel_for_simd:
12172       CaptureRegion = OMPD_teams;
12173       break;
12174     case OMPD_parallel:
12175     case OMPD_parallel_master:
12176     case OMPD_parallel_sections:
12177     case OMPD_parallel_for:
12178     case OMPD_parallel_for_simd:
12179     case OMPD_distribute_parallel_for:
12180     case OMPD_distribute_parallel_for_simd:
12181     case OMPD_parallel_master_taskloop:
12182     case OMPD_parallel_master_taskloop_simd:
12183       // Do not capture num_threads-clause expressions.
12184       break;
12185     case OMPD_target_data:
12186     case OMPD_target_enter_data:
12187     case OMPD_target_exit_data:
12188     case OMPD_target_update:
12189     case OMPD_target:
12190     case OMPD_target_simd:
12191     case OMPD_target_teams:
12192     case OMPD_target_teams_distribute:
12193     case OMPD_target_teams_distribute_simd:
12194     case OMPD_cancel:
12195     case OMPD_task:
12196     case OMPD_taskloop:
12197     case OMPD_taskloop_simd:
12198     case OMPD_master_taskloop:
12199     case OMPD_master_taskloop_simd:
12200     case OMPD_threadprivate:
12201     case OMPD_allocate:
12202     case OMPD_taskyield:
12203     case OMPD_barrier:
12204     case OMPD_taskwait:
12205     case OMPD_cancellation_point:
12206     case OMPD_flush:
12207     case OMPD_depobj:
12208     case OMPD_scan:
12209     case OMPD_declare_reduction:
12210     case OMPD_declare_mapper:
12211     case OMPD_declare_simd:
12212     case OMPD_declare_variant:
12213     case OMPD_begin_declare_variant:
12214     case OMPD_end_declare_variant:
12215     case OMPD_declare_target:
12216     case OMPD_end_declare_target:
12217     case OMPD_teams:
12218     case OMPD_simd:
12219     case OMPD_for:
12220     case OMPD_for_simd:
12221     case OMPD_sections:
12222     case OMPD_section:
12223     case OMPD_single:
12224     case OMPD_master:
12225     case OMPD_critical:
12226     case OMPD_taskgroup:
12227     case OMPD_distribute:
12228     case OMPD_ordered:
12229     case OMPD_atomic:
12230     case OMPD_distribute_simd:
12231     case OMPD_teams_distribute:
12232     case OMPD_teams_distribute_simd:
12233     case OMPD_requires:
12234       llvm_unreachable("Unexpected OpenMP directive with num_threads-clause");
12235     case OMPD_unknown:
12236     default:
12237       llvm_unreachable("Unknown OpenMP directive");
12238     }
12239     break;
12240   case OMPC_num_teams:
12241     switch (DKind) {
12242     case OMPD_target_teams:
12243     case OMPD_target_teams_distribute:
12244     case OMPD_target_teams_distribute_simd:
12245     case OMPD_target_teams_distribute_parallel_for:
12246     case OMPD_target_teams_distribute_parallel_for_simd:
12247       CaptureRegion = OMPD_target;
12248       break;
12249     case OMPD_teams_distribute_parallel_for:
12250     case OMPD_teams_distribute_parallel_for_simd:
12251     case OMPD_teams:
12252     case OMPD_teams_distribute:
12253     case OMPD_teams_distribute_simd:
12254       // Do not capture num_teams-clause expressions.
12255       break;
12256     case OMPD_distribute_parallel_for:
12257     case OMPD_distribute_parallel_for_simd:
12258     case OMPD_task:
12259     case OMPD_taskloop:
12260     case OMPD_taskloop_simd:
12261     case OMPD_master_taskloop:
12262     case OMPD_master_taskloop_simd:
12263     case OMPD_parallel_master_taskloop:
12264     case OMPD_parallel_master_taskloop_simd:
12265     case OMPD_target_data:
12266     case OMPD_target_enter_data:
12267     case OMPD_target_exit_data:
12268     case OMPD_target_update:
12269     case OMPD_cancel:
12270     case OMPD_parallel:
12271     case OMPD_parallel_master:
12272     case OMPD_parallel_sections:
12273     case OMPD_parallel_for:
12274     case OMPD_parallel_for_simd:
12275     case OMPD_target:
12276     case OMPD_target_simd:
12277     case OMPD_target_parallel:
12278     case OMPD_target_parallel_for:
12279     case OMPD_target_parallel_for_simd:
12280     case OMPD_threadprivate:
12281     case OMPD_allocate:
12282     case OMPD_taskyield:
12283     case OMPD_barrier:
12284     case OMPD_taskwait:
12285     case OMPD_cancellation_point:
12286     case OMPD_flush:
12287     case OMPD_depobj:
12288     case OMPD_scan:
12289     case OMPD_declare_reduction:
12290     case OMPD_declare_mapper:
12291     case OMPD_declare_simd:
12292     case OMPD_declare_variant:
12293     case OMPD_begin_declare_variant:
12294     case OMPD_end_declare_variant:
12295     case OMPD_declare_target:
12296     case OMPD_end_declare_target:
12297     case OMPD_simd:
12298     case OMPD_for:
12299     case OMPD_for_simd:
12300     case OMPD_sections:
12301     case OMPD_section:
12302     case OMPD_single:
12303     case OMPD_master:
12304     case OMPD_critical:
12305     case OMPD_taskgroup:
12306     case OMPD_distribute:
12307     case OMPD_ordered:
12308     case OMPD_atomic:
12309     case OMPD_distribute_simd:
12310     case OMPD_requires:
12311       llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
12312     case OMPD_unknown:
12313     default:
12314       llvm_unreachable("Unknown OpenMP directive");
12315     }
12316     break;
12317   case OMPC_thread_limit:
12318     switch (DKind) {
12319     case OMPD_target_teams:
12320     case OMPD_target_teams_distribute:
12321     case OMPD_target_teams_distribute_simd:
12322     case OMPD_target_teams_distribute_parallel_for:
12323     case OMPD_target_teams_distribute_parallel_for_simd:
12324       CaptureRegion = OMPD_target;
12325       break;
12326     case OMPD_teams_distribute_parallel_for:
12327     case OMPD_teams_distribute_parallel_for_simd:
12328     case OMPD_teams:
12329     case OMPD_teams_distribute:
12330     case OMPD_teams_distribute_simd:
12331       // Do not capture thread_limit-clause expressions.
12332       break;
12333     case OMPD_distribute_parallel_for:
12334     case OMPD_distribute_parallel_for_simd:
12335     case OMPD_task:
12336     case OMPD_taskloop:
12337     case OMPD_taskloop_simd:
12338     case OMPD_master_taskloop:
12339     case OMPD_master_taskloop_simd:
12340     case OMPD_parallel_master_taskloop:
12341     case OMPD_parallel_master_taskloop_simd:
12342     case OMPD_target_data:
12343     case OMPD_target_enter_data:
12344     case OMPD_target_exit_data:
12345     case OMPD_target_update:
12346     case OMPD_cancel:
12347     case OMPD_parallel:
12348     case OMPD_parallel_master:
12349     case OMPD_parallel_sections:
12350     case OMPD_parallel_for:
12351     case OMPD_parallel_for_simd:
12352     case OMPD_target:
12353     case OMPD_target_simd:
12354     case OMPD_target_parallel:
12355     case OMPD_target_parallel_for:
12356     case OMPD_target_parallel_for_simd:
12357     case OMPD_threadprivate:
12358     case OMPD_allocate:
12359     case OMPD_taskyield:
12360     case OMPD_barrier:
12361     case OMPD_taskwait:
12362     case OMPD_cancellation_point:
12363     case OMPD_flush:
12364     case OMPD_depobj:
12365     case OMPD_scan:
12366     case OMPD_declare_reduction:
12367     case OMPD_declare_mapper:
12368     case OMPD_declare_simd:
12369     case OMPD_declare_variant:
12370     case OMPD_begin_declare_variant:
12371     case OMPD_end_declare_variant:
12372     case OMPD_declare_target:
12373     case OMPD_end_declare_target:
12374     case OMPD_simd:
12375     case OMPD_for:
12376     case OMPD_for_simd:
12377     case OMPD_sections:
12378     case OMPD_section:
12379     case OMPD_single:
12380     case OMPD_master:
12381     case OMPD_critical:
12382     case OMPD_taskgroup:
12383     case OMPD_distribute:
12384     case OMPD_ordered:
12385     case OMPD_atomic:
12386     case OMPD_distribute_simd:
12387     case OMPD_requires:
12388       llvm_unreachable("Unexpected OpenMP directive with thread_limit-clause");
12389     case OMPD_unknown:
12390     default:
12391       llvm_unreachable("Unknown OpenMP directive");
12392     }
12393     break;
12394   case OMPC_schedule:
12395     switch (DKind) {
12396     case OMPD_parallel_for:
12397     case OMPD_parallel_for_simd:
12398     case OMPD_distribute_parallel_for:
12399     case OMPD_distribute_parallel_for_simd:
12400     case OMPD_teams_distribute_parallel_for:
12401     case OMPD_teams_distribute_parallel_for_simd:
12402     case OMPD_target_parallel_for:
12403     case OMPD_target_parallel_for_simd:
12404     case OMPD_target_teams_distribute_parallel_for:
12405     case OMPD_target_teams_distribute_parallel_for_simd:
12406       CaptureRegion = OMPD_parallel;
12407       break;
12408     case OMPD_for:
12409     case OMPD_for_simd:
12410       // Do not capture schedule-clause expressions.
12411       break;
12412     case OMPD_task:
12413     case OMPD_taskloop:
12414     case OMPD_taskloop_simd:
12415     case OMPD_master_taskloop:
12416     case OMPD_master_taskloop_simd:
12417     case OMPD_parallel_master_taskloop:
12418     case OMPD_parallel_master_taskloop_simd:
12419     case OMPD_target_data:
12420     case OMPD_target_enter_data:
12421     case OMPD_target_exit_data:
12422     case OMPD_target_update:
12423     case OMPD_teams:
12424     case OMPD_teams_distribute:
12425     case OMPD_teams_distribute_simd:
12426     case OMPD_target_teams_distribute:
12427     case OMPD_target_teams_distribute_simd:
12428     case OMPD_target:
12429     case OMPD_target_simd:
12430     case OMPD_target_parallel:
12431     case OMPD_cancel:
12432     case OMPD_parallel:
12433     case OMPD_parallel_master:
12434     case OMPD_parallel_sections:
12435     case OMPD_threadprivate:
12436     case OMPD_allocate:
12437     case OMPD_taskyield:
12438     case OMPD_barrier:
12439     case OMPD_taskwait:
12440     case OMPD_cancellation_point:
12441     case OMPD_flush:
12442     case OMPD_depobj:
12443     case OMPD_scan:
12444     case OMPD_declare_reduction:
12445     case OMPD_declare_mapper:
12446     case OMPD_declare_simd:
12447     case OMPD_declare_variant:
12448     case OMPD_begin_declare_variant:
12449     case OMPD_end_declare_variant:
12450     case OMPD_declare_target:
12451     case OMPD_end_declare_target:
12452     case OMPD_simd:
12453     case OMPD_sections:
12454     case OMPD_section:
12455     case OMPD_single:
12456     case OMPD_master:
12457     case OMPD_critical:
12458     case OMPD_taskgroup:
12459     case OMPD_distribute:
12460     case OMPD_ordered:
12461     case OMPD_atomic:
12462     case OMPD_distribute_simd:
12463     case OMPD_target_teams:
12464     case OMPD_requires:
12465       llvm_unreachable("Unexpected OpenMP directive with schedule clause");
12466     case OMPD_unknown:
12467     default:
12468       llvm_unreachable("Unknown OpenMP directive");
12469     }
12470     break;
12471   case OMPC_dist_schedule:
12472     switch (DKind) {
12473     case OMPD_teams_distribute_parallel_for:
12474     case OMPD_teams_distribute_parallel_for_simd:
12475     case OMPD_teams_distribute:
12476     case OMPD_teams_distribute_simd:
12477     case OMPD_target_teams_distribute_parallel_for:
12478     case OMPD_target_teams_distribute_parallel_for_simd:
12479     case OMPD_target_teams_distribute:
12480     case OMPD_target_teams_distribute_simd:
12481       CaptureRegion = OMPD_teams;
12482       break;
12483     case OMPD_distribute_parallel_for:
12484     case OMPD_distribute_parallel_for_simd:
12485     case OMPD_distribute:
12486     case OMPD_distribute_simd:
12487       // Do not capture thread_limit-clause expressions.
12488       break;
12489     case OMPD_parallel_for:
12490     case OMPD_parallel_for_simd:
12491     case OMPD_target_parallel_for_simd:
12492     case OMPD_target_parallel_for:
12493     case OMPD_task:
12494     case OMPD_taskloop:
12495     case OMPD_taskloop_simd:
12496     case OMPD_master_taskloop:
12497     case OMPD_master_taskloop_simd:
12498     case OMPD_parallel_master_taskloop:
12499     case OMPD_parallel_master_taskloop_simd:
12500     case OMPD_target_data:
12501     case OMPD_target_enter_data:
12502     case OMPD_target_exit_data:
12503     case OMPD_target_update:
12504     case OMPD_teams:
12505     case OMPD_target:
12506     case OMPD_target_simd:
12507     case OMPD_target_parallel:
12508     case OMPD_cancel:
12509     case OMPD_parallel:
12510     case OMPD_parallel_master:
12511     case OMPD_parallel_sections:
12512     case OMPD_threadprivate:
12513     case OMPD_allocate:
12514     case OMPD_taskyield:
12515     case OMPD_barrier:
12516     case OMPD_taskwait:
12517     case OMPD_cancellation_point:
12518     case OMPD_flush:
12519     case OMPD_depobj:
12520     case OMPD_scan:
12521     case OMPD_declare_reduction:
12522     case OMPD_declare_mapper:
12523     case OMPD_declare_simd:
12524     case OMPD_declare_variant:
12525     case OMPD_begin_declare_variant:
12526     case OMPD_end_declare_variant:
12527     case OMPD_declare_target:
12528     case OMPD_end_declare_target:
12529     case OMPD_simd:
12530     case OMPD_for:
12531     case OMPD_for_simd:
12532     case OMPD_sections:
12533     case OMPD_section:
12534     case OMPD_single:
12535     case OMPD_master:
12536     case OMPD_critical:
12537     case OMPD_taskgroup:
12538     case OMPD_ordered:
12539     case OMPD_atomic:
12540     case OMPD_target_teams:
12541     case OMPD_requires:
12542       llvm_unreachable("Unexpected OpenMP directive with schedule clause");
12543     case OMPD_unknown:
12544     default:
12545       llvm_unreachable("Unknown OpenMP directive");
12546     }
12547     break;
12548   case OMPC_device:
12549     switch (DKind) {
12550     case OMPD_target_update:
12551     case OMPD_target_enter_data:
12552     case OMPD_target_exit_data:
12553     case OMPD_target:
12554     case OMPD_target_simd:
12555     case OMPD_target_teams:
12556     case OMPD_target_parallel:
12557     case OMPD_target_teams_distribute:
12558     case OMPD_target_teams_distribute_simd:
12559     case OMPD_target_parallel_for:
12560     case OMPD_target_parallel_for_simd:
12561     case OMPD_target_teams_distribute_parallel_for:
12562     case OMPD_target_teams_distribute_parallel_for_simd:
12563       CaptureRegion = OMPD_task;
12564       break;
12565     case OMPD_target_data:
12566       // Do not capture device-clause expressions.
12567       break;
12568     case OMPD_teams_distribute_parallel_for:
12569     case OMPD_teams_distribute_parallel_for_simd:
12570     case OMPD_teams:
12571     case OMPD_teams_distribute:
12572     case OMPD_teams_distribute_simd:
12573     case OMPD_distribute_parallel_for:
12574     case OMPD_distribute_parallel_for_simd:
12575     case OMPD_task:
12576     case OMPD_taskloop:
12577     case OMPD_taskloop_simd:
12578     case OMPD_master_taskloop:
12579     case OMPD_master_taskloop_simd:
12580     case OMPD_parallel_master_taskloop:
12581     case OMPD_parallel_master_taskloop_simd:
12582     case OMPD_cancel:
12583     case OMPD_parallel:
12584     case OMPD_parallel_master:
12585     case OMPD_parallel_sections:
12586     case OMPD_parallel_for:
12587     case OMPD_parallel_for_simd:
12588     case OMPD_threadprivate:
12589     case OMPD_allocate:
12590     case OMPD_taskyield:
12591     case OMPD_barrier:
12592     case OMPD_taskwait:
12593     case OMPD_cancellation_point:
12594     case OMPD_flush:
12595     case OMPD_depobj:
12596     case OMPD_scan:
12597     case OMPD_declare_reduction:
12598     case OMPD_declare_mapper:
12599     case OMPD_declare_simd:
12600     case OMPD_declare_variant:
12601     case OMPD_begin_declare_variant:
12602     case OMPD_end_declare_variant:
12603     case OMPD_declare_target:
12604     case OMPD_end_declare_target:
12605     case OMPD_simd:
12606     case OMPD_for:
12607     case OMPD_for_simd:
12608     case OMPD_sections:
12609     case OMPD_section:
12610     case OMPD_single:
12611     case OMPD_master:
12612     case OMPD_critical:
12613     case OMPD_taskgroup:
12614     case OMPD_distribute:
12615     case OMPD_ordered:
12616     case OMPD_atomic:
12617     case OMPD_distribute_simd:
12618     case OMPD_requires:
12619       llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
12620     case OMPD_unknown:
12621     default:
12622       llvm_unreachable("Unknown OpenMP directive");
12623     }
12624     break;
12625   case OMPC_grainsize:
12626   case OMPC_num_tasks:
12627   case OMPC_final:
12628   case OMPC_priority:
12629     switch (DKind) {
12630     case OMPD_task:
12631     case OMPD_taskloop:
12632     case OMPD_taskloop_simd:
12633     case OMPD_master_taskloop:
12634     case OMPD_master_taskloop_simd:
12635       break;
12636     case OMPD_parallel_master_taskloop:
12637     case OMPD_parallel_master_taskloop_simd:
12638       CaptureRegion = OMPD_parallel;
12639       break;
12640     case OMPD_target_update:
12641     case OMPD_target_enter_data:
12642     case OMPD_target_exit_data:
12643     case OMPD_target:
12644     case OMPD_target_simd:
12645     case OMPD_target_teams:
12646     case OMPD_target_parallel:
12647     case OMPD_target_teams_distribute:
12648     case OMPD_target_teams_distribute_simd:
12649     case OMPD_target_parallel_for:
12650     case OMPD_target_parallel_for_simd:
12651     case OMPD_target_teams_distribute_parallel_for:
12652     case OMPD_target_teams_distribute_parallel_for_simd:
12653     case OMPD_target_data:
12654     case OMPD_teams_distribute_parallel_for:
12655     case OMPD_teams_distribute_parallel_for_simd:
12656     case OMPD_teams:
12657     case OMPD_teams_distribute:
12658     case OMPD_teams_distribute_simd:
12659     case OMPD_distribute_parallel_for:
12660     case OMPD_distribute_parallel_for_simd:
12661     case OMPD_cancel:
12662     case OMPD_parallel:
12663     case OMPD_parallel_master:
12664     case OMPD_parallel_sections:
12665     case OMPD_parallel_for:
12666     case OMPD_parallel_for_simd:
12667     case OMPD_threadprivate:
12668     case OMPD_allocate:
12669     case OMPD_taskyield:
12670     case OMPD_barrier:
12671     case OMPD_taskwait:
12672     case OMPD_cancellation_point:
12673     case OMPD_flush:
12674     case OMPD_depobj:
12675     case OMPD_scan:
12676     case OMPD_declare_reduction:
12677     case OMPD_declare_mapper:
12678     case OMPD_declare_simd:
12679     case OMPD_declare_variant:
12680     case OMPD_begin_declare_variant:
12681     case OMPD_end_declare_variant:
12682     case OMPD_declare_target:
12683     case OMPD_end_declare_target:
12684     case OMPD_simd:
12685     case OMPD_for:
12686     case OMPD_for_simd:
12687     case OMPD_sections:
12688     case OMPD_section:
12689     case OMPD_single:
12690     case OMPD_master:
12691     case OMPD_critical:
12692     case OMPD_taskgroup:
12693     case OMPD_distribute:
12694     case OMPD_ordered:
12695     case OMPD_atomic:
12696     case OMPD_distribute_simd:
12697     case OMPD_requires:
12698       llvm_unreachable("Unexpected OpenMP directive with grainsize-clause");
12699     case OMPD_unknown:
12700     default:
12701       llvm_unreachable("Unknown OpenMP directive");
12702     }
12703     break;
12704   case OMPC_firstprivate:
12705   case OMPC_lastprivate:
12706   case OMPC_reduction:
12707   case OMPC_task_reduction:
12708   case OMPC_in_reduction:
12709   case OMPC_linear:
12710   case OMPC_default:
12711   case OMPC_proc_bind:
12712   case OMPC_safelen:
12713   case OMPC_simdlen:
12714   case OMPC_allocator:
12715   case OMPC_collapse:
12716   case OMPC_private:
12717   case OMPC_shared:
12718   case OMPC_aligned:
12719   case OMPC_copyin:
12720   case OMPC_copyprivate:
12721   case OMPC_ordered:
12722   case OMPC_nowait:
12723   case OMPC_untied:
12724   case OMPC_mergeable:
12725   case OMPC_threadprivate:
12726   case OMPC_allocate:
12727   case OMPC_flush:
12728   case OMPC_depobj:
12729   case OMPC_read:
12730   case OMPC_write:
12731   case OMPC_update:
12732   case OMPC_capture:
12733   case OMPC_seq_cst:
12734   case OMPC_acq_rel:
12735   case OMPC_acquire:
12736   case OMPC_release:
12737   case OMPC_relaxed:
12738   case OMPC_depend:
12739   case OMPC_threads:
12740   case OMPC_simd:
12741   case OMPC_map:
12742   case OMPC_nogroup:
12743   case OMPC_hint:
12744   case OMPC_defaultmap:
12745   case OMPC_unknown:
12746   case OMPC_uniform:
12747   case OMPC_to:
12748   case OMPC_from:
12749   case OMPC_use_device_ptr:
12750   case OMPC_use_device_addr:
12751   case OMPC_is_device_ptr:
12752   case OMPC_unified_address:
12753   case OMPC_unified_shared_memory:
12754   case OMPC_reverse_offload:
12755   case OMPC_dynamic_allocators:
12756   case OMPC_atomic_default_mem_order:
12757   case OMPC_device_type:
12758   case OMPC_match:
12759   case OMPC_nontemporal:
12760   case OMPC_order:
12761   case OMPC_destroy:
12762   case OMPC_detach:
12763   case OMPC_inclusive:
12764   case OMPC_exclusive:
12765   case OMPC_uses_allocators:
12766   case OMPC_affinity:
12767   default:
12768     llvm_unreachable("Unexpected OpenMP clause.");
12769   }
12770   return CaptureRegion;
12771 }
12772 
12773 OMPClause *Sema::ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
12774                                      Expr *Condition, SourceLocation StartLoc,
12775                                      SourceLocation LParenLoc,
12776                                      SourceLocation NameModifierLoc,
12777                                      SourceLocation ColonLoc,
12778                                      SourceLocation EndLoc) {
12779   Expr *ValExpr = Condition;
12780   Stmt *HelperValStmt = nullptr;
12781   OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
12782   if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
12783       !Condition->isInstantiationDependent() &&
12784       !Condition->containsUnexpandedParameterPack()) {
12785     ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
12786     if (Val.isInvalid())
12787       return nullptr;
12788 
12789     ValExpr = Val.get();
12790 
12791     OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
12792     CaptureRegion = getOpenMPCaptureRegionForClause(
12793         DKind, OMPC_if, LangOpts.OpenMP, NameModifier);
12794     if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
12795       ValExpr = MakeFullExpr(ValExpr).get();
12796       llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
12797       ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
12798       HelperValStmt = buildPreInits(Context, Captures);
12799     }
12800   }
12801 
12802   return new (Context)
12803       OMPIfClause(NameModifier, ValExpr, HelperValStmt, CaptureRegion, StartLoc,
12804                   LParenLoc, NameModifierLoc, ColonLoc, EndLoc);
12805 }
12806 
12807 OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition,
12808                                         SourceLocation StartLoc,
12809                                         SourceLocation LParenLoc,
12810                                         SourceLocation EndLoc) {
12811   Expr *ValExpr = Condition;
12812   Stmt *HelperValStmt = nullptr;
12813   OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
12814   if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
12815       !Condition->isInstantiationDependent() &&
12816       !Condition->containsUnexpandedParameterPack()) {
12817     ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
12818     if (Val.isInvalid())
12819       return nullptr;
12820 
12821     ValExpr = MakeFullExpr(Val.get()).get();
12822 
12823     OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
12824     CaptureRegion =
12825         getOpenMPCaptureRegionForClause(DKind, OMPC_final, LangOpts.OpenMP);
12826     if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
12827       ValExpr = MakeFullExpr(ValExpr).get();
12828       llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
12829       ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
12830       HelperValStmt = buildPreInits(Context, Captures);
12831     }
12832   }
12833 
12834   return new (Context) OMPFinalClause(ValExpr, HelperValStmt, CaptureRegion,
12835                                       StartLoc, LParenLoc, EndLoc);
12836 }
12837 
12838 ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc,
12839                                                         Expr *Op) {
12840   if (!Op)
12841     return ExprError();
12842 
12843   class IntConvertDiagnoser : public ICEConvertDiagnoser {
12844   public:
12845     IntConvertDiagnoser()
12846         : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {}
12847     SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
12848                                          QualType T) override {
12849       return S.Diag(Loc, diag::err_omp_not_integral) << T;
12850     }
12851     SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
12852                                              QualType T) override {
12853       return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
12854     }
12855     SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
12856                                                QualType T,
12857                                                QualType ConvTy) override {
12858       return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
12859     }
12860     SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
12861                                            QualType ConvTy) override {
12862       return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
12863              << ConvTy->isEnumeralType() << ConvTy;
12864     }
12865     SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
12866                                             QualType T) override {
12867       return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
12868     }
12869     SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
12870                                         QualType ConvTy) override {
12871       return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
12872              << ConvTy->isEnumeralType() << ConvTy;
12873     }
12874     SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType,
12875                                              QualType) override {
12876       llvm_unreachable("conversion functions are permitted");
12877     }
12878   } ConvertDiagnoser;
12879   return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
12880 }
12881 
12882 static bool
12883 isNonNegativeIntegerValue(Expr *&ValExpr, Sema &SemaRef, OpenMPClauseKind CKind,
12884                           bool StrictlyPositive, bool BuildCapture = false,
12885                           OpenMPDirectiveKind DKind = OMPD_unknown,
12886                           OpenMPDirectiveKind *CaptureRegion = nullptr,
12887                           Stmt **HelperValStmt = nullptr) {
12888   if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() &&
12889       !ValExpr->isInstantiationDependent()) {
12890     SourceLocation Loc = ValExpr->getExprLoc();
12891     ExprResult Value =
12892         SemaRef.PerformOpenMPImplicitIntegerConversion(Loc, ValExpr);
12893     if (Value.isInvalid())
12894       return false;
12895 
12896     ValExpr = Value.get();
12897     // The expression must evaluate to a non-negative integer value.
12898     if (Optional<llvm::APSInt> Result =
12899             ValExpr->getIntegerConstantExpr(SemaRef.Context)) {
12900       if (Result->isSigned() &&
12901           !((!StrictlyPositive && Result->isNonNegative()) ||
12902             (StrictlyPositive && Result->isStrictlyPositive()))) {
12903         SemaRef.Diag(Loc, diag::err_omp_negative_expression_in_clause)
12904             << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
12905             << ValExpr->getSourceRange();
12906         return false;
12907       }
12908     }
12909     if (!BuildCapture)
12910       return true;
12911     *CaptureRegion =
12912         getOpenMPCaptureRegionForClause(DKind, CKind, SemaRef.LangOpts.OpenMP);
12913     if (*CaptureRegion != OMPD_unknown &&
12914         !SemaRef.CurContext->isDependentContext()) {
12915       ValExpr = SemaRef.MakeFullExpr(ValExpr).get();
12916       llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
12917       ValExpr = tryBuildCapture(SemaRef, ValExpr, Captures).get();
12918       *HelperValStmt = buildPreInits(SemaRef.Context, Captures);
12919     }
12920   }
12921   return true;
12922 }
12923 
12924 OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
12925                                              SourceLocation StartLoc,
12926                                              SourceLocation LParenLoc,
12927                                              SourceLocation EndLoc) {
12928   Expr *ValExpr = NumThreads;
12929   Stmt *HelperValStmt = nullptr;
12930 
12931   // OpenMP [2.5, Restrictions]
12932   //  The num_threads expression must evaluate to a positive integer value.
12933   if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_threads,
12934                                  /*StrictlyPositive=*/true))
12935     return nullptr;
12936 
12937   OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
12938   OpenMPDirectiveKind CaptureRegion =
12939       getOpenMPCaptureRegionForClause(DKind, OMPC_num_threads, LangOpts.OpenMP);
12940   if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
12941     ValExpr = MakeFullExpr(ValExpr).get();
12942     llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
12943     ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
12944     HelperValStmt = buildPreInits(Context, Captures);
12945   }
12946 
12947   return new (Context) OMPNumThreadsClause(
12948       ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
12949 }
12950 
12951 ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
12952                                                        OpenMPClauseKind CKind,
12953                                                        bool StrictlyPositive) {
12954   if (!E)
12955     return ExprError();
12956   if (E->isValueDependent() || E->isTypeDependent() ||
12957       E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
12958     return E;
12959   llvm::APSInt Result;
12960   ExprResult ICE =
12961       VerifyIntegerConstantExpression(E, &Result, /*FIXME*/ AllowFold);
12962   if (ICE.isInvalid())
12963     return ExprError();
12964   if ((StrictlyPositive && !Result.isStrictlyPositive()) ||
12965       (!StrictlyPositive && !Result.isNonNegative())) {
12966     Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
12967         << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
12968         << E->getSourceRange();
12969     return ExprError();
12970   }
12971   if (CKind == OMPC_aligned && !Result.isPowerOf2()) {
12972     Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two)
12973         << E->getSourceRange();
12974     return ExprError();
12975   }
12976   if (CKind == OMPC_collapse && DSAStack->getAssociatedLoops() == 1)
12977     DSAStack->setAssociatedLoops(Result.getExtValue());
12978   else if (CKind == OMPC_ordered)
12979     DSAStack->setAssociatedLoops(Result.getExtValue());
12980   return ICE;
12981 }
12982 
12983 OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
12984                                           SourceLocation LParenLoc,
12985                                           SourceLocation EndLoc) {
12986   // OpenMP [2.8.1, simd construct, Description]
12987   // The parameter of the safelen clause must be a constant
12988   // positive integer expression.
12989   ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen);
12990   if (Safelen.isInvalid())
12991     return nullptr;
12992   return new (Context)
12993       OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc);
12994 }
12995 
12996 OMPClause *Sema::ActOnOpenMPSimdlenClause(Expr *Len, SourceLocation StartLoc,
12997                                           SourceLocation LParenLoc,
12998                                           SourceLocation EndLoc) {
12999   // OpenMP [2.8.1, simd construct, Description]
13000   // The parameter of the simdlen clause must be a constant
13001   // positive integer expression.
13002   ExprResult Simdlen = VerifyPositiveIntegerConstantInClause(Len, OMPC_simdlen);
13003   if (Simdlen.isInvalid())
13004     return nullptr;
13005   return new (Context)
13006       OMPSimdlenClause(Simdlen.get(), StartLoc, LParenLoc, EndLoc);
13007 }
13008 
13009 /// Tries to find omp_allocator_handle_t type.
13010 static bool findOMPAllocatorHandleT(Sema &S, SourceLocation Loc,
13011                                     DSAStackTy *Stack) {
13012   QualType OMPAllocatorHandleT = Stack->getOMPAllocatorHandleT();
13013   if (!OMPAllocatorHandleT.isNull())
13014     return true;
13015   // Build the predefined allocator expressions.
13016   bool ErrorFound = false;
13017   for (int I = 0; I < OMPAllocateDeclAttr::OMPUserDefinedMemAlloc; ++I) {
13018     auto AllocatorKind = static_cast<OMPAllocateDeclAttr::AllocatorTypeTy>(I);
13019     StringRef Allocator =
13020         OMPAllocateDeclAttr::ConvertAllocatorTypeTyToStr(AllocatorKind);
13021     DeclarationName AllocatorName = &S.getASTContext().Idents.get(Allocator);
13022     auto *VD = dyn_cast_or_null<ValueDecl>(
13023         S.LookupSingleName(S.TUScope, AllocatorName, Loc, Sema::LookupAnyName));
13024     if (!VD) {
13025       ErrorFound = true;
13026       break;
13027     }
13028     QualType AllocatorType =
13029         VD->getType().getNonLValueExprType(S.getASTContext());
13030     ExprResult Res = S.BuildDeclRefExpr(VD, AllocatorType, VK_LValue, Loc);
13031     if (!Res.isUsable()) {
13032       ErrorFound = true;
13033       break;
13034     }
13035     if (OMPAllocatorHandleT.isNull())
13036       OMPAllocatorHandleT = AllocatorType;
13037     if (!S.getASTContext().hasSameType(OMPAllocatorHandleT, AllocatorType)) {
13038       ErrorFound = true;
13039       break;
13040     }
13041     Stack->setAllocator(AllocatorKind, Res.get());
13042   }
13043   if (ErrorFound) {
13044     S.Diag(Loc, diag::err_omp_implied_type_not_found)
13045         << "omp_allocator_handle_t";
13046     return false;
13047   }
13048   OMPAllocatorHandleT.addConst();
13049   Stack->setOMPAllocatorHandleT(OMPAllocatorHandleT);
13050   return true;
13051 }
13052 
13053 OMPClause *Sema::ActOnOpenMPAllocatorClause(Expr *A, SourceLocation StartLoc,
13054                                             SourceLocation LParenLoc,
13055                                             SourceLocation EndLoc) {
13056   // OpenMP [2.11.3, allocate Directive, Description]
13057   // allocator is an expression of omp_allocator_handle_t type.
13058   if (!findOMPAllocatorHandleT(*this, A->getExprLoc(), DSAStack))
13059     return nullptr;
13060 
13061   ExprResult Allocator = DefaultLvalueConversion(A);
13062   if (Allocator.isInvalid())
13063     return nullptr;
13064   Allocator = PerformImplicitConversion(Allocator.get(),
13065                                         DSAStack->getOMPAllocatorHandleT(),
13066                                         Sema::AA_Initializing,
13067                                         /*AllowExplicit=*/true);
13068   if (Allocator.isInvalid())
13069     return nullptr;
13070   return new (Context)
13071       OMPAllocatorClause(Allocator.get(), StartLoc, LParenLoc, EndLoc);
13072 }
13073 
13074 OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops,
13075                                            SourceLocation StartLoc,
13076                                            SourceLocation LParenLoc,
13077                                            SourceLocation EndLoc) {
13078   // OpenMP [2.7.1, loop construct, Description]
13079   // OpenMP [2.8.1, simd construct, Description]
13080   // OpenMP [2.9.6, distribute construct, Description]
13081   // The parameter of the collapse clause must be a constant
13082   // positive integer expression.
13083   ExprResult NumForLoopsResult =
13084       VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse);
13085   if (NumForLoopsResult.isInvalid())
13086     return nullptr;
13087   return new (Context)
13088       OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc);
13089 }
13090 
13091 OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc,
13092                                           SourceLocation EndLoc,
13093                                           SourceLocation LParenLoc,
13094                                           Expr *NumForLoops) {
13095   // OpenMP [2.7.1, loop construct, Description]
13096   // OpenMP [2.8.1, simd construct, Description]
13097   // OpenMP [2.9.6, distribute construct, Description]
13098   // The parameter of the ordered clause must be a constant
13099   // positive integer expression if any.
13100   if (NumForLoops && LParenLoc.isValid()) {
13101     ExprResult NumForLoopsResult =
13102         VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_ordered);
13103     if (NumForLoopsResult.isInvalid())
13104       return nullptr;
13105     NumForLoops = NumForLoopsResult.get();
13106   } else {
13107     NumForLoops = nullptr;
13108   }
13109   auto *Clause = OMPOrderedClause::Create(
13110       Context, NumForLoops, NumForLoops ? DSAStack->getAssociatedLoops() : 0,
13111       StartLoc, LParenLoc, EndLoc);
13112   DSAStack->setOrderedRegion(/*IsOrdered=*/true, NumForLoops, Clause);
13113   return Clause;
13114 }
13115 
13116 OMPClause *Sema::ActOnOpenMPSimpleClause(
13117     OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc,
13118     SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
13119   OMPClause *Res = nullptr;
13120   switch (Kind) {
13121   case OMPC_default:
13122     Res = ActOnOpenMPDefaultClause(static_cast<DefaultKind>(Argument),
13123                                    ArgumentLoc, StartLoc, LParenLoc, EndLoc);
13124     break;
13125   case OMPC_proc_bind:
13126     Res = ActOnOpenMPProcBindClause(static_cast<ProcBindKind>(Argument),
13127                                     ArgumentLoc, StartLoc, LParenLoc, EndLoc);
13128     break;
13129   case OMPC_atomic_default_mem_order:
13130     Res = ActOnOpenMPAtomicDefaultMemOrderClause(
13131         static_cast<OpenMPAtomicDefaultMemOrderClauseKind>(Argument),
13132         ArgumentLoc, StartLoc, LParenLoc, EndLoc);
13133     break;
13134   case OMPC_order:
13135     Res = ActOnOpenMPOrderClause(static_cast<OpenMPOrderClauseKind>(Argument),
13136                                  ArgumentLoc, StartLoc, LParenLoc, EndLoc);
13137     break;
13138   case OMPC_update:
13139     Res = ActOnOpenMPUpdateClause(static_cast<OpenMPDependClauseKind>(Argument),
13140                                   ArgumentLoc, StartLoc, LParenLoc, EndLoc);
13141     break;
13142   case OMPC_if:
13143   case OMPC_final:
13144   case OMPC_num_threads:
13145   case OMPC_safelen:
13146   case OMPC_simdlen:
13147   case OMPC_allocator:
13148   case OMPC_collapse:
13149   case OMPC_schedule:
13150   case OMPC_private:
13151   case OMPC_firstprivate:
13152   case OMPC_lastprivate:
13153   case OMPC_shared:
13154   case OMPC_reduction:
13155   case OMPC_task_reduction:
13156   case OMPC_in_reduction:
13157   case OMPC_linear:
13158   case OMPC_aligned:
13159   case OMPC_copyin:
13160   case OMPC_copyprivate:
13161   case OMPC_ordered:
13162   case OMPC_nowait:
13163   case OMPC_untied:
13164   case OMPC_mergeable:
13165   case OMPC_threadprivate:
13166   case OMPC_allocate:
13167   case OMPC_flush:
13168   case OMPC_depobj:
13169   case OMPC_read:
13170   case OMPC_write:
13171   case OMPC_capture:
13172   case OMPC_seq_cst:
13173   case OMPC_acq_rel:
13174   case OMPC_acquire:
13175   case OMPC_release:
13176   case OMPC_relaxed:
13177   case OMPC_depend:
13178   case OMPC_device:
13179   case OMPC_threads:
13180   case OMPC_simd:
13181   case OMPC_map:
13182   case OMPC_num_teams:
13183   case OMPC_thread_limit:
13184   case OMPC_priority:
13185   case OMPC_grainsize:
13186   case OMPC_nogroup:
13187   case OMPC_num_tasks:
13188   case OMPC_hint:
13189   case OMPC_dist_schedule:
13190   case OMPC_defaultmap:
13191   case OMPC_unknown:
13192   case OMPC_uniform:
13193   case OMPC_to:
13194   case OMPC_from:
13195   case OMPC_use_device_ptr:
13196   case OMPC_use_device_addr:
13197   case OMPC_is_device_ptr:
13198   case OMPC_unified_address:
13199   case OMPC_unified_shared_memory:
13200   case OMPC_reverse_offload:
13201   case OMPC_dynamic_allocators:
13202   case OMPC_device_type:
13203   case OMPC_match:
13204   case OMPC_nontemporal:
13205   case OMPC_destroy:
13206   case OMPC_detach:
13207   case OMPC_inclusive:
13208   case OMPC_exclusive:
13209   case OMPC_uses_allocators:
13210   case OMPC_affinity:
13211   default:
13212     llvm_unreachable("Clause is not allowed.");
13213   }
13214   return Res;
13215 }
13216 
13217 static std::string
13218 getListOfPossibleValues(OpenMPClauseKind K, unsigned First, unsigned Last,
13219                         ArrayRef<unsigned> Exclude = llvm::None) {
13220   SmallString<256> Buffer;
13221   llvm::raw_svector_ostream Out(Buffer);
13222   unsigned Skipped = Exclude.size();
13223   auto S = Exclude.begin(), E = Exclude.end();
13224   for (unsigned I = First; I < Last; ++I) {
13225     if (std::find(S, E, I) != E) {
13226       --Skipped;
13227       continue;
13228     }
13229     Out << "'" << getOpenMPSimpleClauseTypeName(K, I) << "'";
13230     if (I + Skipped + 2 == Last)
13231       Out << " or ";
13232     else if (I + Skipped + 1 != Last)
13233       Out << ", ";
13234   }
13235   return std::string(Out.str());
13236 }
13237 
13238 OMPClause *Sema::ActOnOpenMPDefaultClause(DefaultKind Kind,
13239                                           SourceLocation KindKwLoc,
13240                                           SourceLocation StartLoc,
13241                                           SourceLocation LParenLoc,
13242                                           SourceLocation EndLoc) {
13243   if (Kind == OMP_DEFAULT_unknown) {
13244     Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
13245         << getListOfPossibleValues(OMPC_default, /*First=*/0,
13246                                    /*Last=*/unsigned(OMP_DEFAULT_unknown))
13247         << getOpenMPClauseName(OMPC_default);
13248     return nullptr;
13249   }
13250 
13251   switch (Kind) {
13252   case OMP_DEFAULT_none:
13253     DSAStack->setDefaultDSANone(KindKwLoc);
13254     break;
13255   case OMP_DEFAULT_shared:
13256     DSAStack->setDefaultDSAShared(KindKwLoc);
13257     break;
13258   case OMP_DEFAULT_firstprivate:
13259     DSAStack->setDefaultDSAFirstPrivate(KindKwLoc);
13260     break;
13261   default:
13262     llvm_unreachable("DSA unexpected in OpenMP default clause");
13263   }
13264 
13265   return new (Context)
13266       OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
13267 }
13268 
13269 OMPClause *Sema::ActOnOpenMPProcBindClause(ProcBindKind Kind,
13270                                            SourceLocation KindKwLoc,
13271                                            SourceLocation StartLoc,
13272                                            SourceLocation LParenLoc,
13273                                            SourceLocation EndLoc) {
13274   if (Kind == OMP_PROC_BIND_unknown) {
13275     Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
13276         << getListOfPossibleValues(OMPC_proc_bind,
13277                                    /*First=*/unsigned(OMP_PROC_BIND_master),
13278                                    /*Last=*/5)
13279         << getOpenMPClauseName(OMPC_proc_bind);
13280     return nullptr;
13281   }
13282   return new (Context)
13283       OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
13284 }
13285 
13286 OMPClause *Sema::ActOnOpenMPAtomicDefaultMemOrderClause(
13287     OpenMPAtomicDefaultMemOrderClauseKind Kind, SourceLocation KindKwLoc,
13288     SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
13289   if (Kind == OMPC_ATOMIC_DEFAULT_MEM_ORDER_unknown) {
13290     Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
13291         << getListOfPossibleValues(
13292                OMPC_atomic_default_mem_order, /*First=*/0,
13293                /*Last=*/OMPC_ATOMIC_DEFAULT_MEM_ORDER_unknown)
13294         << getOpenMPClauseName(OMPC_atomic_default_mem_order);
13295     return nullptr;
13296   }
13297   return new (Context) OMPAtomicDefaultMemOrderClause(Kind, KindKwLoc, StartLoc,
13298                                                       LParenLoc, EndLoc);
13299 }
13300 
13301 OMPClause *Sema::ActOnOpenMPOrderClause(OpenMPOrderClauseKind Kind,
13302                                         SourceLocation KindKwLoc,
13303                                         SourceLocation StartLoc,
13304                                         SourceLocation LParenLoc,
13305                                         SourceLocation EndLoc) {
13306   if (Kind == OMPC_ORDER_unknown) {
13307     static_assert(OMPC_ORDER_unknown > 0,
13308                   "OMPC_ORDER_unknown not greater than 0");
13309     Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
13310         << getListOfPossibleValues(OMPC_order, /*First=*/0,
13311                                    /*Last=*/OMPC_ORDER_unknown)
13312         << getOpenMPClauseName(OMPC_order);
13313     return nullptr;
13314   }
13315   return new (Context)
13316       OMPOrderClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
13317 }
13318 
13319 OMPClause *Sema::ActOnOpenMPUpdateClause(OpenMPDependClauseKind Kind,
13320                                          SourceLocation KindKwLoc,
13321                                          SourceLocation StartLoc,
13322                                          SourceLocation LParenLoc,
13323                                          SourceLocation EndLoc) {
13324   if (Kind == OMPC_DEPEND_unknown || Kind == OMPC_DEPEND_source ||
13325       Kind == OMPC_DEPEND_sink || Kind == OMPC_DEPEND_depobj) {
13326     unsigned Except[] = {OMPC_DEPEND_source, OMPC_DEPEND_sink,
13327                          OMPC_DEPEND_depobj};
13328     Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
13329         << getListOfPossibleValues(OMPC_depend, /*First=*/0,
13330                                    /*Last=*/OMPC_DEPEND_unknown, Except)
13331         << getOpenMPClauseName(OMPC_update);
13332     return nullptr;
13333   }
13334   return OMPUpdateClause::Create(Context, StartLoc, LParenLoc, KindKwLoc, Kind,
13335                                  EndLoc);
13336 }
13337 
13338 OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause(
13339     OpenMPClauseKind Kind, ArrayRef<unsigned> Argument, Expr *Expr,
13340     SourceLocation StartLoc, SourceLocation LParenLoc,
13341     ArrayRef<SourceLocation> ArgumentLoc, SourceLocation DelimLoc,
13342     SourceLocation EndLoc) {
13343   OMPClause *Res = nullptr;
13344   switch (Kind) {
13345   case OMPC_schedule:
13346     enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements };
13347     assert(Argument.size() == NumberOfElements &&
13348            ArgumentLoc.size() == NumberOfElements);
13349     Res = ActOnOpenMPScheduleClause(
13350         static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier1]),
13351         static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier2]),
13352         static_cast<OpenMPScheduleClauseKind>(Argument[ScheduleKind]), Expr,
13353         StartLoc, LParenLoc, ArgumentLoc[Modifier1], ArgumentLoc[Modifier2],
13354         ArgumentLoc[ScheduleKind], DelimLoc, EndLoc);
13355     break;
13356   case OMPC_if:
13357     assert(Argument.size() == 1 && ArgumentLoc.size() == 1);
13358     Res = ActOnOpenMPIfClause(static_cast<OpenMPDirectiveKind>(Argument.back()),
13359                               Expr, StartLoc, LParenLoc, ArgumentLoc.back(),
13360                               DelimLoc, EndLoc);
13361     break;
13362   case OMPC_dist_schedule:
13363     Res = ActOnOpenMPDistScheduleClause(
13364         static_cast<OpenMPDistScheduleClauseKind>(Argument.back()), Expr,
13365         StartLoc, LParenLoc, ArgumentLoc.back(), DelimLoc, EndLoc);
13366     break;
13367   case OMPC_defaultmap:
13368     enum { Modifier, DefaultmapKind };
13369     Res = ActOnOpenMPDefaultmapClause(
13370         static_cast<OpenMPDefaultmapClauseModifier>(Argument[Modifier]),
13371         static_cast<OpenMPDefaultmapClauseKind>(Argument[DefaultmapKind]),
13372         StartLoc, LParenLoc, ArgumentLoc[Modifier], ArgumentLoc[DefaultmapKind],
13373         EndLoc);
13374     break;
13375   case OMPC_device:
13376     assert(Argument.size() == 1 && ArgumentLoc.size() == 1);
13377     Res = ActOnOpenMPDeviceClause(
13378         static_cast<OpenMPDeviceClauseModifier>(Argument.back()), Expr,
13379         StartLoc, LParenLoc, ArgumentLoc.back(), EndLoc);
13380     break;
13381   case OMPC_final:
13382   case OMPC_num_threads:
13383   case OMPC_safelen:
13384   case OMPC_simdlen:
13385   case OMPC_allocator:
13386   case OMPC_collapse:
13387   case OMPC_default:
13388   case OMPC_proc_bind:
13389   case OMPC_private:
13390   case OMPC_firstprivate:
13391   case OMPC_lastprivate:
13392   case OMPC_shared:
13393   case OMPC_reduction:
13394   case OMPC_task_reduction:
13395   case OMPC_in_reduction:
13396   case OMPC_linear:
13397   case OMPC_aligned:
13398   case OMPC_copyin:
13399   case OMPC_copyprivate:
13400   case OMPC_ordered:
13401   case OMPC_nowait:
13402   case OMPC_untied:
13403   case OMPC_mergeable:
13404   case OMPC_threadprivate:
13405   case OMPC_allocate:
13406   case OMPC_flush:
13407   case OMPC_depobj:
13408   case OMPC_read:
13409   case OMPC_write:
13410   case OMPC_update:
13411   case OMPC_capture:
13412   case OMPC_seq_cst:
13413   case OMPC_acq_rel:
13414   case OMPC_acquire:
13415   case OMPC_release:
13416   case OMPC_relaxed:
13417   case OMPC_depend:
13418   case OMPC_threads:
13419   case OMPC_simd:
13420   case OMPC_map:
13421   case OMPC_num_teams:
13422   case OMPC_thread_limit:
13423   case OMPC_priority:
13424   case OMPC_grainsize:
13425   case OMPC_nogroup:
13426   case OMPC_num_tasks:
13427   case OMPC_hint:
13428   case OMPC_unknown:
13429   case OMPC_uniform:
13430   case OMPC_to:
13431   case OMPC_from:
13432   case OMPC_use_device_ptr:
13433   case OMPC_use_device_addr:
13434   case OMPC_is_device_ptr:
13435   case OMPC_unified_address:
13436   case OMPC_unified_shared_memory:
13437   case OMPC_reverse_offload:
13438   case OMPC_dynamic_allocators:
13439   case OMPC_atomic_default_mem_order:
13440   case OMPC_device_type:
13441   case OMPC_match:
13442   case OMPC_nontemporal:
13443   case OMPC_order:
13444   case OMPC_destroy:
13445   case OMPC_detach:
13446   case OMPC_inclusive:
13447   case OMPC_exclusive:
13448   case OMPC_uses_allocators:
13449   case OMPC_affinity:
13450   default:
13451     llvm_unreachable("Clause is not allowed.");
13452   }
13453   return Res;
13454 }
13455 
13456 static bool checkScheduleModifiers(Sema &S, OpenMPScheduleClauseModifier M1,
13457                                    OpenMPScheduleClauseModifier M2,
13458                                    SourceLocation M1Loc, SourceLocation M2Loc) {
13459   if (M1 == OMPC_SCHEDULE_MODIFIER_unknown && M1Loc.isValid()) {
13460     SmallVector<unsigned, 2> Excluded;
13461     if (M2 != OMPC_SCHEDULE_MODIFIER_unknown)
13462       Excluded.push_back(M2);
13463     if (M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic)
13464       Excluded.push_back(OMPC_SCHEDULE_MODIFIER_monotonic);
13465     if (M2 == OMPC_SCHEDULE_MODIFIER_monotonic)
13466       Excluded.push_back(OMPC_SCHEDULE_MODIFIER_nonmonotonic);
13467     S.Diag(M1Loc, diag::err_omp_unexpected_clause_value)
13468         << getListOfPossibleValues(OMPC_schedule,
13469                                    /*First=*/OMPC_SCHEDULE_MODIFIER_unknown + 1,
13470                                    /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
13471                                    Excluded)
13472         << getOpenMPClauseName(OMPC_schedule);
13473     return true;
13474   }
13475   return false;
13476 }
13477 
13478 OMPClause *Sema::ActOnOpenMPScheduleClause(
13479     OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
13480     OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
13481     SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
13482     SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) {
13483   if (checkScheduleModifiers(*this, M1, M2, M1Loc, M2Loc) ||
13484       checkScheduleModifiers(*this, M2, M1, M2Loc, M1Loc))
13485     return nullptr;
13486   // OpenMP, 2.7.1, Loop Construct, Restrictions
13487   // Either the monotonic modifier or the nonmonotonic modifier can be specified
13488   // but not both.
13489   if ((M1 == M2 && M1 != OMPC_SCHEDULE_MODIFIER_unknown) ||
13490       (M1 == OMPC_SCHEDULE_MODIFIER_monotonic &&
13491        M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) ||
13492       (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic &&
13493        M2 == OMPC_SCHEDULE_MODIFIER_monotonic)) {
13494     Diag(M2Loc, diag::err_omp_unexpected_schedule_modifier)
13495         << getOpenMPSimpleClauseTypeName(OMPC_schedule, M2)
13496         << getOpenMPSimpleClauseTypeName(OMPC_schedule, M1);
13497     return nullptr;
13498   }
13499   if (Kind == OMPC_SCHEDULE_unknown) {
13500     std::string Values;
13501     if (M1Loc.isInvalid() && M2Loc.isInvalid()) {
13502       unsigned Exclude[] = {OMPC_SCHEDULE_unknown};
13503       Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
13504                                        /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
13505                                        Exclude);
13506     } else {
13507       Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
13508                                        /*Last=*/OMPC_SCHEDULE_unknown);
13509     }
13510     Diag(KindLoc, diag::err_omp_unexpected_clause_value)
13511         << Values << getOpenMPClauseName(OMPC_schedule);
13512     return nullptr;
13513   }
13514   // OpenMP, 2.7.1, Loop Construct, Restrictions
13515   // The nonmonotonic modifier can only be specified with schedule(dynamic) or
13516   // schedule(guided).
13517   // OpenMP 5.0 does not have this restriction.
13518   if (LangOpts.OpenMP < 50 &&
13519       (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
13520        M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
13521       Kind != OMPC_SCHEDULE_dynamic && Kind != OMPC_SCHEDULE_guided) {
13522     Diag(M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ? M1Loc : M2Loc,
13523          diag::err_omp_schedule_nonmonotonic_static);
13524     return nullptr;
13525   }
13526   Expr *ValExpr = ChunkSize;
13527   Stmt *HelperValStmt = nullptr;
13528   if (ChunkSize) {
13529     if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
13530         !ChunkSize->isInstantiationDependent() &&
13531         !ChunkSize->containsUnexpandedParameterPack()) {
13532       SourceLocation ChunkSizeLoc = ChunkSize->getBeginLoc();
13533       ExprResult Val =
13534           PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
13535       if (Val.isInvalid())
13536         return nullptr;
13537 
13538       ValExpr = Val.get();
13539 
13540       // OpenMP [2.7.1, Restrictions]
13541       //  chunk_size must be a loop invariant integer expression with a positive
13542       //  value.
13543       if (Optional<llvm::APSInt> Result =
13544               ValExpr->getIntegerConstantExpr(Context)) {
13545         if (Result->isSigned() && !Result->isStrictlyPositive()) {
13546           Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
13547               << "schedule" << 1 << ChunkSize->getSourceRange();
13548           return nullptr;
13549         }
13550       } else if (getOpenMPCaptureRegionForClause(
13551                      DSAStack->getCurrentDirective(), OMPC_schedule,
13552                      LangOpts.OpenMP) != OMPD_unknown &&
13553                  !CurContext->isDependentContext()) {
13554         ValExpr = MakeFullExpr(ValExpr).get();
13555         llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
13556         ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
13557         HelperValStmt = buildPreInits(Context, Captures);
13558       }
13559     }
13560   }
13561 
13562   return new (Context)
13563       OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, Kind,
13564                         ValExpr, HelperValStmt, M1, M1Loc, M2, M2Loc);
13565 }
13566 
13567 OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind,
13568                                    SourceLocation StartLoc,
13569                                    SourceLocation EndLoc) {
13570   OMPClause *Res = nullptr;
13571   switch (Kind) {
13572   case OMPC_ordered:
13573     Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc);
13574     break;
13575   case OMPC_nowait:
13576     Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc);
13577     break;
13578   case OMPC_untied:
13579     Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc);
13580     break;
13581   case OMPC_mergeable:
13582     Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc);
13583     break;
13584   case OMPC_read:
13585     Res = ActOnOpenMPReadClause(StartLoc, EndLoc);
13586     break;
13587   case OMPC_write:
13588     Res = ActOnOpenMPWriteClause(StartLoc, EndLoc);
13589     break;
13590   case OMPC_update:
13591     Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc);
13592     break;
13593   case OMPC_capture:
13594     Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc);
13595     break;
13596   case OMPC_seq_cst:
13597     Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc);
13598     break;
13599   case OMPC_acq_rel:
13600     Res = ActOnOpenMPAcqRelClause(StartLoc, EndLoc);
13601     break;
13602   case OMPC_acquire:
13603     Res = ActOnOpenMPAcquireClause(StartLoc, EndLoc);
13604     break;
13605   case OMPC_release:
13606     Res = ActOnOpenMPReleaseClause(StartLoc, EndLoc);
13607     break;
13608   case OMPC_relaxed:
13609     Res = ActOnOpenMPRelaxedClause(StartLoc, EndLoc);
13610     break;
13611   case OMPC_threads:
13612     Res = ActOnOpenMPThreadsClause(StartLoc, EndLoc);
13613     break;
13614   case OMPC_simd:
13615     Res = ActOnOpenMPSIMDClause(StartLoc, EndLoc);
13616     break;
13617   case OMPC_nogroup:
13618     Res = ActOnOpenMPNogroupClause(StartLoc, EndLoc);
13619     break;
13620   case OMPC_unified_address:
13621     Res = ActOnOpenMPUnifiedAddressClause(StartLoc, EndLoc);
13622     break;
13623   case OMPC_unified_shared_memory:
13624     Res = ActOnOpenMPUnifiedSharedMemoryClause(StartLoc, EndLoc);
13625     break;
13626   case OMPC_reverse_offload:
13627     Res = ActOnOpenMPReverseOffloadClause(StartLoc, EndLoc);
13628     break;
13629   case OMPC_dynamic_allocators:
13630     Res = ActOnOpenMPDynamicAllocatorsClause(StartLoc, EndLoc);
13631     break;
13632   case OMPC_destroy:
13633     Res = ActOnOpenMPDestroyClause(StartLoc, EndLoc);
13634     break;
13635   case OMPC_if:
13636   case OMPC_final:
13637   case OMPC_num_threads:
13638   case OMPC_safelen:
13639   case OMPC_simdlen:
13640   case OMPC_allocator:
13641   case OMPC_collapse:
13642   case OMPC_schedule:
13643   case OMPC_private:
13644   case OMPC_firstprivate:
13645   case OMPC_lastprivate:
13646   case OMPC_shared:
13647   case OMPC_reduction:
13648   case OMPC_task_reduction:
13649   case OMPC_in_reduction:
13650   case OMPC_linear:
13651   case OMPC_aligned:
13652   case OMPC_copyin:
13653   case OMPC_copyprivate:
13654   case OMPC_default:
13655   case OMPC_proc_bind:
13656   case OMPC_threadprivate:
13657   case OMPC_allocate:
13658   case OMPC_flush:
13659   case OMPC_depobj:
13660   case OMPC_depend:
13661   case OMPC_device:
13662   case OMPC_map:
13663   case OMPC_num_teams:
13664   case OMPC_thread_limit:
13665   case OMPC_priority:
13666   case OMPC_grainsize:
13667   case OMPC_num_tasks:
13668   case OMPC_hint:
13669   case OMPC_dist_schedule:
13670   case OMPC_defaultmap:
13671   case OMPC_unknown:
13672   case OMPC_uniform:
13673   case OMPC_to:
13674   case OMPC_from:
13675   case OMPC_use_device_ptr:
13676   case OMPC_use_device_addr:
13677   case OMPC_is_device_ptr:
13678   case OMPC_atomic_default_mem_order:
13679   case OMPC_device_type:
13680   case OMPC_match:
13681   case OMPC_nontemporal:
13682   case OMPC_order:
13683   case OMPC_detach:
13684   case OMPC_inclusive:
13685   case OMPC_exclusive:
13686   case OMPC_uses_allocators:
13687   case OMPC_affinity:
13688   default:
13689     llvm_unreachable("Clause is not allowed.");
13690   }
13691   return Res;
13692 }
13693 
13694 OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc,
13695                                          SourceLocation EndLoc) {
13696   DSAStack->setNowaitRegion();
13697   return new (Context) OMPNowaitClause(StartLoc, EndLoc);
13698 }
13699 
13700 OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc,
13701                                          SourceLocation EndLoc) {
13702   return new (Context) OMPUntiedClause(StartLoc, EndLoc);
13703 }
13704 
13705 OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc,
13706                                             SourceLocation EndLoc) {
13707   return new (Context) OMPMergeableClause(StartLoc, EndLoc);
13708 }
13709 
13710 OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc,
13711                                        SourceLocation EndLoc) {
13712   return new (Context) OMPReadClause(StartLoc, EndLoc);
13713 }
13714 
13715 OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc,
13716                                         SourceLocation EndLoc) {
13717   return new (Context) OMPWriteClause(StartLoc, EndLoc);
13718 }
13719 
13720 OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc,
13721                                          SourceLocation EndLoc) {
13722   return OMPUpdateClause::Create(Context, StartLoc, EndLoc);
13723 }
13724 
13725 OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc,
13726                                           SourceLocation EndLoc) {
13727   return new (Context) OMPCaptureClause(StartLoc, EndLoc);
13728 }
13729 
13730 OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
13731                                          SourceLocation EndLoc) {
13732   return new (Context) OMPSeqCstClause(StartLoc, EndLoc);
13733 }
13734 
13735 OMPClause *Sema::ActOnOpenMPAcqRelClause(SourceLocation StartLoc,
13736                                          SourceLocation EndLoc) {
13737   return new (Context) OMPAcqRelClause(StartLoc, EndLoc);
13738 }
13739 
13740 OMPClause *Sema::ActOnOpenMPAcquireClause(SourceLocation StartLoc,
13741                                           SourceLocation EndLoc) {
13742   return new (Context) OMPAcquireClause(StartLoc, EndLoc);
13743 }
13744 
13745 OMPClause *Sema::ActOnOpenMPReleaseClause(SourceLocation StartLoc,
13746                                           SourceLocation EndLoc) {
13747   return new (Context) OMPReleaseClause(StartLoc, EndLoc);
13748 }
13749 
13750 OMPClause *Sema::ActOnOpenMPRelaxedClause(SourceLocation StartLoc,
13751                                           SourceLocation EndLoc) {
13752   return new (Context) OMPRelaxedClause(StartLoc, EndLoc);
13753 }
13754 
13755 OMPClause *Sema::ActOnOpenMPThreadsClause(SourceLocation StartLoc,
13756                                           SourceLocation EndLoc) {
13757   return new (Context) OMPThreadsClause(StartLoc, EndLoc);
13758 }
13759 
13760 OMPClause *Sema::ActOnOpenMPSIMDClause(SourceLocation StartLoc,
13761                                        SourceLocation EndLoc) {
13762   return new (Context) OMPSIMDClause(StartLoc, EndLoc);
13763 }
13764 
13765 OMPClause *Sema::ActOnOpenMPNogroupClause(SourceLocation StartLoc,
13766                                           SourceLocation EndLoc) {
13767   return new (Context) OMPNogroupClause(StartLoc, EndLoc);
13768 }
13769 
13770 OMPClause *Sema::ActOnOpenMPUnifiedAddressClause(SourceLocation StartLoc,
13771                                                  SourceLocation EndLoc) {
13772   return new (Context) OMPUnifiedAddressClause(StartLoc, EndLoc);
13773 }
13774 
13775 OMPClause *Sema::ActOnOpenMPUnifiedSharedMemoryClause(SourceLocation StartLoc,
13776                                                       SourceLocation EndLoc) {
13777   return new (Context) OMPUnifiedSharedMemoryClause(StartLoc, EndLoc);
13778 }
13779 
13780 OMPClause *Sema::ActOnOpenMPReverseOffloadClause(SourceLocation StartLoc,
13781                                                  SourceLocation EndLoc) {
13782   return new (Context) OMPReverseOffloadClause(StartLoc, EndLoc);
13783 }
13784 
13785 OMPClause *Sema::ActOnOpenMPDynamicAllocatorsClause(SourceLocation StartLoc,
13786                                                     SourceLocation EndLoc) {
13787   return new (Context) OMPDynamicAllocatorsClause(StartLoc, EndLoc);
13788 }
13789 
13790 OMPClause *Sema::ActOnOpenMPDestroyClause(SourceLocation StartLoc,
13791                                           SourceLocation EndLoc) {
13792   return new (Context) OMPDestroyClause(StartLoc, EndLoc);
13793 }
13794 
13795 OMPClause *Sema::ActOnOpenMPVarListClause(
13796     OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *DepModOrTailExpr,
13797     const OMPVarListLocTy &Locs, SourceLocation ColonLoc,
13798     CXXScopeSpec &ReductionOrMapperIdScopeSpec,
13799     DeclarationNameInfo &ReductionOrMapperId, int ExtraModifier,
13800     ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
13801     ArrayRef<SourceLocation> MapTypeModifiersLoc, bool IsMapTypeImplicit,
13802     SourceLocation ExtraModifierLoc,
13803     ArrayRef<OpenMPMotionModifierKind> MotionModifiers,
13804     ArrayRef<SourceLocation> MotionModifiersLoc) {
13805   SourceLocation StartLoc = Locs.StartLoc;
13806   SourceLocation LParenLoc = Locs.LParenLoc;
13807   SourceLocation EndLoc = Locs.EndLoc;
13808   OMPClause *Res = nullptr;
13809   switch (Kind) {
13810   case OMPC_private:
13811     Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
13812     break;
13813   case OMPC_firstprivate:
13814     Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
13815     break;
13816   case OMPC_lastprivate:
13817     assert(0 <= ExtraModifier && ExtraModifier <= OMPC_LASTPRIVATE_unknown &&
13818            "Unexpected lastprivate modifier.");
13819     Res = ActOnOpenMPLastprivateClause(
13820         VarList, static_cast<OpenMPLastprivateModifier>(ExtraModifier),
13821         ExtraModifierLoc, ColonLoc, StartLoc, LParenLoc, EndLoc);
13822     break;
13823   case OMPC_shared:
13824     Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
13825     break;
13826   case OMPC_reduction:
13827     assert(0 <= ExtraModifier && ExtraModifier <= OMPC_REDUCTION_unknown &&
13828            "Unexpected lastprivate modifier.");
13829     Res = ActOnOpenMPReductionClause(
13830         VarList, static_cast<OpenMPReductionClauseModifier>(ExtraModifier),
13831         StartLoc, LParenLoc, ExtraModifierLoc, ColonLoc, EndLoc,
13832         ReductionOrMapperIdScopeSpec, ReductionOrMapperId);
13833     break;
13834   case OMPC_task_reduction:
13835     Res = ActOnOpenMPTaskReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
13836                                          EndLoc, ReductionOrMapperIdScopeSpec,
13837                                          ReductionOrMapperId);
13838     break;
13839   case OMPC_in_reduction:
13840     Res = ActOnOpenMPInReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
13841                                        EndLoc, ReductionOrMapperIdScopeSpec,
13842                                        ReductionOrMapperId);
13843     break;
13844   case OMPC_linear:
13845     assert(0 <= ExtraModifier && ExtraModifier <= OMPC_LINEAR_unknown &&
13846            "Unexpected linear modifier.");
13847     Res = ActOnOpenMPLinearClause(
13848         VarList, DepModOrTailExpr, StartLoc, LParenLoc,
13849         static_cast<OpenMPLinearClauseKind>(ExtraModifier), ExtraModifierLoc,
13850         ColonLoc, EndLoc);
13851     break;
13852   case OMPC_aligned:
13853     Res = ActOnOpenMPAlignedClause(VarList, DepModOrTailExpr, StartLoc,
13854                                    LParenLoc, ColonLoc, EndLoc);
13855     break;
13856   case OMPC_copyin:
13857     Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
13858     break;
13859   case OMPC_copyprivate:
13860     Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
13861     break;
13862   case OMPC_flush:
13863     Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc);
13864     break;
13865   case OMPC_depend:
13866     assert(0 <= ExtraModifier && ExtraModifier <= OMPC_DEPEND_unknown &&
13867            "Unexpected depend modifier.");
13868     Res = ActOnOpenMPDependClause(
13869         DepModOrTailExpr, static_cast<OpenMPDependClauseKind>(ExtraModifier),
13870         ExtraModifierLoc, ColonLoc, VarList, StartLoc, LParenLoc, EndLoc);
13871     break;
13872   case OMPC_map:
13873     assert(0 <= ExtraModifier && ExtraModifier <= OMPC_MAP_unknown &&
13874            "Unexpected map modifier.");
13875     Res = ActOnOpenMPMapClause(
13876         MapTypeModifiers, MapTypeModifiersLoc, ReductionOrMapperIdScopeSpec,
13877         ReductionOrMapperId, static_cast<OpenMPMapClauseKind>(ExtraModifier),
13878         IsMapTypeImplicit, ExtraModifierLoc, ColonLoc, VarList, Locs);
13879     break;
13880   case OMPC_to:
13881     Res = ActOnOpenMPToClause(MotionModifiers, MotionModifiersLoc,
13882                               ReductionOrMapperIdScopeSpec, ReductionOrMapperId,
13883                               ColonLoc, VarList, Locs);
13884     break;
13885   case OMPC_from:
13886     Res = ActOnOpenMPFromClause(MotionModifiers, MotionModifiersLoc,
13887                                 ReductionOrMapperIdScopeSpec,
13888                                 ReductionOrMapperId, ColonLoc, VarList, Locs);
13889     break;
13890   case OMPC_use_device_ptr:
13891     Res = ActOnOpenMPUseDevicePtrClause(VarList, Locs);
13892     break;
13893   case OMPC_use_device_addr:
13894     Res = ActOnOpenMPUseDeviceAddrClause(VarList, Locs);
13895     break;
13896   case OMPC_is_device_ptr:
13897     Res = ActOnOpenMPIsDevicePtrClause(VarList, Locs);
13898     break;
13899   case OMPC_allocate:
13900     Res = ActOnOpenMPAllocateClause(DepModOrTailExpr, VarList, StartLoc,
13901                                     LParenLoc, ColonLoc, EndLoc);
13902     break;
13903   case OMPC_nontemporal:
13904     Res = ActOnOpenMPNontemporalClause(VarList, StartLoc, LParenLoc, EndLoc);
13905     break;
13906   case OMPC_inclusive:
13907     Res = ActOnOpenMPInclusiveClause(VarList, StartLoc, LParenLoc, EndLoc);
13908     break;
13909   case OMPC_exclusive:
13910     Res = ActOnOpenMPExclusiveClause(VarList, StartLoc, LParenLoc, EndLoc);
13911     break;
13912   case OMPC_affinity:
13913     Res = ActOnOpenMPAffinityClause(StartLoc, LParenLoc, ColonLoc, EndLoc,
13914                                     DepModOrTailExpr, VarList);
13915     break;
13916   case OMPC_if:
13917   case OMPC_depobj:
13918   case OMPC_final:
13919   case OMPC_num_threads:
13920   case OMPC_safelen:
13921   case OMPC_simdlen:
13922   case OMPC_allocator:
13923   case OMPC_collapse:
13924   case OMPC_default:
13925   case OMPC_proc_bind:
13926   case OMPC_schedule:
13927   case OMPC_ordered:
13928   case OMPC_nowait:
13929   case OMPC_untied:
13930   case OMPC_mergeable:
13931   case OMPC_threadprivate:
13932   case OMPC_read:
13933   case OMPC_write:
13934   case OMPC_update:
13935   case OMPC_capture:
13936   case OMPC_seq_cst:
13937   case OMPC_acq_rel:
13938   case OMPC_acquire:
13939   case OMPC_release:
13940   case OMPC_relaxed:
13941   case OMPC_device:
13942   case OMPC_threads:
13943   case OMPC_simd:
13944   case OMPC_num_teams:
13945   case OMPC_thread_limit:
13946   case OMPC_priority:
13947   case OMPC_grainsize:
13948   case OMPC_nogroup:
13949   case OMPC_num_tasks:
13950   case OMPC_hint:
13951   case OMPC_dist_schedule:
13952   case OMPC_defaultmap:
13953   case OMPC_unknown:
13954   case OMPC_uniform:
13955   case OMPC_unified_address:
13956   case OMPC_unified_shared_memory:
13957   case OMPC_reverse_offload:
13958   case OMPC_dynamic_allocators:
13959   case OMPC_atomic_default_mem_order:
13960   case OMPC_device_type:
13961   case OMPC_match:
13962   case OMPC_order:
13963   case OMPC_destroy:
13964   case OMPC_detach:
13965   case OMPC_uses_allocators:
13966   default:
13967     llvm_unreachable("Clause is not allowed.");
13968   }
13969   return Res;
13970 }
13971 
13972 ExprResult Sema::getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
13973                                        ExprObjectKind OK, SourceLocation Loc) {
13974   ExprResult Res = BuildDeclRefExpr(
13975       Capture, Capture->getType().getNonReferenceType(), VK_LValue, Loc);
13976   if (!Res.isUsable())
13977     return ExprError();
13978   if (OK == OK_Ordinary && !getLangOpts().CPlusPlus) {
13979     Res = CreateBuiltinUnaryOp(Loc, UO_Deref, Res.get());
13980     if (!Res.isUsable())
13981       return ExprError();
13982   }
13983   if (VK != VK_LValue && Res.get()->isGLValue()) {
13984     Res = DefaultLvalueConversion(Res.get());
13985     if (!Res.isUsable())
13986       return ExprError();
13987   }
13988   return Res;
13989 }
13990 
13991 OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
13992                                           SourceLocation StartLoc,
13993                                           SourceLocation LParenLoc,
13994                                           SourceLocation EndLoc) {
13995   SmallVector<Expr *, 8> Vars;
13996   SmallVector<Expr *, 8> PrivateCopies;
13997   for (Expr *RefExpr : VarList) {
13998     assert(RefExpr && "NULL expr in OpenMP private clause.");
13999     SourceLocation ELoc;
14000     SourceRange ERange;
14001     Expr *SimpleRefExpr = RefExpr;
14002     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
14003     if (Res.second) {
14004       // It will be analyzed later.
14005       Vars.push_back(RefExpr);
14006       PrivateCopies.push_back(nullptr);
14007     }
14008     ValueDecl *D = Res.first;
14009     if (!D)
14010       continue;
14011 
14012     QualType Type = D->getType();
14013     auto *VD = dyn_cast<VarDecl>(D);
14014 
14015     // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
14016     //  A variable that appears in a private clause must not have an incomplete
14017     //  type or a reference type.
14018     if (RequireCompleteType(ELoc, Type, diag::err_omp_private_incomplete_type))
14019       continue;
14020     Type = Type.getNonReferenceType();
14021 
14022     // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
14023     // A variable that is privatized must not have a const-qualified type
14024     // unless it is of class type with a mutable member. This restriction does
14025     // not apply to the firstprivate clause.
14026     //
14027     // OpenMP 3.1 [2.9.3.3, private clause, Restrictions]
14028     // A variable that appears in a private clause must not have a
14029     // const-qualified type unless it is of class type with a mutable member.
14030     if (rejectConstNotMutableType(*this, D, Type, OMPC_private, ELoc))
14031       continue;
14032 
14033     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
14034     // in a Construct]
14035     //  Variables with the predetermined data-sharing attributes may not be
14036     //  listed in data-sharing attributes clauses, except for the cases
14037     //  listed below. For these exceptions only, listing a predetermined
14038     //  variable in a data-sharing attribute clause is allowed and overrides
14039     //  the variable's predetermined data-sharing attributes.
14040     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
14041     if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
14042       Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
14043                                           << getOpenMPClauseName(OMPC_private);
14044       reportOriginalDsa(*this, DSAStack, D, DVar);
14045       continue;
14046     }
14047 
14048     OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
14049     // Variably modified types are not supported for tasks.
14050     if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
14051         isOpenMPTaskingDirective(CurrDir)) {
14052       Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
14053           << getOpenMPClauseName(OMPC_private) << Type
14054           << getOpenMPDirectiveName(CurrDir);
14055       bool IsDecl =
14056           !VD ||
14057           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
14058       Diag(D->getLocation(),
14059            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
14060           << D;
14061       continue;
14062     }
14063 
14064     // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
14065     // A list item cannot appear in both a map clause and a data-sharing
14066     // attribute clause on the same construct
14067     //
14068     // OpenMP 5.0 [2.19.7.1, Restrictions, p.7]
14069     // A list item cannot appear in both a map clause and a data-sharing
14070     // attribute clause on the same construct unless the construct is a
14071     // combined construct.
14072     if ((LangOpts.OpenMP <= 45 && isOpenMPTargetExecutionDirective(CurrDir)) ||
14073         CurrDir == OMPD_target) {
14074       OpenMPClauseKind ConflictKind;
14075       if (DSAStack->checkMappableExprComponentListsForDecl(
14076               VD, /*CurrentRegionOnly=*/true,
14077               [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
14078                   OpenMPClauseKind WhereFoundClauseKind) -> bool {
14079                 ConflictKind = WhereFoundClauseKind;
14080                 return true;
14081               })) {
14082         Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
14083             << getOpenMPClauseName(OMPC_private)
14084             << getOpenMPClauseName(ConflictKind)
14085             << getOpenMPDirectiveName(CurrDir);
14086         reportOriginalDsa(*this, DSAStack, D, DVar);
14087         continue;
14088       }
14089     }
14090 
14091     // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
14092     //  A variable of class type (or array thereof) that appears in a private
14093     //  clause requires an accessible, unambiguous default constructor for the
14094     //  class type.
14095     // Generate helper private variable and initialize it with the default
14096     // value. The address of the original variable is replaced by the address of
14097     // the new private variable in CodeGen. This new variable is not added to
14098     // IdResolver, so the code in the OpenMP region uses original variable for
14099     // proper diagnostics.
14100     Type = Type.getUnqualifiedType();
14101     VarDecl *VDPrivate =
14102         buildVarDecl(*this, ELoc, Type, D->getName(),
14103                      D->hasAttrs() ? &D->getAttrs() : nullptr,
14104                      VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
14105     ActOnUninitializedDecl(VDPrivate);
14106     if (VDPrivate->isInvalidDecl())
14107       continue;
14108     DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
14109         *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
14110 
14111     DeclRefExpr *Ref = nullptr;
14112     if (!VD && !CurContext->isDependentContext())
14113       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
14114     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_private, Ref);
14115     Vars.push_back((VD || CurContext->isDependentContext())
14116                        ? RefExpr->IgnoreParens()
14117                        : Ref);
14118     PrivateCopies.push_back(VDPrivateRefExpr);
14119   }
14120 
14121   if (Vars.empty())
14122     return nullptr;
14123 
14124   return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
14125                                   PrivateCopies);
14126 }
14127 
14128 namespace {
14129 class DiagsUninitializedSeveretyRAII {
14130 private:
14131   DiagnosticsEngine &Diags;
14132   SourceLocation SavedLoc;
14133   bool IsIgnored = false;
14134 
14135 public:
14136   DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc,
14137                                  bool IsIgnored)
14138       : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) {
14139     if (!IsIgnored) {
14140       Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init,
14141                         /*Map*/ diag::Severity::Ignored, Loc);
14142     }
14143   }
14144   ~DiagsUninitializedSeveretyRAII() {
14145     if (!IsIgnored)
14146       Diags.popMappings(SavedLoc);
14147   }
14148 };
14149 }
14150 
14151 OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
14152                                                SourceLocation StartLoc,
14153                                                SourceLocation LParenLoc,
14154                                                SourceLocation EndLoc) {
14155   SmallVector<Expr *, 8> Vars;
14156   SmallVector<Expr *, 8> PrivateCopies;
14157   SmallVector<Expr *, 8> Inits;
14158   SmallVector<Decl *, 4> ExprCaptures;
14159   bool IsImplicitClause =
14160       StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid();
14161   SourceLocation ImplicitClauseLoc = DSAStack->getConstructLoc();
14162 
14163   for (Expr *RefExpr : VarList) {
14164     assert(RefExpr && "NULL expr in OpenMP firstprivate clause.");
14165     SourceLocation ELoc;
14166     SourceRange ERange;
14167     Expr *SimpleRefExpr = RefExpr;
14168     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
14169     if (Res.second) {
14170       // It will be analyzed later.
14171       Vars.push_back(RefExpr);
14172       PrivateCopies.push_back(nullptr);
14173       Inits.push_back(nullptr);
14174     }
14175     ValueDecl *D = Res.first;
14176     if (!D)
14177       continue;
14178 
14179     ELoc = IsImplicitClause ? ImplicitClauseLoc : ELoc;
14180     QualType Type = D->getType();
14181     auto *VD = dyn_cast<VarDecl>(D);
14182 
14183     // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
14184     //  A variable that appears in a private clause must not have an incomplete
14185     //  type or a reference type.
14186     if (RequireCompleteType(ELoc, Type,
14187                             diag::err_omp_firstprivate_incomplete_type))
14188       continue;
14189     Type = Type.getNonReferenceType();
14190 
14191     // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
14192     //  A variable of class type (or array thereof) that appears in a private
14193     //  clause requires an accessible, unambiguous copy constructor for the
14194     //  class type.
14195     QualType ElemType = Context.getBaseElementType(Type).getNonReferenceType();
14196 
14197     // If an implicit firstprivate variable found it was checked already.
14198     DSAStackTy::DSAVarData TopDVar;
14199     if (!IsImplicitClause) {
14200       DSAStackTy::DSAVarData DVar =
14201           DSAStack->getTopDSA(D, /*FromParent=*/false);
14202       TopDVar = DVar;
14203       OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
14204       bool IsConstant = ElemType.isConstant(Context);
14205       // OpenMP [2.4.13, Data-sharing Attribute Clauses]
14206       //  A list item that specifies a given variable may not appear in more
14207       // than one clause on the same directive, except that a variable may be
14208       //  specified in both firstprivate and lastprivate clauses.
14209       // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
14210       // A list item may appear in a firstprivate or lastprivate clause but not
14211       // both.
14212       if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
14213           (isOpenMPDistributeDirective(CurrDir) ||
14214            DVar.CKind != OMPC_lastprivate) &&
14215           DVar.RefExpr) {
14216         Diag(ELoc, diag::err_omp_wrong_dsa)
14217             << getOpenMPClauseName(DVar.CKind)
14218             << getOpenMPClauseName(OMPC_firstprivate);
14219         reportOriginalDsa(*this, DSAStack, D, DVar);
14220         continue;
14221       }
14222 
14223       // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
14224       // in a Construct]
14225       //  Variables with the predetermined data-sharing attributes may not be
14226       //  listed in data-sharing attributes clauses, except for the cases
14227       //  listed below. For these exceptions only, listing a predetermined
14228       //  variable in a data-sharing attribute clause is allowed and overrides
14229       //  the variable's predetermined data-sharing attributes.
14230       // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
14231       // in a Construct, C/C++, p.2]
14232       //  Variables with const-qualified type having no mutable member may be
14233       //  listed in a firstprivate clause, even if they are static data members.
14234       if (!(IsConstant || (VD && VD->isStaticDataMember())) && !DVar.RefExpr &&
14235           DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
14236         Diag(ELoc, diag::err_omp_wrong_dsa)
14237             << getOpenMPClauseName(DVar.CKind)
14238             << getOpenMPClauseName(OMPC_firstprivate);
14239         reportOriginalDsa(*this, DSAStack, D, DVar);
14240         continue;
14241       }
14242 
14243       // OpenMP [2.9.3.4, Restrictions, p.2]
14244       //  A list item that is private within a parallel region must not appear
14245       //  in a firstprivate clause on a worksharing construct if any of the
14246       //  worksharing regions arising from the worksharing construct ever bind
14247       //  to any of the parallel regions arising from the parallel construct.
14248       // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
14249       // A list item that is private within a teams region must not appear in a
14250       // firstprivate clause on a distribute construct if any of the distribute
14251       // regions arising from the distribute construct ever bind to any of the
14252       // teams regions arising from the teams construct.
14253       // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
14254       // A list item that appears in a reduction clause of a teams construct
14255       // must not appear in a firstprivate clause on a distribute construct if
14256       // any of the distribute regions arising from the distribute construct
14257       // ever bind to any of the teams regions arising from the teams construct.
14258       if ((isOpenMPWorksharingDirective(CurrDir) ||
14259            isOpenMPDistributeDirective(CurrDir)) &&
14260           !isOpenMPParallelDirective(CurrDir) &&
14261           !isOpenMPTeamsDirective(CurrDir)) {
14262         DVar = DSAStack->getImplicitDSA(D, true);
14263         if (DVar.CKind != OMPC_shared &&
14264             (isOpenMPParallelDirective(DVar.DKind) ||
14265              isOpenMPTeamsDirective(DVar.DKind) ||
14266              DVar.DKind == OMPD_unknown)) {
14267           Diag(ELoc, diag::err_omp_required_access)
14268               << getOpenMPClauseName(OMPC_firstprivate)
14269               << getOpenMPClauseName(OMPC_shared);
14270           reportOriginalDsa(*this, DSAStack, D, DVar);
14271           continue;
14272         }
14273       }
14274       // OpenMP [2.9.3.4, Restrictions, p.3]
14275       //  A list item that appears in a reduction clause of a parallel construct
14276       //  must not appear in a firstprivate clause on a worksharing or task
14277       //  construct if any of the worksharing or task regions arising from the
14278       //  worksharing or task construct ever bind to any of the parallel regions
14279       //  arising from the parallel construct.
14280       // OpenMP [2.9.3.4, Restrictions, p.4]
14281       //  A list item that appears in a reduction clause in worksharing
14282       //  construct must not appear in a firstprivate clause in a task construct
14283       //  encountered during execution of any of the worksharing regions arising
14284       //  from the worksharing construct.
14285       if (isOpenMPTaskingDirective(CurrDir)) {
14286         DVar = DSAStack->hasInnermostDSA(
14287             D,
14288             [](OpenMPClauseKind C, bool AppliedToPointee) {
14289               return C == OMPC_reduction && !AppliedToPointee;
14290             },
14291             [](OpenMPDirectiveKind K) {
14292               return isOpenMPParallelDirective(K) ||
14293                      isOpenMPWorksharingDirective(K) ||
14294                      isOpenMPTeamsDirective(K);
14295             },
14296             /*FromParent=*/true);
14297         if (DVar.CKind == OMPC_reduction &&
14298             (isOpenMPParallelDirective(DVar.DKind) ||
14299              isOpenMPWorksharingDirective(DVar.DKind) ||
14300              isOpenMPTeamsDirective(DVar.DKind))) {
14301           Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate)
14302               << getOpenMPDirectiveName(DVar.DKind);
14303           reportOriginalDsa(*this, DSAStack, D, DVar);
14304           continue;
14305         }
14306       }
14307 
14308       // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
14309       // A list item cannot appear in both a map clause and a data-sharing
14310       // attribute clause on the same construct
14311       //
14312       // OpenMP 5.0 [2.19.7.1, Restrictions, p.7]
14313       // A list item cannot appear in both a map clause and a data-sharing
14314       // attribute clause on the same construct unless the construct is a
14315       // combined construct.
14316       if ((LangOpts.OpenMP <= 45 &&
14317            isOpenMPTargetExecutionDirective(CurrDir)) ||
14318           CurrDir == OMPD_target) {
14319         OpenMPClauseKind ConflictKind;
14320         if (DSAStack->checkMappableExprComponentListsForDecl(
14321                 VD, /*CurrentRegionOnly=*/true,
14322                 [&ConflictKind](
14323                     OMPClauseMappableExprCommon::MappableExprComponentListRef,
14324                     OpenMPClauseKind WhereFoundClauseKind) {
14325                   ConflictKind = WhereFoundClauseKind;
14326                   return true;
14327                 })) {
14328           Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
14329               << getOpenMPClauseName(OMPC_firstprivate)
14330               << getOpenMPClauseName(ConflictKind)
14331               << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
14332           reportOriginalDsa(*this, DSAStack, D, DVar);
14333           continue;
14334         }
14335       }
14336     }
14337 
14338     // Variably modified types are not supported for tasks.
14339     if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
14340         isOpenMPTaskingDirective(DSAStack->getCurrentDirective())) {
14341       Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
14342           << getOpenMPClauseName(OMPC_firstprivate) << Type
14343           << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
14344       bool IsDecl =
14345           !VD ||
14346           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
14347       Diag(D->getLocation(),
14348            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
14349           << D;
14350       continue;
14351     }
14352 
14353     Type = Type.getUnqualifiedType();
14354     VarDecl *VDPrivate =
14355         buildVarDecl(*this, ELoc, Type, D->getName(),
14356                      D->hasAttrs() ? &D->getAttrs() : nullptr,
14357                      VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
14358     // Generate helper private variable and initialize it with the value of the
14359     // original variable. The address of the original variable is replaced by
14360     // the address of the new private variable in the CodeGen. This new variable
14361     // is not added to IdResolver, so the code in the OpenMP region uses
14362     // original variable for proper diagnostics and variable capturing.
14363     Expr *VDInitRefExpr = nullptr;
14364     // For arrays generate initializer for single element and replace it by the
14365     // original array element in CodeGen.
14366     if (Type->isArrayType()) {
14367       VarDecl *VDInit =
14368           buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, D->getName());
14369       VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc);
14370       Expr *Init = DefaultLvalueConversion(VDInitRefExpr).get();
14371       ElemType = ElemType.getUnqualifiedType();
14372       VarDecl *VDInitTemp = buildVarDecl(*this, RefExpr->getExprLoc(), ElemType,
14373                                          ".firstprivate.temp");
14374       InitializedEntity Entity =
14375           InitializedEntity::InitializeVariable(VDInitTemp);
14376       InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc);
14377 
14378       InitializationSequence InitSeq(*this, Entity, Kind, Init);
14379       ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init);
14380       if (Result.isInvalid())
14381         VDPrivate->setInvalidDecl();
14382       else
14383         VDPrivate->setInit(Result.getAs<Expr>());
14384       // Remove temp variable declaration.
14385       Context.Deallocate(VDInitTemp);
14386     } else {
14387       VarDecl *VDInit = buildVarDecl(*this, RefExpr->getExprLoc(), Type,
14388                                      ".firstprivate.temp");
14389       VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
14390                                        RefExpr->getExprLoc());
14391       AddInitializerToDecl(VDPrivate,
14392                            DefaultLvalueConversion(VDInitRefExpr).get(),
14393                            /*DirectInit=*/false);
14394     }
14395     if (VDPrivate->isInvalidDecl()) {
14396       if (IsImplicitClause) {
14397         Diag(RefExpr->getExprLoc(),
14398              diag::note_omp_task_predetermined_firstprivate_here);
14399       }
14400       continue;
14401     }
14402     CurContext->addDecl(VDPrivate);
14403     DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
14404         *this, VDPrivate, RefExpr->getType().getUnqualifiedType(),
14405         RefExpr->getExprLoc());
14406     DeclRefExpr *Ref = nullptr;
14407     if (!VD && !CurContext->isDependentContext()) {
14408       if (TopDVar.CKind == OMPC_lastprivate) {
14409         Ref = TopDVar.PrivateCopy;
14410       } else {
14411         Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
14412         if (!isOpenMPCapturedDecl(D))
14413           ExprCaptures.push_back(Ref->getDecl());
14414       }
14415     }
14416     if (!IsImplicitClause)
14417       DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
14418     Vars.push_back((VD || CurContext->isDependentContext())
14419                        ? RefExpr->IgnoreParens()
14420                        : Ref);
14421     PrivateCopies.push_back(VDPrivateRefExpr);
14422     Inits.push_back(VDInitRefExpr);
14423   }
14424 
14425   if (Vars.empty())
14426     return nullptr;
14427 
14428   return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
14429                                        Vars, PrivateCopies, Inits,
14430                                        buildPreInits(Context, ExprCaptures));
14431 }
14432 
14433 OMPClause *Sema::ActOnOpenMPLastprivateClause(
14434     ArrayRef<Expr *> VarList, OpenMPLastprivateModifier LPKind,
14435     SourceLocation LPKindLoc, SourceLocation ColonLoc, SourceLocation StartLoc,
14436     SourceLocation LParenLoc, SourceLocation EndLoc) {
14437   if (LPKind == OMPC_LASTPRIVATE_unknown && LPKindLoc.isValid()) {
14438     assert(ColonLoc.isValid() && "Colon location must be valid.");
14439     Diag(LPKindLoc, diag::err_omp_unexpected_clause_value)
14440         << getListOfPossibleValues(OMPC_lastprivate, /*First=*/0,
14441                                    /*Last=*/OMPC_LASTPRIVATE_unknown)
14442         << getOpenMPClauseName(OMPC_lastprivate);
14443     return nullptr;
14444   }
14445 
14446   SmallVector<Expr *, 8> Vars;
14447   SmallVector<Expr *, 8> SrcExprs;
14448   SmallVector<Expr *, 8> DstExprs;
14449   SmallVector<Expr *, 8> AssignmentOps;
14450   SmallVector<Decl *, 4> ExprCaptures;
14451   SmallVector<Expr *, 4> ExprPostUpdates;
14452   for (Expr *RefExpr : VarList) {
14453     assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
14454     SourceLocation ELoc;
14455     SourceRange ERange;
14456     Expr *SimpleRefExpr = RefExpr;
14457     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
14458     if (Res.second) {
14459       // It will be analyzed later.
14460       Vars.push_back(RefExpr);
14461       SrcExprs.push_back(nullptr);
14462       DstExprs.push_back(nullptr);
14463       AssignmentOps.push_back(nullptr);
14464     }
14465     ValueDecl *D = Res.first;
14466     if (!D)
14467       continue;
14468 
14469     QualType Type = D->getType();
14470     auto *VD = dyn_cast<VarDecl>(D);
14471 
14472     // OpenMP [2.14.3.5, Restrictions, C/C++, p.2]
14473     //  A variable that appears in a lastprivate clause must not have an
14474     //  incomplete type or a reference type.
14475     if (RequireCompleteType(ELoc, Type,
14476                             diag::err_omp_lastprivate_incomplete_type))
14477       continue;
14478     Type = Type.getNonReferenceType();
14479 
14480     // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
14481     // A variable that is privatized must not have a const-qualified type
14482     // unless it is of class type with a mutable member. This restriction does
14483     // not apply to the firstprivate clause.
14484     //
14485     // OpenMP 3.1 [2.9.3.5, lastprivate clause, Restrictions]
14486     // A variable that appears in a lastprivate clause must not have a
14487     // const-qualified type unless it is of class type with a mutable member.
14488     if (rejectConstNotMutableType(*this, D, Type, OMPC_lastprivate, ELoc))
14489       continue;
14490 
14491     // OpenMP 5.0 [2.19.4.5 lastprivate Clause, Restrictions]
14492     // A list item that appears in a lastprivate clause with the conditional
14493     // modifier must be a scalar variable.
14494     if (LPKind == OMPC_LASTPRIVATE_conditional && !Type->isScalarType()) {
14495       Diag(ELoc, diag::err_omp_lastprivate_conditional_non_scalar);
14496       bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
14497                                VarDecl::DeclarationOnly;
14498       Diag(D->getLocation(),
14499            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
14500           << D;
14501       continue;
14502     }
14503 
14504     OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
14505     // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
14506     // in a Construct]
14507     //  Variables with the predetermined data-sharing attributes may not be
14508     //  listed in data-sharing attributes clauses, except for the cases
14509     //  listed below.
14510     // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
14511     // A list item may appear in a firstprivate or lastprivate clause but not
14512     // both.
14513     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
14514     if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate &&
14515         (isOpenMPDistributeDirective(CurrDir) ||
14516          DVar.CKind != OMPC_firstprivate) &&
14517         (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
14518       Diag(ELoc, diag::err_omp_wrong_dsa)
14519           << getOpenMPClauseName(DVar.CKind)
14520           << getOpenMPClauseName(OMPC_lastprivate);
14521       reportOriginalDsa(*this, DSAStack, D, DVar);
14522       continue;
14523     }
14524 
14525     // OpenMP [2.14.3.5, Restrictions, p.2]
14526     // A list item that is private within a parallel region, or that appears in
14527     // the reduction clause of a parallel construct, must not appear in a
14528     // lastprivate clause on a worksharing construct if any of the corresponding
14529     // worksharing regions ever binds to any of the corresponding parallel
14530     // regions.
14531     DSAStackTy::DSAVarData TopDVar = DVar;
14532     if (isOpenMPWorksharingDirective(CurrDir) &&
14533         !isOpenMPParallelDirective(CurrDir) &&
14534         !isOpenMPTeamsDirective(CurrDir)) {
14535       DVar = DSAStack->getImplicitDSA(D, true);
14536       if (DVar.CKind != OMPC_shared) {
14537         Diag(ELoc, diag::err_omp_required_access)
14538             << getOpenMPClauseName(OMPC_lastprivate)
14539             << getOpenMPClauseName(OMPC_shared);
14540         reportOriginalDsa(*this, DSAStack, D, DVar);
14541         continue;
14542       }
14543     }
14544 
14545     // OpenMP [2.14.3.5, Restrictions, C++, p.1,2]
14546     //  A variable of class type (or array thereof) that appears in a
14547     //  lastprivate clause requires an accessible, unambiguous default
14548     //  constructor for the class type, unless the list item is also specified
14549     //  in a firstprivate clause.
14550     //  A variable of class type (or array thereof) that appears in a
14551     //  lastprivate clause requires an accessible, unambiguous copy assignment
14552     //  operator for the class type.
14553     Type = Context.getBaseElementType(Type).getNonReferenceType();
14554     VarDecl *SrcVD = buildVarDecl(*this, ERange.getBegin(),
14555                                   Type.getUnqualifiedType(), ".lastprivate.src",
14556                                   D->hasAttrs() ? &D->getAttrs() : nullptr);
14557     DeclRefExpr *PseudoSrcExpr =
14558         buildDeclRefExpr(*this, SrcVD, Type.getUnqualifiedType(), ELoc);
14559     VarDecl *DstVD =
14560         buildVarDecl(*this, ERange.getBegin(), Type, ".lastprivate.dst",
14561                      D->hasAttrs() ? &D->getAttrs() : nullptr);
14562     DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
14563     // For arrays generate assignment operation for single element and replace
14564     // it by the original array element in CodeGen.
14565     ExprResult AssignmentOp = BuildBinOp(/*S=*/nullptr, ELoc, BO_Assign,
14566                                          PseudoDstExpr, PseudoSrcExpr);
14567     if (AssignmentOp.isInvalid())
14568       continue;
14569     AssignmentOp =
14570         ActOnFinishFullExpr(AssignmentOp.get(), ELoc, /*DiscardedValue*/ false);
14571     if (AssignmentOp.isInvalid())
14572       continue;
14573 
14574     DeclRefExpr *Ref = nullptr;
14575     if (!VD && !CurContext->isDependentContext()) {
14576       if (TopDVar.CKind == OMPC_firstprivate) {
14577         Ref = TopDVar.PrivateCopy;
14578       } else {
14579         Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
14580         if (!isOpenMPCapturedDecl(D))
14581           ExprCaptures.push_back(Ref->getDecl());
14582       }
14583       if ((TopDVar.CKind == OMPC_firstprivate && !TopDVar.PrivateCopy) ||
14584           (!isOpenMPCapturedDecl(D) &&
14585            Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>())) {
14586         ExprResult RefRes = DefaultLvalueConversion(Ref);
14587         if (!RefRes.isUsable())
14588           continue;
14589         ExprResult PostUpdateRes =
14590             BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
14591                        RefRes.get());
14592         if (!PostUpdateRes.isUsable())
14593           continue;
14594         ExprPostUpdates.push_back(
14595             IgnoredValueConversions(PostUpdateRes.get()).get());
14596       }
14597     }
14598     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_lastprivate, Ref);
14599     Vars.push_back((VD || CurContext->isDependentContext())
14600                        ? RefExpr->IgnoreParens()
14601                        : Ref);
14602     SrcExprs.push_back(PseudoSrcExpr);
14603     DstExprs.push_back(PseudoDstExpr);
14604     AssignmentOps.push_back(AssignmentOp.get());
14605   }
14606 
14607   if (Vars.empty())
14608     return nullptr;
14609 
14610   return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
14611                                       Vars, SrcExprs, DstExprs, AssignmentOps,
14612                                       LPKind, LPKindLoc, ColonLoc,
14613                                       buildPreInits(Context, ExprCaptures),
14614                                       buildPostUpdate(*this, ExprPostUpdates));
14615 }
14616 
14617 OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
14618                                          SourceLocation StartLoc,
14619                                          SourceLocation LParenLoc,
14620                                          SourceLocation EndLoc) {
14621   SmallVector<Expr *, 8> Vars;
14622   for (Expr *RefExpr : VarList) {
14623     assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
14624     SourceLocation ELoc;
14625     SourceRange ERange;
14626     Expr *SimpleRefExpr = RefExpr;
14627     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
14628     if (Res.second) {
14629       // It will be analyzed later.
14630       Vars.push_back(RefExpr);
14631     }
14632     ValueDecl *D = Res.first;
14633     if (!D)
14634       continue;
14635 
14636     auto *VD = dyn_cast<VarDecl>(D);
14637     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
14638     // in a Construct]
14639     //  Variables with the predetermined data-sharing attributes may not be
14640     //  listed in data-sharing attributes clauses, except for the cases
14641     //  listed below. For these exceptions only, listing a predetermined
14642     //  variable in a data-sharing attribute clause is allowed and overrides
14643     //  the variable's predetermined data-sharing attributes.
14644     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
14645     if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared &&
14646         DVar.RefExpr) {
14647       Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
14648                                           << getOpenMPClauseName(OMPC_shared);
14649       reportOriginalDsa(*this, DSAStack, D, DVar);
14650       continue;
14651     }
14652 
14653     DeclRefExpr *Ref = nullptr;
14654     if (!VD && isOpenMPCapturedDecl(D) && !CurContext->isDependentContext())
14655       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
14656     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_shared, Ref);
14657     Vars.push_back((VD || !Ref || CurContext->isDependentContext())
14658                        ? RefExpr->IgnoreParens()
14659                        : Ref);
14660   }
14661 
14662   if (Vars.empty())
14663     return nullptr;
14664 
14665   return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
14666 }
14667 
14668 namespace {
14669 class DSARefChecker : public StmtVisitor<DSARefChecker, bool> {
14670   DSAStackTy *Stack;
14671 
14672 public:
14673   bool VisitDeclRefExpr(DeclRefExpr *E) {
14674     if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
14675       DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, /*FromParent=*/false);
14676       if (DVar.CKind == OMPC_shared && !DVar.RefExpr)
14677         return false;
14678       if (DVar.CKind != OMPC_unknown)
14679         return true;
14680       DSAStackTy::DSAVarData DVarPrivate = Stack->hasDSA(
14681           VD,
14682           [](OpenMPClauseKind C, bool AppliedToPointee) {
14683             return isOpenMPPrivate(C) && !AppliedToPointee;
14684           },
14685           [](OpenMPDirectiveKind) { return true; },
14686           /*FromParent=*/true);
14687       return DVarPrivate.CKind != OMPC_unknown;
14688     }
14689     return false;
14690   }
14691   bool VisitStmt(Stmt *S) {
14692     for (Stmt *Child : S->children()) {
14693       if (Child && Visit(Child))
14694         return true;
14695     }
14696     return false;
14697   }
14698   explicit DSARefChecker(DSAStackTy *S) : Stack(S) {}
14699 };
14700 } // namespace
14701 
14702 namespace {
14703 // Transform MemberExpression for specified FieldDecl of current class to
14704 // DeclRefExpr to specified OMPCapturedExprDecl.
14705 class TransformExprToCaptures : public TreeTransform<TransformExprToCaptures> {
14706   typedef TreeTransform<TransformExprToCaptures> BaseTransform;
14707   ValueDecl *Field = nullptr;
14708   DeclRefExpr *CapturedExpr = nullptr;
14709 
14710 public:
14711   TransformExprToCaptures(Sema &SemaRef, ValueDecl *FieldDecl)
14712       : BaseTransform(SemaRef), Field(FieldDecl), CapturedExpr(nullptr) {}
14713 
14714   ExprResult TransformMemberExpr(MemberExpr *E) {
14715     if (isa<CXXThisExpr>(E->getBase()->IgnoreParenImpCasts()) &&
14716         E->getMemberDecl() == Field) {
14717       CapturedExpr = buildCapture(SemaRef, Field, E, /*WithInit=*/false);
14718       return CapturedExpr;
14719     }
14720     return BaseTransform::TransformMemberExpr(E);
14721   }
14722   DeclRefExpr *getCapturedExpr() { return CapturedExpr; }
14723 };
14724 } // namespace
14725 
14726 template <typename T, typename U>
14727 static T filterLookupForUDReductionAndMapper(
14728     SmallVectorImpl<U> &Lookups, const llvm::function_ref<T(ValueDecl *)> Gen) {
14729   for (U &Set : Lookups) {
14730     for (auto *D : Set) {
14731       if (T Res = Gen(cast<ValueDecl>(D)))
14732         return Res;
14733     }
14734   }
14735   return T();
14736 }
14737 
14738 static NamedDecl *findAcceptableDecl(Sema &SemaRef, NamedDecl *D) {
14739   assert(!LookupResult::isVisible(SemaRef, D) && "not in slow case");
14740 
14741   for (auto RD : D->redecls()) {
14742     // Don't bother with extra checks if we already know this one isn't visible.
14743     if (RD == D)
14744       continue;
14745 
14746     auto ND = cast<NamedDecl>(RD);
14747     if (LookupResult::isVisible(SemaRef, ND))
14748       return ND;
14749   }
14750 
14751   return nullptr;
14752 }
14753 
14754 static void
14755 argumentDependentLookup(Sema &SemaRef, const DeclarationNameInfo &Id,
14756                         SourceLocation Loc, QualType Ty,
14757                         SmallVectorImpl<UnresolvedSet<8>> &Lookups) {
14758   // Find all of the associated namespaces and classes based on the
14759   // arguments we have.
14760   Sema::AssociatedNamespaceSet AssociatedNamespaces;
14761   Sema::AssociatedClassSet AssociatedClasses;
14762   OpaqueValueExpr OVE(Loc, Ty, VK_LValue);
14763   SemaRef.FindAssociatedClassesAndNamespaces(Loc, &OVE, AssociatedNamespaces,
14764                                              AssociatedClasses);
14765 
14766   // C++ [basic.lookup.argdep]p3:
14767   //   Let X be the lookup set produced by unqualified lookup (3.4.1)
14768   //   and let Y be the lookup set produced by argument dependent
14769   //   lookup (defined as follows). If X contains [...] then Y is
14770   //   empty. Otherwise Y is the set of declarations found in the
14771   //   namespaces associated with the argument types as described
14772   //   below. The set of declarations found by the lookup of the name
14773   //   is the union of X and Y.
14774   //
14775   // Here, we compute Y and add its members to the overloaded
14776   // candidate set.
14777   for (auto *NS : AssociatedNamespaces) {
14778     //   When considering an associated namespace, the lookup is the
14779     //   same as the lookup performed when the associated namespace is
14780     //   used as a qualifier (3.4.3.2) except that:
14781     //
14782     //     -- Any using-directives in the associated namespace are
14783     //        ignored.
14784     //
14785     //     -- Any namespace-scope friend functions declared in
14786     //        associated classes are visible within their respective
14787     //        namespaces even if they are not visible during an ordinary
14788     //        lookup (11.4).
14789     DeclContext::lookup_result R = NS->lookup(Id.getName());
14790     for (auto *D : R) {
14791       auto *Underlying = D;
14792       if (auto *USD = dyn_cast<UsingShadowDecl>(D))
14793         Underlying = USD->getTargetDecl();
14794 
14795       if (!isa<OMPDeclareReductionDecl>(Underlying) &&
14796           !isa<OMPDeclareMapperDecl>(Underlying))
14797         continue;
14798 
14799       if (!SemaRef.isVisible(D)) {
14800         D = findAcceptableDecl(SemaRef, D);
14801         if (!D)
14802           continue;
14803         if (auto *USD = dyn_cast<UsingShadowDecl>(D))
14804           Underlying = USD->getTargetDecl();
14805       }
14806       Lookups.emplace_back();
14807       Lookups.back().addDecl(Underlying);
14808     }
14809   }
14810 }
14811 
14812 static ExprResult
14813 buildDeclareReductionRef(Sema &SemaRef, SourceLocation Loc, SourceRange Range,
14814                          Scope *S, CXXScopeSpec &ReductionIdScopeSpec,
14815                          const DeclarationNameInfo &ReductionId, QualType Ty,
14816                          CXXCastPath &BasePath, Expr *UnresolvedReduction) {
14817   if (ReductionIdScopeSpec.isInvalid())
14818     return ExprError();
14819   SmallVector<UnresolvedSet<8>, 4> Lookups;
14820   if (S) {
14821     LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
14822     Lookup.suppressDiagnostics();
14823     while (S && SemaRef.LookupParsedName(Lookup, S, &ReductionIdScopeSpec)) {
14824       NamedDecl *D = Lookup.getRepresentativeDecl();
14825       do {
14826         S = S->getParent();
14827       } while (S && !S->isDeclScope(D));
14828       if (S)
14829         S = S->getParent();
14830       Lookups.emplace_back();
14831       Lookups.back().append(Lookup.begin(), Lookup.end());
14832       Lookup.clear();
14833     }
14834   } else if (auto *ULE =
14835                  cast_or_null<UnresolvedLookupExpr>(UnresolvedReduction)) {
14836     Lookups.push_back(UnresolvedSet<8>());
14837     Decl *PrevD = nullptr;
14838     for (NamedDecl *D : ULE->decls()) {
14839       if (D == PrevD)
14840         Lookups.push_back(UnresolvedSet<8>());
14841       else if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(D))
14842         Lookups.back().addDecl(DRD);
14843       PrevD = D;
14844     }
14845   }
14846   if (SemaRef.CurContext->isDependentContext() || Ty->isDependentType() ||
14847       Ty->isInstantiationDependentType() ||
14848       Ty->containsUnexpandedParameterPack() ||
14849       filterLookupForUDReductionAndMapper<bool>(Lookups, [](ValueDecl *D) {
14850         return !D->isInvalidDecl() &&
14851                (D->getType()->isDependentType() ||
14852                 D->getType()->isInstantiationDependentType() ||
14853                 D->getType()->containsUnexpandedParameterPack());
14854       })) {
14855     UnresolvedSet<8> ResSet;
14856     for (const UnresolvedSet<8> &Set : Lookups) {
14857       if (Set.empty())
14858         continue;
14859       ResSet.append(Set.begin(), Set.end());
14860       // The last item marks the end of all declarations at the specified scope.
14861       ResSet.addDecl(Set[Set.size() - 1]);
14862     }
14863     return UnresolvedLookupExpr::Create(
14864         SemaRef.Context, /*NamingClass=*/nullptr,
14865         ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), ReductionId,
14866         /*ADL=*/true, /*Overloaded=*/true, ResSet.begin(), ResSet.end());
14867   }
14868   // Lookup inside the classes.
14869   // C++ [over.match.oper]p3:
14870   //   For a unary operator @ with an operand of a type whose
14871   //   cv-unqualified version is T1, and for a binary operator @ with
14872   //   a left operand of a type whose cv-unqualified version is T1 and
14873   //   a right operand of a type whose cv-unqualified version is T2,
14874   //   three sets of candidate functions, designated member
14875   //   candidates, non-member candidates and built-in candidates, are
14876   //   constructed as follows:
14877   //     -- If T1 is a complete class type or a class currently being
14878   //        defined, the set of member candidates is the result of the
14879   //        qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
14880   //        the set of member candidates is empty.
14881   LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
14882   Lookup.suppressDiagnostics();
14883   if (const auto *TyRec = Ty->getAs<RecordType>()) {
14884     // Complete the type if it can be completed.
14885     // If the type is neither complete nor being defined, bail out now.
14886     if (SemaRef.isCompleteType(Loc, Ty) || TyRec->isBeingDefined() ||
14887         TyRec->getDecl()->getDefinition()) {
14888       Lookup.clear();
14889       SemaRef.LookupQualifiedName(Lookup, TyRec->getDecl());
14890       if (Lookup.empty()) {
14891         Lookups.emplace_back();
14892         Lookups.back().append(Lookup.begin(), Lookup.end());
14893       }
14894     }
14895   }
14896   // Perform ADL.
14897   if (SemaRef.getLangOpts().CPlusPlus)
14898     argumentDependentLookup(SemaRef, ReductionId, Loc, Ty, Lookups);
14899   if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
14900           Lookups, [&SemaRef, Ty](ValueDecl *D) -> ValueDecl * {
14901             if (!D->isInvalidDecl() &&
14902                 SemaRef.Context.hasSameType(D->getType(), Ty))
14903               return D;
14904             return nullptr;
14905           }))
14906     return SemaRef.BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(),
14907                                     VK_LValue, Loc);
14908   if (SemaRef.getLangOpts().CPlusPlus) {
14909     if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
14910             Lookups, [&SemaRef, Ty, Loc](ValueDecl *D) -> ValueDecl * {
14911               if (!D->isInvalidDecl() &&
14912                   SemaRef.IsDerivedFrom(Loc, Ty, D->getType()) &&
14913                   !Ty.isMoreQualifiedThan(D->getType()))
14914                 return D;
14915               return nullptr;
14916             })) {
14917       CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
14918                          /*DetectVirtual=*/false);
14919       if (SemaRef.IsDerivedFrom(Loc, Ty, VD->getType(), Paths)) {
14920         if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
14921                 VD->getType().getUnqualifiedType()))) {
14922           if (SemaRef.CheckBaseClassAccess(
14923                   Loc, VD->getType(), Ty, Paths.front(),
14924                   /*DiagID=*/0) != Sema::AR_inaccessible) {
14925             SemaRef.BuildBasePathArray(Paths, BasePath);
14926             return SemaRef.BuildDeclRefExpr(
14927                 VD, VD->getType().getNonReferenceType(), VK_LValue, Loc);
14928           }
14929         }
14930       }
14931     }
14932   }
14933   if (ReductionIdScopeSpec.isSet()) {
14934     SemaRef.Diag(Loc, diag::err_omp_not_resolved_reduction_identifier)
14935         << Ty << Range;
14936     return ExprError();
14937   }
14938   return ExprEmpty();
14939 }
14940 
14941 namespace {
14942 /// Data for the reduction-based clauses.
14943 struct ReductionData {
14944   /// List of original reduction items.
14945   SmallVector<Expr *, 8> Vars;
14946   /// List of private copies of the reduction items.
14947   SmallVector<Expr *, 8> Privates;
14948   /// LHS expressions for the reduction_op expressions.
14949   SmallVector<Expr *, 8> LHSs;
14950   /// RHS expressions for the reduction_op expressions.
14951   SmallVector<Expr *, 8> RHSs;
14952   /// Reduction operation expression.
14953   SmallVector<Expr *, 8> ReductionOps;
14954   /// inscan copy operation expressions.
14955   SmallVector<Expr *, 8> InscanCopyOps;
14956   /// inscan copy temp array expressions for prefix sums.
14957   SmallVector<Expr *, 8> InscanCopyArrayTemps;
14958   /// inscan copy temp array element expressions for prefix sums.
14959   SmallVector<Expr *, 8> InscanCopyArrayElems;
14960   /// Taskgroup descriptors for the corresponding reduction items in
14961   /// in_reduction clauses.
14962   SmallVector<Expr *, 8> TaskgroupDescriptors;
14963   /// List of captures for clause.
14964   SmallVector<Decl *, 4> ExprCaptures;
14965   /// List of postupdate expressions.
14966   SmallVector<Expr *, 4> ExprPostUpdates;
14967   /// Reduction modifier.
14968   unsigned RedModifier = 0;
14969   ReductionData() = delete;
14970   /// Reserves required memory for the reduction data.
14971   ReductionData(unsigned Size, unsigned Modifier = 0) : RedModifier(Modifier) {
14972     Vars.reserve(Size);
14973     Privates.reserve(Size);
14974     LHSs.reserve(Size);
14975     RHSs.reserve(Size);
14976     ReductionOps.reserve(Size);
14977     if (RedModifier == OMPC_REDUCTION_inscan) {
14978       InscanCopyOps.reserve(Size);
14979       InscanCopyArrayTemps.reserve(Size);
14980       InscanCopyArrayElems.reserve(Size);
14981     }
14982     TaskgroupDescriptors.reserve(Size);
14983     ExprCaptures.reserve(Size);
14984     ExprPostUpdates.reserve(Size);
14985   }
14986   /// Stores reduction item and reduction operation only (required for dependent
14987   /// reduction item).
14988   void push(Expr *Item, Expr *ReductionOp) {
14989     Vars.emplace_back(Item);
14990     Privates.emplace_back(nullptr);
14991     LHSs.emplace_back(nullptr);
14992     RHSs.emplace_back(nullptr);
14993     ReductionOps.emplace_back(ReductionOp);
14994     TaskgroupDescriptors.emplace_back(nullptr);
14995     if (RedModifier == OMPC_REDUCTION_inscan) {
14996       InscanCopyOps.push_back(nullptr);
14997       InscanCopyArrayTemps.push_back(nullptr);
14998       InscanCopyArrayElems.push_back(nullptr);
14999     }
15000   }
15001   /// Stores reduction data.
15002   void push(Expr *Item, Expr *Private, Expr *LHS, Expr *RHS, Expr *ReductionOp,
15003             Expr *TaskgroupDescriptor, Expr *CopyOp, Expr *CopyArrayTemp,
15004             Expr *CopyArrayElem) {
15005     Vars.emplace_back(Item);
15006     Privates.emplace_back(Private);
15007     LHSs.emplace_back(LHS);
15008     RHSs.emplace_back(RHS);
15009     ReductionOps.emplace_back(ReductionOp);
15010     TaskgroupDescriptors.emplace_back(TaskgroupDescriptor);
15011     if (RedModifier == OMPC_REDUCTION_inscan) {
15012       InscanCopyOps.push_back(CopyOp);
15013       InscanCopyArrayTemps.push_back(CopyArrayTemp);
15014       InscanCopyArrayElems.push_back(CopyArrayElem);
15015     } else {
15016       assert(CopyOp == nullptr && CopyArrayTemp == nullptr &&
15017              CopyArrayElem == nullptr &&
15018              "Copy operation must be used for inscan reductions only.");
15019     }
15020   }
15021 };
15022 } // namespace
15023 
15024 static bool checkOMPArraySectionConstantForReduction(
15025     ASTContext &Context, const OMPArraySectionExpr *OASE, bool &SingleElement,
15026     SmallVectorImpl<llvm::APSInt> &ArraySizes) {
15027   const Expr *Length = OASE->getLength();
15028   if (Length == nullptr) {
15029     // For array sections of the form [1:] or [:], we would need to analyze
15030     // the lower bound...
15031     if (OASE->getColonLocFirst().isValid())
15032       return false;
15033 
15034     // This is an array subscript which has implicit length 1!
15035     SingleElement = true;
15036     ArraySizes.push_back(llvm::APSInt::get(1));
15037   } else {
15038     Expr::EvalResult Result;
15039     if (!Length->EvaluateAsInt(Result, Context))
15040       return false;
15041 
15042     llvm::APSInt ConstantLengthValue = Result.Val.getInt();
15043     SingleElement = (ConstantLengthValue.getSExtValue() == 1);
15044     ArraySizes.push_back(ConstantLengthValue);
15045   }
15046 
15047   // Get the base of this array section and walk up from there.
15048   const Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
15049 
15050   // We require length = 1 for all array sections except the right-most to
15051   // guarantee that the memory region is contiguous and has no holes in it.
15052   while (const auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base)) {
15053     Length = TempOASE->getLength();
15054     if (Length == nullptr) {
15055       // For array sections of the form [1:] or [:], we would need to analyze
15056       // the lower bound...
15057       if (OASE->getColonLocFirst().isValid())
15058         return false;
15059 
15060       // This is an array subscript which has implicit length 1!
15061       ArraySizes.push_back(llvm::APSInt::get(1));
15062     } else {
15063       Expr::EvalResult Result;
15064       if (!Length->EvaluateAsInt(Result, Context))
15065         return false;
15066 
15067       llvm::APSInt ConstantLengthValue = Result.Val.getInt();
15068       if (ConstantLengthValue.getSExtValue() != 1)
15069         return false;
15070 
15071       ArraySizes.push_back(ConstantLengthValue);
15072     }
15073     Base = TempOASE->getBase()->IgnoreParenImpCasts();
15074   }
15075 
15076   // If we have a single element, we don't need to add the implicit lengths.
15077   if (!SingleElement) {
15078     while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) {
15079       // Has implicit length 1!
15080       ArraySizes.push_back(llvm::APSInt::get(1));
15081       Base = TempASE->getBase()->IgnoreParenImpCasts();
15082     }
15083   }
15084 
15085   // This array section can be privatized as a single value or as a constant
15086   // sized array.
15087   return true;
15088 }
15089 
15090 static bool actOnOMPReductionKindClause(
15091     Sema &S, DSAStackTy *Stack, OpenMPClauseKind ClauseKind,
15092     ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
15093     SourceLocation ColonLoc, SourceLocation EndLoc,
15094     CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
15095     ArrayRef<Expr *> UnresolvedReductions, ReductionData &RD) {
15096   DeclarationName DN = ReductionId.getName();
15097   OverloadedOperatorKind OOK = DN.getCXXOverloadedOperator();
15098   BinaryOperatorKind BOK = BO_Comma;
15099 
15100   ASTContext &Context = S.Context;
15101   // OpenMP [2.14.3.6, reduction clause]
15102   // C
15103   // reduction-identifier is either an identifier or one of the following
15104   // operators: +, -, *,  &, |, ^, && and ||
15105   // C++
15106   // reduction-identifier is either an id-expression or one of the following
15107   // operators: +, -, *, &, |, ^, && and ||
15108   switch (OOK) {
15109   case OO_Plus:
15110   case OO_Minus:
15111     BOK = BO_Add;
15112     break;
15113   case OO_Star:
15114     BOK = BO_Mul;
15115     break;
15116   case OO_Amp:
15117     BOK = BO_And;
15118     break;
15119   case OO_Pipe:
15120     BOK = BO_Or;
15121     break;
15122   case OO_Caret:
15123     BOK = BO_Xor;
15124     break;
15125   case OO_AmpAmp:
15126     BOK = BO_LAnd;
15127     break;
15128   case OO_PipePipe:
15129     BOK = BO_LOr;
15130     break;
15131   case OO_New:
15132   case OO_Delete:
15133   case OO_Array_New:
15134   case OO_Array_Delete:
15135   case OO_Slash:
15136   case OO_Percent:
15137   case OO_Tilde:
15138   case OO_Exclaim:
15139   case OO_Equal:
15140   case OO_Less:
15141   case OO_Greater:
15142   case OO_LessEqual:
15143   case OO_GreaterEqual:
15144   case OO_PlusEqual:
15145   case OO_MinusEqual:
15146   case OO_StarEqual:
15147   case OO_SlashEqual:
15148   case OO_PercentEqual:
15149   case OO_CaretEqual:
15150   case OO_AmpEqual:
15151   case OO_PipeEqual:
15152   case OO_LessLess:
15153   case OO_GreaterGreater:
15154   case OO_LessLessEqual:
15155   case OO_GreaterGreaterEqual:
15156   case OO_EqualEqual:
15157   case OO_ExclaimEqual:
15158   case OO_Spaceship:
15159   case OO_PlusPlus:
15160   case OO_MinusMinus:
15161   case OO_Comma:
15162   case OO_ArrowStar:
15163   case OO_Arrow:
15164   case OO_Call:
15165   case OO_Subscript:
15166   case OO_Conditional:
15167   case OO_Coawait:
15168   case NUM_OVERLOADED_OPERATORS:
15169     llvm_unreachable("Unexpected reduction identifier");
15170   case OO_None:
15171     if (IdentifierInfo *II = DN.getAsIdentifierInfo()) {
15172       if (II->isStr("max"))
15173         BOK = BO_GT;
15174       else if (II->isStr("min"))
15175         BOK = BO_LT;
15176     }
15177     break;
15178   }
15179   SourceRange ReductionIdRange;
15180   if (ReductionIdScopeSpec.isValid())
15181     ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc());
15182   else
15183     ReductionIdRange.setBegin(ReductionId.getBeginLoc());
15184   ReductionIdRange.setEnd(ReductionId.getEndLoc());
15185 
15186   auto IR = UnresolvedReductions.begin(), ER = UnresolvedReductions.end();
15187   bool FirstIter = true;
15188   for (Expr *RefExpr : VarList) {
15189     assert(RefExpr && "nullptr expr in OpenMP reduction clause.");
15190     // OpenMP [2.1, C/C++]
15191     //  A list item is a variable or array section, subject to the restrictions
15192     //  specified in Section 2.4 on page 42 and in each of the sections
15193     // describing clauses and directives for which a list appears.
15194     // OpenMP  [2.14.3.3, Restrictions, p.1]
15195     //  A variable that is part of another variable (as an array or
15196     //  structure element) cannot appear in a private clause.
15197     if (!FirstIter && IR != ER)
15198       ++IR;
15199     FirstIter = false;
15200     SourceLocation ELoc;
15201     SourceRange ERange;
15202     Expr *SimpleRefExpr = RefExpr;
15203     auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange,
15204                               /*AllowArraySection=*/true);
15205     if (Res.second) {
15206       // Try to find 'declare reduction' corresponding construct before using
15207       // builtin/overloaded operators.
15208       QualType Type = Context.DependentTy;
15209       CXXCastPath BasePath;
15210       ExprResult DeclareReductionRef = buildDeclareReductionRef(
15211           S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
15212           ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
15213       Expr *ReductionOp = nullptr;
15214       if (S.CurContext->isDependentContext() &&
15215           (DeclareReductionRef.isUnset() ||
15216            isa<UnresolvedLookupExpr>(DeclareReductionRef.get())))
15217         ReductionOp = DeclareReductionRef.get();
15218       // It will be analyzed later.
15219       RD.push(RefExpr, ReductionOp);
15220     }
15221     ValueDecl *D = Res.first;
15222     if (!D)
15223       continue;
15224 
15225     Expr *TaskgroupDescriptor = nullptr;
15226     QualType Type;
15227     auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr->IgnoreParens());
15228     auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr->IgnoreParens());
15229     if (ASE) {
15230       Type = ASE->getType().getNonReferenceType();
15231     } else if (OASE) {
15232       QualType BaseType =
15233           OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
15234       if (const auto *ATy = BaseType->getAsArrayTypeUnsafe())
15235         Type = ATy->getElementType();
15236       else
15237         Type = BaseType->getPointeeType();
15238       Type = Type.getNonReferenceType();
15239     } else {
15240       Type = Context.getBaseElementType(D->getType().getNonReferenceType());
15241     }
15242     auto *VD = dyn_cast<VarDecl>(D);
15243 
15244     // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
15245     //  A variable that appears in a private clause must not have an incomplete
15246     //  type or a reference type.
15247     if (S.RequireCompleteType(ELoc, D->getType(),
15248                               diag::err_omp_reduction_incomplete_type))
15249       continue;
15250     // OpenMP [2.14.3.6, reduction clause, Restrictions]
15251     // A list item that appears in a reduction clause must not be
15252     // const-qualified.
15253     if (rejectConstNotMutableType(S, D, Type, ClauseKind, ELoc,
15254                                   /*AcceptIfMutable*/ false, ASE || OASE))
15255       continue;
15256 
15257     OpenMPDirectiveKind CurrDir = Stack->getCurrentDirective();
15258     // OpenMP [2.9.3.6, Restrictions, C/C++, p.4]
15259     //  If a list-item is a reference type then it must bind to the same object
15260     //  for all threads of the team.
15261     if (!ASE && !OASE) {
15262       if (VD) {
15263         VarDecl *VDDef = VD->getDefinition();
15264         if (VD->getType()->isReferenceType() && VDDef && VDDef->hasInit()) {
15265           DSARefChecker Check(Stack);
15266           if (Check.Visit(VDDef->getInit())) {
15267             S.Diag(ELoc, diag::err_omp_reduction_ref_type_arg)
15268                 << getOpenMPClauseName(ClauseKind) << ERange;
15269             S.Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef;
15270             continue;
15271           }
15272         }
15273       }
15274 
15275       // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
15276       // in a Construct]
15277       //  Variables with the predetermined data-sharing attributes may not be
15278       //  listed in data-sharing attributes clauses, except for the cases
15279       //  listed below. For these exceptions only, listing a predetermined
15280       //  variable in a data-sharing attribute clause is allowed and overrides
15281       //  the variable's predetermined data-sharing attributes.
15282       // OpenMP [2.14.3.6, Restrictions, p.3]
15283       //  Any number of reduction clauses can be specified on the directive,
15284       //  but a list item can appear only once in the reduction clauses for that
15285       //  directive.
15286       DSAStackTy::DSAVarData DVar = Stack->getTopDSA(D, /*FromParent=*/false);
15287       if (DVar.CKind == OMPC_reduction) {
15288         S.Diag(ELoc, diag::err_omp_once_referenced)
15289             << getOpenMPClauseName(ClauseKind);
15290         if (DVar.RefExpr)
15291           S.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced);
15292         continue;
15293       }
15294       if (DVar.CKind != OMPC_unknown) {
15295         S.Diag(ELoc, diag::err_omp_wrong_dsa)
15296             << getOpenMPClauseName(DVar.CKind)
15297             << getOpenMPClauseName(OMPC_reduction);
15298         reportOriginalDsa(S, Stack, D, DVar);
15299         continue;
15300       }
15301 
15302       // OpenMP [2.14.3.6, Restrictions, p.1]
15303       //  A list item that appears in a reduction clause of a worksharing
15304       //  construct must be shared in the parallel regions to which any of the
15305       //  worksharing regions arising from the worksharing construct bind.
15306       if (isOpenMPWorksharingDirective(CurrDir) &&
15307           !isOpenMPParallelDirective(CurrDir) &&
15308           !isOpenMPTeamsDirective(CurrDir)) {
15309         DVar = Stack->getImplicitDSA(D, true);
15310         if (DVar.CKind != OMPC_shared) {
15311           S.Diag(ELoc, diag::err_omp_required_access)
15312               << getOpenMPClauseName(OMPC_reduction)
15313               << getOpenMPClauseName(OMPC_shared);
15314           reportOriginalDsa(S, Stack, D, DVar);
15315           continue;
15316         }
15317       }
15318     } else {
15319       // Threadprivates cannot be shared between threads, so dignose if the base
15320       // is a threadprivate variable.
15321       DSAStackTy::DSAVarData DVar = Stack->getTopDSA(D, /*FromParent=*/false);
15322       if (DVar.CKind == OMPC_threadprivate) {
15323         S.Diag(ELoc, diag::err_omp_wrong_dsa)
15324             << getOpenMPClauseName(DVar.CKind)
15325             << getOpenMPClauseName(OMPC_reduction);
15326         reportOriginalDsa(S, Stack, D, DVar);
15327         continue;
15328       }
15329     }
15330 
15331     // Try to find 'declare reduction' corresponding construct before using
15332     // builtin/overloaded operators.
15333     CXXCastPath BasePath;
15334     ExprResult DeclareReductionRef = buildDeclareReductionRef(
15335         S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
15336         ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
15337     if (DeclareReductionRef.isInvalid())
15338       continue;
15339     if (S.CurContext->isDependentContext() &&
15340         (DeclareReductionRef.isUnset() ||
15341          isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) {
15342       RD.push(RefExpr, DeclareReductionRef.get());
15343       continue;
15344     }
15345     if (BOK == BO_Comma && DeclareReductionRef.isUnset()) {
15346       // Not allowed reduction identifier is found.
15347       S.Diag(ReductionId.getBeginLoc(),
15348              diag::err_omp_unknown_reduction_identifier)
15349           << Type << ReductionIdRange;
15350       continue;
15351     }
15352 
15353     // OpenMP [2.14.3.6, reduction clause, Restrictions]
15354     // The type of a list item that appears in a reduction clause must be valid
15355     // for the reduction-identifier. For a max or min reduction in C, the type
15356     // of the list item must be an allowed arithmetic data type: char, int,
15357     // float, double, or _Bool, possibly modified with long, short, signed, or
15358     // unsigned. For a max or min reduction in C++, the type of the list item
15359     // must be an allowed arithmetic data type: char, wchar_t, int, float,
15360     // double, or bool, possibly modified with long, short, signed, or unsigned.
15361     if (DeclareReductionRef.isUnset()) {
15362       if ((BOK == BO_GT || BOK == BO_LT) &&
15363           !(Type->isScalarType() ||
15364             (S.getLangOpts().CPlusPlus && Type->isArithmeticType()))) {
15365         S.Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg)
15366             << getOpenMPClauseName(ClauseKind) << S.getLangOpts().CPlusPlus;
15367         if (!ASE && !OASE) {
15368           bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
15369                                    VarDecl::DeclarationOnly;
15370           S.Diag(D->getLocation(),
15371                  IsDecl ? diag::note_previous_decl : diag::note_defined_here)
15372               << D;
15373         }
15374         continue;
15375       }
15376       if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) &&
15377           !S.getLangOpts().CPlusPlus && Type->isFloatingType()) {
15378         S.Diag(ELoc, diag::err_omp_clause_floating_type_arg)
15379             << getOpenMPClauseName(ClauseKind);
15380         if (!ASE && !OASE) {
15381           bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
15382                                    VarDecl::DeclarationOnly;
15383           S.Diag(D->getLocation(),
15384                  IsDecl ? diag::note_previous_decl : diag::note_defined_here)
15385               << D;
15386         }
15387         continue;
15388       }
15389     }
15390 
15391     Type = Type.getNonLValueExprType(Context).getUnqualifiedType();
15392     VarDecl *LHSVD = buildVarDecl(S, ELoc, Type, ".reduction.lhs",
15393                                   D->hasAttrs() ? &D->getAttrs() : nullptr);
15394     VarDecl *RHSVD = buildVarDecl(S, ELoc, Type, D->getName(),
15395                                   D->hasAttrs() ? &D->getAttrs() : nullptr);
15396     QualType PrivateTy = Type;
15397 
15398     // Try if we can determine constant lengths for all array sections and avoid
15399     // the VLA.
15400     bool ConstantLengthOASE = false;
15401     if (OASE) {
15402       bool SingleElement;
15403       llvm::SmallVector<llvm::APSInt, 4> ArraySizes;
15404       ConstantLengthOASE = checkOMPArraySectionConstantForReduction(
15405           Context, OASE, SingleElement, ArraySizes);
15406 
15407       // If we don't have a single element, we must emit a constant array type.
15408       if (ConstantLengthOASE && !SingleElement) {
15409         for (llvm::APSInt &Size : ArraySizes)
15410           PrivateTy = Context.getConstantArrayType(PrivateTy, Size, nullptr,
15411                                                    ArrayType::Normal,
15412                                                    /*IndexTypeQuals=*/0);
15413       }
15414     }
15415 
15416     if ((OASE && !ConstantLengthOASE) ||
15417         (!OASE && !ASE &&
15418          D->getType().getNonReferenceType()->isVariablyModifiedType())) {
15419       if (!Context.getTargetInfo().isVLASupported()) {
15420         if (isOpenMPTargetExecutionDirective(Stack->getCurrentDirective())) {
15421           S.Diag(ELoc, diag::err_omp_reduction_vla_unsupported) << !!OASE;
15422           S.Diag(ELoc, diag::note_vla_unsupported);
15423           continue;
15424         } else {
15425           S.targetDiag(ELoc, diag::err_omp_reduction_vla_unsupported) << !!OASE;
15426           S.targetDiag(ELoc, diag::note_vla_unsupported);
15427         }
15428       }
15429       // For arrays/array sections only:
15430       // Create pseudo array type for private copy. The size for this array will
15431       // be generated during codegen.
15432       // For array subscripts or single variables Private Ty is the same as Type
15433       // (type of the variable or single array element).
15434       PrivateTy = Context.getVariableArrayType(
15435           Type,
15436           new (Context) OpaqueValueExpr(ELoc, Context.getSizeType(), VK_RValue),
15437           ArrayType::Normal, /*IndexTypeQuals=*/0, SourceRange());
15438     } else if (!ASE && !OASE &&
15439                Context.getAsArrayType(D->getType().getNonReferenceType())) {
15440       PrivateTy = D->getType().getNonReferenceType();
15441     }
15442     // Private copy.
15443     VarDecl *PrivateVD =
15444         buildVarDecl(S, ELoc, PrivateTy, D->getName(),
15445                      D->hasAttrs() ? &D->getAttrs() : nullptr,
15446                      VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
15447     // Add initializer for private variable.
15448     Expr *Init = nullptr;
15449     DeclRefExpr *LHSDRE = buildDeclRefExpr(S, LHSVD, Type, ELoc);
15450     DeclRefExpr *RHSDRE = buildDeclRefExpr(S, RHSVD, Type, ELoc);
15451     if (DeclareReductionRef.isUsable()) {
15452       auto *DRDRef = DeclareReductionRef.getAs<DeclRefExpr>();
15453       auto *DRD = cast<OMPDeclareReductionDecl>(DRDRef->getDecl());
15454       if (DRD->getInitializer()) {
15455         S.ActOnUninitializedDecl(PrivateVD);
15456         Init = DRDRef;
15457         RHSVD->setInit(DRDRef);
15458         RHSVD->setInitStyle(VarDecl::CallInit);
15459       }
15460     } else {
15461       switch (BOK) {
15462       case BO_Add:
15463       case BO_Xor:
15464       case BO_Or:
15465       case BO_LOr:
15466         // '+', '-', '^', '|', '||' reduction ops - initializer is '0'.
15467         if (Type->isScalarType() || Type->isAnyComplexType())
15468           Init = S.ActOnIntegerConstant(ELoc, /*Val=*/0).get();
15469         break;
15470       case BO_Mul:
15471       case BO_LAnd:
15472         if (Type->isScalarType() || Type->isAnyComplexType()) {
15473           // '*' and '&&' reduction ops - initializer is '1'.
15474           Init = S.ActOnIntegerConstant(ELoc, /*Val=*/1).get();
15475         }
15476         break;
15477       case BO_And: {
15478         // '&' reduction op - initializer is '~0'.
15479         QualType OrigType = Type;
15480         if (auto *ComplexTy = OrigType->getAs<ComplexType>())
15481           Type = ComplexTy->getElementType();
15482         if (Type->isRealFloatingType()) {
15483           llvm::APFloat InitValue = llvm::APFloat::getAllOnesValue(
15484               Context.getFloatTypeSemantics(Type),
15485               Context.getTypeSize(Type));
15486           Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
15487                                          Type, ELoc);
15488         } else if (Type->isScalarType()) {
15489           uint64_t Size = Context.getTypeSize(Type);
15490           QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0);
15491           llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size);
15492           Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
15493         }
15494         if (Init && OrigType->isAnyComplexType()) {
15495           // Init = 0xFFFF + 0xFFFFi;
15496           auto *Im = new (Context) ImaginaryLiteral(Init, OrigType);
15497           Init = S.CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get();
15498         }
15499         Type = OrigType;
15500         break;
15501       }
15502       case BO_LT:
15503       case BO_GT: {
15504         // 'min' reduction op - initializer is 'Largest representable number in
15505         // the reduction list item type'.
15506         // 'max' reduction op - initializer is 'Least representable number in
15507         // the reduction list item type'.
15508         if (Type->isIntegerType() || Type->isPointerType()) {
15509           bool IsSigned = Type->hasSignedIntegerRepresentation();
15510           uint64_t Size = Context.getTypeSize(Type);
15511           QualType IntTy =
15512               Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned);
15513           llvm::APInt InitValue =
15514               (BOK != BO_LT) ? IsSigned ? llvm::APInt::getSignedMinValue(Size)
15515                                         : llvm::APInt::getMinValue(Size)
15516                              : IsSigned ? llvm::APInt::getSignedMaxValue(Size)
15517                                         : llvm::APInt::getMaxValue(Size);
15518           Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
15519           if (Type->isPointerType()) {
15520             // Cast to pointer type.
15521             ExprResult CastExpr = S.BuildCStyleCastExpr(
15522                 ELoc, Context.getTrivialTypeSourceInfo(Type, ELoc), ELoc, Init);
15523             if (CastExpr.isInvalid())
15524               continue;
15525             Init = CastExpr.get();
15526           }
15527         } else if (Type->isRealFloatingType()) {
15528           llvm::APFloat InitValue = llvm::APFloat::getLargest(
15529               Context.getFloatTypeSemantics(Type), BOK != BO_LT);
15530           Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
15531                                          Type, ELoc);
15532         }
15533         break;
15534       }
15535       case BO_PtrMemD:
15536       case BO_PtrMemI:
15537       case BO_MulAssign:
15538       case BO_Div:
15539       case BO_Rem:
15540       case BO_Sub:
15541       case BO_Shl:
15542       case BO_Shr:
15543       case BO_LE:
15544       case BO_GE:
15545       case BO_EQ:
15546       case BO_NE:
15547       case BO_Cmp:
15548       case BO_AndAssign:
15549       case BO_XorAssign:
15550       case BO_OrAssign:
15551       case BO_Assign:
15552       case BO_AddAssign:
15553       case BO_SubAssign:
15554       case BO_DivAssign:
15555       case BO_RemAssign:
15556       case BO_ShlAssign:
15557       case BO_ShrAssign:
15558       case BO_Comma:
15559         llvm_unreachable("Unexpected reduction operation");
15560       }
15561     }
15562     if (Init && DeclareReductionRef.isUnset()) {
15563       S.AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false);
15564       // Store initializer for single element in private copy. Will be used
15565       // during codegen.
15566       PrivateVD->setInit(RHSVD->getInit());
15567       PrivateVD->setInitStyle(RHSVD->getInitStyle());
15568     } else if (!Init) {
15569       S.ActOnUninitializedDecl(RHSVD);
15570       // Store initializer for single element in private copy. Will be used
15571       // during codegen.
15572       PrivateVD->setInit(RHSVD->getInit());
15573       PrivateVD->setInitStyle(RHSVD->getInitStyle());
15574     }
15575     if (RHSVD->isInvalidDecl())
15576       continue;
15577     if (!RHSVD->hasInit() &&
15578         (DeclareReductionRef.isUnset() || !S.LangOpts.CPlusPlus)) {
15579       S.Diag(ELoc, diag::err_omp_reduction_id_not_compatible)
15580           << Type << ReductionIdRange;
15581       bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
15582                                VarDecl::DeclarationOnly;
15583       S.Diag(D->getLocation(),
15584              IsDecl ? diag::note_previous_decl : diag::note_defined_here)
15585           << D;
15586       continue;
15587     }
15588     DeclRefExpr *PrivateDRE = buildDeclRefExpr(S, PrivateVD, PrivateTy, ELoc);
15589     ExprResult ReductionOp;
15590     if (DeclareReductionRef.isUsable()) {
15591       QualType RedTy = DeclareReductionRef.get()->getType();
15592       QualType PtrRedTy = Context.getPointerType(RedTy);
15593       ExprResult LHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, LHSDRE);
15594       ExprResult RHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RHSDRE);
15595       if (!BasePath.empty()) {
15596         LHS = S.DefaultLvalueConversion(LHS.get());
15597         RHS = S.DefaultLvalueConversion(RHS.get());
15598         LHS = ImplicitCastExpr::Create(
15599             Context, PtrRedTy, CK_UncheckedDerivedToBase, LHS.get(), &BasePath,
15600             LHS.get()->getValueKind(), FPOptionsOverride());
15601         RHS = ImplicitCastExpr::Create(
15602             Context, PtrRedTy, CK_UncheckedDerivedToBase, RHS.get(), &BasePath,
15603             RHS.get()->getValueKind(), FPOptionsOverride());
15604       }
15605       FunctionProtoType::ExtProtoInfo EPI;
15606       QualType Params[] = {PtrRedTy, PtrRedTy};
15607       QualType FnTy = Context.getFunctionType(Context.VoidTy, Params, EPI);
15608       auto *OVE = new (Context) OpaqueValueExpr(
15609           ELoc, Context.getPointerType(FnTy), VK_RValue, OK_Ordinary,
15610           S.DefaultLvalueConversion(DeclareReductionRef.get()).get());
15611       Expr *Args[] = {LHS.get(), RHS.get()};
15612       ReductionOp =
15613           CallExpr::Create(Context, OVE, Args, Context.VoidTy, VK_RValue, ELoc,
15614                            S.CurFPFeatureOverrides());
15615     } else {
15616       ReductionOp = S.BuildBinOp(
15617           Stack->getCurScope(), ReductionId.getBeginLoc(), BOK, LHSDRE, RHSDRE);
15618       if (ReductionOp.isUsable()) {
15619         if (BOK != BO_LT && BOK != BO_GT) {
15620           ReductionOp =
15621               S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(),
15622                            BO_Assign, LHSDRE, ReductionOp.get());
15623         } else {
15624           auto *ConditionalOp = new (Context)
15625               ConditionalOperator(ReductionOp.get(), ELoc, LHSDRE, ELoc, RHSDRE,
15626                                   Type, VK_LValue, OK_Ordinary);
15627           ReductionOp =
15628               S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(),
15629                            BO_Assign, LHSDRE, ConditionalOp);
15630         }
15631         if (ReductionOp.isUsable())
15632           ReductionOp = S.ActOnFinishFullExpr(ReductionOp.get(),
15633                                               /*DiscardedValue*/ false);
15634       }
15635       if (!ReductionOp.isUsable())
15636         continue;
15637     }
15638 
15639     // Add copy operations for inscan reductions.
15640     // LHS = RHS;
15641     ExprResult CopyOpRes, TempArrayRes, TempArrayElem;
15642     if (ClauseKind == OMPC_reduction &&
15643         RD.RedModifier == OMPC_REDUCTION_inscan) {
15644       ExprResult RHS = S.DefaultLvalueConversion(RHSDRE);
15645       CopyOpRes = S.BuildBinOp(Stack->getCurScope(), ELoc, BO_Assign, LHSDRE,
15646                                RHS.get());
15647       if (!CopyOpRes.isUsable())
15648         continue;
15649       CopyOpRes =
15650           S.ActOnFinishFullExpr(CopyOpRes.get(), /*DiscardedValue=*/true);
15651       if (!CopyOpRes.isUsable())
15652         continue;
15653       // For simd directive and simd-based directives in simd mode no need to
15654       // construct temp array, need just a single temp element.
15655       if (Stack->getCurrentDirective() == OMPD_simd ||
15656           (S.getLangOpts().OpenMPSimd &&
15657            isOpenMPSimdDirective(Stack->getCurrentDirective()))) {
15658         VarDecl *TempArrayVD =
15659             buildVarDecl(S, ELoc, PrivateTy, D->getName(),
15660                          D->hasAttrs() ? &D->getAttrs() : nullptr);
15661         // Add a constructor to the temp decl.
15662         S.ActOnUninitializedDecl(TempArrayVD);
15663         TempArrayRes = buildDeclRefExpr(S, TempArrayVD, PrivateTy, ELoc);
15664       } else {
15665         // Build temp array for prefix sum.
15666         auto *Dim = new (S.Context)
15667             OpaqueValueExpr(ELoc, S.Context.getSizeType(), VK_RValue);
15668         QualType ArrayTy =
15669             S.Context.getVariableArrayType(PrivateTy, Dim, ArrayType::Normal,
15670                                            /*IndexTypeQuals=*/0, {ELoc, ELoc});
15671         VarDecl *TempArrayVD =
15672             buildVarDecl(S, ELoc, ArrayTy, D->getName(),
15673                          D->hasAttrs() ? &D->getAttrs() : nullptr);
15674         // Add a constructor to the temp decl.
15675         S.ActOnUninitializedDecl(TempArrayVD);
15676         TempArrayRes = buildDeclRefExpr(S, TempArrayVD, ArrayTy, ELoc);
15677         TempArrayElem =
15678             S.DefaultFunctionArrayLvalueConversion(TempArrayRes.get());
15679         auto *Idx = new (S.Context)
15680             OpaqueValueExpr(ELoc, S.Context.getSizeType(), VK_RValue);
15681         TempArrayElem = S.CreateBuiltinArraySubscriptExpr(TempArrayElem.get(),
15682                                                           ELoc, Idx, ELoc);
15683       }
15684     }
15685 
15686     // OpenMP [2.15.4.6, Restrictions, p.2]
15687     // A list item that appears in an in_reduction clause of a task construct
15688     // must appear in a task_reduction clause of a construct associated with a
15689     // taskgroup region that includes the participating task in its taskgroup
15690     // set. The construct associated with the innermost region that meets this
15691     // condition must specify the same reduction-identifier as the in_reduction
15692     // clause.
15693     if (ClauseKind == OMPC_in_reduction) {
15694       SourceRange ParentSR;
15695       BinaryOperatorKind ParentBOK;
15696       const Expr *ParentReductionOp = nullptr;
15697       Expr *ParentBOKTD = nullptr, *ParentReductionOpTD = nullptr;
15698       DSAStackTy::DSAVarData ParentBOKDSA =
15699           Stack->getTopMostTaskgroupReductionData(D, ParentSR, ParentBOK,
15700                                                   ParentBOKTD);
15701       DSAStackTy::DSAVarData ParentReductionOpDSA =
15702           Stack->getTopMostTaskgroupReductionData(
15703               D, ParentSR, ParentReductionOp, ParentReductionOpTD);
15704       bool IsParentBOK = ParentBOKDSA.DKind != OMPD_unknown;
15705       bool IsParentReductionOp = ParentReductionOpDSA.DKind != OMPD_unknown;
15706       if ((DeclareReductionRef.isUnset() && IsParentReductionOp) ||
15707           (DeclareReductionRef.isUsable() && IsParentBOK) ||
15708           (IsParentBOK && BOK != ParentBOK) || IsParentReductionOp) {
15709         bool EmitError = true;
15710         if (IsParentReductionOp && DeclareReductionRef.isUsable()) {
15711           llvm::FoldingSetNodeID RedId, ParentRedId;
15712           ParentReductionOp->Profile(ParentRedId, Context, /*Canonical=*/true);
15713           DeclareReductionRef.get()->Profile(RedId, Context,
15714                                              /*Canonical=*/true);
15715           EmitError = RedId != ParentRedId;
15716         }
15717         if (EmitError) {
15718           S.Diag(ReductionId.getBeginLoc(),
15719                  diag::err_omp_reduction_identifier_mismatch)
15720               << ReductionIdRange << RefExpr->getSourceRange();
15721           S.Diag(ParentSR.getBegin(),
15722                  diag::note_omp_previous_reduction_identifier)
15723               << ParentSR
15724               << (IsParentBOK ? ParentBOKDSA.RefExpr
15725                               : ParentReductionOpDSA.RefExpr)
15726                      ->getSourceRange();
15727           continue;
15728         }
15729       }
15730       TaskgroupDescriptor = IsParentBOK ? ParentBOKTD : ParentReductionOpTD;
15731     }
15732 
15733     DeclRefExpr *Ref = nullptr;
15734     Expr *VarsExpr = RefExpr->IgnoreParens();
15735     if (!VD && !S.CurContext->isDependentContext()) {
15736       if (ASE || OASE) {
15737         TransformExprToCaptures RebuildToCapture(S, D);
15738         VarsExpr =
15739             RebuildToCapture.TransformExpr(RefExpr->IgnoreParens()).get();
15740         Ref = RebuildToCapture.getCapturedExpr();
15741       } else {
15742         VarsExpr = Ref = buildCapture(S, D, SimpleRefExpr, /*WithInit=*/false);
15743       }
15744       if (!S.isOpenMPCapturedDecl(D)) {
15745         RD.ExprCaptures.emplace_back(Ref->getDecl());
15746         if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
15747           ExprResult RefRes = S.DefaultLvalueConversion(Ref);
15748           if (!RefRes.isUsable())
15749             continue;
15750           ExprResult PostUpdateRes =
15751               S.BuildBinOp(Stack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
15752                            RefRes.get());
15753           if (!PostUpdateRes.isUsable())
15754             continue;
15755           if (isOpenMPTaskingDirective(Stack->getCurrentDirective()) ||
15756               Stack->getCurrentDirective() == OMPD_taskgroup) {
15757             S.Diag(RefExpr->getExprLoc(),
15758                    diag::err_omp_reduction_non_addressable_expression)
15759                 << RefExpr->getSourceRange();
15760             continue;
15761           }
15762           RD.ExprPostUpdates.emplace_back(
15763               S.IgnoredValueConversions(PostUpdateRes.get()).get());
15764         }
15765       }
15766     }
15767     // All reduction items are still marked as reduction (to do not increase
15768     // code base size).
15769     unsigned Modifier = RD.RedModifier;
15770     // Consider task_reductions as reductions with task modifier. Required for
15771     // correct analysis of in_reduction clauses.
15772     if (CurrDir == OMPD_taskgroup && ClauseKind == OMPC_task_reduction)
15773       Modifier = OMPC_REDUCTION_task;
15774     Stack->addDSA(D, RefExpr->IgnoreParens(), OMPC_reduction, Ref, Modifier,
15775                   ASE || OASE);
15776     if (Modifier == OMPC_REDUCTION_task &&
15777         (CurrDir == OMPD_taskgroup ||
15778          ((isOpenMPParallelDirective(CurrDir) ||
15779            isOpenMPWorksharingDirective(CurrDir)) &&
15780           !isOpenMPSimdDirective(CurrDir)))) {
15781       if (DeclareReductionRef.isUsable())
15782         Stack->addTaskgroupReductionData(D, ReductionIdRange,
15783                                          DeclareReductionRef.get());
15784       else
15785         Stack->addTaskgroupReductionData(D, ReductionIdRange, BOK);
15786     }
15787     RD.push(VarsExpr, PrivateDRE, LHSDRE, RHSDRE, ReductionOp.get(),
15788             TaskgroupDescriptor, CopyOpRes.get(), TempArrayRes.get(),
15789             TempArrayElem.get());
15790   }
15791   return RD.Vars.empty();
15792 }
15793 
15794 OMPClause *Sema::ActOnOpenMPReductionClause(
15795     ArrayRef<Expr *> VarList, OpenMPReductionClauseModifier Modifier,
15796     SourceLocation StartLoc, SourceLocation LParenLoc,
15797     SourceLocation ModifierLoc, SourceLocation ColonLoc, SourceLocation EndLoc,
15798     CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
15799     ArrayRef<Expr *> UnresolvedReductions) {
15800   if (ModifierLoc.isValid() && Modifier == OMPC_REDUCTION_unknown) {
15801     Diag(LParenLoc, diag::err_omp_unexpected_clause_value)
15802         << getListOfPossibleValues(OMPC_reduction, /*First=*/0,
15803                                    /*Last=*/OMPC_REDUCTION_unknown)
15804         << getOpenMPClauseName(OMPC_reduction);
15805     return nullptr;
15806   }
15807   // OpenMP 5.0, 2.19.5.4 reduction Clause, Restrictions
15808   // A reduction clause with the inscan reduction-modifier may only appear on a
15809   // worksharing-loop construct, a worksharing-loop SIMD construct, a simd
15810   // construct, a parallel worksharing-loop construct or a parallel
15811   // worksharing-loop SIMD construct.
15812   if (Modifier == OMPC_REDUCTION_inscan &&
15813       (DSAStack->getCurrentDirective() != OMPD_for &&
15814        DSAStack->getCurrentDirective() != OMPD_for_simd &&
15815        DSAStack->getCurrentDirective() != OMPD_simd &&
15816        DSAStack->getCurrentDirective() != OMPD_parallel_for &&
15817        DSAStack->getCurrentDirective() != OMPD_parallel_for_simd)) {
15818     Diag(ModifierLoc, diag::err_omp_wrong_inscan_reduction);
15819     return nullptr;
15820   }
15821 
15822   ReductionData RD(VarList.size(), Modifier);
15823   if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_reduction, VarList,
15824                                   StartLoc, LParenLoc, ColonLoc, EndLoc,
15825                                   ReductionIdScopeSpec, ReductionId,
15826                                   UnresolvedReductions, RD))
15827     return nullptr;
15828 
15829   return OMPReductionClause::Create(
15830       Context, StartLoc, LParenLoc, ModifierLoc, ColonLoc, EndLoc, Modifier,
15831       RD.Vars, ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
15832       RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, RD.InscanCopyOps,
15833       RD.InscanCopyArrayTemps, RD.InscanCopyArrayElems,
15834       buildPreInits(Context, RD.ExprCaptures),
15835       buildPostUpdate(*this, RD.ExprPostUpdates));
15836 }
15837 
15838 OMPClause *Sema::ActOnOpenMPTaskReductionClause(
15839     ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
15840     SourceLocation ColonLoc, SourceLocation EndLoc,
15841     CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
15842     ArrayRef<Expr *> UnresolvedReductions) {
15843   ReductionData RD(VarList.size());
15844   if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_task_reduction, VarList,
15845                                   StartLoc, LParenLoc, ColonLoc, EndLoc,
15846                                   ReductionIdScopeSpec, ReductionId,
15847                                   UnresolvedReductions, RD))
15848     return nullptr;
15849 
15850   return OMPTaskReductionClause::Create(
15851       Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
15852       ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
15853       RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
15854       buildPreInits(Context, RD.ExprCaptures),
15855       buildPostUpdate(*this, RD.ExprPostUpdates));
15856 }
15857 
15858 OMPClause *Sema::ActOnOpenMPInReductionClause(
15859     ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
15860     SourceLocation ColonLoc, SourceLocation EndLoc,
15861     CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
15862     ArrayRef<Expr *> UnresolvedReductions) {
15863   ReductionData RD(VarList.size());
15864   if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_in_reduction, VarList,
15865                                   StartLoc, LParenLoc, ColonLoc, EndLoc,
15866                                   ReductionIdScopeSpec, ReductionId,
15867                                   UnresolvedReductions, RD))
15868     return nullptr;
15869 
15870   return OMPInReductionClause::Create(
15871       Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
15872       ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
15873       RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, RD.TaskgroupDescriptors,
15874       buildPreInits(Context, RD.ExprCaptures),
15875       buildPostUpdate(*this, RD.ExprPostUpdates));
15876 }
15877 
15878 bool Sema::CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
15879                                      SourceLocation LinLoc) {
15880   if ((!LangOpts.CPlusPlus && LinKind != OMPC_LINEAR_val) ||
15881       LinKind == OMPC_LINEAR_unknown) {
15882     Diag(LinLoc, diag::err_omp_wrong_linear_modifier) << LangOpts.CPlusPlus;
15883     return true;
15884   }
15885   return false;
15886 }
15887 
15888 bool Sema::CheckOpenMPLinearDecl(const ValueDecl *D, SourceLocation ELoc,
15889                                  OpenMPLinearClauseKind LinKind, QualType Type,
15890                                  bool IsDeclareSimd) {
15891   const auto *VD = dyn_cast_or_null<VarDecl>(D);
15892   // A variable must not have an incomplete type or a reference type.
15893   if (RequireCompleteType(ELoc, Type, diag::err_omp_linear_incomplete_type))
15894     return true;
15895   if ((LinKind == OMPC_LINEAR_uval || LinKind == OMPC_LINEAR_ref) &&
15896       !Type->isReferenceType()) {
15897     Diag(ELoc, diag::err_omp_wrong_linear_modifier_non_reference)
15898         << Type << getOpenMPSimpleClauseTypeName(OMPC_linear, LinKind);
15899     return true;
15900   }
15901   Type = Type.getNonReferenceType();
15902 
15903   // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
15904   // A variable that is privatized must not have a const-qualified type
15905   // unless it is of class type with a mutable member. This restriction does
15906   // not apply to the firstprivate clause, nor to the linear clause on
15907   // declarative directives (like declare simd).
15908   if (!IsDeclareSimd &&
15909       rejectConstNotMutableType(*this, D, Type, OMPC_linear, ELoc))
15910     return true;
15911 
15912   // A list item must be of integral or pointer type.
15913   Type = Type.getUnqualifiedType().getCanonicalType();
15914   const auto *Ty = Type.getTypePtrOrNull();
15915   if (!Ty || (LinKind != OMPC_LINEAR_ref && !Ty->isDependentType() &&
15916               !Ty->isIntegralType(Context) && !Ty->isPointerType())) {
15917     Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << Type;
15918     if (D) {
15919       bool IsDecl =
15920           !VD ||
15921           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
15922       Diag(D->getLocation(),
15923            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
15924           << D;
15925     }
15926     return true;
15927   }
15928   return false;
15929 }
15930 
15931 OMPClause *Sema::ActOnOpenMPLinearClause(
15932     ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc,
15933     SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind,
15934     SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
15935   SmallVector<Expr *, 8> Vars;
15936   SmallVector<Expr *, 8> Privates;
15937   SmallVector<Expr *, 8> Inits;
15938   SmallVector<Decl *, 4> ExprCaptures;
15939   SmallVector<Expr *, 4> ExprPostUpdates;
15940   if (CheckOpenMPLinearModifier(LinKind, LinLoc))
15941     LinKind = OMPC_LINEAR_val;
15942   for (Expr *RefExpr : VarList) {
15943     assert(RefExpr && "NULL expr in OpenMP linear clause.");
15944     SourceLocation ELoc;
15945     SourceRange ERange;
15946     Expr *SimpleRefExpr = RefExpr;
15947     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
15948     if (Res.second) {
15949       // It will be analyzed later.
15950       Vars.push_back(RefExpr);
15951       Privates.push_back(nullptr);
15952       Inits.push_back(nullptr);
15953     }
15954     ValueDecl *D = Res.first;
15955     if (!D)
15956       continue;
15957 
15958     QualType Type = D->getType();
15959     auto *VD = dyn_cast<VarDecl>(D);
15960 
15961     // OpenMP [2.14.3.7, linear clause]
15962     //  A list-item cannot appear in more than one linear clause.
15963     //  A list-item that appears in a linear clause cannot appear in any
15964     //  other data-sharing attribute clause.
15965     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
15966     if (DVar.RefExpr) {
15967       Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
15968                                           << getOpenMPClauseName(OMPC_linear);
15969       reportOriginalDsa(*this, DSAStack, D, DVar);
15970       continue;
15971     }
15972 
15973     if (CheckOpenMPLinearDecl(D, ELoc, LinKind, Type))
15974       continue;
15975     Type = Type.getNonReferenceType().getUnqualifiedType().getCanonicalType();
15976 
15977     // Build private copy of original var.
15978     VarDecl *Private =
15979         buildVarDecl(*this, ELoc, Type, D->getName(),
15980                      D->hasAttrs() ? &D->getAttrs() : nullptr,
15981                      VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
15982     DeclRefExpr *PrivateRef = buildDeclRefExpr(*this, Private, Type, ELoc);
15983     // Build var to save initial value.
15984     VarDecl *Init = buildVarDecl(*this, ELoc, Type, ".linear.start");
15985     Expr *InitExpr;
15986     DeclRefExpr *Ref = nullptr;
15987     if (!VD && !CurContext->isDependentContext()) {
15988       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
15989       if (!isOpenMPCapturedDecl(D)) {
15990         ExprCaptures.push_back(Ref->getDecl());
15991         if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
15992           ExprResult RefRes = DefaultLvalueConversion(Ref);
15993           if (!RefRes.isUsable())
15994             continue;
15995           ExprResult PostUpdateRes =
15996               BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
15997                          SimpleRefExpr, RefRes.get());
15998           if (!PostUpdateRes.isUsable())
15999             continue;
16000           ExprPostUpdates.push_back(
16001               IgnoredValueConversions(PostUpdateRes.get()).get());
16002         }
16003       }
16004     }
16005     if (LinKind == OMPC_LINEAR_uval)
16006       InitExpr = VD ? VD->getInit() : SimpleRefExpr;
16007     else
16008       InitExpr = VD ? SimpleRefExpr : Ref;
16009     AddInitializerToDecl(Init, DefaultLvalueConversion(InitExpr).get(),
16010                          /*DirectInit=*/false);
16011     DeclRefExpr *InitRef = buildDeclRefExpr(*this, Init, Type, ELoc);
16012 
16013     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_linear, Ref);
16014     Vars.push_back((VD || CurContext->isDependentContext())
16015                        ? RefExpr->IgnoreParens()
16016                        : Ref);
16017     Privates.push_back(PrivateRef);
16018     Inits.push_back(InitRef);
16019   }
16020 
16021   if (Vars.empty())
16022     return nullptr;
16023 
16024   Expr *StepExpr = Step;
16025   Expr *CalcStepExpr = nullptr;
16026   if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
16027       !Step->isInstantiationDependent() &&
16028       !Step->containsUnexpandedParameterPack()) {
16029     SourceLocation StepLoc = Step->getBeginLoc();
16030     ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step);
16031     if (Val.isInvalid())
16032       return nullptr;
16033     StepExpr = Val.get();
16034 
16035     // Build var to save the step value.
16036     VarDecl *SaveVar =
16037         buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step");
16038     ExprResult SaveRef =
16039         buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc);
16040     ExprResult CalcStep =
16041         BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr);
16042     CalcStep = ActOnFinishFullExpr(CalcStep.get(), /*DiscardedValue*/ false);
16043 
16044     // Warn about zero linear step (it would be probably better specified as
16045     // making corresponding variables 'const').
16046     if (Optional<llvm::APSInt> Result =
16047             StepExpr->getIntegerConstantExpr(Context)) {
16048       if (!Result->isNegative() && !Result->isStrictlyPositive())
16049         Diag(StepLoc, diag::warn_omp_linear_step_zero)
16050             << Vars[0] << (Vars.size() > 1);
16051     } else if (CalcStep.isUsable()) {
16052       // Calculate the step beforehand instead of doing this on each iteration.
16053       // (This is not used if the number of iterations may be kfold-ed).
16054       CalcStepExpr = CalcStep.get();
16055     }
16056   }
16057 
16058   return OMPLinearClause::Create(Context, StartLoc, LParenLoc, LinKind, LinLoc,
16059                                  ColonLoc, EndLoc, Vars, Privates, Inits,
16060                                  StepExpr, CalcStepExpr,
16061                                  buildPreInits(Context, ExprCaptures),
16062                                  buildPostUpdate(*this, ExprPostUpdates));
16063 }
16064 
16065 static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
16066                                      Expr *NumIterations, Sema &SemaRef,
16067                                      Scope *S, DSAStackTy *Stack) {
16068   // Walk the vars and build update/final expressions for the CodeGen.
16069   SmallVector<Expr *, 8> Updates;
16070   SmallVector<Expr *, 8> Finals;
16071   SmallVector<Expr *, 8> UsedExprs;
16072   Expr *Step = Clause.getStep();
16073   Expr *CalcStep = Clause.getCalcStep();
16074   // OpenMP [2.14.3.7, linear clause]
16075   // If linear-step is not specified it is assumed to be 1.
16076   if (!Step)
16077     Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
16078   else if (CalcStep)
16079     Step = cast<BinaryOperator>(CalcStep)->getLHS();
16080   bool HasErrors = false;
16081   auto CurInit = Clause.inits().begin();
16082   auto CurPrivate = Clause.privates().begin();
16083   OpenMPLinearClauseKind LinKind = Clause.getModifier();
16084   for (Expr *RefExpr : Clause.varlists()) {
16085     SourceLocation ELoc;
16086     SourceRange ERange;
16087     Expr *SimpleRefExpr = RefExpr;
16088     auto Res = getPrivateItem(SemaRef, SimpleRefExpr, ELoc, ERange);
16089     ValueDecl *D = Res.first;
16090     if (Res.second || !D) {
16091       Updates.push_back(nullptr);
16092       Finals.push_back(nullptr);
16093       HasErrors = true;
16094       continue;
16095     }
16096     auto &&Info = Stack->isLoopControlVariable(D);
16097     // OpenMP [2.15.11, distribute simd Construct]
16098     // A list item may not appear in a linear clause, unless it is the loop
16099     // iteration variable.
16100     if (isOpenMPDistributeDirective(Stack->getCurrentDirective()) &&
16101         isOpenMPSimdDirective(Stack->getCurrentDirective()) && !Info.first) {
16102       SemaRef.Diag(ELoc,
16103                    diag::err_omp_linear_distribute_var_non_loop_iteration);
16104       Updates.push_back(nullptr);
16105       Finals.push_back(nullptr);
16106       HasErrors = true;
16107       continue;
16108     }
16109     Expr *InitExpr = *CurInit;
16110 
16111     // Build privatized reference to the current linear var.
16112     auto *DE = cast<DeclRefExpr>(SimpleRefExpr);
16113     Expr *CapturedRef;
16114     if (LinKind == OMPC_LINEAR_uval)
16115       CapturedRef = cast<VarDecl>(DE->getDecl())->getInit();
16116     else
16117       CapturedRef =
16118           buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()),
16119                            DE->getType().getUnqualifiedType(), DE->getExprLoc(),
16120                            /*RefersToCapture=*/true);
16121 
16122     // Build update: Var = InitExpr + IV * Step
16123     ExprResult Update;
16124     if (!Info.first)
16125       Update = buildCounterUpdate(
16126           SemaRef, S, RefExpr->getExprLoc(), *CurPrivate, InitExpr, IV, Step,
16127           /*Subtract=*/false, /*IsNonRectangularLB=*/false);
16128     else
16129       Update = *CurPrivate;
16130     Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getBeginLoc(),
16131                                          /*DiscardedValue*/ false);
16132 
16133     // Build final: Var = InitExpr + NumIterations * Step
16134     ExprResult Final;
16135     if (!Info.first)
16136       Final =
16137           buildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), CapturedRef,
16138                              InitExpr, NumIterations, Step, /*Subtract=*/false,
16139                              /*IsNonRectangularLB=*/false);
16140     else
16141       Final = *CurPrivate;
16142     Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getBeginLoc(),
16143                                         /*DiscardedValue*/ false);
16144 
16145     if (!Update.isUsable() || !Final.isUsable()) {
16146       Updates.push_back(nullptr);
16147       Finals.push_back(nullptr);
16148       UsedExprs.push_back(nullptr);
16149       HasErrors = true;
16150     } else {
16151       Updates.push_back(Update.get());
16152       Finals.push_back(Final.get());
16153       if (!Info.first)
16154         UsedExprs.push_back(SimpleRefExpr);
16155     }
16156     ++CurInit;
16157     ++CurPrivate;
16158   }
16159   if (Expr *S = Clause.getStep())
16160     UsedExprs.push_back(S);
16161   // Fill the remaining part with the nullptr.
16162   UsedExprs.append(Clause.varlist_size() + 1 - UsedExprs.size(), nullptr);
16163   Clause.setUpdates(Updates);
16164   Clause.setFinals(Finals);
16165   Clause.setUsedExprs(UsedExprs);
16166   return HasErrors;
16167 }
16168 
16169 OMPClause *Sema::ActOnOpenMPAlignedClause(
16170     ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc,
16171     SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
16172   SmallVector<Expr *, 8> Vars;
16173   for (Expr *RefExpr : VarList) {
16174     assert(RefExpr && "NULL expr in OpenMP linear clause.");
16175     SourceLocation ELoc;
16176     SourceRange ERange;
16177     Expr *SimpleRefExpr = RefExpr;
16178     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
16179     if (Res.second) {
16180       // It will be analyzed later.
16181       Vars.push_back(RefExpr);
16182     }
16183     ValueDecl *D = Res.first;
16184     if (!D)
16185       continue;
16186 
16187     QualType QType = D->getType();
16188     auto *VD = dyn_cast<VarDecl>(D);
16189 
16190     // OpenMP  [2.8.1, simd construct, Restrictions]
16191     // The type of list items appearing in the aligned clause must be
16192     // array, pointer, reference to array, or reference to pointer.
16193     QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType();
16194     const Type *Ty = QType.getTypePtrOrNull();
16195     if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
16196       Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr)
16197           << QType << getLangOpts().CPlusPlus << ERange;
16198       bool IsDecl =
16199           !VD ||
16200           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
16201       Diag(D->getLocation(),
16202            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
16203           << D;
16204       continue;
16205     }
16206 
16207     // OpenMP  [2.8.1, simd construct, Restrictions]
16208     // A list-item cannot appear in more than one aligned clause.
16209     if (const Expr *PrevRef = DSAStack->addUniqueAligned(D, SimpleRefExpr)) {
16210       Diag(ELoc, diag::err_omp_used_in_clause_twice)
16211           << 0 << getOpenMPClauseName(OMPC_aligned) << ERange;
16212       Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
16213           << getOpenMPClauseName(OMPC_aligned);
16214       continue;
16215     }
16216 
16217     DeclRefExpr *Ref = nullptr;
16218     if (!VD && isOpenMPCapturedDecl(D))
16219       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
16220     Vars.push_back(DefaultFunctionArrayConversion(
16221                        (VD || !Ref) ? RefExpr->IgnoreParens() : Ref)
16222                        .get());
16223   }
16224 
16225   // OpenMP [2.8.1, simd construct, Description]
16226   // The parameter of the aligned clause, alignment, must be a constant
16227   // positive integer expression.
16228   // If no optional parameter is specified, implementation-defined default
16229   // alignments for SIMD instructions on the target platforms are assumed.
16230   if (Alignment != nullptr) {
16231     ExprResult AlignResult =
16232         VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned);
16233     if (AlignResult.isInvalid())
16234       return nullptr;
16235     Alignment = AlignResult.get();
16236   }
16237   if (Vars.empty())
16238     return nullptr;
16239 
16240   return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
16241                                   EndLoc, Vars, Alignment);
16242 }
16243 
16244 OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
16245                                          SourceLocation StartLoc,
16246                                          SourceLocation LParenLoc,
16247                                          SourceLocation EndLoc) {
16248   SmallVector<Expr *, 8> Vars;
16249   SmallVector<Expr *, 8> SrcExprs;
16250   SmallVector<Expr *, 8> DstExprs;
16251   SmallVector<Expr *, 8> AssignmentOps;
16252   for (Expr *RefExpr : VarList) {
16253     assert(RefExpr && "NULL expr in OpenMP copyin clause.");
16254     if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
16255       // It will be analyzed later.
16256       Vars.push_back(RefExpr);
16257       SrcExprs.push_back(nullptr);
16258       DstExprs.push_back(nullptr);
16259       AssignmentOps.push_back(nullptr);
16260       continue;
16261     }
16262 
16263     SourceLocation ELoc = RefExpr->getExprLoc();
16264     // OpenMP [2.1, C/C++]
16265     //  A list item is a variable name.
16266     // OpenMP  [2.14.4.1, Restrictions, p.1]
16267     //  A list item that appears in a copyin clause must be threadprivate.
16268     auto *DE = dyn_cast<DeclRefExpr>(RefExpr);
16269     if (!DE || !isa<VarDecl>(DE->getDecl())) {
16270       Diag(ELoc, diag::err_omp_expected_var_name_member_expr)
16271           << 0 << RefExpr->getSourceRange();
16272       continue;
16273     }
16274 
16275     Decl *D = DE->getDecl();
16276     auto *VD = cast<VarDecl>(D);
16277 
16278     QualType Type = VD->getType();
16279     if (Type->isDependentType() || Type->isInstantiationDependentType()) {
16280       // It will be analyzed later.
16281       Vars.push_back(DE);
16282       SrcExprs.push_back(nullptr);
16283       DstExprs.push_back(nullptr);
16284       AssignmentOps.push_back(nullptr);
16285       continue;
16286     }
16287 
16288     // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
16289     //  A list item that appears in a copyin clause must be threadprivate.
16290     if (!DSAStack->isThreadPrivate(VD)) {
16291       Diag(ELoc, diag::err_omp_required_access)
16292           << getOpenMPClauseName(OMPC_copyin)
16293           << getOpenMPDirectiveName(OMPD_threadprivate);
16294       continue;
16295     }
16296 
16297     // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
16298     //  A variable of class type (or array thereof) that appears in a
16299     //  copyin clause requires an accessible, unambiguous copy assignment
16300     //  operator for the class type.
16301     QualType ElemType = Context.getBaseElementType(Type).getNonReferenceType();
16302     VarDecl *SrcVD =
16303         buildVarDecl(*this, DE->getBeginLoc(), ElemType.getUnqualifiedType(),
16304                      ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr);
16305     DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr(
16306         *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc());
16307     VarDecl *DstVD =
16308         buildVarDecl(*this, DE->getBeginLoc(), ElemType, ".copyin.dst",
16309                      VD->hasAttrs() ? &VD->getAttrs() : nullptr);
16310     DeclRefExpr *PseudoDstExpr =
16311         buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc());
16312     // For arrays generate assignment operation for single element and replace
16313     // it by the original array element in CodeGen.
16314     ExprResult AssignmentOp =
16315         BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign, PseudoDstExpr,
16316                    PseudoSrcExpr);
16317     if (AssignmentOp.isInvalid())
16318       continue;
16319     AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
16320                                        /*DiscardedValue*/ false);
16321     if (AssignmentOp.isInvalid())
16322       continue;
16323 
16324     DSAStack->addDSA(VD, DE, OMPC_copyin);
16325     Vars.push_back(DE);
16326     SrcExprs.push_back(PseudoSrcExpr);
16327     DstExprs.push_back(PseudoDstExpr);
16328     AssignmentOps.push_back(AssignmentOp.get());
16329   }
16330 
16331   if (Vars.empty())
16332     return nullptr;
16333 
16334   return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
16335                                  SrcExprs, DstExprs, AssignmentOps);
16336 }
16337 
16338 OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
16339                                               SourceLocation StartLoc,
16340                                               SourceLocation LParenLoc,
16341                                               SourceLocation EndLoc) {
16342   SmallVector<Expr *, 8> Vars;
16343   SmallVector<Expr *, 8> SrcExprs;
16344   SmallVector<Expr *, 8> DstExprs;
16345   SmallVector<Expr *, 8> AssignmentOps;
16346   for (Expr *RefExpr : VarList) {
16347     assert(RefExpr && "NULL expr in OpenMP linear clause.");
16348     SourceLocation ELoc;
16349     SourceRange ERange;
16350     Expr *SimpleRefExpr = RefExpr;
16351     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
16352     if (Res.second) {
16353       // It will be analyzed later.
16354       Vars.push_back(RefExpr);
16355       SrcExprs.push_back(nullptr);
16356       DstExprs.push_back(nullptr);
16357       AssignmentOps.push_back(nullptr);
16358     }
16359     ValueDecl *D = Res.first;
16360     if (!D)
16361       continue;
16362 
16363     QualType Type = D->getType();
16364     auto *VD = dyn_cast<VarDecl>(D);
16365 
16366     // OpenMP [2.14.4.2, Restrictions, p.2]
16367     //  A list item that appears in a copyprivate clause may not appear in a
16368     //  private or firstprivate clause on the single construct.
16369     if (!VD || !DSAStack->isThreadPrivate(VD)) {
16370       DSAStackTy::DSAVarData DVar =
16371           DSAStack->getTopDSA(D, /*FromParent=*/false);
16372       if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate &&
16373           DVar.RefExpr) {
16374         Diag(ELoc, diag::err_omp_wrong_dsa)
16375             << getOpenMPClauseName(DVar.CKind)
16376             << getOpenMPClauseName(OMPC_copyprivate);
16377         reportOriginalDsa(*this, DSAStack, D, DVar);
16378         continue;
16379       }
16380 
16381       // OpenMP [2.11.4.2, Restrictions, p.1]
16382       //  All list items that appear in a copyprivate clause must be either
16383       //  threadprivate or private in the enclosing context.
16384       if (DVar.CKind == OMPC_unknown) {
16385         DVar = DSAStack->getImplicitDSA(D, false);
16386         if (DVar.CKind == OMPC_shared) {
16387           Diag(ELoc, diag::err_omp_required_access)
16388               << getOpenMPClauseName(OMPC_copyprivate)
16389               << "threadprivate or private in the enclosing context";
16390           reportOriginalDsa(*this, DSAStack, D, DVar);
16391           continue;
16392         }
16393       }
16394     }
16395 
16396     // Variably modified types are not supported.
16397     if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) {
16398       Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
16399           << getOpenMPClauseName(OMPC_copyprivate) << Type
16400           << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
16401       bool IsDecl =
16402           !VD ||
16403           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
16404       Diag(D->getLocation(),
16405            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
16406           << D;
16407       continue;
16408     }
16409 
16410     // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
16411     //  A variable of class type (or array thereof) that appears in a
16412     //  copyin clause requires an accessible, unambiguous copy assignment
16413     //  operator for the class type.
16414     Type = Context.getBaseElementType(Type.getNonReferenceType())
16415                .getUnqualifiedType();
16416     VarDecl *SrcVD =
16417         buildVarDecl(*this, RefExpr->getBeginLoc(), Type, ".copyprivate.src",
16418                      D->hasAttrs() ? &D->getAttrs() : nullptr);
16419     DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr(*this, SrcVD, Type, ELoc);
16420     VarDecl *DstVD =
16421         buildVarDecl(*this, RefExpr->getBeginLoc(), Type, ".copyprivate.dst",
16422                      D->hasAttrs() ? &D->getAttrs() : nullptr);
16423     DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
16424     ExprResult AssignmentOp = BuildBinOp(
16425         DSAStack->getCurScope(), ELoc, BO_Assign, PseudoDstExpr, PseudoSrcExpr);
16426     if (AssignmentOp.isInvalid())
16427       continue;
16428     AssignmentOp =
16429         ActOnFinishFullExpr(AssignmentOp.get(), ELoc, /*DiscardedValue*/ false);
16430     if (AssignmentOp.isInvalid())
16431       continue;
16432 
16433     // No need to mark vars as copyprivate, they are already threadprivate or
16434     // implicitly private.
16435     assert(VD || isOpenMPCapturedDecl(D));
16436     Vars.push_back(
16437         VD ? RefExpr->IgnoreParens()
16438            : buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false));
16439     SrcExprs.push_back(PseudoSrcExpr);
16440     DstExprs.push_back(PseudoDstExpr);
16441     AssignmentOps.push_back(AssignmentOp.get());
16442   }
16443 
16444   if (Vars.empty())
16445     return nullptr;
16446 
16447   return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
16448                                       Vars, SrcExprs, DstExprs, AssignmentOps);
16449 }
16450 
16451 OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
16452                                         SourceLocation StartLoc,
16453                                         SourceLocation LParenLoc,
16454                                         SourceLocation EndLoc) {
16455   if (VarList.empty())
16456     return nullptr;
16457 
16458   return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList);
16459 }
16460 
16461 /// Tries to find omp_depend_t. type.
16462 static bool findOMPDependT(Sema &S, SourceLocation Loc, DSAStackTy *Stack,
16463                            bool Diagnose = true) {
16464   QualType OMPDependT = Stack->getOMPDependT();
16465   if (!OMPDependT.isNull())
16466     return true;
16467   IdentifierInfo *II = &S.PP.getIdentifierTable().get("omp_depend_t");
16468   ParsedType PT = S.getTypeName(*II, Loc, S.getCurScope());
16469   if (!PT.getAsOpaquePtr() || PT.get().isNull()) {
16470     if (Diagnose)
16471       S.Diag(Loc, diag::err_omp_implied_type_not_found) << "omp_depend_t";
16472     return false;
16473   }
16474   Stack->setOMPDependT(PT.get());
16475   return true;
16476 }
16477 
16478 OMPClause *Sema::ActOnOpenMPDepobjClause(Expr *Depobj, SourceLocation StartLoc,
16479                                          SourceLocation LParenLoc,
16480                                          SourceLocation EndLoc) {
16481   if (!Depobj)
16482     return nullptr;
16483 
16484   bool OMPDependTFound = findOMPDependT(*this, StartLoc, DSAStack);
16485 
16486   // OpenMP 5.0, 2.17.10.1 depobj Construct
16487   // depobj is an lvalue expression of type omp_depend_t.
16488   if (!Depobj->isTypeDependent() && !Depobj->isValueDependent() &&
16489       !Depobj->isInstantiationDependent() &&
16490       !Depobj->containsUnexpandedParameterPack() &&
16491       (OMPDependTFound &&
16492        !Context.typesAreCompatible(DSAStack->getOMPDependT(), Depobj->getType(),
16493                                    /*CompareUnqualified=*/true))) {
16494     Diag(Depobj->getExprLoc(), diag::err_omp_expected_omp_depend_t_lvalue)
16495         << 0 << Depobj->getType() << Depobj->getSourceRange();
16496   }
16497 
16498   if (!Depobj->isLValue()) {
16499     Diag(Depobj->getExprLoc(), diag::err_omp_expected_omp_depend_t_lvalue)
16500         << 1 << Depobj->getSourceRange();
16501   }
16502 
16503   return OMPDepobjClause::Create(Context, StartLoc, LParenLoc, EndLoc, Depobj);
16504 }
16505 
16506 OMPClause *
16507 Sema::ActOnOpenMPDependClause(Expr *DepModifier, OpenMPDependClauseKind DepKind,
16508                               SourceLocation DepLoc, SourceLocation ColonLoc,
16509                               ArrayRef<Expr *> VarList, SourceLocation StartLoc,
16510                               SourceLocation LParenLoc, SourceLocation EndLoc) {
16511   if (DSAStack->getCurrentDirective() == OMPD_ordered &&
16512       DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink) {
16513     Diag(DepLoc, diag::err_omp_unexpected_clause_value)
16514         << "'source' or 'sink'" << getOpenMPClauseName(OMPC_depend);
16515     return nullptr;
16516   }
16517   if ((DSAStack->getCurrentDirective() != OMPD_ordered ||
16518        DSAStack->getCurrentDirective() == OMPD_depobj) &&
16519       (DepKind == OMPC_DEPEND_unknown || DepKind == OMPC_DEPEND_source ||
16520        DepKind == OMPC_DEPEND_sink ||
16521        ((LangOpts.OpenMP < 50 ||
16522          DSAStack->getCurrentDirective() == OMPD_depobj) &&
16523         DepKind == OMPC_DEPEND_depobj))) {
16524     SmallVector<unsigned, 3> Except;
16525     Except.push_back(OMPC_DEPEND_source);
16526     Except.push_back(OMPC_DEPEND_sink);
16527     if (LangOpts.OpenMP < 50 || DSAStack->getCurrentDirective() == OMPD_depobj)
16528       Except.push_back(OMPC_DEPEND_depobj);
16529     std::string Expected = (LangOpts.OpenMP >= 50 && !DepModifier)
16530                                ? "depend modifier(iterator) or "
16531                                : "";
16532     Diag(DepLoc, diag::err_omp_unexpected_clause_value)
16533         << Expected + getListOfPossibleValues(OMPC_depend, /*First=*/0,
16534                                               /*Last=*/OMPC_DEPEND_unknown,
16535                                               Except)
16536         << getOpenMPClauseName(OMPC_depend);
16537     return nullptr;
16538   }
16539   if (DepModifier &&
16540       (DepKind == OMPC_DEPEND_source || DepKind == OMPC_DEPEND_sink)) {
16541     Diag(DepModifier->getExprLoc(),
16542          diag::err_omp_depend_sink_source_with_modifier);
16543     return nullptr;
16544   }
16545   if (DepModifier &&
16546       !DepModifier->getType()->isSpecificBuiltinType(BuiltinType::OMPIterator))
16547     Diag(DepModifier->getExprLoc(), diag::err_omp_depend_modifier_not_iterator);
16548 
16549   SmallVector<Expr *, 8> Vars;
16550   DSAStackTy::OperatorOffsetTy OpsOffs;
16551   llvm::APSInt DepCounter(/*BitWidth=*/32);
16552   llvm::APSInt TotalDepCount(/*BitWidth=*/32);
16553   if (DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) {
16554     if (const Expr *OrderedCountExpr =
16555             DSAStack->getParentOrderedRegionParam().first) {
16556       TotalDepCount = OrderedCountExpr->EvaluateKnownConstInt(Context);
16557       TotalDepCount.setIsUnsigned(/*Val=*/true);
16558     }
16559   }
16560   for (Expr *RefExpr : VarList) {
16561     assert(RefExpr && "NULL expr in OpenMP shared clause.");
16562     if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
16563       // It will be analyzed later.
16564       Vars.push_back(RefExpr);
16565       continue;
16566     }
16567 
16568     SourceLocation ELoc = RefExpr->getExprLoc();
16569     Expr *SimpleExpr = RefExpr->IgnoreParenCasts();
16570     if (DepKind == OMPC_DEPEND_sink) {
16571       if (DSAStack->getParentOrderedRegionParam().first &&
16572           DepCounter >= TotalDepCount) {
16573         Diag(ELoc, diag::err_omp_depend_sink_unexpected_expr);
16574         continue;
16575       }
16576       ++DepCounter;
16577       // OpenMP  [2.13.9, Summary]
16578       // depend(dependence-type : vec), where dependence-type is:
16579       // 'sink' and where vec is the iteration vector, which has the form:
16580       //  x1 [+- d1], x2 [+- d2 ], . . . , xn [+- dn]
16581       // where n is the value specified by the ordered clause in the loop
16582       // directive, xi denotes the loop iteration variable of the i-th nested
16583       // loop associated with the loop directive, and di is a constant
16584       // non-negative integer.
16585       if (CurContext->isDependentContext()) {
16586         // It will be analyzed later.
16587         Vars.push_back(RefExpr);
16588         continue;
16589       }
16590       SimpleExpr = SimpleExpr->IgnoreImplicit();
16591       OverloadedOperatorKind OOK = OO_None;
16592       SourceLocation OOLoc;
16593       Expr *LHS = SimpleExpr;
16594       Expr *RHS = nullptr;
16595       if (auto *BO = dyn_cast<BinaryOperator>(SimpleExpr)) {
16596         OOK = BinaryOperator::getOverloadedOperator(BO->getOpcode());
16597         OOLoc = BO->getOperatorLoc();
16598         LHS = BO->getLHS()->IgnoreParenImpCasts();
16599         RHS = BO->getRHS()->IgnoreParenImpCasts();
16600       } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(SimpleExpr)) {
16601         OOK = OCE->getOperator();
16602         OOLoc = OCE->getOperatorLoc();
16603         LHS = OCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
16604         RHS = OCE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
16605       } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SimpleExpr)) {
16606         OOK = MCE->getMethodDecl()
16607                   ->getNameInfo()
16608                   .getName()
16609                   .getCXXOverloadedOperator();
16610         OOLoc = MCE->getCallee()->getExprLoc();
16611         LHS = MCE->getImplicitObjectArgument()->IgnoreParenImpCasts();
16612         RHS = MCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
16613       }
16614       SourceLocation ELoc;
16615       SourceRange ERange;
16616       auto Res = getPrivateItem(*this, LHS, ELoc, ERange);
16617       if (Res.second) {
16618         // It will be analyzed later.
16619         Vars.push_back(RefExpr);
16620       }
16621       ValueDecl *D = Res.first;
16622       if (!D)
16623         continue;
16624 
16625       if (OOK != OO_Plus && OOK != OO_Minus && (RHS || OOK != OO_None)) {
16626         Diag(OOLoc, diag::err_omp_depend_sink_expected_plus_minus);
16627         continue;
16628       }
16629       if (RHS) {
16630         ExprResult RHSRes = VerifyPositiveIntegerConstantInClause(
16631             RHS, OMPC_depend, /*StrictlyPositive=*/false);
16632         if (RHSRes.isInvalid())
16633           continue;
16634       }
16635       if (!CurContext->isDependentContext() &&
16636           DSAStack->getParentOrderedRegionParam().first &&
16637           DepCounter != DSAStack->isParentLoopControlVariable(D).first) {
16638         const ValueDecl *VD =
16639             DSAStack->getParentLoopControlVariable(DepCounter.getZExtValue());
16640         if (VD)
16641           Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration)
16642               << 1 << VD;
16643         else
16644           Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration) << 0;
16645         continue;
16646       }
16647       OpsOffs.emplace_back(RHS, OOK);
16648     } else {
16649       bool OMPDependTFound = LangOpts.OpenMP >= 50;
16650       if (OMPDependTFound)
16651         OMPDependTFound = findOMPDependT(*this, StartLoc, DSAStack,
16652                                          DepKind == OMPC_DEPEND_depobj);
16653       if (DepKind == OMPC_DEPEND_depobj) {
16654         // OpenMP 5.0, 2.17.11 depend Clause, Restrictions, C/C++
16655         // List items used in depend clauses with the depobj dependence type
16656         // must be expressions of the omp_depend_t type.
16657         if (!RefExpr->isValueDependent() && !RefExpr->isTypeDependent() &&
16658             !RefExpr->isInstantiationDependent() &&
16659             !RefExpr->containsUnexpandedParameterPack() &&
16660             (OMPDependTFound &&
16661              !Context.hasSameUnqualifiedType(DSAStack->getOMPDependT(),
16662                                              RefExpr->getType()))) {
16663           Diag(ELoc, diag::err_omp_expected_omp_depend_t_lvalue)
16664               << 0 << RefExpr->getType() << RefExpr->getSourceRange();
16665           continue;
16666         }
16667         if (!RefExpr->isLValue()) {
16668           Diag(ELoc, diag::err_omp_expected_omp_depend_t_lvalue)
16669               << 1 << RefExpr->getType() << RefExpr->getSourceRange();
16670           continue;
16671         }
16672       } else {
16673         // OpenMP 5.0 [2.17.11, Restrictions]
16674         // List items used in depend clauses cannot be zero-length array
16675         // sections.
16676         QualType ExprTy = RefExpr->getType().getNonReferenceType();
16677         const auto *OASE = dyn_cast<OMPArraySectionExpr>(SimpleExpr);
16678         if (OASE) {
16679           QualType BaseType =
16680               OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
16681           if (const auto *ATy = BaseType->getAsArrayTypeUnsafe())
16682             ExprTy = ATy->getElementType();
16683           else
16684             ExprTy = BaseType->getPointeeType();
16685           ExprTy = ExprTy.getNonReferenceType();
16686           const Expr *Length = OASE->getLength();
16687           Expr::EvalResult Result;
16688           if (Length && !Length->isValueDependent() &&
16689               Length->EvaluateAsInt(Result, Context) &&
16690               Result.Val.getInt().isNullValue()) {
16691             Diag(ELoc,
16692                  diag::err_omp_depend_zero_length_array_section_not_allowed)
16693                 << SimpleExpr->getSourceRange();
16694             continue;
16695           }
16696         }
16697 
16698         // OpenMP 5.0, 2.17.11 depend Clause, Restrictions, C/C++
16699         // List items used in depend clauses with the in, out, inout or
16700         // mutexinoutset dependence types cannot be expressions of the
16701         // omp_depend_t type.
16702         if (!RefExpr->isValueDependent() && !RefExpr->isTypeDependent() &&
16703             !RefExpr->isInstantiationDependent() &&
16704             !RefExpr->containsUnexpandedParameterPack() &&
16705             (OMPDependTFound &&
16706              DSAStack->getOMPDependT().getTypePtr() == ExprTy.getTypePtr())) {
16707           Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
16708               << (LangOpts.OpenMP >= 50 ? 1 : 0) << 1
16709               << RefExpr->getSourceRange();
16710           continue;
16711         }
16712 
16713         auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr);
16714         if (!RefExpr->IgnoreParenImpCasts()->isLValue() ||
16715             (ASE && !ASE->getBase()->isTypeDependent() &&
16716              !ASE->getBase()
16717                   ->getType()
16718                   .getNonReferenceType()
16719                   ->isPointerType() &&
16720              !ASE->getBase()->getType().getNonReferenceType()->isArrayType())) {
16721           Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
16722               << (LangOpts.OpenMP >= 50 ? 1 : 0)
16723               << (LangOpts.OpenMP >= 50 ? 1 : 0) << RefExpr->getSourceRange();
16724           continue;
16725         }
16726 
16727         ExprResult Res;
16728         {
16729           Sema::TentativeAnalysisScope Trap(*this);
16730           Res = CreateBuiltinUnaryOp(ELoc, UO_AddrOf,
16731                                      RefExpr->IgnoreParenImpCasts());
16732         }
16733         if (!Res.isUsable() && !isa<OMPArraySectionExpr>(SimpleExpr) &&
16734             !isa<OMPArrayShapingExpr>(SimpleExpr)) {
16735           Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
16736               << (LangOpts.OpenMP >= 50 ? 1 : 0)
16737               << (LangOpts.OpenMP >= 50 ? 1 : 0) << RefExpr->getSourceRange();
16738           continue;
16739         }
16740       }
16741     }
16742     Vars.push_back(RefExpr->IgnoreParenImpCasts());
16743   }
16744 
16745   if (!CurContext->isDependentContext() && DepKind == OMPC_DEPEND_sink &&
16746       TotalDepCount > VarList.size() &&
16747       DSAStack->getParentOrderedRegionParam().first &&
16748       DSAStack->getParentLoopControlVariable(VarList.size() + 1)) {
16749     Diag(EndLoc, diag::err_omp_depend_sink_expected_loop_iteration)
16750         << 1 << DSAStack->getParentLoopControlVariable(VarList.size() + 1);
16751   }
16752   if (DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink &&
16753       Vars.empty())
16754     return nullptr;
16755 
16756   auto *C = OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc,
16757                                     DepModifier, DepKind, DepLoc, ColonLoc,
16758                                     Vars, TotalDepCount.getZExtValue());
16759   if ((DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) &&
16760       DSAStack->isParentOrderedRegion())
16761     DSAStack->addDoacrossDependClause(C, OpsOffs);
16762   return C;
16763 }
16764 
16765 OMPClause *Sema::ActOnOpenMPDeviceClause(OpenMPDeviceClauseModifier Modifier,
16766                                          Expr *Device, SourceLocation StartLoc,
16767                                          SourceLocation LParenLoc,
16768                                          SourceLocation ModifierLoc,
16769                                          SourceLocation EndLoc) {
16770   assert((ModifierLoc.isInvalid() || LangOpts.OpenMP >= 50) &&
16771          "Unexpected device modifier in OpenMP < 50.");
16772 
16773   bool ErrorFound = false;
16774   if (ModifierLoc.isValid() && Modifier == OMPC_DEVICE_unknown) {
16775     std::string Values =
16776         getListOfPossibleValues(OMPC_device, /*First=*/0, OMPC_DEVICE_unknown);
16777     Diag(ModifierLoc, diag::err_omp_unexpected_clause_value)
16778         << Values << getOpenMPClauseName(OMPC_device);
16779     ErrorFound = true;
16780   }
16781 
16782   Expr *ValExpr = Device;
16783   Stmt *HelperValStmt = nullptr;
16784 
16785   // OpenMP [2.9.1, Restrictions]
16786   // The device expression must evaluate to a non-negative integer value.
16787   ErrorFound = !isNonNegativeIntegerValue(ValExpr, *this, OMPC_device,
16788                                           /*StrictlyPositive=*/false) ||
16789                ErrorFound;
16790   if (ErrorFound)
16791     return nullptr;
16792 
16793   OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
16794   OpenMPDirectiveKind CaptureRegion =
16795       getOpenMPCaptureRegionForClause(DKind, OMPC_device, LangOpts.OpenMP);
16796   if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
16797     ValExpr = MakeFullExpr(ValExpr).get();
16798     llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
16799     ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
16800     HelperValStmt = buildPreInits(Context, Captures);
16801   }
16802 
16803   return new (Context)
16804       OMPDeviceClause(Modifier, ValExpr, HelperValStmt, CaptureRegion, StartLoc,
16805                       LParenLoc, ModifierLoc, EndLoc);
16806 }
16807 
16808 static bool checkTypeMappable(SourceLocation SL, SourceRange SR, Sema &SemaRef,
16809                               DSAStackTy *Stack, QualType QTy,
16810                               bool FullCheck = true) {
16811   NamedDecl *ND;
16812   if (QTy->isIncompleteType(&ND)) {
16813     SemaRef.Diag(SL, diag::err_incomplete_type) << QTy << SR;
16814     return false;
16815   }
16816   if (FullCheck && !SemaRef.CurContext->isDependentContext() &&
16817       !QTy.isTriviallyCopyableType(SemaRef.Context))
16818     SemaRef.Diag(SL, diag::warn_omp_non_trivial_type_mapped) << QTy << SR;
16819   return true;
16820 }
16821 
16822 /// Return true if it can be proven that the provided array expression
16823 /// (array section or array subscript) does NOT specify the whole size of the
16824 /// array whose base type is \a BaseQTy.
16825 static bool checkArrayExpressionDoesNotReferToWholeSize(Sema &SemaRef,
16826                                                         const Expr *E,
16827                                                         QualType BaseQTy) {
16828   const auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
16829 
16830   // If this is an array subscript, it refers to the whole size if the size of
16831   // the dimension is constant and equals 1. Also, an array section assumes the
16832   // format of an array subscript if no colon is used.
16833   if (isa<ArraySubscriptExpr>(E) ||
16834       (OASE && OASE->getColonLocFirst().isInvalid())) {
16835     if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
16836       return ATy->getSize().getSExtValue() != 1;
16837     // Size can't be evaluated statically.
16838     return false;
16839   }
16840 
16841   assert(OASE && "Expecting array section if not an array subscript.");
16842   const Expr *LowerBound = OASE->getLowerBound();
16843   const Expr *Length = OASE->getLength();
16844 
16845   // If there is a lower bound that does not evaluates to zero, we are not
16846   // covering the whole dimension.
16847   if (LowerBound) {
16848     Expr::EvalResult Result;
16849     if (!LowerBound->EvaluateAsInt(Result, SemaRef.getASTContext()))
16850       return false; // Can't get the integer value as a constant.
16851 
16852     llvm::APSInt ConstLowerBound = Result.Val.getInt();
16853     if (ConstLowerBound.getSExtValue())
16854       return true;
16855   }
16856 
16857   // If we don't have a length we covering the whole dimension.
16858   if (!Length)
16859     return false;
16860 
16861   // If the base is a pointer, we don't have a way to get the size of the
16862   // pointee.
16863   if (BaseQTy->isPointerType())
16864     return false;
16865 
16866   // We can only check if the length is the same as the size of the dimension
16867   // if we have a constant array.
16868   const auto *CATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr());
16869   if (!CATy)
16870     return false;
16871 
16872   Expr::EvalResult Result;
16873   if (!Length->EvaluateAsInt(Result, SemaRef.getASTContext()))
16874     return false; // Can't get the integer value as a constant.
16875 
16876   llvm::APSInt ConstLength = Result.Val.getInt();
16877   return CATy->getSize().getSExtValue() != ConstLength.getSExtValue();
16878 }
16879 
16880 // Return true if it can be proven that the provided array expression (array
16881 // section or array subscript) does NOT specify a single element of the array
16882 // whose base type is \a BaseQTy.
16883 static bool checkArrayExpressionDoesNotReferToUnitySize(Sema &SemaRef,
16884                                                         const Expr *E,
16885                                                         QualType BaseQTy) {
16886   const auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
16887 
16888   // An array subscript always refer to a single element. Also, an array section
16889   // assumes the format of an array subscript if no colon is used.
16890   if (isa<ArraySubscriptExpr>(E) ||
16891       (OASE && OASE->getColonLocFirst().isInvalid()))
16892     return false;
16893 
16894   assert(OASE && "Expecting array section if not an array subscript.");
16895   const Expr *Length = OASE->getLength();
16896 
16897   // If we don't have a length we have to check if the array has unitary size
16898   // for this dimension. Also, we should always expect a length if the base type
16899   // is pointer.
16900   if (!Length) {
16901     if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
16902       return ATy->getSize().getSExtValue() != 1;
16903     // We cannot assume anything.
16904     return false;
16905   }
16906 
16907   // Check if the length evaluates to 1.
16908   Expr::EvalResult Result;
16909   if (!Length->EvaluateAsInt(Result, SemaRef.getASTContext()))
16910     return false; // Can't get the integer value as a constant.
16911 
16912   llvm::APSInt ConstLength = Result.Val.getInt();
16913   return ConstLength.getSExtValue() != 1;
16914 }
16915 
16916 // The base of elements of list in a map clause have to be either:
16917 //  - a reference to variable or field.
16918 //  - a member expression.
16919 //  - an array expression.
16920 //
16921 // E.g. if we have the expression 'r.S.Arr[:12]', we want to retrieve the
16922 // reference to 'r'.
16923 //
16924 // If we have:
16925 //
16926 // struct SS {
16927 //   Bla S;
16928 //   foo() {
16929 //     #pragma omp target map (S.Arr[:12]);
16930 //   }
16931 // }
16932 //
16933 // We want to retrieve the member expression 'this->S';
16934 
16935 // OpenMP 5.0 [2.19.7.1, map Clause, Restrictions, p.2]
16936 //  If a list item is an array section, it must specify contiguous storage.
16937 //
16938 // For this restriction it is sufficient that we make sure only references
16939 // to variables or fields and array expressions, and that no array sections
16940 // exist except in the rightmost expression (unless they cover the whole
16941 // dimension of the array). E.g. these would be invalid:
16942 //
16943 //   r.ArrS[3:5].Arr[6:7]
16944 //
16945 //   r.ArrS[3:5].x
16946 //
16947 // but these would be valid:
16948 //   r.ArrS[3].Arr[6:7]
16949 //
16950 //   r.ArrS[3].x
16951 namespace {
16952 class MapBaseChecker final : public StmtVisitor<MapBaseChecker, bool> {
16953   Sema &SemaRef;
16954   OpenMPClauseKind CKind = OMPC_unknown;
16955   OpenMPDirectiveKind DKind = OMPD_unknown;
16956   OMPClauseMappableExprCommon::MappableExprComponentList &Components;
16957   bool IsNonContiguous = false;
16958   bool NoDiagnose = false;
16959   const Expr *RelevantExpr = nullptr;
16960   bool AllowUnitySizeArraySection = true;
16961   bool AllowWholeSizeArraySection = true;
16962   bool AllowAnotherPtr = true;
16963   SourceLocation ELoc;
16964   SourceRange ERange;
16965 
16966   void emitErrorMsg() {
16967     // If nothing else worked, this is not a valid map clause expression.
16968     if (SemaRef.getLangOpts().OpenMP < 50) {
16969       SemaRef.Diag(ELoc,
16970                    diag::err_omp_expected_named_var_member_or_array_expression)
16971           << ERange;
16972     } else {
16973       SemaRef.Diag(ELoc, diag::err_omp_non_lvalue_in_map_or_motion_clauses)
16974           << getOpenMPClauseName(CKind) << ERange;
16975     }
16976   }
16977 
16978 public:
16979   bool VisitDeclRefExpr(DeclRefExpr *DRE) {
16980     if (!isa<VarDecl>(DRE->getDecl())) {
16981       emitErrorMsg();
16982       return false;
16983     }
16984     assert(!RelevantExpr && "RelevantExpr is expected to be nullptr");
16985     RelevantExpr = DRE;
16986     // Record the component.
16987     Components.emplace_back(DRE, DRE->getDecl(), IsNonContiguous);
16988     return true;
16989   }
16990 
16991   bool VisitMemberExpr(MemberExpr *ME) {
16992     Expr *E = ME;
16993     Expr *BaseE = ME->getBase()->IgnoreParenCasts();
16994 
16995     if (isa<CXXThisExpr>(BaseE)) {
16996       assert(!RelevantExpr && "RelevantExpr is expected to be nullptr");
16997       // We found a base expression: this->Val.
16998       RelevantExpr = ME;
16999     } else {
17000       E = BaseE;
17001     }
17002 
17003     if (!isa<FieldDecl>(ME->getMemberDecl())) {
17004       if (!NoDiagnose) {
17005         SemaRef.Diag(ELoc, diag::err_omp_expected_access_to_data_field)
17006           << ME->getSourceRange();
17007         return false;
17008       }
17009       if (RelevantExpr)
17010         return false;
17011       return Visit(E);
17012     }
17013 
17014     auto *FD = cast<FieldDecl>(ME->getMemberDecl());
17015 
17016     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
17017     //  A bit-field cannot appear in a map clause.
17018     //
17019     if (FD->isBitField()) {
17020       if (!NoDiagnose) {
17021         SemaRef.Diag(ELoc, diag::err_omp_bit_fields_forbidden_in_clause)
17022           << ME->getSourceRange() << getOpenMPClauseName(CKind);
17023         return false;
17024       }
17025       if (RelevantExpr)
17026         return false;
17027       return Visit(E);
17028     }
17029 
17030     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
17031     //  If the type of a list item is a reference to a type T then the type
17032     //  will be considered to be T for all purposes of this clause.
17033     QualType CurType = BaseE->getType().getNonReferenceType();
17034 
17035     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.2]
17036     //  A list item cannot be a variable that is a member of a structure with
17037     //  a union type.
17038     //
17039     if (CurType->isUnionType()) {
17040       if (!NoDiagnose) {
17041         SemaRef.Diag(ELoc, diag::err_omp_union_type_not_allowed)
17042           << ME->getSourceRange();
17043         return false;
17044       }
17045       return RelevantExpr || Visit(E);
17046     }
17047 
17048     // If we got a member expression, we should not expect any array section
17049     // before that:
17050     //
17051     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.7]
17052     //  If a list item is an element of a structure, only the rightmost symbol
17053     //  of the variable reference can be an array section.
17054     //
17055     AllowUnitySizeArraySection = false;
17056     AllowWholeSizeArraySection = false;
17057 
17058     // Record the component.
17059     Components.emplace_back(ME, FD, IsNonContiguous);
17060     return RelevantExpr || Visit(E);
17061   }
17062 
17063   bool VisitArraySubscriptExpr(ArraySubscriptExpr *AE) {
17064     Expr *E = AE->getBase()->IgnoreParenImpCasts();
17065 
17066     if (!E->getType()->isAnyPointerType() && !E->getType()->isArrayType()) {
17067       if (!NoDiagnose) {
17068         SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
17069           << 0 << AE->getSourceRange();
17070         return false;
17071       }
17072       return RelevantExpr || Visit(E);
17073     }
17074 
17075     // If we got an array subscript that express the whole dimension we
17076     // can have any array expressions before. If it only expressing part of
17077     // the dimension, we can only have unitary-size array expressions.
17078     if (checkArrayExpressionDoesNotReferToWholeSize(SemaRef, AE,
17079                                                     E->getType()))
17080       AllowWholeSizeArraySection = false;
17081 
17082     if (const auto *TE = dyn_cast<CXXThisExpr>(E->IgnoreParenCasts())) {
17083       Expr::EvalResult Result;
17084       if (!AE->getIdx()->isValueDependent() &&
17085           AE->getIdx()->EvaluateAsInt(Result, SemaRef.getASTContext()) &&
17086           !Result.Val.getInt().isNullValue()) {
17087         SemaRef.Diag(AE->getIdx()->getExprLoc(),
17088                      diag::err_omp_invalid_map_this_expr);
17089         SemaRef.Diag(AE->getIdx()->getExprLoc(),
17090                      diag::note_omp_invalid_subscript_on_this_ptr_map);
17091       }
17092       assert(!RelevantExpr && "RelevantExpr is expected to be nullptr");
17093       RelevantExpr = TE;
17094     }
17095 
17096     // Record the component - we don't have any declaration associated.
17097     Components.emplace_back(AE, nullptr, IsNonContiguous);
17098 
17099     return RelevantExpr || Visit(E);
17100   }
17101 
17102   bool VisitOMPArraySectionExpr(OMPArraySectionExpr *OASE) {
17103     assert(!NoDiagnose && "Array sections cannot be implicitly mapped.");
17104     Expr *E = OASE->getBase()->IgnoreParenImpCasts();
17105     QualType CurType =
17106       OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
17107 
17108     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
17109     //  If the type of a list item is a reference to a type T then the type
17110     //  will be considered to be T for all purposes of this clause.
17111     if (CurType->isReferenceType())
17112       CurType = CurType->getPointeeType();
17113 
17114     bool IsPointer = CurType->isAnyPointerType();
17115 
17116     if (!IsPointer && !CurType->isArrayType()) {
17117       SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
17118         << 0 << OASE->getSourceRange();
17119       return false;
17120     }
17121 
17122     bool NotWhole =
17123       checkArrayExpressionDoesNotReferToWholeSize(SemaRef, OASE, CurType);
17124     bool NotUnity =
17125       checkArrayExpressionDoesNotReferToUnitySize(SemaRef, OASE, CurType);
17126 
17127     if (AllowWholeSizeArraySection) {
17128       // Any array section is currently allowed. Allowing a whole size array
17129       // section implies allowing a unity array section as well.
17130       //
17131       // If this array section refers to the whole dimension we can still
17132       // accept other array sections before this one, except if the base is a
17133       // pointer. Otherwise, only unitary sections are accepted.
17134       if (NotWhole || IsPointer)
17135         AllowWholeSizeArraySection = false;
17136     } else if (DKind == OMPD_target_update &&
17137                SemaRef.getLangOpts().OpenMP >= 50) {
17138       if (IsPointer && !AllowAnotherPtr)
17139         SemaRef.Diag(ELoc, diag::err_omp_section_length_undefined)
17140             << /*array of unknown bound */ 1;
17141       else
17142         IsNonContiguous = true;
17143     } else if (AllowUnitySizeArraySection && NotUnity) {
17144       // A unity or whole array section is not allowed and that is not
17145       // compatible with the properties of the current array section.
17146       SemaRef.Diag(
17147         ELoc, diag::err_array_section_does_not_specify_contiguous_storage)
17148         << OASE->getSourceRange();
17149       return false;
17150     }
17151 
17152     if (IsPointer)
17153       AllowAnotherPtr = false;
17154 
17155     if (const auto *TE = dyn_cast<CXXThisExpr>(E)) {
17156       Expr::EvalResult ResultR;
17157       Expr::EvalResult ResultL;
17158       if (!OASE->getLength()->isValueDependent() &&
17159           OASE->getLength()->EvaluateAsInt(ResultR, SemaRef.getASTContext()) &&
17160           !ResultR.Val.getInt().isOneValue()) {
17161         SemaRef.Diag(OASE->getLength()->getExprLoc(),
17162                      diag::err_omp_invalid_map_this_expr);
17163         SemaRef.Diag(OASE->getLength()->getExprLoc(),
17164                      diag::note_omp_invalid_length_on_this_ptr_mapping);
17165       }
17166       if (OASE->getLowerBound() && !OASE->getLowerBound()->isValueDependent() &&
17167           OASE->getLowerBound()->EvaluateAsInt(ResultL,
17168                                                SemaRef.getASTContext()) &&
17169           !ResultL.Val.getInt().isNullValue()) {
17170         SemaRef.Diag(OASE->getLowerBound()->getExprLoc(),
17171                      diag::err_omp_invalid_map_this_expr);
17172         SemaRef.Diag(OASE->getLowerBound()->getExprLoc(),
17173                      diag::note_omp_invalid_lower_bound_on_this_ptr_mapping);
17174       }
17175       assert(!RelevantExpr && "RelevantExpr is expected to be nullptr");
17176       RelevantExpr = TE;
17177     }
17178 
17179     // Record the component - we don't have any declaration associated.
17180     Components.emplace_back(OASE, nullptr, /*IsNonContiguous=*/false);
17181     return RelevantExpr || Visit(E);
17182   }
17183   bool VisitOMPArrayShapingExpr(OMPArrayShapingExpr *E) {
17184     Expr *Base = E->getBase();
17185 
17186     // Record the component - we don't have any declaration associated.
17187     Components.emplace_back(E, nullptr, IsNonContiguous);
17188 
17189     return Visit(Base->IgnoreParenImpCasts());
17190   }
17191 
17192   bool VisitUnaryOperator(UnaryOperator *UO) {
17193     if (SemaRef.getLangOpts().OpenMP < 50 || !UO->isLValue() ||
17194         UO->getOpcode() != UO_Deref) {
17195       emitErrorMsg();
17196       return false;
17197     }
17198     if (!RelevantExpr) {
17199       // Record the component if haven't found base decl.
17200       Components.emplace_back(UO, nullptr, /*IsNonContiguous=*/false);
17201     }
17202     return RelevantExpr || Visit(UO->getSubExpr()->IgnoreParenImpCasts());
17203   }
17204   bool VisitBinaryOperator(BinaryOperator *BO) {
17205     if (SemaRef.getLangOpts().OpenMP < 50 || !BO->getType()->isPointerType()) {
17206       emitErrorMsg();
17207       return false;
17208     }
17209 
17210     // Pointer arithmetic is the only thing we expect to happen here so after we
17211     // make sure the binary operator is a pointer type, the we only thing need
17212     // to to is to visit the subtree that has the same type as root (so that we
17213     // know the other subtree is just an offset)
17214     Expr *LE = BO->getLHS()->IgnoreParenImpCasts();
17215     Expr *RE = BO->getRHS()->IgnoreParenImpCasts();
17216     Components.emplace_back(BO, nullptr, false);
17217     assert((LE->getType().getTypePtr() == BO->getType().getTypePtr() ||
17218             RE->getType().getTypePtr() == BO->getType().getTypePtr()) &&
17219            "Either LHS or RHS have base decl inside");
17220     if (BO->getType().getTypePtr() == LE->getType().getTypePtr())
17221       return RelevantExpr || Visit(LE);
17222     return RelevantExpr || Visit(RE);
17223   }
17224   bool VisitCXXThisExpr(CXXThisExpr *CTE) {
17225     assert(!RelevantExpr && "RelevantExpr is expected to be nullptr");
17226     RelevantExpr = CTE;
17227     Components.emplace_back(CTE, nullptr, IsNonContiguous);
17228     return true;
17229   }
17230   bool VisitCXXOperatorCallExpr(CXXOperatorCallExpr *COCE) {
17231     assert(!RelevantExpr && "RelevantExpr is expected to be nullptr");
17232     Components.emplace_back(COCE, nullptr, IsNonContiguous);
17233     return true;
17234   }
17235   bool VisitStmt(Stmt *) {
17236     emitErrorMsg();
17237     return false;
17238   }
17239   const Expr *getFoundBase() const {
17240     return RelevantExpr;
17241   }
17242   explicit MapBaseChecker(
17243       Sema &SemaRef, OpenMPClauseKind CKind, OpenMPDirectiveKind DKind,
17244       OMPClauseMappableExprCommon::MappableExprComponentList &Components,
17245       bool NoDiagnose, SourceLocation &ELoc, SourceRange &ERange)
17246       : SemaRef(SemaRef), CKind(CKind), DKind(DKind), Components(Components),
17247         NoDiagnose(NoDiagnose), ELoc(ELoc), ERange(ERange) {}
17248 };
17249 } // namespace
17250 
17251 /// Return the expression of the base of the mappable expression or null if it
17252 /// cannot be determined and do all the necessary checks to see if the expression
17253 /// is valid as a standalone mappable expression. In the process, record all the
17254 /// components of the expression.
17255 static const Expr *checkMapClauseExpressionBase(
17256     Sema &SemaRef, Expr *E,
17257     OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
17258     OpenMPClauseKind CKind, OpenMPDirectiveKind DKind, bool NoDiagnose) {
17259   SourceLocation ELoc = E->getExprLoc();
17260   SourceRange ERange = E->getSourceRange();
17261   MapBaseChecker Checker(SemaRef, CKind, DKind, CurComponents, NoDiagnose, ELoc,
17262                          ERange);
17263   if (Checker.Visit(E->IgnoreParens())) {
17264     // Check if the highest dimension array section has length specified
17265     if (SemaRef.getLangOpts().OpenMP >= 50 && !CurComponents.empty() &&
17266         (CKind == OMPC_to || CKind == OMPC_from)) {
17267       auto CI = CurComponents.rbegin();
17268       auto CE = CurComponents.rend();
17269       for (; CI != CE; ++CI) {
17270         const auto *OASE =
17271             dyn_cast<OMPArraySectionExpr>(CI->getAssociatedExpression());
17272         if (!OASE)
17273           continue;
17274         if (OASE && OASE->getLength())
17275           break;
17276         SemaRef.Diag(ELoc, diag::err_array_section_does_not_specify_length)
17277             << ERange;
17278       }
17279     }
17280     return Checker.getFoundBase();
17281   }
17282   return nullptr;
17283 }
17284 
17285 // Return true if expression E associated with value VD has conflicts with other
17286 // map information.
17287 static bool checkMapConflicts(
17288     Sema &SemaRef, DSAStackTy *DSAS, const ValueDecl *VD, const Expr *E,
17289     bool CurrentRegionOnly,
17290     OMPClauseMappableExprCommon::MappableExprComponentListRef CurComponents,
17291     OpenMPClauseKind CKind) {
17292   assert(VD && E);
17293   SourceLocation ELoc = E->getExprLoc();
17294   SourceRange ERange = E->getSourceRange();
17295 
17296   // In order to easily check the conflicts we need to match each component of
17297   // the expression under test with the components of the expressions that are
17298   // already in the stack.
17299 
17300   assert(!CurComponents.empty() && "Map clause expression with no components!");
17301   assert(CurComponents.back().getAssociatedDeclaration() == VD &&
17302          "Map clause expression with unexpected base!");
17303 
17304   // Variables to help detecting enclosing problems in data environment nests.
17305   bool IsEnclosedByDataEnvironmentExpr = false;
17306   const Expr *EnclosingExpr = nullptr;
17307 
17308   bool FoundError = DSAS->checkMappableExprComponentListsForDecl(
17309       VD, CurrentRegionOnly,
17310       [&IsEnclosedByDataEnvironmentExpr, &SemaRef, VD, CurrentRegionOnly, ELoc,
17311        ERange, CKind, &EnclosingExpr,
17312        CurComponents](OMPClauseMappableExprCommon::MappableExprComponentListRef
17313                           StackComponents,
17314                       OpenMPClauseKind) {
17315         assert(!StackComponents.empty() &&
17316                "Map clause expression with no components!");
17317         assert(StackComponents.back().getAssociatedDeclaration() == VD &&
17318                "Map clause expression with unexpected base!");
17319         (void)VD;
17320 
17321         // The whole expression in the stack.
17322         const Expr *RE = StackComponents.front().getAssociatedExpression();
17323 
17324         // Expressions must start from the same base. Here we detect at which
17325         // point both expressions diverge from each other and see if we can
17326         // detect if the memory referred to both expressions is contiguous and
17327         // do not overlap.
17328         auto CI = CurComponents.rbegin();
17329         auto CE = CurComponents.rend();
17330         auto SI = StackComponents.rbegin();
17331         auto SE = StackComponents.rend();
17332         for (; CI != CE && SI != SE; ++CI, ++SI) {
17333 
17334           // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.3]
17335           //  At most one list item can be an array item derived from a given
17336           //  variable in map clauses of the same construct.
17337           if (CurrentRegionOnly &&
17338               (isa<ArraySubscriptExpr>(CI->getAssociatedExpression()) ||
17339                isa<OMPArraySectionExpr>(CI->getAssociatedExpression()) ||
17340                isa<OMPArrayShapingExpr>(CI->getAssociatedExpression())) &&
17341               (isa<ArraySubscriptExpr>(SI->getAssociatedExpression()) ||
17342                isa<OMPArraySectionExpr>(SI->getAssociatedExpression()) ||
17343                isa<OMPArrayShapingExpr>(SI->getAssociatedExpression()))) {
17344             SemaRef.Diag(CI->getAssociatedExpression()->getExprLoc(),
17345                          diag::err_omp_multiple_array_items_in_map_clause)
17346                 << CI->getAssociatedExpression()->getSourceRange();
17347             SemaRef.Diag(SI->getAssociatedExpression()->getExprLoc(),
17348                          diag::note_used_here)
17349                 << SI->getAssociatedExpression()->getSourceRange();
17350             return true;
17351           }
17352 
17353           // Do both expressions have the same kind?
17354           if (CI->getAssociatedExpression()->getStmtClass() !=
17355               SI->getAssociatedExpression()->getStmtClass())
17356             break;
17357 
17358           // Are we dealing with different variables/fields?
17359           if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration())
17360             break;
17361         }
17362         // Check if the extra components of the expressions in the enclosing
17363         // data environment are redundant for the current base declaration.
17364         // If they are, the maps completely overlap, which is legal.
17365         for (; SI != SE; ++SI) {
17366           QualType Type;
17367           if (const auto *ASE =
17368                   dyn_cast<ArraySubscriptExpr>(SI->getAssociatedExpression())) {
17369             Type = ASE->getBase()->IgnoreParenImpCasts()->getType();
17370           } else if (const auto *OASE = dyn_cast<OMPArraySectionExpr>(
17371                          SI->getAssociatedExpression())) {
17372             const Expr *E = OASE->getBase()->IgnoreParenImpCasts();
17373             Type =
17374                 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
17375           } else if (const auto *OASE = dyn_cast<OMPArrayShapingExpr>(
17376                          SI->getAssociatedExpression())) {
17377             Type = OASE->getBase()->getType()->getPointeeType();
17378           }
17379           if (Type.isNull() || Type->isAnyPointerType() ||
17380               checkArrayExpressionDoesNotReferToWholeSize(
17381                   SemaRef, SI->getAssociatedExpression(), Type))
17382             break;
17383         }
17384 
17385         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
17386         //  List items of map clauses in the same construct must not share
17387         //  original storage.
17388         //
17389         // If the expressions are exactly the same or one is a subset of the
17390         // other, it means they are sharing storage.
17391         if (CI == CE && SI == SE) {
17392           if (CurrentRegionOnly) {
17393             if (CKind == OMPC_map) {
17394               SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
17395             } else {
17396               assert(CKind == OMPC_to || CKind == OMPC_from);
17397               SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
17398                   << ERange;
17399             }
17400             SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
17401                 << RE->getSourceRange();
17402             return true;
17403           }
17404           // If we find the same expression in the enclosing data environment,
17405           // that is legal.
17406           IsEnclosedByDataEnvironmentExpr = true;
17407           return false;
17408         }
17409 
17410         QualType DerivedType =
17411             std::prev(CI)->getAssociatedDeclaration()->getType();
17412         SourceLocation DerivedLoc =
17413             std::prev(CI)->getAssociatedExpression()->getExprLoc();
17414 
17415         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
17416         //  If the type of a list item is a reference to a type T then the type
17417         //  will be considered to be T for all purposes of this clause.
17418         DerivedType = DerivedType.getNonReferenceType();
17419 
17420         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.1]
17421         //  A variable for which the type is pointer and an array section
17422         //  derived from that variable must not appear as list items of map
17423         //  clauses of the same construct.
17424         //
17425         // Also, cover one of the cases in:
17426         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
17427         //  If any part of the original storage of a list item has corresponding
17428         //  storage in the device data environment, all of the original storage
17429         //  must have corresponding storage in the device data environment.
17430         //
17431         if (DerivedType->isAnyPointerType()) {
17432           if (CI == CE || SI == SE) {
17433             SemaRef.Diag(
17434                 DerivedLoc,
17435                 diag::err_omp_pointer_mapped_along_with_derived_section)
17436                 << DerivedLoc;
17437             SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
17438                 << RE->getSourceRange();
17439             return true;
17440           }
17441           if (CI->getAssociatedExpression()->getStmtClass() !=
17442                          SI->getAssociatedExpression()->getStmtClass() ||
17443                      CI->getAssociatedDeclaration()->getCanonicalDecl() ==
17444                          SI->getAssociatedDeclaration()->getCanonicalDecl()) {
17445             assert(CI != CE && SI != SE);
17446             SemaRef.Diag(DerivedLoc, diag::err_omp_same_pointer_dereferenced)
17447                 << DerivedLoc;
17448             SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
17449                 << RE->getSourceRange();
17450             return true;
17451           }
17452         }
17453 
17454         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
17455         //  List items of map clauses in the same construct must not share
17456         //  original storage.
17457         //
17458         // An expression is a subset of the other.
17459         if (CurrentRegionOnly && (CI == CE || SI == SE)) {
17460           if (CKind == OMPC_map) {
17461             if (CI != CE || SI != SE) {
17462               // Allow constructs like this: map(s, s.ptr[0:1]), where s.ptr is
17463               // a pointer.
17464               auto Begin =
17465                   CI != CE ? CurComponents.begin() : StackComponents.begin();
17466               auto End = CI != CE ? CurComponents.end() : StackComponents.end();
17467               auto It = Begin;
17468               while (It != End && !It->getAssociatedDeclaration())
17469                 std::advance(It, 1);
17470               assert(It != End &&
17471                      "Expected at least one component with the declaration.");
17472               if (It != Begin && It->getAssociatedDeclaration()
17473                                      ->getType()
17474                                      .getCanonicalType()
17475                                      ->isAnyPointerType()) {
17476                 IsEnclosedByDataEnvironmentExpr = false;
17477                 EnclosingExpr = nullptr;
17478                 return false;
17479               }
17480             }
17481             SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
17482           } else {
17483             assert(CKind == OMPC_to || CKind == OMPC_from);
17484             SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
17485                 << ERange;
17486           }
17487           SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
17488               << RE->getSourceRange();
17489           return true;
17490         }
17491 
17492         // The current expression uses the same base as other expression in the
17493         // data environment but does not contain it completely.
17494         if (!CurrentRegionOnly && SI != SE)
17495           EnclosingExpr = RE;
17496 
17497         // The current expression is a subset of the expression in the data
17498         // environment.
17499         IsEnclosedByDataEnvironmentExpr |=
17500             (!CurrentRegionOnly && CI != CE && SI == SE);
17501 
17502         return false;
17503       });
17504 
17505   if (CurrentRegionOnly)
17506     return FoundError;
17507 
17508   // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
17509   //  If any part of the original storage of a list item has corresponding
17510   //  storage in the device data environment, all of the original storage must
17511   //  have corresponding storage in the device data environment.
17512   // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.6]
17513   //  If a list item is an element of a structure, and a different element of
17514   //  the structure has a corresponding list item in the device data environment
17515   //  prior to a task encountering the construct associated with the map clause,
17516   //  then the list item must also have a corresponding list item in the device
17517   //  data environment prior to the task encountering the construct.
17518   //
17519   if (EnclosingExpr && !IsEnclosedByDataEnvironmentExpr) {
17520     SemaRef.Diag(ELoc,
17521                  diag::err_omp_original_storage_is_shared_and_does_not_contain)
17522         << ERange;
17523     SemaRef.Diag(EnclosingExpr->getExprLoc(), diag::note_used_here)
17524         << EnclosingExpr->getSourceRange();
17525     return true;
17526   }
17527 
17528   return FoundError;
17529 }
17530 
17531 // Look up the user-defined mapper given the mapper name and mapped type, and
17532 // build a reference to it.
17533 static ExprResult buildUserDefinedMapperRef(Sema &SemaRef, Scope *S,
17534                                             CXXScopeSpec &MapperIdScopeSpec,
17535                                             const DeclarationNameInfo &MapperId,
17536                                             QualType Type,
17537                                             Expr *UnresolvedMapper) {
17538   if (MapperIdScopeSpec.isInvalid())
17539     return ExprError();
17540   // Get the actual type for the array type.
17541   if (Type->isArrayType()) {
17542     assert(Type->getAsArrayTypeUnsafe() && "Expect to get a valid array type");
17543     Type = Type->getAsArrayTypeUnsafe()->getElementType().getCanonicalType();
17544   }
17545   // Find all user-defined mappers with the given MapperId.
17546   SmallVector<UnresolvedSet<8>, 4> Lookups;
17547   LookupResult Lookup(SemaRef, MapperId, Sema::LookupOMPMapperName);
17548   Lookup.suppressDiagnostics();
17549   if (S) {
17550     while (S && SemaRef.LookupParsedName(Lookup, S, &MapperIdScopeSpec)) {
17551       NamedDecl *D = Lookup.getRepresentativeDecl();
17552       while (S && !S->isDeclScope(D))
17553         S = S->getParent();
17554       if (S)
17555         S = S->getParent();
17556       Lookups.emplace_back();
17557       Lookups.back().append(Lookup.begin(), Lookup.end());
17558       Lookup.clear();
17559     }
17560   } else if (auto *ULE = cast_or_null<UnresolvedLookupExpr>(UnresolvedMapper)) {
17561     // Extract the user-defined mappers with the given MapperId.
17562     Lookups.push_back(UnresolvedSet<8>());
17563     for (NamedDecl *D : ULE->decls()) {
17564       auto *DMD = cast<OMPDeclareMapperDecl>(D);
17565       assert(DMD && "Expect valid OMPDeclareMapperDecl during instantiation.");
17566       Lookups.back().addDecl(DMD);
17567     }
17568   }
17569   // Defer the lookup for dependent types. The results will be passed through
17570   // UnresolvedMapper on instantiation.
17571   if (SemaRef.CurContext->isDependentContext() || Type->isDependentType() ||
17572       Type->isInstantiationDependentType() ||
17573       Type->containsUnexpandedParameterPack() ||
17574       filterLookupForUDReductionAndMapper<bool>(Lookups, [](ValueDecl *D) {
17575         return !D->isInvalidDecl() &&
17576                (D->getType()->isDependentType() ||
17577                 D->getType()->isInstantiationDependentType() ||
17578                 D->getType()->containsUnexpandedParameterPack());
17579       })) {
17580     UnresolvedSet<8> URS;
17581     for (const UnresolvedSet<8> &Set : Lookups) {
17582       if (Set.empty())
17583         continue;
17584       URS.append(Set.begin(), Set.end());
17585     }
17586     return UnresolvedLookupExpr::Create(
17587         SemaRef.Context, /*NamingClass=*/nullptr,
17588         MapperIdScopeSpec.getWithLocInContext(SemaRef.Context), MapperId,
17589         /*ADL=*/false, /*Overloaded=*/true, URS.begin(), URS.end());
17590   }
17591   SourceLocation Loc = MapperId.getLoc();
17592   // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
17593   //  The type must be of struct, union or class type in C and C++
17594   if (!Type->isStructureOrClassType() && !Type->isUnionType() &&
17595       (MapperIdScopeSpec.isSet() || MapperId.getAsString() != "default")) {
17596     SemaRef.Diag(Loc, diag::err_omp_mapper_wrong_type);
17597     return ExprError();
17598   }
17599   // Perform argument dependent lookup.
17600   if (SemaRef.getLangOpts().CPlusPlus && !MapperIdScopeSpec.isSet())
17601     argumentDependentLookup(SemaRef, MapperId, Loc, Type, Lookups);
17602   // Return the first user-defined mapper with the desired type.
17603   if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
17604           Lookups, [&SemaRef, Type](ValueDecl *D) -> ValueDecl * {
17605             if (!D->isInvalidDecl() &&
17606                 SemaRef.Context.hasSameType(D->getType(), Type))
17607               return D;
17608             return nullptr;
17609           }))
17610     return SemaRef.BuildDeclRefExpr(VD, Type, VK_LValue, Loc);
17611   // Find the first user-defined mapper with a type derived from the desired
17612   // type.
17613   if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
17614           Lookups, [&SemaRef, Type, Loc](ValueDecl *D) -> ValueDecl * {
17615             if (!D->isInvalidDecl() &&
17616                 SemaRef.IsDerivedFrom(Loc, Type, D->getType()) &&
17617                 !Type.isMoreQualifiedThan(D->getType()))
17618               return D;
17619             return nullptr;
17620           })) {
17621     CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
17622                        /*DetectVirtual=*/false);
17623     if (SemaRef.IsDerivedFrom(Loc, Type, VD->getType(), Paths)) {
17624       if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
17625               VD->getType().getUnqualifiedType()))) {
17626         if (SemaRef.CheckBaseClassAccess(
17627                 Loc, VD->getType(), Type, Paths.front(),
17628                 /*DiagID=*/0) != Sema::AR_inaccessible) {
17629           return SemaRef.BuildDeclRefExpr(VD, Type, VK_LValue, Loc);
17630         }
17631       }
17632     }
17633   }
17634   // Report error if a mapper is specified, but cannot be found.
17635   if (MapperIdScopeSpec.isSet() || MapperId.getAsString() != "default") {
17636     SemaRef.Diag(Loc, diag::err_omp_invalid_mapper)
17637         << Type << MapperId.getName();
17638     return ExprError();
17639   }
17640   return ExprEmpty();
17641 }
17642 
17643 namespace {
17644 // Utility struct that gathers all the related lists associated with a mappable
17645 // expression.
17646 struct MappableVarListInfo {
17647   // The list of expressions.
17648   ArrayRef<Expr *> VarList;
17649   // The list of processed expressions.
17650   SmallVector<Expr *, 16> ProcessedVarList;
17651   // The mappble components for each expression.
17652   OMPClauseMappableExprCommon::MappableExprComponentLists VarComponents;
17653   // The base declaration of the variable.
17654   SmallVector<ValueDecl *, 16> VarBaseDeclarations;
17655   // The reference to the user-defined mapper associated with every expression.
17656   SmallVector<Expr *, 16> UDMapperList;
17657 
17658   MappableVarListInfo(ArrayRef<Expr *> VarList) : VarList(VarList) {
17659     // We have a list of components and base declarations for each entry in the
17660     // variable list.
17661     VarComponents.reserve(VarList.size());
17662     VarBaseDeclarations.reserve(VarList.size());
17663   }
17664 };
17665 }
17666 
17667 // Check the validity of the provided variable list for the provided clause kind
17668 // \a CKind. In the check process the valid expressions, mappable expression
17669 // components, variables, and user-defined mappers are extracted and used to
17670 // fill \a ProcessedVarList, \a VarComponents, \a VarBaseDeclarations, and \a
17671 // UDMapperList in MVLI. \a MapType, \a IsMapTypeImplicit, \a MapperIdScopeSpec,
17672 // and \a MapperId are expected to be valid if the clause kind is 'map'.
17673 static void checkMappableExpressionList(
17674     Sema &SemaRef, DSAStackTy *DSAS, OpenMPClauseKind CKind,
17675     MappableVarListInfo &MVLI, SourceLocation StartLoc,
17676     CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo MapperId,
17677     ArrayRef<Expr *> UnresolvedMappers,
17678     OpenMPMapClauseKind MapType = OMPC_MAP_unknown,
17679     bool IsMapTypeImplicit = false) {
17680   // We only expect mappable expressions in 'to', 'from', and 'map' clauses.
17681   assert((CKind == OMPC_map || CKind == OMPC_to || CKind == OMPC_from) &&
17682          "Unexpected clause kind with mappable expressions!");
17683 
17684   // If the identifier of user-defined mapper is not specified, it is "default".
17685   // We do not change the actual name in this clause to distinguish whether a
17686   // mapper is specified explicitly, i.e., it is not explicitly specified when
17687   // MapperId.getName() is empty.
17688   if (!MapperId.getName() || MapperId.getName().isEmpty()) {
17689     auto &DeclNames = SemaRef.getASTContext().DeclarationNames;
17690     MapperId.setName(DeclNames.getIdentifier(
17691         &SemaRef.getASTContext().Idents.get("default")));
17692     MapperId.setLoc(StartLoc);
17693   }
17694 
17695   // Iterators to find the current unresolved mapper expression.
17696   auto UMIt = UnresolvedMappers.begin(), UMEnd = UnresolvedMappers.end();
17697   bool UpdateUMIt = false;
17698   Expr *UnresolvedMapper = nullptr;
17699 
17700   // Keep track of the mappable components and base declarations in this clause.
17701   // Each entry in the list is going to have a list of components associated. We
17702   // record each set of the components so that we can build the clause later on.
17703   // In the end we should have the same amount of declarations and component
17704   // lists.
17705 
17706   for (Expr *RE : MVLI.VarList) {
17707     assert(RE && "Null expr in omp to/from/map clause");
17708     SourceLocation ELoc = RE->getExprLoc();
17709 
17710     // Find the current unresolved mapper expression.
17711     if (UpdateUMIt && UMIt != UMEnd) {
17712       UMIt++;
17713       assert(
17714           UMIt != UMEnd &&
17715           "Expect the size of UnresolvedMappers to match with that of VarList");
17716     }
17717     UpdateUMIt = true;
17718     if (UMIt != UMEnd)
17719       UnresolvedMapper = *UMIt;
17720 
17721     const Expr *VE = RE->IgnoreParenLValueCasts();
17722 
17723     if (VE->isValueDependent() || VE->isTypeDependent() ||
17724         VE->isInstantiationDependent() ||
17725         VE->containsUnexpandedParameterPack()) {
17726       // Try to find the associated user-defined mapper.
17727       ExprResult ER = buildUserDefinedMapperRef(
17728           SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
17729           VE->getType().getCanonicalType(), UnresolvedMapper);
17730       if (ER.isInvalid())
17731         continue;
17732       MVLI.UDMapperList.push_back(ER.get());
17733       // We can only analyze this information once the missing information is
17734       // resolved.
17735       MVLI.ProcessedVarList.push_back(RE);
17736       continue;
17737     }
17738 
17739     Expr *SimpleExpr = RE->IgnoreParenCasts();
17740 
17741     if (!RE->isLValue()) {
17742       if (SemaRef.getLangOpts().OpenMP < 50) {
17743         SemaRef.Diag(
17744             ELoc, diag::err_omp_expected_named_var_member_or_array_expression)
17745             << RE->getSourceRange();
17746       } else {
17747         SemaRef.Diag(ELoc, diag::err_omp_non_lvalue_in_map_or_motion_clauses)
17748             << getOpenMPClauseName(CKind) << RE->getSourceRange();
17749       }
17750       continue;
17751     }
17752 
17753     OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
17754     ValueDecl *CurDeclaration = nullptr;
17755 
17756     // Obtain the array or member expression bases if required. Also, fill the
17757     // components array with all the components identified in the process.
17758     const Expr *BE = checkMapClauseExpressionBase(
17759         SemaRef, SimpleExpr, CurComponents, CKind, DSAS->getCurrentDirective(),
17760         /*NoDiagnose=*/false);
17761     if (!BE)
17762       continue;
17763 
17764     assert(!CurComponents.empty() &&
17765            "Invalid mappable expression information.");
17766 
17767     if (const auto *TE = dyn_cast<CXXThisExpr>(BE)) {
17768       // Add store "this" pointer to class in DSAStackTy for future checking
17769       DSAS->addMappedClassesQualTypes(TE->getType());
17770       // Try to find the associated user-defined mapper.
17771       ExprResult ER = buildUserDefinedMapperRef(
17772           SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
17773           VE->getType().getCanonicalType(), UnresolvedMapper);
17774       if (ER.isInvalid())
17775         continue;
17776       MVLI.UDMapperList.push_back(ER.get());
17777       // Skip restriction checking for variable or field declarations
17778       MVLI.ProcessedVarList.push_back(RE);
17779       MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
17780       MVLI.VarComponents.back().append(CurComponents.begin(),
17781                                        CurComponents.end());
17782       MVLI.VarBaseDeclarations.push_back(nullptr);
17783       continue;
17784     }
17785 
17786     // For the following checks, we rely on the base declaration which is
17787     // expected to be associated with the last component. The declaration is
17788     // expected to be a variable or a field (if 'this' is being mapped).
17789     CurDeclaration = CurComponents.back().getAssociatedDeclaration();
17790     assert(CurDeclaration && "Null decl on map clause.");
17791     assert(
17792         CurDeclaration->isCanonicalDecl() &&
17793         "Expecting components to have associated only canonical declarations.");
17794 
17795     auto *VD = dyn_cast<VarDecl>(CurDeclaration);
17796     const auto *FD = dyn_cast<FieldDecl>(CurDeclaration);
17797 
17798     assert((VD || FD) && "Only variables or fields are expected here!");
17799     (void)FD;
17800 
17801     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.10]
17802     // threadprivate variables cannot appear in a map clause.
17803     // OpenMP 4.5 [2.10.5, target update Construct]
17804     // threadprivate variables cannot appear in a from clause.
17805     if (VD && DSAS->isThreadPrivate(VD)) {
17806       DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false);
17807       SemaRef.Diag(ELoc, diag::err_omp_threadprivate_in_clause)
17808           << getOpenMPClauseName(CKind);
17809       reportOriginalDsa(SemaRef, DSAS, VD, DVar);
17810       continue;
17811     }
17812 
17813     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
17814     //  A list item cannot appear in both a map clause and a data-sharing
17815     //  attribute clause on the same construct.
17816 
17817     // Check conflicts with other map clause expressions. We check the conflicts
17818     // with the current construct separately from the enclosing data
17819     // environment, because the restrictions are different. We only have to
17820     // check conflicts across regions for the map clauses.
17821     if (checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
17822                           /*CurrentRegionOnly=*/true, CurComponents, CKind))
17823       break;
17824     if (CKind == OMPC_map &&
17825         (SemaRef.getLangOpts().OpenMP <= 45 || StartLoc.isValid()) &&
17826         checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
17827                           /*CurrentRegionOnly=*/false, CurComponents, CKind))
17828       break;
17829 
17830     // OpenMP 4.5 [2.10.5, target update Construct]
17831     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
17832     //  If the type of a list item is a reference to a type T then the type will
17833     //  be considered to be T for all purposes of this clause.
17834     auto I = llvm::find_if(
17835         CurComponents,
17836         [](const OMPClauseMappableExprCommon::MappableComponent &MC) {
17837           return MC.getAssociatedDeclaration();
17838         });
17839     assert(I != CurComponents.end() && "Null decl on map clause.");
17840     QualType Type;
17841     auto *ASE = dyn_cast<ArraySubscriptExpr>(VE->IgnoreParens());
17842     auto *OASE = dyn_cast<OMPArraySectionExpr>(VE->IgnoreParens());
17843     auto *OAShE = dyn_cast<OMPArrayShapingExpr>(VE->IgnoreParens());
17844     if (ASE) {
17845       Type = ASE->getType().getNonReferenceType();
17846     } else if (OASE) {
17847       QualType BaseType =
17848           OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
17849       if (const auto *ATy = BaseType->getAsArrayTypeUnsafe())
17850         Type = ATy->getElementType();
17851       else
17852         Type = BaseType->getPointeeType();
17853       Type = Type.getNonReferenceType();
17854     } else if (OAShE) {
17855       Type = OAShE->getBase()->getType()->getPointeeType();
17856     } else {
17857       Type = VE->getType();
17858     }
17859 
17860     // OpenMP 4.5 [2.10.5, target update Construct, Restrictions, p.4]
17861     // A list item in a to or from clause must have a mappable type.
17862     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
17863     //  A list item must have a mappable type.
17864     if (!checkTypeMappable(VE->getExprLoc(), VE->getSourceRange(), SemaRef,
17865                            DSAS, Type))
17866       continue;
17867 
17868     Type = I->getAssociatedDeclaration()->getType().getNonReferenceType();
17869 
17870     if (CKind == OMPC_map) {
17871       // target enter data
17872       // OpenMP [2.10.2, Restrictions, p. 99]
17873       // A map-type must be specified in all map clauses and must be either
17874       // to or alloc.
17875       OpenMPDirectiveKind DKind = DSAS->getCurrentDirective();
17876       if (DKind == OMPD_target_enter_data &&
17877           !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_alloc)) {
17878         SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
17879             << (IsMapTypeImplicit ? 1 : 0)
17880             << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
17881             << getOpenMPDirectiveName(DKind);
17882         continue;
17883       }
17884 
17885       // target exit_data
17886       // OpenMP [2.10.3, Restrictions, p. 102]
17887       // A map-type must be specified in all map clauses and must be either
17888       // from, release, or delete.
17889       if (DKind == OMPD_target_exit_data &&
17890           !(MapType == OMPC_MAP_from || MapType == OMPC_MAP_release ||
17891             MapType == OMPC_MAP_delete)) {
17892         SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
17893             << (IsMapTypeImplicit ? 1 : 0)
17894             << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
17895             << getOpenMPDirectiveName(DKind);
17896         continue;
17897       }
17898 
17899       // target, target data
17900       // OpenMP 5.0 [2.12.2, Restrictions, p. 163]
17901       // OpenMP 5.0 [2.12.5, Restrictions, p. 174]
17902       // A map-type in a map clause must be to, from, tofrom or alloc
17903       if ((DKind == OMPD_target_data ||
17904            isOpenMPTargetExecutionDirective(DKind)) &&
17905           !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_from ||
17906             MapType == OMPC_MAP_tofrom || MapType == OMPC_MAP_alloc)) {
17907         SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
17908             << (IsMapTypeImplicit ? 1 : 0)
17909             << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
17910             << getOpenMPDirectiveName(DKind);
17911         continue;
17912       }
17913 
17914       // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
17915       // A list item cannot appear in both a map clause and a data-sharing
17916       // attribute clause on the same construct
17917       //
17918       // OpenMP 5.0 [2.19.7.1, Restrictions, p.7]
17919       // A list item cannot appear in both a map clause and a data-sharing
17920       // attribute clause on the same construct unless the construct is a
17921       // combined construct.
17922       if (VD && ((SemaRef.LangOpts.OpenMP <= 45 &&
17923                   isOpenMPTargetExecutionDirective(DKind)) ||
17924                  DKind == OMPD_target)) {
17925         DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false);
17926         if (isOpenMPPrivate(DVar.CKind)) {
17927           SemaRef.Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
17928               << getOpenMPClauseName(DVar.CKind)
17929               << getOpenMPClauseName(OMPC_map)
17930               << getOpenMPDirectiveName(DSAS->getCurrentDirective());
17931           reportOriginalDsa(SemaRef, DSAS, CurDeclaration, DVar);
17932           continue;
17933         }
17934       }
17935     }
17936 
17937     // Try to find the associated user-defined mapper.
17938     ExprResult ER = buildUserDefinedMapperRef(
17939         SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
17940         Type.getCanonicalType(), UnresolvedMapper);
17941     if (ER.isInvalid())
17942       continue;
17943     MVLI.UDMapperList.push_back(ER.get());
17944 
17945     // Save the current expression.
17946     MVLI.ProcessedVarList.push_back(RE);
17947 
17948     // Store the components in the stack so that they can be used to check
17949     // against other clauses later on.
17950     DSAS->addMappableExpressionComponents(CurDeclaration, CurComponents,
17951                                           /*WhereFoundClauseKind=*/OMPC_map);
17952 
17953     // Save the components and declaration to create the clause. For purposes of
17954     // the clause creation, any component list that has has base 'this' uses
17955     // null as base declaration.
17956     MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
17957     MVLI.VarComponents.back().append(CurComponents.begin(),
17958                                      CurComponents.end());
17959     MVLI.VarBaseDeclarations.push_back(isa<MemberExpr>(BE) ? nullptr
17960                                                            : CurDeclaration);
17961   }
17962 }
17963 
17964 OMPClause *Sema::ActOnOpenMPMapClause(
17965     ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
17966     ArrayRef<SourceLocation> MapTypeModifiersLoc,
17967     CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo &MapperId,
17968     OpenMPMapClauseKind MapType, bool IsMapTypeImplicit, SourceLocation MapLoc,
17969     SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
17970     const OMPVarListLocTy &Locs, ArrayRef<Expr *> UnresolvedMappers) {
17971   OpenMPMapModifierKind Modifiers[] = {
17972       OMPC_MAP_MODIFIER_unknown, OMPC_MAP_MODIFIER_unknown,
17973       OMPC_MAP_MODIFIER_unknown, OMPC_MAP_MODIFIER_unknown};
17974   SourceLocation ModifiersLoc[NumberOfOMPMapClauseModifiers];
17975 
17976   // Process map-type-modifiers, flag errors for duplicate modifiers.
17977   unsigned Count = 0;
17978   for (unsigned I = 0, E = MapTypeModifiers.size(); I < E; ++I) {
17979     if (MapTypeModifiers[I] != OMPC_MAP_MODIFIER_unknown &&
17980         llvm::find(Modifiers, MapTypeModifiers[I]) != std::end(Modifiers)) {
17981       Diag(MapTypeModifiersLoc[I], diag::err_omp_duplicate_map_type_modifier);
17982       continue;
17983     }
17984     assert(Count < NumberOfOMPMapClauseModifiers &&
17985            "Modifiers exceed the allowed number of map type modifiers");
17986     Modifiers[Count] = MapTypeModifiers[I];
17987     ModifiersLoc[Count] = MapTypeModifiersLoc[I];
17988     ++Count;
17989   }
17990 
17991   MappableVarListInfo MVLI(VarList);
17992   checkMappableExpressionList(*this, DSAStack, OMPC_map, MVLI, Locs.StartLoc,
17993                               MapperIdScopeSpec, MapperId, UnresolvedMappers,
17994                               MapType, IsMapTypeImplicit);
17995 
17996   // We need to produce a map clause even if we don't have variables so that
17997   // other diagnostics related with non-existing map clauses are accurate.
17998   return OMPMapClause::Create(Context, Locs, MVLI.ProcessedVarList,
17999                               MVLI.VarBaseDeclarations, MVLI.VarComponents,
18000                               MVLI.UDMapperList, Modifiers, ModifiersLoc,
18001                               MapperIdScopeSpec.getWithLocInContext(Context),
18002                               MapperId, MapType, IsMapTypeImplicit, MapLoc);
18003 }
18004 
18005 QualType Sema::ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
18006                                                TypeResult ParsedType) {
18007   assert(ParsedType.isUsable());
18008 
18009   QualType ReductionType = GetTypeFromParser(ParsedType.get());
18010   if (ReductionType.isNull())
18011     return QualType();
18012 
18013   // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions, C\C++
18014   // A type name in a declare reduction directive cannot be a function type, an
18015   // array type, a reference type, or a type qualified with const, volatile or
18016   // restrict.
18017   if (ReductionType.hasQualifiers()) {
18018     Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 0;
18019     return QualType();
18020   }
18021 
18022   if (ReductionType->isFunctionType()) {
18023     Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 1;
18024     return QualType();
18025   }
18026   if (ReductionType->isReferenceType()) {
18027     Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 2;
18028     return QualType();
18029   }
18030   if (ReductionType->isArrayType()) {
18031     Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 3;
18032     return QualType();
18033   }
18034   return ReductionType;
18035 }
18036 
18037 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveStart(
18038     Scope *S, DeclContext *DC, DeclarationName Name,
18039     ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
18040     AccessSpecifier AS, Decl *PrevDeclInScope) {
18041   SmallVector<Decl *, 8> Decls;
18042   Decls.reserve(ReductionTypes.size());
18043 
18044   LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPReductionName,
18045                       forRedeclarationInCurContext());
18046   // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
18047   // A reduction-identifier may not be re-declared in the current scope for the
18048   // same type or for a type that is compatible according to the base language
18049   // rules.
18050   llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
18051   OMPDeclareReductionDecl *PrevDRD = nullptr;
18052   bool InCompoundScope = true;
18053   if (S != nullptr) {
18054     // Find previous declaration with the same name not referenced in other
18055     // declarations.
18056     FunctionScopeInfo *ParentFn = getEnclosingFunction();
18057     InCompoundScope =
18058         (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
18059     LookupName(Lookup, S);
18060     FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
18061                          /*AllowInlineNamespace=*/false);
18062     llvm::DenseMap<OMPDeclareReductionDecl *, bool> UsedAsPrevious;
18063     LookupResult::Filter Filter = Lookup.makeFilter();
18064     while (Filter.hasNext()) {
18065       auto *PrevDecl = cast<OMPDeclareReductionDecl>(Filter.next());
18066       if (InCompoundScope) {
18067         auto I = UsedAsPrevious.find(PrevDecl);
18068         if (I == UsedAsPrevious.end())
18069           UsedAsPrevious[PrevDecl] = false;
18070         if (OMPDeclareReductionDecl *D = PrevDecl->getPrevDeclInScope())
18071           UsedAsPrevious[D] = true;
18072       }
18073       PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
18074           PrevDecl->getLocation();
18075     }
18076     Filter.done();
18077     if (InCompoundScope) {
18078       for (const auto &PrevData : UsedAsPrevious) {
18079         if (!PrevData.second) {
18080           PrevDRD = PrevData.first;
18081           break;
18082         }
18083       }
18084     }
18085   } else if (PrevDeclInScope != nullptr) {
18086     auto *PrevDRDInScope = PrevDRD =
18087         cast<OMPDeclareReductionDecl>(PrevDeclInScope);
18088     do {
18089       PreviousRedeclTypes[PrevDRDInScope->getType().getCanonicalType()] =
18090           PrevDRDInScope->getLocation();
18091       PrevDRDInScope = PrevDRDInScope->getPrevDeclInScope();
18092     } while (PrevDRDInScope != nullptr);
18093   }
18094   for (const auto &TyData : ReductionTypes) {
18095     const auto I = PreviousRedeclTypes.find(TyData.first.getCanonicalType());
18096     bool Invalid = false;
18097     if (I != PreviousRedeclTypes.end()) {
18098       Diag(TyData.second, diag::err_omp_declare_reduction_redefinition)
18099           << TyData.first;
18100       Diag(I->second, diag::note_previous_definition);
18101       Invalid = true;
18102     }
18103     PreviousRedeclTypes[TyData.first.getCanonicalType()] = TyData.second;
18104     auto *DRD = OMPDeclareReductionDecl::Create(Context, DC, TyData.second,
18105                                                 Name, TyData.first, PrevDRD);
18106     DC->addDecl(DRD);
18107     DRD->setAccess(AS);
18108     Decls.push_back(DRD);
18109     if (Invalid)
18110       DRD->setInvalidDecl();
18111     else
18112       PrevDRD = DRD;
18113   }
18114 
18115   return DeclGroupPtrTy::make(
18116       DeclGroupRef::Create(Context, Decls.begin(), Decls.size()));
18117 }
18118 
18119 void Sema::ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D) {
18120   auto *DRD = cast<OMPDeclareReductionDecl>(D);
18121 
18122   // Enter new function scope.
18123   PushFunctionScope();
18124   setFunctionHasBranchProtectedScope();
18125   getCurFunction()->setHasOMPDeclareReductionCombiner();
18126 
18127   if (S != nullptr)
18128     PushDeclContext(S, DRD);
18129   else
18130     CurContext = DRD;
18131 
18132   PushExpressionEvaluationContext(
18133       ExpressionEvaluationContext::PotentiallyEvaluated);
18134 
18135   QualType ReductionType = DRD->getType();
18136   // Create 'T* omp_parm;T omp_in;'. All references to 'omp_in' will
18137   // be replaced by '*omp_parm' during codegen. This required because 'omp_in'
18138   // uses semantics of argument handles by value, but it should be passed by
18139   // reference. C lang does not support references, so pass all parameters as
18140   // pointers.
18141   // Create 'T omp_in;' variable.
18142   VarDecl *OmpInParm =
18143       buildVarDecl(*this, D->getLocation(), ReductionType, "omp_in");
18144   // Create 'T* omp_parm;T omp_out;'. All references to 'omp_out' will
18145   // be replaced by '*omp_parm' during codegen. This required because 'omp_out'
18146   // uses semantics of argument handles by value, but it should be passed by
18147   // reference. C lang does not support references, so pass all parameters as
18148   // pointers.
18149   // Create 'T omp_out;' variable.
18150   VarDecl *OmpOutParm =
18151       buildVarDecl(*this, D->getLocation(), ReductionType, "omp_out");
18152   if (S != nullptr) {
18153     PushOnScopeChains(OmpInParm, S);
18154     PushOnScopeChains(OmpOutParm, S);
18155   } else {
18156     DRD->addDecl(OmpInParm);
18157     DRD->addDecl(OmpOutParm);
18158   }
18159   Expr *InE =
18160       ::buildDeclRefExpr(*this, OmpInParm, ReductionType, D->getLocation());
18161   Expr *OutE =
18162       ::buildDeclRefExpr(*this, OmpOutParm, ReductionType, D->getLocation());
18163   DRD->setCombinerData(InE, OutE);
18164 }
18165 
18166 void Sema::ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner) {
18167   auto *DRD = cast<OMPDeclareReductionDecl>(D);
18168   DiscardCleanupsInEvaluationContext();
18169   PopExpressionEvaluationContext();
18170 
18171   PopDeclContext();
18172   PopFunctionScopeInfo();
18173 
18174   if (Combiner != nullptr)
18175     DRD->setCombiner(Combiner);
18176   else
18177     DRD->setInvalidDecl();
18178 }
18179 
18180 VarDecl *Sema::ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D) {
18181   auto *DRD = cast<OMPDeclareReductionDecl>(D);
18182 
18183   // Enter new function scope.
18184   PushFunctionScope();
18185   setFunctionHasBranchProtectedScope();
18186 
18187   if (S != nullptr)
18188     PushDeclContext(S, DRD);
18189   else
18190     CurContext = DRD;
18191 
18192   PushExpressionEvaluationContext(
18193       ExpressionEvaluationContext::PotentiallyEvaluated);
18194 
18195   QualType ReductionType = DRD->getType();
18196   // Create 'T* omp_parm;T omp_priv;'. All references to 'omp_priv' will
18197   // be replaced by '*omp_parm' during codegen. This required because 'omp_priv'
18198   // uses semantics of argument handles by value, but it should be passed by
18199   // reference. C lang does not support references, so pass all parameters as
18200   // pointers.
18201   // Create 'T omp_priv;' variable.
18202   VarDecl *OmpPrivParm =
18203       buildVarDecl(*this, D->getLocation(), ReductionType, "omp_priv");
18204   // Create 'T* omp_parm;T omp_orig;'. All references to 'omp_orig' will
18205   // be replaced by '*omp_parm' during codegen. This required because 'omp_orig'
18206   // uses semantics of argument handles by value, but it should be passed by
18207   // reference. C lang does not support references, so pass all parameters as
18208   // pointers.
18209   // Create 'T omp_orig;' variable.
18210   VarDecl *OmpOrigParm =
18211       buildVarDecl(*this, D->getLocation(), ReductionType, "omp_orig");
18212   if (S != nullptr) {
18213     PushOnScopeChains(OmpPrivParm, S);
18214     PushOnScopeChains(OmpOrigParm, S);
18215   } else {
18216     DRD->addDecl(OmpPrivParm);
18217     DRD->addDecl(OmpOrigParm);
18218   }
18219   Expr *OrigE =
18220       ::buildDeclRefExpr(*this, OmpOrigParm, ReductionType, D->getLocation());
18221   Expr *PrivE =
18222       ::buildDeclRefExpr(*this, OmpPrivParm, ReductionType, D->getLocation());
18223   DRD->setInitializerData(OrigE, PrivE);
18224   return OmpPrivParm;
18225 }
18226 
18227 void Sema::ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer,
18228                                                      VarDecl *OmpPrivParm) {
18229   auto *DRD = cast<OMPDeclareReductionDecl>(D);
18230   DiscardCleanupsInEvaluationContext();
18231   PopExpressionEvaluationContext();
18232 
18233   PopDeclContext();
18234   PopFunctionScopeInfo();
18235 
18236   if (Initializer != nullptr) {
18237     DRD->setInitializer(Initializer, OMPDeclareReductionDecl::CallInit);
18238   } else if (OmpPrivParm->hasInit()) {
18239     DRD->setInitializer(OmpPrivParm->getInit(),
18240                         OmpPrivParm->isDirectInit()
18241                             ? OMPDeclareReductionDecl::DirectInit
18242                             : OMPDeclareReductionDecl::CopyInit);
18243   } else {
18244     DRD->setInvalidDecl();
18245   }
18246 }
18247 
18248 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveEnd(
18249     Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid) {
18250   for (Decl *D : DeclReductions.get()) {
18251     if (IsValid) {
18252       if (S)
18253         PushOnScopeChains(cast<OMPDeclareReductionDecl>(D), S,
18254                           /*AddToContext=*/false);
18255     } else {
18256       D->setInvalidDecl();
18257     }
18258   }
18259   return DeclReductions;
18260 }
18261 
18262 TypeResult Sema::ActOnOpenMPDeclareMapperVarDecl(Scope *S, Declarator &D) {
18263   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
18264   QualType T = TInfo->getType();
18265   if (D.isInvalidType())
18266     return true;
18267 
18268   if (getLangOpts().CPlusPlus) {
18269     // Check that there are no default arguments (C++ only).
18270     CheckExtraCXXDefaultArguments(D);
18271   }
18272 
18273   return CreateParsedType(T, TInfo);
18274 }
18275 
18276 QualType Sema::ActOnOpenMPDeclareMapperType(SourceLocation TyLoc,
18277                                             TypeResult ParsedType) {
18278   assert(ParsedType.isUsable() && "Expect usable parsed mapper type");
18279 
18280   QualType MapperType = GetTypeFromParser(ParsedType.get());
18281   assert(!MapperType.isNull() && "Expect valid mapper type");
18282 
18283   // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
18284   //  The type must be of struct, union or class type in C and C++
18285   if (!MapperType->isStructureOrClassType() && !MapperType->isUnionType()) {
18286     Diag(TyLoc, diag::err_omp_mapper_wrong_type);
18287     return QualType();
18288   }
18289   return MapperType;
18290 }
18291 
18292 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareMapperDirective(
18293     Scope *S, DeclContext *DC, DeclarationName Name, QualType MapperType,
18294     SourceLocation StartLoc, DeclarationName VN, AccessSpecifier AS,
18295     Expr *MapperVarRef, ArrayRef<OMPClause *> Clauses, Decl *PrevDeclInScope) {
18296   LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPMapperName,
18297                       forRedeclarationInCurContext());
18298   // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
18299   //  A mapper-identifier may not be redeclared in the current scope for the
18300   //  same type or for a type that is compatible according to the base language
18301   //  rules.
18302   llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
18303   OMPDeclareMapperDecl *PrevDMD = nullptr;
18304   bool InCompoundScope = true;
18305   if (S != nullptr) {
18306     // Find previous declaration with the same name not referenced in other
18307     // declarations.
18308     FunctionScopeInfo *ParentFn = getEnclosingFunction();
18309     InCompoundScope =
18310         (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
18311     LookupName(Lookup, S);
18312     FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
18313                          /*AllowInlineNamespace=*/false);
18314     llvm::DenseMap<OMPDeclareMapperDecl *, bool> UsedAsPrevious;
18315     LookupResult::Filter Filter = Lookup.makeFilter();
18316     while (Filter.hasNext()) {
18317       auto *PrevDecl = cast<OMPDeclareMapperDecl>(Filter.next());
18318       if (InCompoundScope) {
18319         auto I = UsedAsPrevious.find(PrevDecl);
18320         if (I == UsedAsPrevious.end())
18321           UsedAsPrevious[PrevDecl] = false;
18322         if (OMPDeclareMapperDecl *D = PrevDecl->getPrevDeclInScope())
18323           UsedAsPrevious[D] = true;
18324       }
18325       PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
18326           PrevDecl->getLocation();
18327     }
18328     Filter.done();
18329     if (InCompoundScope) {
18330       for (const auto &PrevData : UsedAsPrevious) {
18331         if (!PrevData.second) {
18332           PrevDMD = PrevData.first;
18333           break;
18334         }
18335       }
18336     }
18337   } else if (PrevDeclInScope) {
18338     auto *PrevDMDInScope = PrevDMD =
18339         cast<OMPDeclareMapperDecl>(PrevDeclInScope);
18340     do {
18341       PreviousRedeclTypes[PrevDMDInScope->getType().getCanonicalType()] =
18342           PrevDMDInScope->getLocation();
18343       PrevDMDInScope = PrevDMDInScope->getPrevDeclInScope();
18344     } while (PrevDMDInScope != nullptr);
18345   }
18346   const auto I = PreviousRedeclTypes.find(MapperType.getCanonicalType());
18347   bool Invalid = false;
18348   if (I != PreviousRedeclTypes.end()) {
18349     Diag(StartLoc, diag::err_omp_declare_mapper_redefinition)
18350         << MapperType << Name;
18351     Diag(I->second, diag::note_previous_definition);
18352     Invalid = true;
18353   }
18354   auto *DMD = OMPDeclareMapperDecl::Create(Context, DC, StartLoc, Name,
18355                                            MapperType, VN, Clauses, PrevDMD);
18356   if (S)
18357     PushOnScopeChains(DMD, S);
18358   else
18359     DC->addDecl(DMD);
18360   DMD->setAccess(AS);
18361   if (Invalid)
18362     DMD->setInvalidDecl();
18363 
18364   auto *VD = cast<DeclRefExpr>(MapperVarRef)->getDecl();
18365   VD->setDeclContext(DMD);
18366   VD->setLexicalDeclContext(DMD);
18367   DMD->addDecl(VD);
18368   DMD->setMapperVarRef(MapperVarRef);
18369 
18370   return DeclGroupPtrTy::make(DeclGroupRef(DMD));
18371 }
18372 
18373 ExprResult
18374 Sema::ActOnOpenMPDeclareMapperDirectiveVarDecl(Scope *S, QualType MapperType,
18375                                                SourceLocation StartLoc,
18376                                                DeclarationName VN) {
18377   TypeSourceInfo *TInfo =
18378       Context.getTrivialTypeSourceInfo(MapperType, StartLoc);
18379   auto *VD = VarDecl::Create(Context, Context.getTranslationUnitDecl(),
18380                              StartLoc, StartLoc, VN.getAsIdentifierInfo(),
18381                              MapperType, TInfo, SC_None);
18382   if (S)
18383     PushOnScopeChains(VD, S, /*AddToContext=*/false);
18384   Expr *E = buildDeclRefExpr(*this, VD, MapperType, StartLoc);
18385   DSAStack->addDeclareMapperVarRef(E);
18386   return E;
18387 }
18388 
18389 bool Sema::isOpenMPDeclareMapperVarDeclAllowed(const VarDecl *VD) const {
18390   assert(LangOpts.OpenMP && "Expected OpenMP mode.");
18391   const Expr *Ref = DSAStack->getDeclareMapperVarRef();
18392   if (const auto *DRE = cast_or_null<DeclRefExpr>(Ref))
18393     return VD->getCanonicalDecl() == DRE->getDecl()->getCanonicalDecl();
18394   return true;
18395 }
18396 
18397 const ValueDecl *Sema::getOpenMPDeclareMapperVarName() const {
18398   assert(LangOpts.OpenMP && "Expected OpenMP mode.");
18399   return cast<DeclRefExpr>(DSAStack->getDeclareMapperVarRef())->getDecl();
18400 }
18401 
18402 OMPClause *Sema::ActOnOpenMPNumTeamsClause(Expr *NumTeams,
18403                                            SourceLocation StartLoc,
18404                                            SourceLocation LParenLoc,
18405                                            SourceLocation EndLoc) {
18406   Expr *ValExpr = NumTeams;
18407   Stmt *HelperValStmt = nullptr;
18408 
18409   // OpenMP [teams Constrcut, Restrictions]
18410   // The num_teams expression must evaluate to a positive integer value.
18411   if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_teams,
18412                                  /*StrictlyPositive=*/true))
18413     return nullptr;
18414 
18415   OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
18416   OpenMPDirectiveKind CaptureRegion =
18417       getOpenMPCaptureRegionForClause(DKind, OMPC_num_teams, LangOpts.OpenMP);
18418   if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
18419     ValExpr = MakeFullExpr(ValExpr).get();
18420     llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
18421     ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
18422     HelperValStmt = buildPreInits(Context, Captures);
18423   }
18424 
18425   return new (Context) OMPNumTeamsClause(ValExpr, HelperValStmt, CaptureRegion,
18426                                          StartLoc, LParenLoc, EndLoc);
18427 }
18428 
18429 OMPClause *Sema::ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
18430                                               SourceLocation StartLoc,
18431                                               SourceLocation LParenLoc,
18432                                               SourceLocation EndLoc) {
18433   Expr *ValExpr = ThreadLimit;
18434   Stmt *HelperValStmt = nullptr;
18435 
18436   // OpenMP [teams Constrcut, Restrictions]
18437   // The thread_limit expression must evaluate to a positive integer value.
18438   if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_thread_limit,
18439                                  /*StrictlyPositive=*/true))
18440     return nullptr;
18441 
18442   OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
18443   OpenMPDirectiveKind CaptureRegion = getOpenMPCaptureRegionForClause(
18444       DKind, OMPC_thread_limit, LangOpts.OpenMP);
18445   if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
18446     ValExpr = MakeFullExpr(ValExpr).get();
18447     llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
18448     ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
18449     HelperValStmt = buildPreInits(Context, Captures);
18450   }
18451 
18452   return new (Context) OMPThreadLimitClause(
18453       ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
18454 }
18455 
18456 OMPClause *Sema::ActOnOpenMPPriorityClause(Expr *Priority,
18457                                            SourceLocation StartLoc,
18458                                            SourceLocation LParenLoc,
18459                                            SourceLocation EndLoc) {
18460   Expr *ValExpr = Priority;
18461   Stmt *HelperValStmt = nullptr;
18462   OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
18463 
18464   // OpenMP [2.9.1, task Constrcut]
18465   // The priority-value is a non-negative numerical scalar expression.
18466   if (!isNonNegativeIntegerValue(
18467           ValExpr, *this, OMPC_priority,
18468           /*StrictlyPositive=*/false, /*BuildCapture=*/true,
18469           DSAStack->getCurrentDirective(), &CaptureRegion, &HelperValStmt))
18470     return nullptr;
18471 
18472   return new (Context) OMPPriorityClause(ValExpr, HelperValStmt, CaptureRegion,
18473                                          StartLoc, LParenLoc, EndLoc);
18474 }
18475 
18476 OMPClause *Sema::ActOnOpenMPGrainsizeClause(Expr *Grainsize,
18477                                             SourceLocation StartLoc,
18478                                             SourceLocation LParenLoc,
18479                                             SourceLocation EndLoc) {
18480   Expr *ValExpr = Grainsize;
18481   Stmt *HelperValStmt = nullptr;
18482   OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
18483 
18484   // OpenMP [2.9.2, taskloop Constrcut]
18485   // The parameter of the grainsize clause must be a positive integer
18486   // expression.
18487   if (!isNonNegativeIntegerValue(
18488           ValExpr, *this, OMPC_grainsize,
18489           /*StrictlyPositive=*/true, /*BuildCapture=*/true,
18490           DSAStack->getCurrentDirective(), &CaptureRegion, &HelperValStmt))
18491     return nullptr;
18492 
18493   return new (Context) OMPGrainsizeClause(ValExpr, HelperValStmt, CaptureRegion,
18494                                           StartLoc, LParenLoc, EndLoc);
18495 }
18496 
18497 OMPClause *Sema::ActOnOpenMPNumTasksClause(Expr *NumTasks,
18498                                            SourceLocation StartLoc,
18499                                            SourceLocation LParenLoc,
18500                                            SourceLocation EndLoc) {
18501   Expr *ValExpr = NumTasks;
18502   Stmt *HelperValStmt = nullptr;
18503   OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
18504 
18505   // OpenMP [2.9.2, taskloop Constrcut]
18506   // The parameter of the num_tasks clause must be a positive integer
18507   // expression.
18508   if (!isNonNegativeIntegerValue(
18509           ValExpr, *this, OMPC_num_tasks,
18510           /*StrictlyPositive=*/true, /*BuildCapture=*/true,
18511           DSAStack->getCurrentDirective(), &CaptureRegion, &HelperValStmt))
18512     return nullptr;
18513 
18514   return new (Context) OMPNumTasksClause(ValExpr, HelperValStmt, CaptureRegion,
18515                                          StartLoc, LParenLoc, EndLoc);
18516 }
18517 
18518 OMPClause *Sema::ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
18519                                        SourceLocation LParenLoc,
18520                                        SourceLocation EndLoc) {
18521   // OpenMP [2.13.2, critical construct, Description]
18522   // ... where hint-expression is an integer constant expression that evaluates
18523   // to a valid lock hint.
18524   ExprResult HintExpr = VerifyPositiveIntegerConstantInClause(Hint, OMPC_hint);
18525   if (HintExpr.isInvalid())
18526     return nullptr;
18527   return new (Context)
18528       OMPHintClause(HintExpr.get(), StartLoc, LParenLoc, EndLoc);
18529 }
18530 
18531 /// Tries to find omp_event_handle_t type.
18532 static bool findOMPEventHandleT(Sema &S, SourceLocation Loc,
18533                                 DSAStackTy *Stack) {
18534   QualType OMPEventHandleT = Stack->getOMPEventHandleT();
18535   if (!OMPEventHandleT.isNull())
18536     return true;
18537   IdentifierInfo *II = &S.PP.getIdentifierTable().get("omp_event_handle_t");
18538   ParsedType PT = S.getTypeName(*II, Loc, S.getCurScope());
18539   if (!PT.getAsOpaquePtr() || PT.get().isNull()) {
18540     S.Diag(Loc, diag::err_omp_implied_type_not_found) << "omp_event_handle_t";
18541     return false;
18542   }
18543   Stack->setOMPEventHandleT(PT.get());
18544   return true;
18545 }
18546 
18547 OMPClause *Sema::ActOnOpenMPDetachClause(Expr *Evt, SourceLocation StartLoc,
18548                                          SourceLocation LParenLoc,
18549                                          SourceLocation EndLoc) {
18550   if (!Evt->isValueDependent() && !Evt->isTypeDependent() &&
18551       !Evt->isInstantiationDependent() &&
18552       !Evt->containsUnexpandedParameterPack()) {
18553     if (!findOMPEventHandleT(*this, Evt->getExprLoc(), DSAStack))
18554       return nullptr;
18555     // OpenMP 5.0, 2.10.1 task Construct.
18556     // event-handle is a variable of the omp_event_handle_t type.
18557     auto *Ref = dyn_cast<DeclRefExpr>(Evt->IgnoreParenImpCasts());
18558     if (!Ref) {
18559       Diag(Evt->getExprLoc(), diag::err_omp_var_expected)
18560           << "omp_event_handle_t" << 0 << Evt->getSourceRange();
18561       return nullptr;
18562     }
18563     auto *VD = dyn_cast_or_null<VarDecl>(Ref->getDecl());
18564     if (!VD) {
18565       Diag(Evt->getExprLoc(), diag::err_omp_var_expected)
18566           << "omp_event_handle_t" << 0 << Evt->getSourceRange();
18567       return nullptr;
18568     }
18569     if (!Context.hasSameUnqualifiedType(DSAStack->getOMPEventHandleT(),
18570                                         VD->getType()) ||
18571         VD->getType().isConstant(Context)) {
18572       Diag(Evt->getExprLoc(), diag::err_omp_var_expected)
18573           << "omp_event_handle_t" << 1 << VD->getType()
18574           << Evt->getSourceRange();
18575       return nullptr;
18576     }
18577     // OpenMP 5.0, 2.10.1 task Construct
18578     // [detach clause]... The event-handle will be considered as if it was
18579     // specified on a firstprivate clause.
18580     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, /*FromParent=*/false);
18581     if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
18582         DVar.RefExpr) {
18583       Diag(Evt->getExprLoc(), diag::err_omp_wrong_dsa)
18584           << getOpenMPClauseName(DVar.CKind)
18585           << getOpenMPClauseName(OMPC_firstprivate);
18586       reportOriginalDsa(*this, DSAStack, VD, DVar);
18587       return nullptr;
18588     }
18589   }
18590 
18591   return new (Context) OMPDetachClause(Evt, StartLoc, LParenLoc, EndLoc);
18592 }
18593 
18594 OMPClause *Sema::ActOnOpenMPDistScheduleClause(
18595     OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
18596     SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc,
18597     SourceLocation EndLoc) {
18598   if (Kind == OMPC_DIST_SCHEDULE_unknown) {
18599     std::string Values;
18600     Values += "'";
18601     Values += getOpenMPSimpleClauseTypeName(OMPC_dist_schedule, 0);
18602     Values += "'";
18603     Diag(KindLoc, diag::err_omp_unexpected_clause_value)
18604         << Values << getOpenMPClauseName(OMPC_dist_schedule);
18605     return nullptr;
18606   }
18607   Expr *ValExpr = ChunkSize;
18608   Stmt *HelperValStmt = nullptr;
18609   if (ChunkSize) {
18610     if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
18611         !ChunkSize->isInstantiationDependent() &&
18612         !ChunkSize->containsUnexpandedParameterPack()) {
18613       SourceLocation ChunkSizeLoc = ChunkSize->getBeginLoc();
18614       ExprResult Val =
18615           PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
18616       if (Val.isInvalid())
18617         return nullptr;
18618 
18619       ValExpr = Val.get();
18620 
18621       // OpenMP [2.7.1, Restrictions]
18622       //  chunk_size must be a loop invariant integer expression with a positive
18623       //  value.
18624       if (Optional<llvm::APSInt> Result =
18625               ValExpr->getIntegerConstantExpr(Context)) {
18626         if (Result->isSigned() && !Result->isStrictlyPositive()) {
18627           Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
18628               << "dist_schedule" << ChunkSize->getSourceRange();
18629           return nullptr;
18630         }
18631       } else if (getOpenMPCaptureRegionForClause(
18632                      DSAStack->getCurrentDirective(), OMPC_dist_schedule,
18633                      LangOpts.OpenMP) != OMPD_unknown &&
18634                  !CurContext->isDependentContext()) {
18635         ValExpr = MakeFullExpr(ValExpr).get();
18636         llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
18637         ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
18638         HelperValStmt = buildPreInits(Context, Captures);
18639       }
18640     }
18641   }
18642 
18643   return new (Context)
18644       OMPDistScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc,
18645                             Kind, ValExpr, HelperValStmt);
18646 }
18647 
18648 OMPClause *Sema::ActOnOpenMPDefaultmapClause(
18649     OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
18650     SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
18651     SourceLocation KindLoc, SourceLocation EndLoc) {
18652   if (getLangOpts().OpenMP < 50) {
18653     if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom ||
18654         Kind != OMPC_DEFAULTMAP_scalar) {
18655       std::string Value;
18656       SourceLocation Loc;
18657       Value += "'";
18658       if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom) {
18659         Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
18660                                                OMPC_DEFAULTMAP_MODIFIER_tofrom);
18661         Loc = MLoc;
18662       } else {
18663         Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
18664                                                OMPC_DEFAULTMAP_scalar);
18665         Loc = KindLoc;
18666       }
18667       Value += "'";
18668       Diag(Loc, diag::err_omp_unexpected_clause_value)
18669           << Value << getOpenMPClauseName(OMPC_defaultmap);
18670       return nullptr;
18671     }
18672   } else {
18673     bool isDefaultmapModifier = (M != OMPC_DEFAULTMAP_MODIFIER_unknown);
18674     bool isDefaultmapKind = (Kind != OMPC_DEFAULTMAP_unknown) ||
18675                             (LangOpts.OpenMP >= 50 && KindLoc.isInvalid());
18676     if (!isDefaultmapKind || !isDefaultmapModifier) {
18677       StringRef KindValue = "'scalar', 'aggregate', 'pointer'";
18678       if (LangOpts.OpenMP == 50) {
18679         StringRef ModifierValue = "'alloc', 'from', 'to', 'tofrom', "
18680                                   "'firstprivate', 'none', 'default'";
18681         if (!isDefaultmapKind && isDefaultmapModifier) {
18682           Diag(KindLoc, diag::err_omp_unexpected_clause_value)
18683               << KindValue << getOpenMPClauseName(OMPC_defaultmap);
18684         } else if (isDefaultmapKind && !isDefaultmapModifier) {
18685           Diag(MLoc, diag::err_omp_unexpected_clause_value)
18686               << ModifierValue << getOpenMPClauseName(OMPC_defaultmap);
18687         } else {
18688           Diag(MLoc, diag::err_omp_unexpected_clause_value)
18689               << ModifierValue << getOpenMPClauseName(OMPC_defaultmap);
18690           Diag(KindLoc, diag::err_omp_unexpected_clause_value)
18691               << KindValue << getOpenMPClauseName(OMPC_defaultmap);
18692         }
18693       } else {
18694         StringRef ModifierValue =
18695             "'alloc', 'from', 'to', 'tofrom', "
18696             "'firstprivate', 'none', 'default', 'present'";
18697         if (!isDefaultmapKind && isDefaultmapModifier) {
18698           Diag(KindLoc, diag::err_omp_unexpected_clause_value)
18699               << KindValue << getOpenMPClauseName(OMPC_defaultmap);
18700         } else if (isDefaultmapKind && !isDefaultmapModifier) {
18701           Diag(MLoc, diag::err_omp_unexpected_clause_value)
18702               << ModifierValue << getOpenMPClauseName(OMPC_defaultmap);
18703         } else {
18704           Diag(MLoc, diag::err_omp_unexpected_clause_value)
18705               << ModifierValue << getOpenMPClauseName(OMPC_defaultmap);
18706           Diag(KindLoc, diag::err_omp_unexpected_clause_value)
18707               << KindValue << getOpenMPClauseName(OMPC_defaultmap);
18708         }
18709       }
18710       return nullptr;
18711     }
18712 
18713     // OpenMP [5.0, 2.12.5, Restrictions, p. 174]
18714     //  At most one defaultmap clause for each category can appear on the
18715     //  directive.
18716     if (DSAStack->checkDefaultmapCategory(Kind)) {
18717       Diag(StartLoc, diag::err_omp_one_defaultmap_each_category);
18718       return nullptr;
18719     }
18720   }
18721   if (Kind == OMPC_DEFAULTMAP_unknown) {
18722     // Variable category is not specified - mark all categories.
18723     DSAStack->setDefaultDMAAttr(M, OMPC_DEFAULTMAP_aggregate, StartLoc);
18724     DSAStack->setDefaultDMAAttr(M, OMPC_DEFAULTMAP_scalar, StartLoc);
18725     DSAStack->setDefaultDMAAttr(M, OMPC_DEFAULTMAP_pointer, StartLoc);
18726   } else {
18727     DSAStack->setDefaultDMAAttr(M, Kind, StartLoc);
18728   }
18729 
18730   return new (Context)
18731       OMPDefaultmapClause(StartLoc, LParenLoc, MLoc, KindLoc, EndLoc, Kind, M);
18732 }
18733 
18734 bool Sema::ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc) {
18735   DeclContext *CurLexicalContext = getCurLexicalContext();
18736   if (!CurLexicalContext->isFileContext() &&
18737       !CurLexicalContext->isExternCContext() &&
18738       !CurLexicalContext->isExternCXXContext() &&
18739       !isa<CXXRecordDecl>(CurLexicalContext) &&
18740       !isa<ClassTemplateDecl>(CurLexicalContext) &&
18741       !isa<ClassTemplatePartialSpecializationDecl>(CurLexicalContext) &&
18742       !isa<ClassTemplateSpecializationDecl>(CurLexicalContext)) {
18743     Diag(Loc, diag::err_omp_region_not_file_context);
18744     return false;
18745   }
18746   DeclareTargetNesting.push_back(Loc);
18747   return true;
18748 }
18749 
18750 void Sema::ActOnFinishOpenMPDeclareTargetDirective() {
18751   assert(!DeclareTargetNesting.empty() &&
18752          "Unexpected ActOnFinishOpenMPDeclareTargetDirective");
18753   DeclareTargetNesting.pop_back();
18754 }
18755 
18756 NamedDecl *
18757 Sema::lookupOpenMPDeclareTargetName(Scope *CurScope, CXXScopeSpec &ScopeSpec,
18758                                     const DeclarationNameInfo &Id,
18759                                     NamedDeclSetType &SameDirectiveDecls) {
18760   LookupResult Lookup(*this, Id, LookupOrdinaryName);
18761   LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
18762 
18763   if (Lookup.isAmbiguous())
18764     return nullptr;
18765   Lookup.suppressDiagnostics();
18766 
18767   if (!Lookup.isSingleResult()) {
18768     VarOrFuncDeclFilterCCC CCC(*this);
18769     if (TypoCorrection Corrected =
18770             CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr, CCC,
18771                         CTK_ErrorRecovery)) {
18772       diagnoseTypo(Corrected, PDiag(diag::err_undeclared_var_use_suggest)
18773                                   << Id.getName());
18774       checkDeclIsAllowedInOpenMPTarget(nullptr, Corrected.getCorrectionDecl());
18775       return nullptr;
18776     }
18777 
18778     Diag(Id.getLoc(), diag::err_undeclared_var_use) << Id.getName();
18779     return nullptr;
18780   }
18781 
18782   NamedDecl *ND = Lookup.getAsSingle<NamedDecl>();
18783   if (!isa<VarDecl>(ND) && !isa<FunctionDecl>(ND) &&
18784       !isa<FunctionTemplateDecl>(ND)) {
18785     Diag(Id.getLoc(), diag::err_omp_invalid_target_decl) << Id.getName();
18786     return nullptr;
18787   }
18788   if (!SameDirectiveDecls.insert(cast<NamedDecl>(ND->getCanonicalDecl())))
18789     Diag(Id.getLoc(), diag::err_omp_declare_target_multiple) << Id.getName();
18790   return ND;
18791 }
18792 
18793 void Sema::ActOnOpenMPDeclareTargetName(
18794     NamedDecl *ND, SourceLocation Loc, OMPDeclareTargetDeclAttr::MapTypeTy MT,
18795     OMPDeclareTargetDeclAttr::DevTypeTy DT) {
18796   assert((isa<VarDecl>(ND) || isa<FunctionDecl>(ND) ||
18797           isa<FunctionTemplateDecl>(ND)) &&
18798          "Expected variable, function or function template.");
18799 
18800   // Diagnose marking after use as it may lead to incorrect diagnosis and
18801   // codegen.
18802   if (LangOpts.OpenMP >= 50 &&
18803       (ND->isUsed(/*CheckUsedAttr=*/false) || ND->isReferenced()))
18804     Diag(Loc, diag::warn_omp_declare_target_after_first_use);
18805 
18806   auto *VD = cast<ValueDecl>(ND);
18807   Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
18808       OMPDeclareTargetDeclAttr::getDeviceType(VD);
18809   Optional<SourceLocation> AttrLoc = OMPDeclareTargetDeclAttr::getLocation(VD);
18810   if (DevTy.hasValue() && *DevTy != DT &&
18811       (DeclareTargetNesting.empty() ||
18812        *AttrLoc != DeclareTargetNesting.back())) {
18813     Diag(Loc, diag::err_omp_device_type_mismatch)
18814         << OMPDeclareTargetDeclAttr::ConvertDevTypeTyToStr(DT)
18815         << OMPDeclareTargetDeclAttr::ConvertDevTypeTyToStr(*DevTy);
18816     return;
18817   }
18818   Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
18819       OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
18820   if (!Res || (!DeclareTargetNesting.empty() &&
18821                *AttrLoc == DeclareTargetNesting.back())) {
18822     auto *A = OMPDeclareTargetDeclAttr::CreateImplicit(
18823         Context, MT, DT, DeclareTargetNesting.size() + 1,
18824         SourceRange(Loc, Loc));
18825     ND->addAttr(A);
18826     if (ASTMutationListener *ML = Context.getASTMutationListener())
18827       ML->DeclarationMarkedOpenMPDeclareTarget(ND, A);
18828     checkDeclIsAllowedInOpenMPTarget(nullptr, ND, Loc);
18829   } else if (*Res != MT) {
18830     Diag(Loc, diag::err_omp_declare_target_to_and_link) << ND;
18831   }
18832 }
18833 
18834 static void checkDeclInTargetContext(SourceLocation SL, SourceRange SR,
18835                                      Sema &SemaRef, Decl *D) {
18836   if (!D || !isa<VarDecl>(D))
18837     return;
18838   auto *VD = cast<VarDecl>(D);
18839   Optional<OMPDeclareTargetDeclAttr::MapTypeTy> MapTy =
18840       OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
18841   if (SemaRef.LangOpts.OpenMP >= 50 &&
18842       (SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true) ||
18843        SemaRef.getCurBlock() || SemaRef.getCurCapturedRegion()) &&
18844       VD->hasGlobalStorage()) {
18845     llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> MapTy =
18846         OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
18847     if (!MapTy || *MapTy != OMPDeclareTargetDeclAttr::MT_To) {
18848       // OpenMP 5.0, 2.12.7 declare target Directive, Restrictions
18849       // If a lambda declaration and definition appears between a
18850       // declare target directive and the matching end declare target
18851       // directive, all variables that are captured by the lambda
18852       // expression must also appear in a to clause.
18853       SemaRef.Diag(VD->getLocation(),
18854                    diag::err_omp_lambda_capture_in_declare_target_not_to);
18855       SemaRef.Diag(SL, diag::note_var_explicitly_captured_here)
18856           << VD << 0 << SR;
18857       return;
18858     }
18859   }
18860   if (MapTy.hasValue())
18861     return;
18862   SemaRef.Diag(VD->getLocation(), diag::warn_omp_not_in_target_context);
18863   SemaRef.Diag(SL, diag::note_used_here) << SR;
18864 }
18865 
18866 static bool checkValueDeclInTarget(SourceLocation SL, SourceRange SR,
18867                                    Sema &SemaRef, DSAStackTy *Stack,
18868                                    ValueDecl *VD) {
18869   return OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD) ||
18870          checkTypeMappable(SL, SR, SemaRef, Stack, VD->getType(),
18871                            /*FullCheck=*/false);
18872 }
18873 
18874 void Sema::checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D,
18875                                             SourceLocation IdLoc) {
18876   if (!D || D->isInvalidDecl())
18877     return;
18878   SourceRange SR = E ? E->getSourceRange() : D->getSourceRange();
18879   SourceLocation SL = E ? E->getBeginLoc() : D->getLocation();
18880   if (auto *VD = dyn_cast<VarDecl>(D)) {
18881     // Only global variables can be marked as declare target.
18882     if (!VD->isFileVarDecl() && !VD->isStaticLocal() &&
18883         !VD->isStaticDataMember())
18884       return;
18885     // 2.10.6: threadprivate variable cannot appear in a declare target
18886     // directive.
18887     if (DSAStack->isThreadPrivate(VD)) {
18888       Diag(SL, diag::err_omp_threadprivate_in_target);
18889       reportOriginalDsa(*this, DSAStack, VD, DSAStack->getTopDSA(VD, false));
18890       return;
18891     }
18892   }
18893   if (const auto *FTD = dyn_cast<FunctionTemplateDecl>(D))
18894     D = FTD->getTemplatedDecl();
18895   if (auto *FD = dyn_cast<FunctionDecl>(D)) {
18896     llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
18897         OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(FD);
18898     if (IdLoc.isValid() && Res && *Res == OMPDeclareTargetDeclAttr::MT_Link) {
18899       Diag(IdLoc, diag::err_omp_function_in_link_clause);
18900       Diag(FD->getLocation(), diag::note_defined_here) << FD;
18901       return;
18902     }
18903   }
18904   if (auto *VD = dyn_cast<ValueDecl>(D)) {
18905     // Problem if any with var declared with incomplete type will be reported
18906     // as normal, so no need to check it here.
18907     if ((E || !VD->getType()->isIncompleteType()) &&
18908         !checkValueDeclInTarget(SL, SR, *this, DSAStack, VD))
18909       return;
18910     if (!E && !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) {
18911       // Checking declaration inside declare target region.
18912       if (isa<VarDecl>(D) || isa<FunctionDecl>(D) ||
18913           isa<FunctionTemplateDecl>(D)) {
18914         auto *A = OMPDeclareTargetDeclAttr::CreateImplicit(
18915             Context, OMPDeclareTargetDeclAttr::MT_To,
18916             OMPDeclareTargetDeclAttr::DT_Any, DeclareTargetNesting.size(),
18917             SourceRange(DeclareTargetNesting.back(),
18918                         DeclareTargetNesting.back()));
18919         D->addAttr(A);
18920         if (ASTMutationListener *ML = Context.getASTMutationListener())
18921           ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
18922       }
18923       return;
18924     }
18925   }
18926   if (!E)
18927     return;
18928   checkDeclInTargetContext(E->getExprLoc(), E->getSourceRange(), *this, D);
18929 }
18930 
18931 OMPClause *Sema::ActOnOpenMPToClause(
18932     ArrayRef<OpenMPMotionModifierKind> MotionModifiers,
18933     ArrayRef<SourceLocation> MotionModifiersLoc,
18934     CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo &MapperId,
18935     SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
18936     const OMPVarListLocTy &Locs, ArrayRef<Expr *> UnresolvedMappers) {
18937   OpenMPMotionModifierKind Modifiers[] = {OMPC_MOTION_MODIFIER_unknown,
18938                                           OMPC_MOTION_MODIFIER_unknown};
18939   SourceLocation ModifiersLoc[NumberOfOMPMotionModifiers];
18940 
18941   // Process motion-modifiers, flag errors for duplicate modifiers.
18942   unsigned Count = 0;
18943   for (unsigned I = 0, E = MotionModifiers.size(); I < E; ++I) {
18944     if (MotionModifiers[I] != OMPC_MOTION_MODIFIER_unknown &&
18945         llvm::find(Modifiers, MotionModifiers[I]) != std::end(Modifiers)) {
18946       Diag(MotionModifiersLoc[I], diag::err_omp_duplicate_motion_modifier);
18947       continue;
18948     }
18949     assert(Count < NumberOfOMPMotionModifiers &&
18950            "Modifiers exceed the allowed number of motion modifiers");
18951     Modifiers[Count] = MotionModifiers[I];
18952     ModifiersLoc[Count] = MotionModifiersLoc[I];
18953     ++Count;
18954   }
18955 
18956   MappableVarListInfo MVLI(VarList);
18957   checkMappableExpressionList(*this, DSAStack, OMPC_to, MVLI, Locs.StartLoc,
18958                               MapperIdScopeSpec, MapperId, UnresolvedMappers);
18959   if (MVLI.ProcessedVarList.empty())
18960     return nullptr;
18961 
18962   return OMPToClause::Create(
18963       Context, Locs, MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
18964       MVLI.VarComponents, MVLI.UDMapperList, Modifiers, ModifiersLoc,
18965       MapperIdScopeSpec.getWithLocInContext(Context), MapperId);
18966 }
18967 
18968 OMPClause *Sema::ActOnOpenMPFromClause(
18969     ArrayRef<OpenMPMotionModifierKind> MotionModifiers,
18970     ArrayRef<SourceLocation> MotionModifiersLoc,
18971     CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo &MapperId,
18972     SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
18973     const OMPVarListLocTy &Locs, ArrayRef<Expr *> UnresolvedMappers) {
18974   OpenMPMotionModifierKind Modifiers[] = {OMPC_MOTION_MODIFIER_unknown,
18975                                           OMPC_MOTION_MODIFIER_unknown};
18976   SourceLocation ModifiersLoc[NumberOfOMPMotionModifiers];
18977 
18978   // Process motion-modifiers, flag errors for duplicate modifiers.
18979   unsigned Count = 0;
18980   for (unsigned I = 0, E = MotionModifiers.size(); I < E; ++I) {
18981     if (MotionModifiers[I] != OMPC_MOTION_MODIFIER_unknown &&
18982         llvm::find(Modifiers, MotionModifiers[I]) != std::end(Modifiers)) {
18983       Diag(MotionModifiersLoc[I], diag::err_omp_duplicate_motion_modifier);
18984       continue;
18985     }
18986     assert(Count < NumberOfOMPMotionModifiers &&
18987            "Modifiers exceed the allowed number of motion modifiers");
18988     Modifiers[Count] = MotionModifiers[I];
18989     ModifiersLoc[Count] = MotionModifiersLoc[I];
18990     ++Count;
18991   }
18992 
18993   MappableVarListInfo MVLI(VarList);
18994   checkMappableExpressionList(*this, DSAStack, OMPC_from, MVLI, Locs.StartLoc,
18995                               MapperIdScopeSpec, MapperId, UnresolvedMappers);
18996   if (MVLI.ProcessedVarList.empty())
18997     return nullptr;
18998 
18999   return OMPFromClause::Create(
19000       Context, Locs, MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
19001       MVLI.VarComponents, MVLI.UDMapperList, Modifiers, ModifiersLoc,
19002       MapperIdScopeSpec.getWithLocInContext(Context), MapperId);
19003 }
19004 
19005 OMPClause *Sema::ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
19006                                                const OMPVarListLocTy &Locs) {
19007   MappableVarListInfo MVLI(VarList);
19008   SmallVector<Expr *, 8> PrivateCopies;
19009   SmallVector<Expr *, 8> Inits;
19010 
19011   for (Expr *RefExpr : VarList) {
19012     assert(RefExpr && "NULL expr in OpenMP use_device_ptr clause.");
19013     SourceLocation ELoc;
19014     SourceRange ERange;
19015     Expr *SimpleRefExpr = RefExpr;
19016     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
19017     if (Res.second) {
19018       // It will be analyzed later.
19019       MVLI.ProcessedVarList.push_back(RefExpr);
19020       PrivateCopies.push_back(nullptr);
19021       Inits.push_back(nullptr);
19022     }
19023     ValueDecl *D = Res.first;
19024     if (!D)
19025       continue;
19026 
19027     QualType Type = D->getType();
19028     Type = Type.getNonReferenceType().getUnqualifiedType();
19029 
19030     auto *VD = dyn_cast<VarDecl>(D);
19031 
19032     // Item should be a pointer or reference to pointer.
19033     if (!Type->isPointerType()) {
19034       Diag(ELoc, diag::err_omp_usedeviceptr_not_a_pointer)
19035           << 0 << RefExpr->getSourceRange();
19036       continue;
19037     }
19038 
19039     // Build the private variable and the expression that refers to it.
19040     auto VDPrivate =
19041         buildVarDecl(*this, ELoc, Type, D->getName(),
19042                      D->hasAttrs() ? &D->getAttrs() : nullptr,
19043                      VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
19044     if (VDPrivate->isInvalidDecl())
19045       continue;
19046 
19047     CurContext->addDecl(VDPrivate);
19048     DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
19049         *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
19050 
19051     // Add temporary variable to initialize the private copy of the pointer.
19052     VarDecl *VDInit =
19053         buildVarDecl(*this, RefExpr->getExprLoc(), Type, ".devptr.temp");
19054     DeclRefExpr *VDInitRefExpr = buildDeclRefExpr(
19055         *this, VDInit, RefExpr->getType(), RefExpr->getExprLoc());
19056     AddInitializerToDecl(VDPrivate,
19057                          DefaultLvalueConversion(VDInitRefExpr).get(),
19058                          /*DirectInit=*/false);
19059 
19060     // If required, build a capture to implement the privatization initialized
19061     // with the current list item value.
19062     DeclRefExpr *Ref = nullptr;
19063     if (!VD)
19064       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
19065     MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref);
19066     PrivateCopies.push_back(VDPrivateRefExpr);
19067     Inits.push_back(VDInitRefExpr);
19068 
19069     // We need to add a data sharing attribute for this variable to make sure it
19070     // is correctly captured. A variable that shows up in a use_device_ptr has
19071     // similar properties of a first private variable.
19072     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
19073 
19074     // Create a mappable component for the list item. List items in this clause
19075     // only need a component.
19076     MVLI.VarBaseDeclarations.push_back(D);
19077     MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
19078     MVLI.VarComponents.back().emplace_back(SimpleRefExpr, D,
19079                                            /*IsNonContiguous=*/false);
19080   }
19081 
19082   if (MVLI.ProcessedVarList.empty())
19083     return nullptr;
19084 
19085   return OMPUseDevicePtrClause::Create(
19086       Context, Locs, MVLI.ProcessedVarList, PrivateCopies, Inits,
19087       MVLI.VarBaseDeclarations, MVLI.VarComponents);
19088 }
19089 
19090 OMPClause *Sema::ActOnOpenMPUseDeviceAddrClause(ArrayRef<Expr *> VarList,
19091                                                 const OMPVarListLocTy &Locs) {
19092   MappableVarListInfo MVLI(VarList);
19093 
19094   for (Expr *RefExpr : VarList) {
19095     assert(RefExpr && "NULL expr in OpenMP use_device_addr clause.");
19096     SourceLocation ELoc;
19097     SourceRange ERange;
19098     Expr *SimpleRefExpr = RefExpr;
19099     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
19100                               /*AllowArraySection=*/true);
19101     if (Res.second) {
19102       // It will be analyzed later.
19103       MVLI.ProcessedVarList.push_back(RefExpr);
19104     }
19105     ValueDecl *D = Res.first;
19106     if (!D)
19107       continue;
19108     auto *VD = dyn_cast<VarDecl>(D);
19109 
19110     // If required, build a capture to implement the privatization initialized
19111     // with the current list item value.
19112     DeclRefExpr *Ref = nullptr;
19113     if (!VD)
19114       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
19115     MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref);
19116 
19117     // We need to add a data sharing attribute for this variable to make sure it
19118     // is correctly captured. A variable that shows up in a use_device_addr has
19119     // similar properties of a first private variable.
19120     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
19121 
19122     // Create a mappable component for the list item. List items in this clause
19123     // only need a component.
19124     MVLI.VarBaseDeclarations.push_back(D);
19125     MVLI.VarComponents.emplace_back();
19126     Expr *Component = SimpleRefExpr;
19127     if (VD && (isa<OMPArraySectionExpr>(RefExpr->IgnoreParenImpCasts()) ||
19128                isa<ArraySubscriptExpr>(RefExpr->IgnoreParenImpCasts())))
19129       Component = DefaultFunctionArrayLvalueConversion(SimpleRefExpr).get();
19130     MVLI.VarComponents.back().emplace_back(Component, D,
19131                                            /*IsNonContiguous=*/false);
19132   }
19133 
19134   if (MVLI.ProcessedVarList.empty())
19135     return nullptr;
19136 
19137   return OMPUseDeviceAddrClause::Create(Context, Locs, MVLI.ProcessedVarList,
19138                                         MVLI.VarBaseDeclarations,
19139                                         MVLI.VarComponents);
19140 }
19141 
19142 OMPClause *Sema::ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
19143                                               const OMPVarListLocTy &Locs) {
19144   MappableVarListInfo MVLI(VarList);
19145   for (Expr *RefExpr : VarList) {
19146     assert(RefExpr && "NULL expr in OpenMP is_device_ptr clause.");
19147     SourceLocation ELoc;
19148     SourceRange ERange;
19149     Expr *SimpleRefExpr = RefExpr;
19150     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
19151     if (Res.second) {
19152       // It will be analyzed later.
19153       MVLI.ProcessedVarList.push_back(RefExpr);
19154     }
19155     ValueDecl *D = Res.first;
19156     if (!D)
19157       continue;
19158 
19159     QualType Type = D->getType();
19160     // item should be a pointer or array or reference to pointer or array
19161     if (!Type.getNonReferenceType()->isPointerType() &&
19162         !Type.getNonReferenceType()->isArrayType()) {
19163       Diag(ELoc, diag::err_omp_argument_type_isdeviceptr)
19164           << 0 << RefExpr->getSourceRange();
19165       continue;
19166     }
19167 
19168     // Check if the declaration in the clause does not show up in any data
19169     // sharing attribute.
19170     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
19171     if (isOpenMPPrivate(DVar.CKind)) {
19172       Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
19173           << getOpenMPClauseName(DVar.CKind)
19174           << getOpenMPClauseName(OMPC_is_device_ptr)
19175           << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
19176       reportOriginalDsa(*this, DSAStack, D, DVar);
19177       continue;
19178     }
19179 
19180     const Expr *ConflictExpr;
19181     if (DSAStack->checkMappableExprComponentListsForDecl(
19182             D, /*CurrentRegionOnly=*/true,
19183             [&ConflictExpr](
19184                 OMPClauseMappableExprCommon::MappableExprComponentListRef R,
19185                 OpenMPClauseKind) -> bool {
19186               ConflictExpr = R.front().getAssociatedExpression();
19187               return true;
19188             })) {
19189       Diag(ELoc, diag::err_omp_map_shared_storage) << RefExpr->getSourceRange();
19190       Diag(ConflictExpr->getExprLoc(), diag::note_used_here)
19191           << ConflictExpr->getSourceRange();
19192       continue;
19193     }
19194 
19195     // Store the components in the stack so that they can be used to check
19196     // against other clauses later on.
19197     OMPClauseMappableExprCommon::MappableComponent MC(
19198         SimpleRefExpr, D, /*IsNonContiguous=*/false);
19199     DSAStack->addMappableExpressionComponents(
19200         D, MC, /*WhereFoundClauseKind=*/OMPC_is_device_ptr);
19201 
19202     // Record the expression we've just processed.
19203     MVLI.ProcessedVarList.push_back(SimpleRefExpr);
19204 
19205     // Create a mappable component for the list item. List items in this clause
19206     // only need a component. We use a null declaration to signal fields in
19207     // 'this'.
19208     assert((isa<DeclRefExpr>(SimpleRefExpr) ||
19209             isa<CXXThisExpr>(cast<MemberExpr>(SimpleRefExpr)->getBase())) &&
19210            "Unexpected device pointer expression!");
19211     MVLI.VarBaseDeclarations.push_back(
19212         isa<DeclRefExpr>(SimpleRefExpr) ? D : nullptr);
19213     MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
19214     MVLI.VarComponents.back().push_back(MC);
19215   }
19216 
19217   if (MVLI.ProcessedVarList.empty())
19218     return nullptr;
19219 
19220   return OMPIsDevicePtrClause::Create(Context, Locs, MVLI.ProcessedVarList,
19221                                       MVLI.VarBaseDeclarations,
19222                                       MVLI.VarComponents);
19223 }
19224 
19225 OMPClause *Sema::ActOnOpenMPAllocateClause(
19226     Expr *Allocator, ArrayRef<Expr *> VarList, SourceLocation StartLoc,
19227     SourceLocation ColonLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
19228   if (Allocator) {
19229     // OpenMP [2.11.4 allocate Clause, Description]
19230     // allocator is an expression of omp_allocator_handle_t type.
19231     if (!findOMPAllocatorHandleT(*this, Allocator->getExprLoc(), DSAStack))
19232       return nullptr;
19233 
19234     ExprResult AllocatorRes = DefaultLvalueConversion(Allocator);
19235     if (AllocatorRes.isInvalid())
19236       return nullptr;
19237     AllocatorRes = PerformImplicitConversion(AllocatorRes.get(),
19238                                              DSAStack->getOMPAllocatorHandleT(),
19239                                              Sema::AA_Initializing,
19240                                              /*AllowExplicit=*/true);
19241     if (AllocatorRes.isInvalid())
19242       return nullptr;
19243     Allocator = AllocatorRes.get();
19244   } else {
19245     // OpenMP 5.0, 2.11.4 allocate Clause, Restrictions.
19246     // allocate clauses that appear on a target construct or on constructs in a
19247     // target region must specify an allocator expression unless a requires
19248     // directive with the dynamic_allocators clause is present in the same
19249     // compilation unit.
19250     if (LangOpts.OpenMPIsDevice &&
19251         !DSAStack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>())
19252       targetDiag(StartLoc, diag::err_expected_allocator_expression);
19253   }
19254   // Analyze and build list of variables.
19255   SmallVector<Expr *, 8> Vars;
19256   for (Expr *RefExpr : VarList) {
19257     assert(RefExpr && "NULL expr in OpenMP private clause.");
19258     SourceLocation ELoc;
19259     SourceRange ERange;
19260     Expr *SimpleRefExpr = RefExpr;
19261     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
19262     if (Res.second) {
19263       // It will be analyzed later.
19264       Vars.push_back(RefExpr);
19265     }
19266     ValueDecl *D = Res.first;
19267     if (!D)
19268       continue;
19269 
19270     auto *VD = dyn_cast<VarDecl>(D);
19271     DeclRefExpr *Ref = nullptr;
19272     if (!VD && !CurContext->isDependentContext())
19273       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
19274     Vars.push_back((VD || CurContext->isDependentContext())
19275                        ? RefExpr->IgnoreParens()
19276                        : Ref);
19277   }
19278 
19279   if (Vars.empty())
19280     return nullptr;
19281 
19282   if (Allocator)
19283     DSAStack->addInnerAllocatorExpr(Allocator);
19284   return OMPAllocateClause::Create(Context, StartLoc, LParenLoc, Allocator,
19285                                    ColonLoc, EndLoc, Vars);
19286 }
19287 
19288 OMPClause *Sema::ActOnOpenMPNontemporalClause(ArrayRef<Expr *> VarList,
19289                                               SourceLocation StartLoc,
19290                                               SourceLocation LParenLoc,
19291                                               SourceLocation EndLoc) {
19292   SmallVector<Expr *, 8> Vars;
19293   for (Expr *RefExpr : VarList) {
19294     assert(RefExpr && "NULL expr in OpenMP nontemporal clause.");
19295     SourceLocation ELoc;
19296     SourceRange ERange;
19297     Expr *SimpleRefExpr = RefExpr;
19298     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
19299     if (Res.second)
19300       // It will be analyzed later.
19301       Vars.push_back(RefExpr);
19302     ValueDecl *D = Res.first;
19303     if (!D)
19304       continue;
19305 
19306     // OpenMP 5.0, 2.9.3.1 simd Construct, Restrictions.
19307     // A list-item cannot appear in more than one nontemporal clause.
19308     if (const Expr *PrevRef =
19309             DSAStack->addUniqueNontemporal(D, SimpleRefExpr)) {
19310       Diag(ELoc, diag::err_omp_used_in_clause_twice)
19311           << 0 << getOpenMPClauseName(OMPC_nontemporal) << ERange;
19312       Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
19313           << getOpenMPClauseName(OMPC_nontemporal);
19314       continue;
19315     }
19316 
19317     Vars.push_back(RefExpr);
19318   }
19319 
19320   if (Vars.empty())
19321     return nullptr;
19322 
19323   return OMPNontemporalClause::Create(Context, StartLoc, LParenLoc, EndLoc,
19324                                       Vars);
19325 }
19326 
19327 OMPClause *Sema::ActOnOpenMPInclusiveClause(ArrayRef<Expr *> VarList,
19328                                             SourceLocation StartLoc,
19329                                             SourceLocation LParenLoc,
19330                                             SourceLocation EndLoc) {
19331   SmallVector<Expr *, 8> Vars;
19332   for (Expr *RefExpr : VarList) {
19333     assert(RefExpr && "NULL expr in OpenMP nontemporal clause.");
19334     SourceLocation ELoc;
19335     SourceRange ERange;
19336     Expr *SimpleRefExpr = RefExpr;
19337     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
19338                               /*AllowArraySection=*/true);
19339     if (Res.second)
19340       // It will be analyzed later.
19341       Vars.push_back(RefExpr);
19342     ValueDecl *D = Res.first;
19343     if (!D)
19344       continue;
19345 
19346     const DSAStackTy::DSAVarData DVar =
19347         DSAStack->getTopDSA(D, /*FromParent=*/true);
19348     // OpenMP 5.0, 2.9.6, scan Directive, Restrictions.
19349     // A list item that appears in the inclusive or exclusive clause must appear
19350     // in a reduction clause with the inscan modifier on the enclosing
19351     // worksharing-loop, worksharing-loop SIMD, or simd construct.
19352     if (DVar.CKind != OMPC_reduction ||
19353         DVar.Modifier != OMPC_REDUCTION_inscan)
19354       Diag(ELoc, diag::err_omp_inclusive_exclusive_not_reduction)
19355           << RefExpr->getSourceRange();
19356 
19357     if (DSAStack->getParentDirective() != OMPD_unknown)
19358       DSAStack->markDeclAsUsedInScanDirective(D);
19359     Vars.push_back(RefExpr);
19360   }
19361 
19362   if (Vars.empty())
19363     return nullptr;
19364 
19365   return OMPInclusiveClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
19366 }
19367 
19368 OMPClause *Sema::ActOnOpenMPExclusiveClause(ArrayRef<Expr *> VarList,
19369                                             SourceLocation StartLoc,
19370                                             SourceLocation LParenLoc,
19371                                             SourceLocation EndLoc) {
19372   SmallVector<Expr *, 8> Vars;
19373   for (Expr *RefExpr : VarList) {
19374     assert(RefExpr && "NULL expr in OpenMP nontemporal clause.");
19375     SourceLocation ELoc;
19376     SourceRange ERange;
19377     Expr *SimpleRefExpr = RefExpr;
19378     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
19379                               /*AllowArraySection=*/true);
19380     if (Res.second)
19381       // It will be analyzed later.
19382       Vars.push_back(RefExpr);
19383     ValueDecl *D = Res.first;
19384     if (!D)
19385       continue;
19386 
19387     OpenMPDirectiveKind ParentDirective = DSAStack->getParentDirective();
19388     DSAStackTy::DSAVarData DVar;
19389     if (ParentDirective != OMPD_unknown)
19390       DVar = DSAStack->getTopDSA(D, /*FromParent=*/true);
19391     // OpenMP 5.0, 2.9.6, scan Directive, Restrictions.
19392     // A list item that appears in the inclusive or exclusive clause must appear
19393     // in a reduction clause with the inscan modifier on the enclosing
19394     // worksharing-loop, worksharing-loop SIMD, or simd construct.
19395     if (ParentDirective == OMPD_unknown || DVar.CKind != OMPC_reduction ||
19396         DVar.Modifier != OMPC_REDUCTION_inscan) {
19397       Diag(ELoc, diag::err_omp_inclusive_exclusive_not_reduction)
19398           << RefExpr->getSourceRange();
19399     } else {
19400       DSAStack->markDeclAsUsedInScanDirective(D);
19401     }
19402     Vars.push_back(RefExpr);
19403   }
19404 
19405   if (Vars.empty())
19406     return nullptr;
19407 
19408   return OMPExclusiveClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
19409 }
19410 
19411 /// Tries to find omp_alloctrait_t type.
19412 static bool findOMPAlloctraitT(Sema &S, SourceLocation Loc, DSAStackTy *Stack) {
19413   QualType OMPAlloctraitT = Stack->getOMPAlloctraitT();
19414   if (!OMPAlloctraitT.isNull())
19415     return true;
19416   IdentifierInfo &II = S.PP.getIdentifierTable().get("omp_alloctrait_t");
19417   ParsedType PT = S.getTypeName(II, Loc, S.getCurScope());
19418   if (!PT.getAsOpaquePtr() || PT.get().isNull()) {
19419     S.Diag(Loc, diag::err_omp_implied_type_not_found) << "omp_alloctrait_t";
19420     return false;
19421   }
19422   Stack->setOMPAlloctraitT(PT.get());
19423   return true;
19424 }
19425 
19426 OMPClause *Sema::ActOnOpenMPUsesAllocatorClause(
19427     SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc,
19428     ArrayRef<UsesAllocatorsData> Data) {
19429   // OpenMP [2.12.5, target Construct]
19430   // allocator is an identifier of omp_allocator_handle_t type.
19431   if (!findOMPAllocatorHandleT(*this, StartLoc, DSAStack))
19432     return nullptr;
19433   // OpenMP [2.12.5, target Construct]
19434   // allocator-traits-array is an identifier of const omp_alloctrait_t * type.
19435   if (llvm::any_of(
19436           Data,
19437           [](const UsesAllocatorsData &D) { return D.AllocatorTraits; }) &&
19438       !findOMPAlloctraitT(*this, StartLoc, DSAStack))
19439     return nullptr;
19440   llvm::SmallPtrSet<CanonicalDeclPtr<Decl>, 4> PredefinedAllocators;
19441   for (int I = 0; I < OMPAllocateDeclAttr::OMPUserDefinedMemAlloc; ++I) {
19442     auto AllocatorKind = static_cast<OMPAllocateDeclAttr::AllocatorTypeTy>(I);
19443     StringRef Allocator =
19444         OMPAllocateDeclAttr::ConvertAllocatorTypeTyToStr(AllocatorKind);
19445     DeclarationName AllocatorName = &Context.Idents.get(Allocator);
19446     PredefinedAllocators.insert(LookupSingleName(
19447         TUScope, AllocatorName, StartLoc, Sema::LookupAnyName));
19448   }
19449 
19450   SmallVector<OMPUsesAllocatorsClause::Data, 4> NewData;
19451   for (const UsesAllocatorsData &D : Data) {
19452     Expr *AllocatorExpr = nullptr;
19453     // Check allocator expression.
19454     if (D.Allocator->isTypeDependent()) {
19455       AllocatorExpr = D.Allocator;
19456     } else {
19457       // Traits were specified - need to assign new allocator to the specified
19458       // allocator, so it must be an lvalue.
19459       AllocatorExpr = D.Allocator->IgnoreParenImpCasts();
19460       auto *DRE = dyn_cast<DeclRefExpr>(AllocatorExpr);
19461       bool IsPredefinedAllocator = false;
19462       if (DRE)
19463         IsPredefinedAllocator = PredefinedAllocators.count(DRE->getDecl());
19464       if (!DRE ||
19465           !(Context.hasSameUnqualifiedType(
19466                 AllocatorExpr->getType(), DSAStack->getOMPAllocatorHandleT()) ||
19467             Context.typesAreCompatible(AllocatorExpr->getType(),
19468                                        DSAStack->getOMPAllocatorHandleT(),
19469                                        /*CompareUnqualified=*/true)) ||
19470           (!IsPredefinedAllocator &&
19471            (AllocatorExpr->getType().isConstant(Context) ||
19472             !AllocatorExpr->isLValue()))) {
19473         Diag(D.Allocator->getExprLoc(), diag::err_omp_var_expected)
19474             << "omp_allocator_handle_t" << (DRE ? 1 : 0)
19475             << AllocatorExpr->getType() << D.Allocator->getSourceRange();
19476         continue;
19477       }
19478       // OpenMP [2.12.5, target Construct]
19479       // Predefined allocators appearing in a uses_allocators clause cannot have
19480       // traits specified.
19481       if (IsPredefinedAllocator && D.AllocatorTraits) {
19482         Diag(D.AllocatorTraits->getExprLoc(),
19483              diag::err_omp_predefined_allocator_with_traits)
19484             << D.AllocatorTraits->getSourceRange();
19485         Diag(D.Allocator->getExprLoc(), diag::note_omp_predefined_allocator)
19486             << cast<NamedDecl>(DRE->getDecl())->getName()
19487             << D.Allocator->getSourceRange();
19488         continue;
19489       }
19490       // OpenMP [2.12.5, target Construct]
19491       // Non-predefined allocators appearing in a uses_allocators clause must
19492       // have traits specified.
19493       if (!IsPredefinedAllocator && !D.AllocatorTraits) {
19494         Diag(D.Allocator->getExprLoc(),
19495              diag::err_omp_nonpredefined_allocator_without_traits);
19496         continue;
19497       }
19498       // No allocator traits - just convert it to rvalue.
19499       if (!D.AllocatorTraits)
19500         AllocatorExpr = DefaultLvalueConversion(AllocatorExpr).get();
19501       DSAStack->addUsesAllocatorsDecl(
19502           DRE->getDecl(),
19503           IsPredefinedAllocator
19504               ? DSAStackTy::UsesAllocatorsDeclKind::PredefinedAllocator
19505               : DSAStackTy::UsesAllocatorsDeclKind::UserDefinedAllocator);
19506     }
19507     Expr *AllocatorTraitsExpr = nullptr;
19508     if (D.AllocatorTraits) {
19509       if (D.AllocatorTraits->isTypeDependent()) {
19510         AllocatorTraitsExpr = D.AllocatorTraits;
19511       } else {
19512         // OpenMP [2.12.5, target Construct]
19513         // Arrays that contain allocator traits that appear in a uses_allocators
19514         // clause must be constant arrays, have constant values and be defined
19515         // in the same scope as the construct in which the clause appears.
19516         AllocatorTraitsExpr = D.AllocatorTraits->IgnoreParenImpCasts();
19517         // Check that traits expr is a constant array.
19518         QualType TraitTy;
19519         if (const ArrayType *Ty =
19520                 AllocatorTraitsExpr->getType()->getAsArrayTypeUnsafe())
19521           if (const auto *ConstArrayTy = dyn_cast<ConstantArrayType>(Ty))
19522             TraitTy = ConstArrayTy->getElementType();
19523         if (TraitTy.isNull() ||
19524             !(Context.hasSameUnqualifiedType(TraitTy,
19525                                              DSAStack->getOMPAlloctraitT()) ||
19526               Context.typesAreCompatible(TraitTy, DSAStack->getOMPAlloctraitT(),
19527                                          /*CompareUnqualified=*/true))) {
19528           Diag(D.AllocatorTraits->getExprLoc(),
19529                diag::err_omp_expected_array_alloctraits)
19530               << AllocatorTraitsExpr->getType();
19531           continue;
19532         }
19533         // Do not map by default allocator traits if it is a standalone
19534         // variable.
19535         if (auto *DRE = dyn_cast<DeclRefExpr>(AllocatorTraitsExpr))
19536           DSAStack->addUsesAllocatorsDecl(
19537               DRE->getDecl(),
19538               DSAStackTy::UsesAllocatorsDeclKind::AllocatorTrait);
19539       }
19540     }
19541     OMPUsesAllocatorsClause::Data &NewD = NewData.emplace_back();
19542     NewD.Allocator = AllocatorExpr;
19543     NewD.AllocatorTraits = AllocatorTraitsExpr;
19544     NewD.LParenLoc = D.LParenLoc;
19545     NewD.RParenLoc = D.RParenLoc;
19546   }
19547   return OMPUsesAllocatorsClause::Create(Context, StartLoc, LParenLoc, EndLoc,
19548                                          NewData);
19549 }
19550 
19551 OMPClause *Sema::ActOnOpenMPAffinityClause(
19552     SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc,
19553     SourceLocation EndLoc, Expr *Modifier, ArrayRef<Expr *> Locators) {
19554   SmallVector<Expr *, 8> Vars;
19555   for (Expr *RefExpr : Locators) {
19556     assert(RefExpr && "NULL expr in OpenMP shared clause.");
19557     if (isa<DependentScopeDeclRefExpr>(RefExpr) || RefExpr->isTypeDependent()) {
19558       // It will be analyzed later.
19559       Vars.push_back(RefExpr);
19560       continue;
19561     }
19562 
19563     SourceLocation ELoc = RefExpr->getExprLoc();
19564     Expr *SimpleExpr = RefExpr->IgnoreParenImpCasts();
19565 
19566     if (!SimpleExpr->isLValue()) {
19567       Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
19568           << 1 << 0 << RefExpr->getSourceRange();
19569       continue;
19570     }
19571 
19572     ExprResult Res;
19573     {
19574       Sema::TentativeAnalysisScope Trap(*this);
19575       Res = CreateBuiltinUnaryOp(ELoc, UO_AddrOf, SimpleExpr);
19576     }
19577     if (!Res.isUsable() && !isa<OMPArraySectionExpr>(SimpleExpr) &&
19578         !isa<OMPArrayShapingExpr>(SimpleExpr)) {
19579       Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
19580           << 1 << 0 << RefExpr->getSourceRange();
19581       continue;
19582     }
19583     Vars.push_back(SimpleExpr);
19584   }
19585 
19586   return OMPAffinityClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
19587                                    EndLoc, Modifier, Vars);
19588 }
19589