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 }
1889 
1890 namespace {
1891 /// Status of the function emission on the host/device.
1892 enum class FunctionEmissionStatus {
1893   Emitted,
1894   Discarded,
1895   Unknown,
1896 };
1897 } // anonymous namespace
1898 
1899 Sema::SemaDiagnosticBuilder Sema::diagIfOpenMPDeviceCode(SourceLocation Loc,
1900                                                          unsigned DiagID,
1901                                                          FunctionDecl *FD) {
1902   assert(LangOpts.OpenMP && LangOpts.OpenMPIsDevice &&
1903          "Expected OpenMP device compilation.");
1904 
1905   SemaDiagnosticBuilder::Kind Kind = SemaDiagnosticBuilder::K_Nop;
1906   if (FD) {
1907     FunctionEmissionStatus FES = getEmissionStatus(FD);
1908     switch (FES) {
1909     case FunctionEmissionStatus::Emitted:
1910       Kind = SemaDiagnosticBuilder::K_Immediate;
1911       break;
1912     case FunctionEmissionStatus::Unknown:
1913       // TODO: We should always delay diagnostics here in case a target
1914       //       region is in a function we do not emit. However, as the
1915       //       current diagnostics are associated with the function containing
1916       //       the target region and we do not emit that one, we would miss out
1917       //       on diagnostics for the target region itself. We need to anchor
1918       //       the diagnostics with the new generated function *or* ensure we
1919       //       emit diagnostics associated with the surrounding function.
1920       Kind = isOpenMPDeviceDelayedContext(*this)
1921                  ? SemaDiagnosticBuilder::K_Deferred
1922                  : SemaDiagnosticBuilder::K_Immediate;
1923       break;
1924     case FunctionEmissionStatus::TemplateDiscarded:
1925     case FunctionEmissionStatus::OMPDiscarded:
1926       Kind = SemaDiagnosticBuilder::K_Nop;
1927       break;
1928     case FunctionEmissionStatus::CUDADiscarded:
1929       llvm_unreachable("CUDADiscarded unexpected in OpenMP device compilation");
1930       break;
1931     }
1932   }
1933 
1934   return SemaDiagnosticBuilder(Kind, Loc, DiagID, FD, *this);
1935 }
1936 
1937 Sema::SemaDiagnosticBuilder Sema::diagIfOpenMPHostCode(SourceLocation Loc,
1938                                                        unsigned DiagID,
1939                                                        FunctionDecl *FD) {
1940   assert(LangOpts.OpenMP && !LangOpts.OpenMPIsDevice &&
1941          "Expected OpenMP host compilation.");
1942 
1943   SemaDiagnosticBuilder::Kind Kind = SemaDiagnosticBuilder::K_Nop;
1944   if (FD) {
1945     FunctionEmissionStatus FES = getEmissionStatus(FD);
1946     switch (FES) {
1947     case FunctionEmissionStatus::Emitted:
1948       Kind = SemaDiagnosticBuilder::K_Immediate;
1949       break;
1950     case FunctionEmissionStatus::Unknown:
1951       Kind = SemaDiagnosticBuilder::K_Deferred;
1952       break;
1953     case FunctionEmissionStatus::TemplateDiscarded:
1954     case FunctionEmissionStatus::OMPDiscarded:
1955     case FunctionEmissionStatus::CUDADiscarded:
1956       Kind = SemaDiagnosticBuilder::K_Nop;
1957       break;
1958     }
1959   }
1960 
1961   return SemaDiagnosticBuilder(Kind, Loc, DiagID, FD, *this);
1962 }
1963 
1964 static OpenMPDefaultmapClauseKind
1965 getVariableCategoryFromDecl(const LangOptions &LO, const ValueDecl *VD) {
1966   if (LO.OpenMP <= 45) {
1967     if (VD->getType().getNonReferenceType()->isScalarType())
1968       return OMPC_DEFAULTMAP_scalar;
1969     return OMPC_DEFAULTMAP_aggregate;
1970   }
1971   if (VD->getType().getNonReferenceType()->isAnyPointerType())
1972     return OMPC_DEFAULTMAP_pointer;
1973   if (VD->getType().getNonReferenceType()->isScalarType())
1974     return OMPC_DEFAULTMAP_scalar;
1975   return OMPC_DEFAULTMAP_aggregate;
1976 }
1977 
1978 bool Sema::isOpenMPCapturedByRef(const ValueDecl *D, unsigned Level,
1979                                  unsigned OpenMPCaptureLevel) const {
1980   assert(LangOpts.OpenMP && "OpenMP is not allowed");
1981 
1982   ASTContext &Ctx = getASTContext();
1983   bool IsByRef = true;
1984 
1985   // Find the directive that is associated with the provided scope.
1986   D = cast<ValueDecl>(D->getCanonicalDecl());
1987   QualType Ty = D->getType();
1988 
1989   bool IsVariableUsedInMapClause = false;
1990   if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, Level)) {
1991     // This table summarizes how a given variable should be passed to the device
1992     // given its type and the clauses where it appears. This table is based on
1993     // the description in OpenMP 4.5 [2.10.4, target Construct] and
1994     // OpenMP 4.5 [2.15.5, Data-mapping Attribute Rules and Clauses].
1995     //
1996     // =========================================================================
1997     // | type |  defaultmap   | pvt | first | is_device_ptr |    map   | res.  |
1998     // |      |(tofrom:scalar)|     |  pvt  |               |          |       |
1999     // =========================================================================
2000     // | scl  |               |     |       |       -       |          | bycopy|
2001     // | scl  |               |  -  |   x   |       -       |     -    | bycopy|
2002     // | scl  |               |  x  |   -   |       -       |     -    | null  |
2003     // | scl  |       x       |     |       |       -       |          | byref |
2004     // | scl  |       x       |  -  |   x   |       -       |     -    | bycopy|
2005     // | scl  |       x       |  x  |   -   |       -       |     -    | null  |
2006     // | scl  |               |  -  |   -   |       -       |     x    | byref |
2007     // | scl  |       x       |  -  |   -   |       -       |     x    | byref |
2008     //
2009     // | agg  |      n.a.     |     |       |       -       |          | byref |
2010     // | agg  |      n.a.     |  -  |   x   |       -       |     -    | byref |
2011     // | agg  |      n.a.     |  x  |   -   |       -       |     -    | null  |
2012     // | agg  |      n.a.     |  -  |   -   |       -       |     x    | byref |
2013     // | agg  |      n.a.     |  -  |   -   |       -       |    x[]   | byref |
2014     //
2015     // | ptr  |      n.a.     |     |       |       -       |          | bycopy|
2016     // | ptr  |      n.a.     |  -  |   x   |       -       |     -    | bycopy|
2017     // | ptr  |      n.a.     |  x  |   -   |       -       |     -    | null  |
2018     // | ptr  |      n.a.     |  -  |   -   |       -       |     x    | byref |
2019     // | ptr  |      n.a.     |  -  |   -   |       -       |    x[]   | bycopy|
2020     // | ptr  |      n.a.     |  -  |   -   |       x       |          | bycopy|
2021     // | ptr  |      n.a.     |  -  |   -   |       x       |     x    | bycopy|
2022     // | ptr  |      n.a.     |  -  |   -   |       x       |    x[]   | bycopy|
2023     // =========================================================================
2024     // Legend:
2025     //  scl - scalar
2026     //  ptr - pointer
2027     //  agg - aggregate
2028     //  x - applies
2029     //  - - invalid in this combination
2030     //  [] - mapped with an array section
2031     //  byref - should be mapped by reference
2032     //  byval - should be mapped by value
2033     //  null - initialize a local variable to null on the device
2034     //
2035     // Observations:
2036     //  - All scalar declarations that show up in a map clause have to be passed
2037     //    by reference, because they may have been mapped in the enclosing data
2038     //    environment.
2039     //  - If the scalar value does not fit the size of uintptr, it has to be
2040     //    passed by reference, regardless the result in the table above.
2041     //  - For pointers mapped by value that have either an implicit map or an
2042     //    array section, the runtime library may pass the NULL value to the
2043     //    device instead of the value passed to it by the compiler.
2044 
2045     if (Ty->isReferenceType())
2046       Ty = Ty->castAs<ReferenceType>()->getPointeeType();
2047 
2048     // Locate map clauses and see if the variable being captured is referred to
2049     // in any of those clauses. Here we only care about variables, not fields,
2050     // because fields are part of aggregates.
2051     bool IsVariableAssociatedWithSection = false;
2052 
2053     DSAStack->checkMappableExprComponentListsForDeclAtLevel(
2054         D, Level,
2055         [&IsVariableUsedInMapClause, &IsVariableAssociatedWithSection, D](
2056             OMPClauseMappableExprCommon::MappableExprComponentListRef
2057                 MapExprComponents,
2058             OpenMPClauseKind WhereFoundClauseKind) {
2059           // Only the map clause information influences how a variable is
2060           // captured. E.g. is_device_ptr does not require changing the default
2061           // behavior.
2062           if (WhereFoundClauseKind != OMPC_map)
2063             return false;
2064 
2065           auto EI = MapExprComponents.rbegin();
2066           auto EE = MapExprComponents.rend();
2067 
2068           assert(EI != EE && "Invalid map expression!");
2069 
2070           if (isa<DeclRefExpr>(EI->getAssociatedExpression()))
2071             IsVariableUsedInMapClause |= EI->getAssociatedDeclaration() == D;
2072 
2073           ++EI;
2074           if (EI == EE)
2075             return false;
2076 
2077           if (isa<ArraySubscriptExpr>(EI->getAssociatedExpression()) ||
2078               isa<OMPArraySectionExpr>(EI->getAssociatedExpression()) ||
2079               isa<MemberExpr>(EI->getAssociatedExpression()) ||
2080               isa<OMPArrayShapingExpr>(EI->getAssociatedExpression())) {
2081             IsVariableAssociatedWithSection = true;
2082             // There is nothing more we need to know about this variable.
2083             return true;
2084           }
2085 
2086           // Keep looking for more map info.
2087           return false;
2088         });
2089 
2090     if (IsVariableUsedInMapClause) {
2091       // If variable is identified in a map clause it is always captured by
2092       // reference except if it is a pointer that is dereferenced somehow.
2093       IsByRef = !(Ty->isPointerType() && IsVariableAssociatedWithSection);
2094     } else {
2095       // By default, all the data that has a scalar type is mapped by copy
2096       // (except for reduction variables).
2097       // Defaultmap scalar is mutual exclusive to defaultmap pointer
2098       IsByRef = (DSAStack->isForceCaptureByReferenceInTargetExecutable() &&
2099                  !Ty->isAnyPointerType()) ||
2100                 !Ty->isScalarType() ||
2101                 DSAStack->isDefaultmapCapturedByRef(
2102                     Level, getVariableCategoryFromDecl(LangOpts, D)) ||
2103                 DSAStack->hasExplicitDSA(
2104                     D,
2105                     [](OpenMPClauseKind K, bool AppliedToPointee) {
2106                       return K == OMPC_reduction && !AppliedToPointee;
2107                     },
2108                     Level);
2109     }
2110   }
2111 
2112   if (IsByRef && Ty.getNonReferenceType()->isScalarType()) {
2113     IsByRef =
2114         ((IsVariableUsedInMapClause &&
2115           DSAStack->getCaptureRegion(Level, OpenMPCaptureLevel) ==
2116               OMPD_target) ||
2117          !(DSAStack->hasExplicitDSA(
2118                D,
2119                [](OpenMPClauseKind K, bool AppliedToPointee) -> bool {
2120                  return K == OMPC_firstprivate ||
2121                         (K == OMPC_reduction && AppliedToPointee);
2122                },
2123                Level, /*NotLastprivate=*/true) ||
2124            DSAStack->isUsesAllocatorsDecl(Level, D))) &&
2125         // If the variable is artificial and must be captured by value - try to
2126         // capture by value.
2127         !(isa<OMPCapturedExprDecl>(D) && !D->hasAttr<OMPCaptureNoInitAttr>() &&
2128           !cast<OMPCapturedExprDecl>(D)->getInit()->isGLValue()) &&
2129         // If the variable is implicitly firstprivate and scalar - capture by
2130         // copy
2131         !(DSAStack->getDefaultDSA() == DSA_firstprivate &&
2132           !DSAStack->hasExplicitDSA(
2133               D, [](OpenMPClauseKind K, bool) { return K != OMPC_unknown; },
2134               Level) &&
2135           !DSAStack->isLoopControlVariable(D, Level).first);
2136   }
2137 
2138   // When passing data by copy, we need to make sure it fits the uintptr size
2139   // and alignment, because the runtime library only deals with uintptr types.
2140   // If it does not fit the uintptr size, we need to pass the data by reference
2141   // instead.
2142   if (!IsByRef &&
2143       (Ctx.getTypeSizeInChars(Ty) >
2144            Ctx.getTypeSizeInChars(Ctx.getUIntPtrType()) ||
2145        Ctx.getDeclAlign(D) > Ctx.getTypeAlignInChars(Ctx.getUIntPtrType()))) {
2146     IsByRef = true;
2147   }
2148 
2149   return IsByRef;
2150 }
2151 
2152 unsigned Sema::getOpenMPNestingLevel() const {
2153   assert(getLangOpts().OpenMP);
2154   return DSAStack->getNestingLevel();
2155 }
2156 
2157 bool Sema::isInOpenMPTargetExecutionDirective() const {
2158   return (isOpenMPTargetExecutionDirective(DSAStack->getCurrentDirective()) &&
2159           !DSAStack->isClauseParsingMode()) ||
2160          DSAStack->hasDirective(
2161              [](OpenMPDirectiveKind K, const DeclarationNameInfo &,
2162                 SourceLocation) -> bool {
2163                return isOpenMPTargetExecutionDirective(K);
2164              },
2165              false);
2166 }
2167 
2168 VarDecl *Sema::isOpenMPCapturedDecl(ValueDecl *D, bool CheckScopeInfo,
2169                                     unsigned StopAt) {
2170   assert(LangOpts.OpenMP && "OpenMP is not allowed");
2171   D = getCanonicalDecl(D);
2172 
2173   auto *VD = dyn_cast<VarDecl>(D);
2174   // Do not capture constexpr variables.
2175   if (VD && VD->isConstexpr())
2176     return nullptr;
2177 
2178   // If we want to determine whether the variable should be captured from the
2179   // perspective of the current capturing scope, and we've already left all the
2180   // capturing scopes of the top directive on the stack, check from the
2181   // perspective of its parent directive (if any) instead.
2182   DSAStackTy::ParentDirectiveScope InParentDirectiveRAII(
2183       *DSAStack, CheckScopeInfo && DSAStack->isBodyComplete());
2184 
2185   // If we are attempting to capture a global variable in a directive with
2186   // 'target' we return true so that this global is also mapped to the device.
2187   //
2188   if (VD && !VD->hasLocalStorage() &&
2189       (getCurCapturedRegion() || getCurBlock() || getCurLambda())) {
2190     if (isInOpenMPDeclareTargetContext()) {
2191       // Try to mark variable as declare target if it is used in capturing
2192       // regions.
2193       if (LangOpts.OpenMP <= 45 &&
2194           !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
2195         checkDeclIsAllowedInOpenMPTarget(nullptr, VD);
2196       return nullptr;
2197     }
2198     if (isInOpenMPTargetExecutionDirective()) {
2199       // If the declaration is enclosed in a 'declare target' directive,
2200       // then it should not be captured.
2201       //
2202       if (OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
2203         return nullptr;
2204       CapturedRegionScopeInfo *CSI = nullptr;
2205       for (FunctionScopeInfo *FSI : llvm::drop_begin(
2206                llvm::reverse(FunctionScopes),
2207                CheckScopeInfo ? (FunctionScopes.size() - (StopAt + 1)) : 0)) {
2208         if (!isa<CapturingScopeInfo>(FSI))
2209           return nullptr;
2210         if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(FSI))
2211           if (RSI->CapRegionKind == CR_OpenMP) {
2212             CSI = RSI;
2213             break;
2214           }
2215       }
2216       assert(CSI && "Failed to find CapturedRegionScopeInfo");
2217       SmallVector<OpenMPDirectiveKind, 4> Regions;
2218       getOpenMPCaptureRegions(Regions,
2219                               DSAStack->getDirective(CSI->OpenMPLevel));
2220       if (Regions[CSI->OpenMPCaptureLevel] != OMPD_task)
2221         return VD;
2222     }
2223   }
2224 
2225   if (CheckScopeInfo) {
2226     bool OpenMPFound = false;
2227     for (unsigned I = StopAt + 1; I > 0; --I) {
2228       FunctionScopeInfo *FSI = FunctionScopes[I - 1];
2229       if(!isa<CapturingScopeInfo>(FSI))
2230         return nullptr;
2231       if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(FSI))
2232         if (RSI->CapRegionKind == CR_OpenMP) {
2233           OpenMPFound = true;
2234           break;
2235         }
2236     }
2237     if (!OpenMPFound)
2238       return nullptr;
2239   }
2240 
2241   if (DSAStack->getCurrentDirective() != OMPD_unknown &&
2242       (!DSAStack->isClauseParsingMode() ||
2243        DSAStack->getParentDirective() != OMPD_unknown)) {
2244     auto &&Info = DSAStack->isLoopControlVariable(D);
2245     if (Info.first ||
2246         (VD && VD->hasLocalStorage() &&
2247          isImplicitOrExplicitTaskingRegion(DSAStack->getCurrentDirective())) ||
2248         (VD && DSAStack->isForceVarCapturing()))
2249       return VD ? VD : Info.second;
2250     DSAStackTy::DSAVarData DVarTop =
2251         DSAStack->getTopDSA(D, DSAStack->isClauseParsingMode());
2252     if (DVarTop.CKind != OMPC_unknown && isOpenMPPrivate(DVarTop.CKind) &&
2253         (!VD || VD->hasLocalStorage() || !DVarTop.AppliedToPointee))
2254       return VD ? VD : cast<VarDecl>(DVarTop.PrivateCopy->getDecl());
2255     // Threadprivate variables must not be captured.
2256     if (isOpenMPThreadPrivate(DVarTop.CKind))
2257       return nullptr;
2258     // The variable is not private or it is the variable in the directive with
2259     // default(none) clause and not used in any clause.
2260     DSAStackTy::DSAVarData DVarPrivate = DSAStack->hasDSA(
2261         D,
2262         [](OpenMPClauseKind C, bool AppliedToPointee) {
2263           return isOpenMPPrivate(C) && !AppliedToPointee;
2264         },
2265         [](OpenMPDirectiveKind) { return true; },
2266         DSAStack->isClauseParsingMode());
2267     // Global shared must not be captured.
2268     if (VD && !VD->hasLocalStorage() && DVarPrivate.CKind == OMPC_unknown &&
2269         ((DSAStack->getDefaultDSA() != DSA_none &&
2270           DSAStack->getDefaultDSA() != DSA_firstprivate) ||
2271          DVarTop.CKind == OMPC_shared))
2272       return nullptr;
2273     if (DVarPrivate.CKind != OMPC_unknown ||
2274         (VD && (DSAStack->getDefaultDSA() == DSA_none ||
2275                 DSAStack->getDefaultDSA() == DSA_firstprivate)))
2276       return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
2277   }
2278   return nullptr;
2279 }
2280 
2281 void Sema::adjustOpenMPTargetScopeIndex(unsigned &FunctionScopesIndex,
2282                                         unsigned Level) const {
2283   FunctionScopesIndex -= getOpenMPCaptureLevels(DSAStack->getDirective(Level));
2284 }
2285 
2286 void Sema::startOpenMPLoop() {
2287   assert(LangOpts.OpenMP && "OpenMP must be enabled.");
2288   if (isOpenMPLoopDirective(DSAStack->getCurrentDirective()))
2289     DSAStack->loopInit();
2290 }
2291 
2292 void Sema::startOpenMPCXXRangeFor() {
2293   assert(LangOpts.OpenMP && "OpenMP must be enabled.");
2294   if (isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
2295     DSAStack->resetPossibleLoopCounter();
2296     DSAStack->loopStart();
2297   }
2298 }
2299 
2300 OpenMPClauseKind Sema::isOpenMPPrivateDecl(ValueDecl *D, unsigned Level,
2301                                            unsigned CapLevel) const {
2302   assert(LangOpts.OpenMP && "OpenMP is not allowed");
2303   if (DSAStack->hasExplicitDirective(
2304           [](OpenMPDirectiveKind K) { return isOpenMPTaskingDirective(K); },
2305           Level)) {
2306     bool IsTriviallyCopyable =
2307         D->getType().getNonReferenceType().isTriviallyCopyableType(Context) &&
2308         !D->getType()
2309              .getNonReferenceType()
2310              .getCanonicalType()
2311              ->getAsCXXRecordDecl();
2312     OpenMPDirectiveKind DKind = DSAStack->getDirective(Level);
2313     SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
2314     getOpenMPCaptureRegions(CaptureRegions, DKind);
2315     if (isOpenMPTaskingDirective(CaptureRegions[CapLevel]) &&
2316         (IsTriviallyCopyable ||
2317          !isOpenMPTaskLoopDirective(CaptureRegions[CapLevel]))) {
2318       if (DSAStack->hasExplicitDSA(
2319               D,
2320               [](OpenMPClauseKind K, bool) { return K == OMPC_firstprivate; },
2321               Level, /*NotLastprivate=*/true))
2322         return OMPC_firstprivate;
2323       DSAStackTy::DSAVarData DVar = DSAStack->getImplicitDSA(D, Level);
2324       if (DVar.CKind != OMPC_shared &&
2325           !DSAStack->isLoopControlVariable(D, Level).first && !DVar.RefExpr) {
2326         DSAStack->addImplicitTaskFirstprivate(Level, D);
2327         return OMPC_firstprivate;
2328       }
2329     }
2330   }
2331   if (isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
2332     if (DSAStack->getAssociatedLoops() > 0 &&
2333         !DSAStack->isLoopStarted()) {
2334       DSAStack->resetPossibleLoopCounter(D);
2335       DSAStack->loopStart();
2336       return OMPC_private;
2337     }
2338     if ((DSAStack->getPossiblyLoopCunter() == D->getCanonicalDecl() ||
2339          DSAStack->isLoopControlVariable(D).first) &&
2340         !DSAStack->hasExplicitDSA(
2341             D, [](OpenMPClauseKind K, bool) { return K != OMPC_private; },
2342             Level) &&
2343         !isOpenMPSimdDirective(DSAStack->getCurrentDirective()))
2344       return OMPC_private;
2345   }
2346   if (const auto *VD = dyn_cast<VarDecl>(D)) {
2347     if (DSAStack->isThreadPrivate(const_cast<VarDecl *>(VD)) &&
2348         DSAStack->isForceVarCapturing() &&
2349         !DSAStack->hasExplicitDSA(
2350             D, [](OpenMPClauseKind K, bool) { return K == OMPC_copyin; },
2351             Level))
2352       return OMPC_private;
2353   }
2354   // User-defined allocators are private since they must be defined in the
2355   // context of target region.
2356   if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, Level) &&
2357       DSAStack->isUsesAllocatorsDecl(Level, D).getValueOr(
2358           DSAStackTy::UsesAllocatorsDeclKind::AllocatorTrait) ==
2359           DSAStackTy::UsesAllocatorsDeclKind::UserDefinedAllocator)
2360     return OMPC_private;
2361   return (DSAStack->hasExplicitDSA(
2362               D, [](OpenMPClauseKind K, bool) { return K == OMPC_private; },
2363               Level) ||
2364           (DSAStack->isClauseParsingMode() &&
2365            DSAStack->getClauseParsingMode() == OMPC_private) ||
2366           // Consider taskgroup reduction descriptor variable a private
2367           // to avoid possible capture in the region.
2368           (DSAStack->hasExplicitDirective(
2369                [](OpenMPDirectiveKind K) {
2370                  return K == OMPD_taskgroup ||
2371                         ((isOpenMPParallelDirective(K) ||
2372                           isOpenMPWorksharingDirective(K)) &&
2373                          !isOpenMPSimdDirective(K));
2374                },
2375                Level) &&
2376            DSAStack->isTaskgroupReductionRef(D, Level)))
2377              ? OMPC_private
2378              : OMPC_unknown;
2379 }
2380 
2381 void Sema::setOpenMPCaptureKind(FieldDecl *FD, const ValueDecl *D,
2382                                 unsigned Level) {
2383   assert(LangOpts.OpenMP && "OpenMP is not allowed");
2384   D = getCanonicalDecl(D);
2385   OpenMPClauseKind OMPC = OMPC_unknown;
2386   for (unsigned I = DSAStack->getNestingLevel() + 1; I > Level; --I) {
2387     const unsigned NewLevel = I - 1;
2388     if (DSAStack->hasExplicitDSA(
2389             D,
2390             [&OMPC](const OpenMPClauseKind K, bool AppliedToPointee) {
2391               if (isOpenMPPrivate(K) && !AppliedToPointee) {
2392                 OMPC = K;
2393                 return true;
2394               }
2395               return false;
2396             },
2397             NewLevel))
2398       break;
2399     if (DSAStack->checkMappableExprComponentListsForDeclAtLevel(
2400             D, NewLevel,
2401             [](OMPClauseMappableExprCommon::MappableExprComponentListRef,
2402                OpenMPClauseKind) { return true; })) {
2403       OMPC = OMPC_map;
2404       break;
2405     }
2406     if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
2407                                        NewLevel)) {
2408       OMPC = OMPC_map;
2409       if (DSAStack->mustBeFirstprivateAtLevel(
2410               NewLevel, getVariableCategoryFromDecl(LangOpts, D)))
2411         OMPC = OMPC_firstprivate;
2412       break;
2413     }
2414   }
2415   if (OMPC != OMPC_unknown)
2416     FD->addAttr(OMPCaptureKindAttr::CreateImplicit(Context, unsigned(OMPC)));
2417 }
2418 
2419 bool Sema::isOpenMPTargetCapturedDecl(const ValueDecl *D, unsigned Level,
2420                                       unsigned CaptureLevel) const {
2421   assert(LangOpts.OpenMP && "OpenMP is not allowed");
2422   // Return true if the current level is no longer enclosed in a target region.
2423 
2424   SmallVector<OpenMPDirectiveKind, 4> Regions;
2425   getOpenMPCaptureRegions(Regions, DSAStack->getDirective(Level));
2426   const auto *VD = dyn_cast<VarDecl>(D);
2427   return VD && !VD->hasLocalStorage() &&
2428          DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
2429                                         Level) &&
2430          Regions[CaptureLevel] != OMPD_task;
2431 }
2432 
2433 bool Sema::isOpenMPGlobalCapturedDecl(ValueDecl *D, unsigned Level,
2434                                       unsigned CaptureLevel) const {
2435   assert(LangOpts.OpenMP && "OpenMP is not allowed");
2436   // Return true if the current level is no longer enclosed in a target region.
2437 
2438   if (const auto *VD = dyn_cast<VarDecl>(D)) {
2439     if (!VD->hasLocalStorage()) {
2440       if (isInOpenMPTargetExecutionDirective())
2441         return true;
2442       DSAStackTy::DSAVarData TopDVar =
2443           DSAStack->getTopDSA(D, /*FromParent=*/false);
2444       unsigned NumLevels =
2445           getOpenMPCaptureLevels(DSAStack->getDirective(Level));
2446       if (Level == 0)
2447         return (NumLevels == CaptureLevel + 1) && TopDVar.CKind != OMPC_shared;
2448       do {
2449         --Level;
2450         DSAStackTy::DSAVarData DVar = DSAStack->getImplicitDSA(D, Level);
2451         if (DVar.CKind != OMPC_shared)
2452           return true;
2453       } while (Level > 0);
2454     }
2455   }
2456   return true;
2457 }
2458 
2459 void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; }
2460 
2461 void Sema::ActOnOpenMPBeginDeclareVariant(SourceLocation Loc,
2462                                           OMPTraitInfo &TI) {
2463   OMPDeclareVariantScopes.push_back(OMPDeclareVariantScope(TI));
2464 }
2465 
2466 void Sema::ActOnOpenMPEndDeclareVariant() {
2467   assert(isInOpenMPDeclareVariantScope() &&
2468          "Not in OpenMP declare variant scope!");
2469 
2470   OMPDeclareVariantScopes.pop_back();
2471 }
2472 
2473 void Sema::finalizeOpenMPDelayedAnalysis(const FunctionDecl *Caller,
2474                                          const FunctionDecl *Callee,
2475                                          SourceLocation Loc) {
2476   assert(LangOpts.OpenMP && "Expected OpenMP compilation mode.");
2477   Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
2478       OMPDeclareTargetDeclAttr::getDeviceType(Caller->getMostRecentDecl());
2479   // Ignore host functions during device analyzis.
2480   if (LangOpts.OpenMPIsDevice && DevTy &&
2481       *DevTy == OMPDeclareTargetDeclAttr::DT_Host)
2482     return;
2483   // Ignore nohost functions during host analyzis.
2484   if (!LangOpts.OpenMPIsDevice && DevTy &&
2485       *DevTy == OMPDeclareTargetDeclAttr::DT_NoHost)
2486     return;
2487   const FunctionDecl *FD = Callee->getMostRecentDecl();
2488   DevTy = OMPDeclareTargetDeclAttr::getDeviceType(FD);
2489   if (LangOpts.OpenMPIsDevice && DevTy &&
2490       *DevTy == OMPDeclareTargetDeclAttr::DT_Host) {
2491     // Diagnose host function called during device codegen.
2492     StringRef HostDevTy =
2493         getOpenMPSimpleClauseTypeName(OMPC_device_type, OMPC_DEVICE_TYPE_host);
2494     Diag(Loc, diag::err_omp_wrong_device_function_call) << HostDevTy << 0;
2495     Diag(*OMPDeclareTargetDeclAttr::getLocation(FD),
2496          diag::note_omp_marked_device_type_here)
2497         << HostDevTy;
2498     return;
2499   }
2500       if (!LangOpts.OpenMPIsDevice && DevTy &&
2501           *DevTy == OMPDeclareTargetDeclAttr::DT_NoHost) {
2502         // Diagnose nohost function called during host codegen.
2503         StringRef NoHostDevTy = getOpenMPSimpleClauseTypeName(
2504             OMPC_device_type, OMPC_DEVICE_TYPE_nohost);
2505         Diag(Loc, diag::err_omp_wrong_device_function_call) << NoHostDevTy << 1;
2506         Diag(*OMPDeclareTargetDeclAttr::getLocation(FD),
2507              diag::note_omp_marked_device_type_here)
2508             << NoHostDevTy;
2509       }
2510 }
2511 
2512 void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind,
2513                                const DeclarationNameInfo &DirName,
2514                                Scope *CurScope, SourceLocation Loc) {
2515   DSAStack->push(DKind, DirName, CurScope, Loc);
2516   PushExpressionEvaluationContext(
2517       ExpressionEvaluationContext::PotentiallyEvaluated);
2518 }
2519 
2520 void Sema::StartOpenMPClause(OpenMPClauseKind K) {
2521   DSAStack->setClauseParsingMode(K);
2522 }
2523 
2524 void Sema::EndOpenMPClause() {
2525   DSAStack->setClauseParsingMode(/*K=*/OMPC_unknown);
2526 }
2527 
2528 static std::pair<ValueDecl *, bool>
2529 getPrivateItem(Sema &S, Expr *&RefExpr, SourceLocation &ELoc,
2530                SourceRange &ERange, bool AllowArraySection = false);
2531 
2532 /// Check consistency of the reduction clauses.
2533 static void checkReductionClauses(Sema &S, DSAStackTy *Stack,
2534                                   ArrayRef<OMPClause *> Clauses) {
2535   bool InscanFound = false;
2536   SourceLocation InscanLoc;
2537   // OpenMP 5.0, 2.19.5.4 reduction Clause, Restrictions.
2538   // A reduction clause without the inscan reduction-modifier may not appear on
2539   // a construct on which a reduction clause with the inscan reduction-modifier
2540   // appears.
2541   for (OMPClause *C : Clauses) {
2542     if (C->getClauseKind() != OMPC_reduction)
2543       continue;
2544     auto *RC = cast<OMPReductionClause>(C);
2545     if (RC->getModifier() == OMPC_REDUCTION_inscan) {
2546       InscanFound = true;
2547       InscanLoc = RC->getModifierLoc();
2548       continue;
2549     }
2550     if (RC->getModifier() == OMPC_REDUCTION_task) {
2551       // OpenMP 5.0, 2.19.5.4 reduction Clause.
2552       // A reduction clause with the task reduction-modifier may only appear on
2553       // a parallel construct, a worksharing construct or a combined or
2554       // composite construct for which any of the aforementioned constructs is a
2555       // constituent construct and simd or loop are not constituent constructs.
2556       OpenMPDirectiveKind CurDir = Stack->getCurrentDirective();
2557       if (!(isOpenMPParallelDirective(CurDir) ||
2558             isOpenMPWorksharingDirective(CurDir)) ||
2559           isOpenMPSimdDirective(CurDir))
2560         S.Diag(RC->getModifierLoc(),
2561                diag::err_omp_reduction_task_not_parallel_or_worksharing);
2562       continue;
2563     }
2564   }
2565   if (InscanFound) {
2566     for (OMPClause *C : Clauses) {
2567       if (C->getClauseKind() != OMPC_reduction)
2568         continue;
2569       auto *RC = cast<OMPReductionClause>(C);
2570       if (RC->getModifier() != OMPC_REDUCTION_inscan) {
2571         S.Diag(RC->getModifier() == OMPC_REDUCTION_unknown
2572                    ? RC->getBeginLoc()
2573                    : RC->getModifierLoc(),
2574                diag::err_omp_inscan_reduction_expected);
2575         S.Diag(InscanLoc, diag::note_omp_previous_inscan_reduction);
2576         continue;
2577       }
2578       for (Expr *Ref : RC->varlists()) {
2579         assert(Ref && "NULL expr in OpenMP nontemporal clause.");
2580         SourceLocation ELoc;
2581         SourceRange ERange;
2582         Expr *SimpleRefExpr = Ref;
2583         auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange,
2584                                   /*AllowArraySection=*/true);
2585         ValueDecl *D = Res.first;
2586         if (!D)
2587           continue;
2588         if (!Stack->isUsedInScanDirective(getCanonicalDecl(D))) {
2589           S.Diag(Ref->getExprLoc(),
2590                  diag::err_omp_reduction_not_inclusive_exclusive)
2591               << Ref->getSourceRange();
2592         }
2593       }
2594     }
2595   }
2596 }
2597 
2598 static void checkAllocateClauses(Sema &S, DSAStackTy *Stack,
2599                                  ArrayRef<OMPClause *> Clauses);
2600 static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr,
2601                                  bool WithInit);
2602 
2603 static void reportOriginalDsa(Sema &SemaRef, const DSAStackTy *Stack,
2604                               const ValueDecl *D,
2605                               const DSAStackTy::DSAVarData &DVar,
2606                               bool IsLoopIterVar = false);
2607 
2608 void Sema::EndOpenMPDSABlock(Stmt *CurDirective) {
2609   // OpenMP [2.14.3.5, Restrictions, C/C++, p.1]
2610   //  A variable of class type (or array thereof) that appears in a lastprivate
2611   //  clause requires an accessible, unambiguous default constructor for the
2612   //  class type, unless the list item is also specified in a firstprivate
2613   //  clause.
2614   if (const auto *D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) {
2615     for (OMPClause *C : D->clauses()) {
2616       if (auto *Clause = dyn_cast<OMPLastprivateClause>(C)) {
2617         SmallVector<Expr *, 8> PrivateCopies;
2618         for (Expr *DE : Clause->varlists()) {
2619           if (DE->isValueDependent() || DE->isTypeDependent()) {
2620             PrivateCopies.push_back(nullptr);
2621             continue;
2622           }
2623           auto *DRE = cast<DeclRefExpr>(DE->IgnoreParens());
2624           auto *VD = cast<VarDecl>(DRE->getDecl());
2625           QualType Type = VD->getType().getNonReferenceType();
2626           const DSAStackTy::DSAVarData DVar =
2627               DSAStack->getTopDSA(VD, /*FromParent=*/false);
2628           if (DVar.CKind == OMPC_lastprivate) {
2629             // Generate helper private variable and initialize it with the
2630             // default value. The address of the original variable is replaced
2631             // by the address of the new private variable in CodeGen. This new
2632             // variable is not added to IdResolver, so the code in the OpenMP
2633             // region uses original variable for proper diagnostics.
2634             VarDecl *VDPrivate = buildVarDecl(
2635                 *this, DE->getExprLoc(), Type.getUnqualifiedType(),
2636                 VD->getName(), VD->hasAttrs() ? &VD->getAttrs() : nullptr, DRE);
2637             ActOnUninitializedDecl(VDPrivate);
2638             if (VDPrivate->isInvalidDecl()) {
2639               PrivateCopies.push_back(nullptr);
2640               continue;
2641             }
2642             PrivateCopies.push_back(buildDeclRefExpr(
2643                 *this, VDPrivate, DE->getType(), DE->getExprLoc()));
2644           } else {
2645             // The variable is also a firstprivate, so initialization sequence
2646             // for private copy is generated already.
2647             PrivateCopies.push_back(nullptr);
2648           }
2649         }
2650         Clause->setPrivateCopies(PrivateCopies);
2651         continue;
2652       }
2653       // Finalize nontemporal clause by handling private copies, if any.
2654       if (auto *Clause = dyn_cast<OMPNontemporalClause>(C)) {
2655         SmallVector<Expr *, 8> PrivateRefs;
2656         for (Expr *RefExpr : Clause->varlists()) {
2657           assert(RefExpr && "NULL expr in OpenMP nontemporal clause.");
2658           SourceLocation ELoc;
2659           SourceRange ERange;
2660           Expr *SimpleRefExpr = RefExpr;
2661           auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
2662           if (Res.second)
2663             // It will be analyzed later.
2664             PrivateRefs.push_back(RefExpr);
2665           ValueDecl *D = Res.first;
2666           if (!D)
2667             continue;
2668 
2669           const DSAStackTy::DSAVarData DVar =
2670               DSAStack->getTopDSA(D, /*FromParent=*/false);
2671           PrivateRefs.push_back(DVar.PrivateCopy ? DVar.PrivateCopy
2672                                                  : SimpleRefExpr);
2673         }
2674         Clause->setPrivateRefs(PrivateRefs);
2675         continue;
2676       }
2677       if (auto *Clause = dyn_cast<OMPUsesAllocatorsClause>(C)) {
2678         for (unsigned I = 0, E = Clause->getNumberOfAllocators(); I < E; ++I) {
2679           OMPUsesAllocatorsClause::Data D = Clause->getAllocatorData(I);
2680           auto *DRE = dyn_cast<DeclRefExpr>(D.Allocator->IgnoreParenImpCasts());
2681           if (!DRE)
2682             continue;
2683           ValueDecl *VD = DRE->getDecl();
2684           if (!VD || !isa<VarDecl>(VD))
2685             continue;
2686           DSAStackTy::DSAVarData DVar =
2687               DSAStack->getTopDSA(VD, /*FromParent=*/false);
2688           // OpenMP [2.12.5, target Construct]
2689           // Memory allocators that appear in a uses_allocators clause cannot
2690           // appear in other data-sharing attribute clauses or data-mapping
2691           // attribute clauses in the same construct.
2692           Expr *MapExpr = nullptr;
2693           if (DVar.RefExpr ||
2694               DSAStack->checkMappableExprComponentListsForDecl(
2695                   VD, /*CurrentRegionOnly=*/true,
2696                   [VD, &MapExpr](
2697                       OMPClauseMappableExprCommon::MappableExprComponentListRef
2698                           MapExprComponents,
2699                       OpenMPClauseKind C) {
2700                     auto MI = MapExprComponents.rbegin();
2701                     auto ME = MapExprComponents.rend();
2702                     if (MI != ME &&
2703                         MI->getAssociatedDeclaration()->getCanonicalDecl() ==
2704                             VD->getCanonicalDecl()) {
2705                       MapExpr = MI->getAssociatedExpression();
2706                       return true;
2707                     }
2708                     return false;
2709                   })) {
2710             Diag(D.Allocator->getExprLoc(),
2711                  diag::err_omp_allocator_used_in_clauses)
2712                 << D.Allocator->getSourceRange();
2713             if (DVar.RefExpr)
2714               reportOriginalDsa(*this, DSAStack, VD, DVar);
2715             else
2716               Diag(MapExpr->getExprLoc(), diag::note_used_here)
2717                   << MapExpr->getSourceRange();
2718           }
2719         }
2720         continue;
2721       }
2722     }
2723     // Check allocate clauses.
2724     if (!CurContext->isDependentContext())
2725       checkAllocateClauses(*this, DSAStack, D->clauses());
2726     checkReductionClauses(*this, DSAStack, D->clauses());
2727   }
2728 
2729   DSAStack->pop();
2730   DiscardCleanupsInEvaluationContext();
2731   PopExpressionEvaluationContext();
2732 }
2733 
2734 static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
2735                                      Expr *NumIterations, Sema &SemaRef,
2736                                      Scope *S, DSAStackTy *Stack);
2737 
2738 namespace {
2739 
2740 class VarDeclFilterCCC final : public CorrectionCandidateCallback {
2741 private:
2742   Sema &SemaRef;
2743 
2744 public:
2745   explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {}
2746   bool ValidateCandidate(const TypoCorrection &Candidate) override {
2747     NamedDecl *ND = Candidate.getCorrectionDecl();
2748     if (const auto *VD = dyn_cast_or_null<VarDecl>(ND)) {
2749       return VD->hasGlobalStorage() &&
2750              SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
2751                                    SemaRef.getCurScope());
2752     }
2753     return false;
2754   }
2755 
2756   std::unique_ptr<CorrectionCandidateCallback> clone() override {
2757     return std::make_unique<VarDeclFilterCCC>(*this);
2758   }
2759 
2760 };
2761 
2762 class VarOrFuncDeclFilterCCC final : public CorrectionCandidateCallback {
2763 private:
2764   Sema &SemaRef;
2765 
2766 public:
2767   explicit VarOrFuncDeclFilterCCC(Sema &S) : SemaRef(S) {}
2768   bool ValidateCandidate(const TypoCorrection &Candidate) override {
2769     NamedDecl *ND = Candidate.getCorrectionDecl();
2770     if (ND && ((isa<VarDecl>(ND) && ND->getKind() == Decl::Var) ||
2771                isa<FunctionDecl>(ND))) {
2772       return SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
2773                                    SemaRef.getCurScope());
2774     }
2775     return false;
2776   }
2777 
2778   std::unique_ptr<CorrectionCandidateCallback> clone() override {
2779     return std::make_unique<VarOrFuncDeclFilterCCC>(*this);
2780   }
2781 };
2782 
2783 } // namespace
2784 
2785 ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope,
2786                                          CXXScopeSpec &ScopeSpec,
2787                                          const DeclarationNameInfo &Id,
2788                                          OpenMPDirectiveKind Kind) {
2789   LookupResult Lookup(*this, Id, LookupOrdinaryName);
2790   LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
2791 
2792   if (Lookup.isAmbiguous())
2793     return ExprError();
2794 
2795   VarDecl *VD;
2796   if (!Lookup.isSingleResult()) {
2797     VarDeclFilterCCC CCC(*this);
2798     if (TypoCorrection Corrected =
2799             CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr, CCC,
2800                         CTK_ErrorRecovery)) {
2801       diagnoseTypo(Corrected,
2802                    PDiag(Lookup.empty()
2803                              ? diag::err_undeclared_var_use_suggest
2804                              : diag::err_omp_expected_var_arg_suggest)
2805                        << Id.getName());
2806       VD = Corrected.getCorrectionDeclAs<VarDecl>();
2807     } else {
2808       Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use
2809                                        : diag::err_omp_expected_var_arg)
2810           << Id.getName();
2811       return ExprError();
2812     }
2813   } else if (!(VD = Lookup.getAsSingle<VarDecl>())) {
2814     Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName();
2815     Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at);
2816     return ExprError();
2817   }
2818   Lookup.suppressDiagnostics();
2819 
2820   // OpenMP [2.9.2, Syntax, C/C++]
2821   //   Variables must be file-scope, namespace-scope, or static block-scope.
2822   if (Kind == OMPD_threadprivate && !VD->hasGlobalStorage()) {
2823     Diag(Id.getLoc(), diag::err_omp_global_var_arg)
2824         << getOpenMPDirectiveName(Kind) << !VD->isStaticLocal();
2825     bool IsDecl =
2826         VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2827     Diag(VD->getLocation(),
2828          IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2829         << VD;
2830     return ExprError();
2831   }
2832 
2833   VarDecl *CanonicalVD = VD->getCanonicalDecl();
2834   NamedDecl *ND = CanonicalVD;
2835   // OpenMP [2.9.2, Restrictions, C/C++, p.2]
2836   //   A threadprivate directive for file-scope variables must appear outside
2837   //   any definition or declaration.
2838   if (CanonicalVD->getDeclContext()->isTranslationUnit() &&
2839       !getCurLexicalContext()->isTranslationUnit()) {
2840     Diag(Id.getLoc(), diag::err_omp_var_scope)
2841         << getOpenMPDirectiveName(Kind) << VD;
2842     bool IsDecl =
2843         VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2844     Diag(VD->getLocation(),
2845          IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2846         << VD;
2847     return ExprError();
2848   }
2849   // OpenMP [2.9.2, Restrictions, C/C++, p.3]
2850   //   A threadprivate directive for static class member variables must appear
2851   //   in the class definition, in the same scope in which the member
2852   //   variables are declared.
2853   if (CanonicalVD->isStaticDataMember() &&
2854       !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) {
2855     Diag(Id.getLoc(), diag::err_omp_var_scope)
2856         << getOpenMPDirectiveName(Kind) << VD;
2857     bool IsDecl =
2858         VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2859     Diag(VD->getLocation(),
2860          IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2861         << VD;
2862     return ExprError();
2863   }
2864   // OpenMP [2.9.2, Restrictions, C/C++, p.4]
2865   //   A threadprivate directive for namespace-scope variables must appear
2866   //   outside any definition or declaration other than the namespace
2867   //   definition itself.
2868   if (CanonicalVD->getDeclContext()->isNamespace() &&
2869       (!getCurLexicalContext()->isFileContext() ||
2870        !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) {
2871     Diag(Id.getLoc(), diag::err_omp_var_scope)
2872         << getOpenMPDirectiveName(Kind) << VD;
2873     bool IsDecl =
2874         VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2875     Diag(VD->getLocation(),
2876          IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2877         << VD;
2878     return ExprError();
2879   }
2880   // OpenMP [2.9.2, Restrictions, C/C++, p.6]
2881   //   A threadprivate directive for static block-scope variables must appear
2882   //   in the scope of the variable and not in a nested scope.
2883   if (CanonicalVD->isLocalVarDecl() && CurScope &&
2884       !isDeclInScope(ND, getCurLexicalContext(), CurScope)) {
2885     Diag(Id.getLoc(), diag::err_omp_var_scope)
2886         << getOpenMPDirectiveName(Kind) << VD;
2887     bool IsDecl =
2888         VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2889     Diag(VD->getLocation(),
2890          IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2891         << VD;
2892     return ExprError();
2893   }
2894 
2895   // OpenMP [2.9.2, Restrictions, C/C++, p.2-6]
2896   //   A threadprivate directive must lexically precede all references to any
2897   //   of the variables in its list.
2898   if (Kind == OMPD_threadprivate && VD->isUsed() &&
2899       !DSAStack->isThreadPrivate(VD)) {
2900     Diag(Id.getLoc(), diag::err_omp_var_used)
2901         << getOpenMPDirectiveName(Kind) << VD;
2902     return ExprError();
2903   }
2904 
2905   QualType ExprType = VD->getType().getNonReferenceType();
2906   return DeclRefExpr::Create(Context, NestedNameSpecifierLoc(),
2907                              SourceLocation(), VD,
2908                              /*RefersToEnclosingVariableOrCapture=*/false,
2909                              Id.getLoc(), ExprType, VK_LValue);
2910 }
2911 
2912 Sema::DeclGroupPtrTy
2913 Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc,
2914                                         ArrayRef<Expr *> VarList) {
2915   if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) {
2916     CurContext->addDecl(D);
2917     return DeclGroupPtrTy::make(DeclGroupRef(D));
2918   }
2919   return nullptr;
2920 }
2921 
2922 namespace {
2923 class LocalVarRefChecker final
2924     : public ConstStmtVisitor<LocalVarRefChecker, bool> {
2925   Sema &SemaRef;
2926 
2927 public:
2928   bool VisitDeclRefExpr(const DeclRefExpr *E) {
2929     if (const auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
2930       if (VD->hasLocalStorage()) {
2931         SemaRef.Diag(E->getBeginLoc(),
2932                      diag::err_omp_local_var_in_threadprivate_init)
2933             << E->getSourceRange();
2934         SemaRef.Diag(VD->getLocation(), diag::note_defined_here)
2935             << VD << VD->getSourceRange();
2936         return true;
2937       }
2938     }
2939     return false;
2940   }
2941   bool VisitStmt(const Stmt *S) {
2942     for (const Stmt *Child : S->children()) {
2943       if (Child && Visit(Child))
2944         return true;
2945     }
2946     return false;
2947   }
2948   explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {}
2949 };
2950 } // namespace
2951 
2952 OMPThreadPrivateDecl *
2953 Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) {
2954   SmallVector<Expr *, 8> Vars;
2955   for (Expr *RefExpr : VarList) {
2956     auto *DE = cast<DeclRefExpr>(RefExpr);
2957     auto *VD = cast<VarDecl>(DE->getDecl());
2958     SourceLocation ILoc = DE->getExprLoc();
2959 
2960     // Mark variable as used.
2961     VD->setReferenced();
2962     VD->markUsed(Context);
2963 
2964     QualType QType = VD->getType();
2965     if (QType->isDependentType() || QType->isInstantiationDependentType()) {
2966       // It will be analyzed later.
2967       Vars.push_back(DE);
2968       continue;
2969     }
2970 
2971     // OpenMP [2.9.2, Restrictions, C/C++, p.10]
2972     //   A threadprivate variable must not have an incomplete type.
2973     if (RequireCompleteType(ILoc, VD->getType(),
2974                             diag::err_omp_threadprivate_incomplete_type)) {
2975       continue;
2976     }
2977 
2978     // OpenMP [2.9.2, Restrictions, C/C++, p.10]
2979     //   A threadprivate variable must not have a reference type.
2980     if (VD->getType()->isReferenceType()) {
2981       Diag(ILoc, diag::err_omp_ref_type_arg)
2982           << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType();
2983       bool IsDecl =
2984           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2985       Diag(VD->getLocation(),
2986            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2987           << VD;
2988       continue;
2989     }
2990 
2991     // Check if this is a TLS variable. If TLS is not being supported, produce
2992     // the corresponding diagnostic.
2993     if ((VD->getTLSKind() != VarDecl::TLS_None &&
2994          !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
2995            getLangOpts().OpenMPUseTLS &&
2996            getASTContext().getTargetInfo().isTLSSupported())) ||
2997         (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
2998          !VD->isLocalVarDecl())) {
2999       Diag(ILoc, diag::err_omp_var_thread_local)
3000           << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1);
3001       bool IsDecl =
3002           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
3003       Diag(VD->getLocation(),
3004            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
3005           << VD;
3006       continue;
3007     }
3008 
3009     // Check if initial value of threadprivate variable reference variable with
3010     // local storage (it is not supported by runtime).
3011     if (const Expr *Init = VD->getAnyInitializer()) {
3012       LocalVarRefChecker Checker(*this);
3013       if (Checker.Visit(Init))
3014         continue;
3015     }
3016 
3017     Vars.push_back(RefExpr);
3018     DSAStack->addDSA(VD, DE, OMPC_threadprivate);
3019     VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit(
3020         Context, SourceRange(Loc, Loc)));
3021     if (ASTMutationListener *ML = Context.getASTMutationListener())
3022       ML->DeclarationMarkedOpenMPThreadPrivate(VD);
3023   }
3024   OMPThreadPrivateDecl *D = nullptr;
3025   if (!Vars.empty()) {
3026     D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc,
3027                                      Vars);
3028     D->setAccess(AS_public);
3029   }
3030   return D;
3031 }
3032 
3033 static OMPAllocateDeclAttr::AllocatorTypeTy
3034 getAllocatorKind(Sema &S, DSAStackTy *Stack, Expr *Allocator) {
3035   if (!Allocator)
3036     return OMPAllocateDeclAttr::OMPNullMemAlloc;
3037   if (Allocator->isTypeDependent() || Allocator->isValueDependent() ||
3038       Allocator->isInstantiationDependent() ||
3039       Allocator->containsUnexpandedParameterPack())
3040     return OMPAllocateDeclAttr::OMPUserDefinedMemAlloc;
3041   auto AllocatorKindRes = OMPAllocateDeclAttr::OMPUserDefinedMemAlloc;
3042   const Expr *AE = Allocator->IgnoreParenImpCasts();
3043   for (int I = 0; I < OMPAllocateDeclAttr::OMPUserDefinedMemAlloc; ++I) {
3044     auto AllocatorKind = static_cast<OMPAllocateDeclAttr::AllocatorTypeTy>(I);
3045     const Expr *DefAllocator = Stack->getAllocator(AllocatorKind);
3046     llvm::FoldingSetNodeID AEId, DAEId;
3047     AE->Profile(AEId, S.getASTContext(), /*Canonical=*/true);
3048     DefAllocator->Profile(DAEId, S.getASTContext(), /*Canonical=*/true);
3049     if (AEId == DAEId) {
3050       AllocatorKindRes = AllocatorKind;
3051       break;
3052     }
3053   }
3054   return AllocatorKindRes;
3055 }
3056 
3057 static bool checkPreviousOMPAllocateAttribute(
3058     Sema &S, DSAStackTy *Stack, Expr *RefExpr, VarDecl *VD,
3059     OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind, Expr *Allocator) {
3060   if (!VD->hasAttr<OMPAllocateDeclAttr>())
3061     return false;
3062   const auto *A = VD->getAttr<OMPAllocateDeclAttr>();
3063   Expr *PrevAllocator = A->getAllocator();
3064   OMPAllocateDeclAttr::AllocatorTypeTy PrevAllocatorKind =
3065       getAllocatorKind(S, Stack, PrevAllocator);
3066   bool AllocatorsMatch = AllocatorKind == PrevAllocatorKind;
3067   if (AllocatorsMatch &&
3068       AllocatorKind == OMPAllocateDeclAttr::OMPUserDefinedMemAlloc &&
3069       Allocator && PrevAllocator) {
3070     const Expr *AE = Allocator->IgnoreParenImpCasts();
3071     const Expr *PAE = PrevAllocator->IgnoreParenImpCasts();
3072     llvm::FoldingSetNodeID AEId, PAEId;
3073     AE->Profile(AEId, S.Context, /*Canonical=*/true);
3074     PAE->Profile(PAEId, S.Context, /*Canonical=*/true);
3075     AllocatorsMatch = AEId == PAEId;
3076   }
3077   if (!AllocatorsMatch) {
3078     SmallString<256> AllocatorBuffer;
3079     llvm::raw_svector_ostream AllocatorStream(AllocatorBuffer);
3080     if (Allocator)
3081       Allocator->printPretty(AllocatorStream, nullptr, S.getPrintingPolicy());
3082     SmallString<256> PrevAllocatorBuffer;
3083     llvm::raw_svector_ostream PrevAllocatorStream(PrevAllocatorBuffer);
3084     if (PrevAllocator)
3085       PrevAllocator->printPretty(PrevAllocatorStream, nullptr,
3086                                  S.getPrintingPolicy());
3087 
3088     SourceLocation AllocatorLoc =
3089         Allocator ? Allocator->getExprLoc() : RefExpr->getExprLoc();
3090     SourceRange AllocatorRange =
3091         Allocator ? Allocator->getSourceRange() : RefExpr->getSourceRange();
3092     SourceLocation PrevAllocatorLoc =
3093         PrevAllocator ? PrevAllocator->getExprLoc() : A->getLocation();
3094     SourceRange PrevAllocatorRange =
3095         PrevAllocator ? PrevAllocator->getSourceRange() : A->getRange();
3096     S.Diag(AllocatorLoc, diag::warn_omp_used_different_allocator)
3097         << (Allocator ? 1 : 0) << AllocatorStream.str()
3098         << (PrevAllocator ? 1 : 0) << PrevAllocatorStream.str()
3099         << AllocatorRange;
3100     S.Diag(PrevAllocatorLoc, diag::note_omp_previous_allocator)
3101         << PrevAllocatorRange;
3102     return true;
3103   }
3104   return false;
3105 }
3106 
3107 static void
3108 applyOMPAllocateAttribute(Sema &S, VarDecl *VD,
3109                           OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind,
3110                           Expr *Allocator, SourceRange SR) {
3111   if (VD->hasAttr<OMPAllocateDeclAttr>())
3112     return;
3113   if (Allocator &&
3114       (Allocator->isTypeDependent() || Allocator->isValueDependent() ||
3115        Allocator->isInstantiationDependent() ||
3116        Allocator->containsUnexpandedParameterPack()))
3117     return;
3118   auto *A = OMPAllocateDeclAttr::CreateImplicit(S.Context, AllocatorKind,
3119                                                 Allocator, SR);
3120   VD->addAttr(A);
3121   if (ASTMutationListener *ML = S.Context.getASTMutationListener())
3122     ML->DeclarationMarkedOpenMPAllocate(VD, A);
3123 }
3124 
3125 Sema::DeclGroupPtrTy Sema::ActOnOpenMPAllocateDirective(
3126     SourceLocation Loc, ArrayRef<Expr *> VarList,
3127     ArrayRef<OMPClause *> Clauses, DeclContext *Owner) {
3128   assert(Clauses.size() <= 1 && "Expected at most one clause.");
3129   Expr *Allocator = nullptr;
3130   if (Clauses.empty()) {
3131     // OpenMP 5.0, 2.11.3 allocate Directive, Restrictions.
3132     // allocate directives that appear in a target region must specify an
3133     // allocator clause unless a requires directive with the dynamic_allocators
3134     // clause is present in the same compilation unit.
3135     if (LangOpts.OpenMPIsDevice &&
3136         !DSAStack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>())
3137       targetDiag(Loc, diag::err_expected_allocator_clause);
3138   } else {
3139     Allocator = cast<OMPAllocatorClause>(Clauses.back())->getAllocator();
3140   }
3141   OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind =
3142       getAllocatorKind(*this, DSAStack, Allocator);
3143   SmallVector<Expr *, 8> Vars;
3144   for (Expr *RefExpr : VarList) {
3145     auto *DE = cast<DeclRefExpr>(RefExpr);
3146     auto *VD = cast<VarDecl>(DE->getDecl());
3147 
3148     // Check if this is a TLS variable or global register.
3149     if (VD->getTLSKind() != VarDecl::TLS_None ||
3150         VD->hasAttr<OMPThreadPrivateDeclAttr>() ||
3151         (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
3152          !VD->isLocalVarDecl()))
3153       continue;
3154 
3155     // If the used several times in the allocate directive, the same allocator
3156     // must be used.
3157     if (checkPreviousOMPAllocateAttribute(*this, DSAStack, RefExpr, VD,
3158                                           AllocatorKind, Allocator))
3159       continue;
3160 
3161     // OpenMP, 2.11.3 allocate Directive, Restrictions, C / C++
3162     // If a list item has a static storage type, the allocator expression in the
3163     // allocator clause must be a constant expression that evaluates to one of
3164     // the predefined memory allocator values.
3165     if (Allocator && VD->hasGlobalStorage()) {
3166       if (AllocatorKind == OMPAllocateDeclAttr::OMPUserDefinedMemAlloc) {
3167         Diag(Allocator->getExprLoc(),
3168              diag::err_omp_expected_predefined_allocator)
3169             << Allocator->getSourceRange();
3170         bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
3171                       VarDecl::DeclarationOnly;
3172         Diag(VD->getLocation(),
3173              IsDecl ? diag::note_previous_decl : diag::note_defined_here)
3174             << VD;
3175         continue;
3176       }
3177     }
3178 
3179     Vars.push_back(RefExpr);
3180     applyOMPAllocateAttribute(*this, VD, AllocatorKind, Allocator,
3181                               DE->getSourceRange());
3182   }
3183   if (Vars.empty())
3184     return nullptr;
3185   if (!Owner)
3186     Owner = getCurLexicalContext();
3187   auto *D = OMPAllocateDecl::Create(Context, Owner, Loc, Vars, Clauses);
3188   D->setAccess(AS_public);
3189   Owner->addDecl(D);
3190   return DeclGroupPtrTy::make(DeclGroupRef(D));
3191 }
3192 
3193 Sema::DeclGroupPtrTy
3194 Sema::ActOnOpenMPRequiresDirective(SourceLocation Loc,
3195                                    ArrayRef<OMPClause *> ClauseList) {
3196   OMPRequiresDecl *D = nullptr;
3197   if (!CurContext->isFileContext()) {
3198     Diag(Loc, diag::err_omp_invalid_scope) << "requires";
3199   } else {
3200     D = CheckOMPRequiresDecl(Loc, ClauseList);
3201     if (D) {
3202       CurContext->addDecl(D);
3203       DSAStack->addRequiresDecl(D);
3204     }
3205   }
3206   return DeclGroupPtrTy::make(DeclGroupRef(D));
3207 }
3208 
3209 void Sema::ActOnOpenMPAssumesDirective(SourceLocation Loc,
3210                                        OpenMPDirectiveKind DKind,
3211                                        ArrayRef<StringRef> Assumptions,
3212                                        bool SkippedClauses) {
3213   if (!SkippedClauses && Assumptions.empty())
3214     Diag(Loc, diag::err_omp_no_clause_for_directive)
3215         << llvm::omp::getAllAssumeClauseOptions()
3216         << llvm::omp::getOpenMPDirectiveName(DKind);
3217 
3218   auto *AA = AssumptionAttr::Create(Context, llvm::join(Assumptions, ","), Loc);
3219   if (DKind == llvm::omp::Directive::OMPD_begin_assumes) {
3220     OMPAssumeScoped.push_back(AA);
3221     return;
3222   }
3223 
3224   // Global assumes without assumption clauses are ignored.
3225   if (Assumptions.empty())
3226     return;
3227 
3228   assert(DKind == llvm::omp::Directive::OMPD_assumes &&
3229          "Unexpected omp assumption directive!");
3230   OMPAssumeGlobal.push_back(AA);
3231 
3232   // The OMPAssumeGlobal scope above will take care of new declarations but
3233   // we also want to apply the assumption to existing ones, e.g., to
3234   // declarations in included headers. To this end, we traverse all existing
3235   // declaration contexts and annotate function declarations here.
3236   SmallVector<DeclContext *, 8> DeclContexts;
3237   auto *Ctx = CurContext;
3238   while (Ctx->getLexicalParent())
3239     Ctx = Ctx->getLexicalParent();
3240   DeclContexts.push_back(Ctx);
3241   while (!DeclContexts.empty()) {
3242     DeclContext *DC = DeclContexts.pop_back_val();
3243     for (auto *SubDC : DC->decls()) {
3244       if (SubDC->isInvalidDecl())
3245         continue;
3246       if (auto *CTD = dyn_cast<ClassTemplateDecl>(SubDC)) {
3247         DeclContexts.push_back(CTD->getTemplatedDecl());
3248         for (auto *S : CTD->specializations())
3249           DeclContexts.push_back(S);
3250         continue;
3251       }
3252       if (auto *DC = dyn_cast<DeclContext>(SubDC))
3253         DeclContexts.push_back(DC);
3254       if (auto *F = dyn_cast<FunctionDecl>(SubDC)) {
3255         F->addAttr(AA);
3256         continue;
3257       }
3258     }
3259   }
3260 }
3261 
3262 void Sema::ActOnOpenMPEndAssumesDirective() {
3263   assert(isInOpenMPAssumeScope() && "Not in OpenMP assumes scope!");
3264   OMPAssumeScoped.pop_back();
3265 }
3266 
3267 OMPRequiresDecl *Sema::CheckOMPRequiresDecl(SourceLocation Loc,
3268                                             ArrayRef<OMPClause *> ClauseList) {
3269   /// For target specific clauses, the requires directive cannot be
3270   /// specified after the handling of any of the target regions in the
3271   /// current compilation unit.
3272   ArrayRef<SourceLocation> TargetLocations =
3273       DSAStack->getEncounteredTargetLocs();
3274   SourceLocation AtomicLoc = DSAStack->getAtomicDirectiveLoc();
3275   if (!TargetLocations.empty() || !AtomicLoc.isInvalid()) {
3276     for (const OMPClause *CNew : ClauseList) {
3277       // Check if any of the requires clauses affect target regions.
3278       if (isa<OMPUnifiedSharedMemoryClause>(CNew) ||
3279           isa<OMPUnifiedAddressClause>(CNew) ||
3280           isa<OMPReverseOffloadClause>(CNew) ||
3281           isa<OMPDynamicAllocatorsClause>(CNew)) {
3282         Diag(Loc, diag::err_omp_directive_before_requires)
3283             << "target" << getOpenMPClauseName(CNew->getClauseKind());
3284         for (SourceLocation TargetLoc : TargetLocations) {
3285           Diag(TargetLoc, diag::note_omp_requires_encountered_directive)
3286               << "target";
3287         }
3288       } else if (!AtomicLoc.isInvalid() &&
3289                  isa<OMPAtomicDefaultMemOrderClause>(CNew)) {
3290         Diag(Loc, diag::err_omp_directive_before_requires)
3291             << "atomic" << getOpenMPClauseName(CNew->getClauseKind());
3292         Diag(AtomicLoc, diag::note_omp_requires_encountered_directive)
3293             << "atomic";
3294       }
3295     }
3296   }
3297 
3298   if (!DSAStack->hasDuplicateRequiresClause(ClauseList))
3299     return OMPRequiresDecl::Create(Context, getCurLexicalContext(), Loc,
3300                                    ClauseList);
3301   return nullptr;
3302 }
3303 
3304 static void reportOriginalDsa(Sema &SemaRef, const DSAStackTy *Stack,
3305                               const ValueDecl *D,
3306                               const DSAStackTy::DSAVarData &DVar,
3307                               bool IsLoopIterVar) {
3308   if (DVar.RefExpr) {
3309     SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
3310         << getOpenMPClauseName(DVar.CKind);
3311     return;
3312   }
3313   enum {
3314     PDSA_StaticMemberShared,
3315     PDSA_StaticLocalVarShared,
3316     PDSA_LoopIterVarPrivate,
3317     PDSA_LoopIterVarLinear,
3318     PDSA_LoopIterVarLastprivate,
3319     PDSA_ConstVarShared,
3320     PDSA_GlobalVarShared,
3321     PDSA_TaskVarFirstprivate,
3322     PDSA_LocalVarPrivate,
3323     PDSA_Implicit
3324   } Reason = PDSA_Implicit;
3325   bool ReportHint = false;
3326   auto ReportLoc = D->getLocation();
3327   auto *VD = dyn_cast<VarDecl>(D);
3328   if (IsLoopIterVar) {
3329     if (DVar.CKind == OMPC_private)
3330       Reason = PDSA_LoopIterVarPrivate;
3331     else if (DVar.CKind == OMPC_lastprivate)
3332       Reason = PDSA_LoopIterVarLastprivate;
3333     else
3334       Reason = PDSA_LoopIterVarLinear;
3335   } else if (isOpenMPTaskingDirective(DVar.DKind) &&
3336              DVar.CKind == OMPC_firstprivate) {
3337     Reason = PDSA_TaskVarFirstprivate;
3338     ReportLoc = DVar.ImplicitDSALoc;
3339   } else if (VD && VD->isStaticLocal())
3340     Reason = PDSA_StaticLocalVarShared;
3341   else if (VD && VD->isStaticDataMember())
3342     Reason = PDSA_StaticMemberShared;
3343   else if (VD && VD->isFileVarDecl())
3344     Reason = PDSA_GlobalVarShared;
3345   else if (D->getType().isConstant(SemaRef.getASTContext()))
3346     Reason = PDSA_ConstVarShared;
3347   else if (VD && VD->isLocalVarDecl() && DVar.CKind == OMPC_private) {
3348     ReportHint = true;
3349     Reason = PDSA_LocalVarPrivate;
3350   }
3351   if (Reason != PDSA_Implicit) {
3352     SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa)
3353         << Reason << ReportHint
3354         << getOpenMPDirectiveName(Stack->getCurrentDirective());
3355   } else if (DVar.ImplicitDSALoc.isValid()) {
3356     SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa)
3357         << getOpenMPClauseName(DVar.CKind);
3358   }
3359 }
3360 
3361 static OpenMPMapClauseKind
3362 getMapClauseKindFromModifier(OpenMPDefaultmapClauseModifier M,
3363                              bool IsAggregateOrDeclareTarget) {
3364   OpenMPMapClauseKind Kind = OMPC_MAP_unknown;
3365   switch (M) {
3366   case OMPC_DEFAULTMAP_MODIFIER_alloc:
3367     Kind = OMPC_MAP_alloc;
3368     break;
3369   case OMPC_DEFAULTMAP_MODIFIER_to:
3370     Kind = OMPC_MAP_to;
3371     break;
3372   case OMPC_DEFAULTMAP_MODIFIER_from:
3373     Kind = OMPC_MAP_from;
3374     break;
3375   case OMPC_DEFAULTMAP_MODIFIER_tofrom:
3376     Kind = OMPC_MAP_tofrom;
3377     break;
3378   case OMPC_DEFAULTMAP_MODIFIER_present:
3379     // OpenMP 5.1 [2.21.7.3] defaultmap clause, Description]
3380     // If implicit-behavior is present, each variable referenced in the
3381     // construct in the category specified by variable-category is treated as if
3382     // it had been listed in a map clause with the map-type of alloc and
3383     // map-type-modifier of present.
3384     Kind = OMPC_MAP_alloc;
3385     break;
3386   case OMPC_DEFAULTMAP_MODIFIER_firstprivate:
3387   case OMPC_DEFAULTMAP_MODIFIER_last:
3388     llvm_unreachable("Unexpected defaultmap implicit behavior");
3389   case OMPC_DEFAULTMAP_MODIFIER_none:
3390   case OMPC_DEFAULTMAP_MODIFIER_default:
3391   case OMPC_DEFAULTMAP_MODIFIER_unknown:
3392     // IsAggregateOrDeclareTarget could be true if:
3393     // 1. the implicit behavior for aggregate is tofrom
3394     // 2. it's a declare target link
3395     if (IsAggregateOrDeclareTarget) {
3396       Kind = OMPC_MAP_tofrom;
3397       break;
3398     }
3399     llvm_unreachable("Unexpected defaultmap implicit behavior");
3400   }
3401   assert(Kind != OMPC_MAP_unknown && "Expect map kind to be known");
3402   return Kind;
3403 }
3404 
3405 namespace {
3406 class DSAAttrChecker final : public StmtVisitor<DSAAttrChecker, void> {
3407   DSAStackTy *Stack;
3408   Sema &SemaRef;
3409   bool ErrorFound = false;
3410   bool TryCaptureCXXThisMembers = false;
3411   CapturedStmt *CS = nullptr;
3412   const static unsigned DefaultmapKindNum = OMPC_DEFAULTMAP_pointer + 1;
3413   llvm::SmallVector<Expr *, 4> ImplicitFirstprivate;
3414   llvm::SmallVector<Expr *, 4> ImplicitMap[DefaultmapKindNum][OMPC_MAP_delete];
3415   llvm::SmallVector<OpenMPMapModifierKind, NumberOfOMPMapClauseModifiers>
3416       ImplicitMapModifier[DefaultmapKindNum];
3417   Sema::VarsWithInheritedDSAType VarsWithInheritedDSA;
3418   llvm::SmallDenseSet<const ValueDecl *, 4> ImplicitDeclarations;
3419 
3420   void VisitSubCaptures(OMPExecutableDirective *S) {
3421     // Check implicitly captured variables.
3422     if (!S->hasAssociatedStmt() || !S->getAssociatedStmt())
3423       return;
3424     if (S->getDirectiveKind() == OMPD_atomic ||
3425         S->getDirectiveKind() == OMPD_critical ||
3426         S->getDirectiveKind() == OMPD_section ||
3427         S->getDirectiveKind() == OMPD_master ||
3428         isOpenMPLoopTransformationDirective(S->getDirectiveKind())) {
3429       Visit(S->getAssociatedStmt());
3430       return;
3431     }
3432     visitSubCaptures(S->getInnermostCapturedStmt());
3433     // Try to capture inner this->member references to generate correct mappings
3434     // and diagnostics.
3435     if (TryCaptureCXXThisMembers ||
3436         (isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()) &&
3437          llvm::any_of(S->getInnermostCapturedStmt()->captures(),
3438                       [](const CapturedStmt::Capture &C) {
3439                         return C.capturesThis();
3440                       }))) {
3441       bool SavedTryCaptureCXXThisMembers = TryCaptureCXXThisMembers;
3442       TryCaptureCXXThisMembers = true;
3443       Visit(S->getInnermostCapturedStmt()->getCapturedStmt());
3444       TryCaptureCXXThisMembers = SavedTryCaptureCXXThisMembers;
3445     }
3446     // In tasks firstprivates are not captured anymore, need to analyze them
3447     // explicitly.
3448     if (isOpenMPTaskingDirective(S->getDirectiveKind()) &&
3449         !isOpenMPTaskLoopDirective(S->getDirectiveKind())) {
3450       for (OMPClause *C : S->clauses())
3451         if (auto *FC = dyn_cast<OMPFirstprivateClause>(C)) {
3452           for (Expr *Ref : FC->varlists())
3453             Visit(Ref);
3454         }
3455     }
3456   }
3457 
3458 public:
3459   void VisitDeclRefExpr(DeclRefExpr *E) {
3460     if (TryCaptureCXXThisMembers || E->isTypeDependent() ||
3461         E->isValueDependent() || E->containsUnexpandedParameterPack() ||
3462         E->isInstantiationDependent())
3463       return;
3464     if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
3465       // Check the datasharing rules for the expressions in the clauses.
3466       if (!CS) {
3467         if (auto *CED = dyn_cast<OMPCapturedExprDecl>(VD))
3468           if (!CED->hasAttr<OMPCaptureNoInitAttr>()) {
3469             Visit(CED->getInit());
3470             return;
3471           }
3472       } else if (VD->isImplicit() || isa<OMPCapturedExprDecl>(VD))
3473         // Do not analyze internal variables and do not enclose them into
3474         // implicit clauses.
3475         return;
3476       VD = VD->getCanonicalDecl();
3477       // Skip internally declared variables.
3478       if (VD->hasLocalStorage() && CS && !CS->capturesVariable(VD) &&
3479           !Stack->isImplicitTaskFirstprivate(VD))
3480         return;
3481       // Skip allocators in uses_allocators clauses.
3482       if (Stack->isUsesAllocatorsDecl(VD).hasValue())
3483         return;
3484 
3485       DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, /*FromParent=*/false);
3486       // Check if the variable has explicit DSA set and stop analysis if it so.
3487       if (DVar.RefExpr || !ImplicitDeclarations.insert(VD).second)
3488         return;
3489 
3490       // Skip internally declared static variables.
3491       llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
3492           OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
3493       if (VD->hasGlobalStorage() && CS && !CS->capturesVariable(VD) &&
3494           (Stack->hasRequiresDeclWithClause<OMPUnifiedSharedMemoryClause>() ||
3495            !Res || *Res != OMPDeclareTargetDeclAttr::MT_Link) &&
3496           !Stack->isImplicitTaskFirstprivate(VD))
3497         return;
3498 
3499       SourceLocation ELoc = E->getExprLoc();
3500       OpenMPDirectiveKind DKind = Stack->getCurrentDirective();
3501       // The default(none) clause requires that each variable that is referenced
3502       // in the construct, and does not have a predetermined data-sharing
3503       // attribute, must have its data-sharing attribute explicitly determined
3504       // by being listed in a data-sharing attribute clause.
3505       if (DVar.CKind == OMPC_unknown &&
3506           (Stack->getDefaultDSA() == DSA_none ||
3507            Stack->getDefaultDSA() == DSA_firstprivate) &&
3508           isImplicitOrExplicitTaskingRegion(DKind) &&
3509           VarsWithInheritedDSA.count(VD) == 0) {
3510         bool InheritedDSA = Stack->getDefaultDSA() == DSA_none;
3511         if (!InheritedDSA && Stack->getDefaultDSA() == DSA_firstprivate) {
3512           DSAStackTy::DSAVarData DVar =
3513               Stack->getImplicitDSA(VD, /*FromParent=*/false);
3514           InheritedDSA = DVar.CKind == OMPC_unknown;
3515         }
3516         if (InheritedDSA)
3517           VarsWithInheritedDSA[VD] = E;
3518         return;
3519       }
3520 
3521       // OpenMP 5.0 [2.19.7.2, defaultmap clause, Description]
3522       // If implicit-behavior is none, each variable referenced in the
3523       // construct that does not have a predetermined data-sharing attribute
3524       // and does not appear in a to or link clause on a declare target
3525       // directive must be listed in a data-mapping attribute clause, a
3526       // data-haring attribute clause (including a data-sharing attribute
3527       // clause on a combined construct where target. is one of the
3528       // constituent constructs), or an is_device_ptr clause.
3529       OpenMPDefaultmapClauseKind ClauseKind =
3530           getVariableCategoryFromDecl(SemaRef.getLangOpts(), VD);
3531       if (SemaRef.getLangOpts().OpenMP >= 50) {
3532         bool IsModifierNone = Stack->getDefaultmapModifier(ClauseKind) ==
3533                               OMPC_DEFAULTMAP_MODIFIER_none;
3534         if (DVar.CKind == OMPC_unknown && IsModifierNone &&
3535             VarsWithInheritedDSA.count(VD) == 0 && !Res) {
3536           // Only check for data-mapping attribute and is_device_ptr here
3537           // since we have already make sure that the declaration does not
3538           // have a data-sharing attribute above
3539           if (!Stack->checkMappableExprComponentListsForDecl(
3540                   VD, /*CurrentRegionOnly=*/true,
3541                   [VD](OMPClauseMappableExprCommon::MappableExprComponentListRef
3542                            MapExprComponents,
3543                        OpenMPClauseKind) {
3544                     auto MI = MapExprComponents.rbegin();
3545                     auto ME = MapExprComponents.rend();
3546                     return MI != ME && MI->getAssociatedDeclaration() == VD;
3547                   })) {
3548             VarsWithInheritedDSA[VD] = E;
3549             return;
3550           }
3551         }
3552       }
3553       if (SemaRef.getLangOpts().OpenMP > 50) {
3554         bool IsModifierPresent = Stack->getDefaultmapModifier(ClauseKind) ==
3555                                  OMPC_DEFAULTMAP_MODIFIER_present;
3556         if (IsModifierPresent) {
3557           if (llvm::find(ImplicitMapModifier[ClauseKind],
3558                          OMPC_MAP_MODIFIER_present) ==
3559               std::end(ImplicitMapModifier[ClauseKind])) {
3560             ImplicitMapModifier[ClauseKind].push_back(
3561                 OMPC_MAP_MODIFIER_present);
3562           }
3563         }
3564       }
3565 
3566       if (isOpenMPTargetExecutionDirective(DKind) &&
3567           !Stack->isLoopControlVariable(VD).first) {
3568         if (!Stack->checkMappableExprComponentListsForDecl(
3569                 VD, /*CurrentRegionOnly=*/true,
3570                 [this](OMPClauseMappableExprCommon::MappableExprComponentListRef
3571                            StackComponents,
3572                        OpenMPClauseKind) {
3573                   if (SemaRef.LangOpts.OpenMP >= 50)
3574                     return !StackComponents.empty();
3575                   // Variable is used if it has been marked as an array, array
3576                   // section, array shaping or the variable iself.
3577                   return StackComponents.size() == 1 ||
3578                          std::all_of(
3579                              std::next(StackComponents.rbegin()),
3580                              StackComponents.rend(),
3581                              [](const OMPClauseMappableExprCommon::
3582                                     MappableComponent &MC) {
3583                                return MC.getAssociatedDeclaration() ==
3584                                           nullptr &&
3585                                       (isa<OMPArraySectionExpr>(
3586                                            MC.getAssociatedExpression()) ||
3587                                        isa<OMPArrayShapingExpr>(
3588                                            MC.getAssociatedExpression()) ||
3589                                        isa<ArraySubscriptExpr>(
3590                                            MC.getAssociatedExpression()));
3591                              });
3592                 })) {
3593           bool IsFirstprivate = false;
3594           // By default lambdas are captured as firstprivates.
3595           if (const auto *RD =
3596                   VD->getType().getNonReferenceType()->getAsCXXRecordDecl())
3597             IsFirstprivate = RD->isLambda();
3598           IsFirstprivate =
3599               IsFirstprivate || (Stack->mustBeFirstprivate(ClauseKind) && !Res);
3600           if (IsFirstprivate) {
3601             ImplicitFirstprivate.emplace_back(E);
3602           } else {
3603             OpenMPDefaultmapClauseModifier M =
3604                 Stack->getDefaultmapModifier(ClauseKind);
3605             OpenMPMapClauseKind Kind = getMapClauseKindFromModifier(
3606                 M, ClauseKind == OMPC_DEFAULTMAP_aggregate || Res);
3607             ImplicitMap[ClauseKind][Kind].emplace_back(E);
3608           }
3609           return;
3610         }
3611       }
3612 
3613       // OpenMP [2.9.3.6, Restrictions, p.2]
3614       //  A list item that appears in a reduction clause of the innermost
3615       //  enclosing worksharing or parallel construct may not be accessed in an
3616       //  explicit task.
3617       DVar = Stack->hasInnermostDSA(
3618           VD,
3619           [](OpenMPClauseKind C, bool AppliedToPointee) {
3620             return C == OMPC_reduction && !AppliedToPointee;
3621           },
3622           [](OpenMPDirectiveKind K) {
3623             return isOpenMPParallelDirective(K) ||
3624                    isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
3625           },
3626           /*FromParent=*/true);
3627       if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
3628         ErrorFound = true;
3629         SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
3630         reportOriginalDsa(SemaRef, Stack, VD, DVar);
3631         return;
3632       }
3633 
3634       // Define implicit data-sharing attributes for task.
3635       DVar = Stack->getImplicitDSA(VD, /*FromParent=*/false);
3636       if (((isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared) ||
3637            (Stack->getDefaultDSA() == DSA_firstprivate &&
3638             DVar.CKind == OMPC_firstprivate && !DVar.RefExpr)) &&
3639           !Stack->isLoopControlVariable(VD).first) {
3640         ImplicitFirstprivate.push_back(E);
3641         return;
3642       }
3643 
3644       // Store implicitly used globals with declare target link for parent
3645       // target.
3646       if (!isOpenMPTargetExecutionDirective(DKind) && Res &&
3647           *Res == OMPDeclareTargetDeclAttr::MT_Link) {
3648         Stack->addToParentTargetRegionLinkGlobals(E);
3649         return;
3650       }
3651     }
3652   }
3653   void VisitMemberExpr(MemberExpr *E) {
3654     if (E->isTypeDependent() || E->isValueDependent() ||
3655         E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
3656       return;
3657     auto *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
3658     OpenMPDirectiveKind DKind = Stack->getCurrentDirective();
3659     if (auto *TE = dyn_cast<CXXThisExpr>(E->getBase()->IgnoreParenCasts())) {
3660       if (!FD)
3661         return;
3662       DSAStackTy::DSAVarData DVar = Stack->getTopDSA(FD, /*FromParent=*/false);
3663       // Check if the variable has explicit DSA set and stop analysis if it
3664       // so.
3665       if (DVar.RefExpr || !ImplicitDeclarations.insert(FD).second)
3666         return;
3667 
3668       if (isOpenMPTargetExecutionDirective(DKind) &&
3669           !Stack->isLoopControlVariable(FD).first &&
3670           !Stack->checkMappableExprComponentListsForDecl(
3671               FD, /*CurrentRegionOnly=*/true,
3672               [](OMPClauseMappableExprCommon::MappableExprComponentListRef
3673                      StackComponents,
3674                  OpenMPClauseKind) {
3675                 return isa<CXXThisExpr>(
3676                     cast<MemberExpr>(
3677                         StackComponents.back().getAssociatedExpression())
3678                         ->getBase()
3679                         ->IgnoreParens());
3680               })) {
3681         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
3682         //  A bit-field cannot appear in a map clause.
3683         //
3684         if (FD->isBitField())
3685           return;
3686 
3687         // Check to see if the member expression is referencing a class that
3688         // has already been explicitly mapped
3689         if (Stack->isClassPreviouslyMapped(TE->getType()))
3690           return;
3691 
3692         OpenMPDefaultmapClauseModifier Modifier =
3693             Stack->getDefaultmapModifier(OMPC_DEFAULTMAP_aggregate);
3694         OpenMPDefaultmapClauseKind ClauseKind =
3695             getVariableCategoryFromDecl(SemaRef.getLangOpts(), FD);
3696         OpenMPMapClauseKind Kind = getMapClauseKindFromModifier(
3697             Modifier, /*IsAggregateOrDeclareTarget*/ true);
3698         ImplicitMap[ClauseKind][Kind].emplace_back(E);
3699         return;
3700       }
3701 
3702       SourceLocation ELoc = E->getExprLoc();
3703       // OpenMP [2.9.3.6, Restrictions, p.2]
3704       //  A list item that appears in a reduction clause of the innermost
3705       //  enclosing worksharing or parallel construct may not be accessed in
3706       //  an  explicit task.
3707       DVar = Stack->hasInnermostDSA(
3708           FD,
3709           [](OpenMPClauseKind C, bool AppliedToPointee) {
3710             return C == OMPC_reduction && !AppliedToPointee;
3711           },
3712           [](OpenMPDirectiveKind K) {
3713             return isOpenMPParallelDirective(K) ||
3714                    isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
3715           },
3716           /*FromParent=*/true);
3717       if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
3718         ErrorFound = true;
3719         SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
3720         reportOriginalDsa(SemaRef, Stack, FD, DVar);
3721         return;
3722       }
3723 
3724       // Define implicit data-sharing attributes for task.
3725       DVar = Stack->getImplicitDSA(FD, /*FromParent=*/false);
3726       if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
3727           !Stack->isLoopControlVariable(FD).first) {
3728         // Check if there is a captured expression for the current field in the
3729         // region. Do not mark it as firstprivate unless there is no captured
3730         // expression.
3731         // TODO: try to make it firstprivate.
3732         if (DVar.CKind != OMPC_unknown)
3733           ImplicitFirstprivate.push_back(E);
3734       }
3735       return;
3736     }
3737     if (isOpenMPTargetExecutionDirective(DKind)) {
3738       OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
3739       if (!checkMapClauseExpressionBase(SemaRef, E, CurComponents, OMPC_map,
3740                                         Stack->getCurrentDirective(),
3741                                         /*NoDiagnose=*/true))
3742         return;
3743       const auto *VD = cast<ValueDecl>(
3744           CurComponents.back().getAssociatedDeclaration()->getCanonicalDecl());
3745       if (!Stack->checkMappableExprComponentListsForDecl(
3746               VD, /*CurrentRegionOnly=*/true,
3747               [&CurComponents](
3748                   OMPClauseMappableExprCommon::MappableExprComponentListRef
3749                       StackComponents,
3750                   OpenMPClauseKind) {
3751                 auto CCI = CurComponents.rbegin();
3752                 auto CCE = CurComponents.rend();
3753                 for (const auto &SC : llvm::reverse(StackComponents)) {
3754                   // Do both expressions have the same kind?
3755                   if (CCI->getAssociatedExpression()->getStmtClass() !=
3756                       SC.getAssociatedExpression()->getStmtClass())
3757                     if (!((isa<OMPArraySectionExpr>(
3758                                SC.getAssociatedExpression()) ||
3759                            isa<OMPArrayShapingExpr>(
3760                                SC.getAssociatedExpression())) &&
3761                           isa<ArraySubscriptExpr>(
3762                               CCI->getAssociatedExpression())))
3763                       return false;
3764 
3765                   const Decl *CCD = CCI->getAssociatedDeclaration();
3766                   const Decl *SCD = SC.getAssociatedDeclaration();
3767                   CCD = CCD ? CCD->getCanonicalDecl() : nullptr;
3768                   SCD = SCD ? SCD->getCanonicalDecl() : nullptr;
3769                   if (SCD != CCD)
3770                     return false;
3771                   std::advance(CCI, 1);
3772                   if (CCI == CCE)
3773                     break;
3774                 }
3775                 return true;
3776               })) {
3777         Visit(E->getBase());
3778       }
3779     } else if (!TryCaptureCXXThisMembers) {
3780       Visit(E->getBase());
3781     }
3782   }
3783   void VisitOMPExecutableDirective(OMPExecutableDirective *S) {
3784     for (OMPClause *C : S->clauses()) {
3785       // Skip analysis of arguments of implicitly defined firstprivate clause
3786       // for task|target directives.
3787       // Skip analysis of arguments of implicitly defined map clause for target
3788       // directives.
3789       if (C && !((isa<OMPFirstprivateClause>(C) || isa<OMPMapClause>(C)) &&
3790                  C->isImplicit() &&
3791                  !isOpenMPTaskingDirective(Stack->getCurrentDirective()))) {
3792         for (Stmt *CC : C->children()) {
3793           if (CC)
3794             Visit(CC);
3795         }
3796       }
3797     }
3798     // Check implicitly captured variables.
3799     VisitSubCaptures(S);
3800   }
3801 
3802   void VisitOMPTileDirective(OMPTileDirective *S) {
3803     // #pragma omp tile does not introduce data sharing.
3804     VisitStmt(S);
3805   }
3806 
3807   void VisitStmt(Stmt *S) {
3808     for (Stmt *C : S->children()) {
3809       if (C) {
3810         // Check implicitly captured variables in the task-based directives to
3811         // check if they must be firstprivatized.
3812         Visit(C);
3813       }
3814     }
3815   }
3816 
3817   void visitSubCaptures(CapturedStmt *S) {
3818     for (const CapturedStmt::Capture &Cap : S->captures()) {
3819       if (!Cap.capturesVariable() && !Cap.capturesVariableByCopy())
3820         continue;
3821       VarDecl *VD = Cap.getCapturedVar();
3822       // Do not try to map the variable if it or its sub-component was mapped
3823       // already.
3824       if (isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()) &&
3825           Stack->checkMappableExprComponentListsForDecl(
3826               VD, /*CurrentRegionOnly=*/true,
3827               [](OMPClauseMappableExprCommon::MappableExprComponentListRef,
3828                  OpenMPClauseKind) { return true; }))
3829         continue;
3830       DeclRefExpr *DRE = buildDeclRefExpr(
3831           SemaRef, VD, VD->getType().getNonLValueExprType(SemaRef.Context),
3832           Cap.getLocation(), /*RefersToCapture=*/true);
3833       Visit(DRE);
3834     }
3835   }
3836   bool isErrorFound() const { return ErrorFound; }
3837   ArrayRef<Expr *> getImplicitFirstprivate() const {
3838     return ImplicitFirstprivate;
3839   }
3840   ArrayRef<Expr *> getImplicitMap(OpenMPDefaultmapClauseKind DK,
3841                                   OpenMPMapClauseKind MK) const {
3842     return ImplicitMap[DK][MK];
3843   }
3844   ArrayRef<OpenMPMapModifierKind>
3845   getImplicitMapModifier(OpenMPDefaultmapClauseKind Kind) const {
3846     return ImplicitMapModifier[Kind];
3847   }
3848   const Sema::VarsWithInheritedDSAType &getVarsWithInheritedDSA() const {
3849     return VarsWithInheritedDSA;
3850   }
3851 
3852   DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS)
3853       : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {
3854     // Process declare target link variables for the target directives.
3855     if (isOpenMPTargetExecutionDirective(S->getCurrentDirective())) {
3856       for (DeclRefExpr *E : Stack->getLinkGlobals())
3857         Visit(E);
3858     }
3859   }
3860 };
3861 } // namespace
3862 
3863 void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) {
3864   switch (DKind) {
3865   case OMPD_parallel:
3866   case OMPD_parallel_for:
3867   case OMPD_parallel_for_simd:
3868   case OMPD_parallel_sections:
3869   case OMPD_parallel_master:
3870   case OMPD_teams:
3871   case OMPD_teams_distribute:
3872   case OMPD_teams_distribute_simd: {
3873     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
3874     QualType KmpInt32PtrTy =
3875         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3876     Sema::CapturedParamNameType Params[] = {
3877         std::make_pair(".global_tid.", KmpInt32PtrTy),
3878         std::make_pair(".bound_tid.", KmpInt32PtrTy),
3879         std::make_pair(StringRef(), QualType()) // __context with shared vars
3880     };
3881     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3882                              Params);
3883     break;
3884   }
3885   case OMPD_target_teams:
3886   case OMPD_target_parallel:
3887   case OMPD_target_parallel_for:
3888   case OMPD_target_parallel_for_simd:
3889   case OMPD_target_teams_distribute:
3890   case OMPD_target_teams_distribute_simd: {
3891     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
3892     QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
3893     QualType KmpInt32PtrTy =
3894         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3895     QualType Args[] = {VoidPtrTy};
3896     FunctionProtoType::ExtProtoInfo EPI;
3897     EPI.Variadic = true;
3898     QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
3899     Sema::CapturedParamNameType Params[] = {
3900         std::make_pair(".global_tid.", KmpInt32Ty),
3901         std::make_pair(".part_id.", KmpInt32PtrTy),
3902         std::make_pair(".privates.", VoidPtrTy),
3903         std::make_pair(
3904             ".copy_fn.",
3905             Context.getPointerType(CopyFnType).withConst().withRestrict()),
3906         std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
3907         std::make_pair(StringRef(), QualType()) // __context with shared vars
3908     };
3909     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3910                              Params, /*OpenMPCaptureLevel=*/0);
3911     // Mark this captured region as inlined, because we don't use outlined
3912     // function directly.
3913     getCurCapturedRegion()->TheCapturedDecl->addAttr(
3914         AlwaysInlineAttr::CreateImplicit(
3915             Context, {}, AttributeCommonInfo::AS_Keyword,
3916             AlwaysInlineAttr::Keyword_forceinline));
3917     Sema::CapturedParamNameType ParamsTarget[] = {
3918         std::make_pair(StringRef(), QualType()) // __context with shared vars
3919     };
3920     // Start a captured region for 'target' with no implicit parameters.
3921     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3922                              ParamsTarget, /*OpenMPCaptureLevel=*/1);
3923     Sema::CapturedParamNameType ParamsTeamsOrParallel[] = {
3924         std::make_pair(".global_tid.", KmpInt32PtrTy),
3925         std::make_pair(".bound_tid.", KmpInt32PtrTy),
3926         std::make_pair(StringRef(), QualType()) // __context with shared vars
3927     };
3928     // Start a captured region for 'teams' or 'parallel'.  Both regions have
3929     // the same implicit parameters.
3930     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3931                              ParamsTeamsOrParallel, /*OpenMPCaptureLevel=*/2);
3932     break;
3933   }
3934   case OMPD_target:
3935   case OMPD_target_simd: {
3936     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
3937     QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
3938     QualType KmpInt32PtrTy =
3939         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3940     QualType Args[] = {VoidPtrTy};
3941     FunctionProtoType::ExtProtoInfo EPI;
3942     EPI.Variadic = true;
3943     QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
3944     Sema::CapturedParamNameType Params[] = {
3945         std::make_pair(".global_tid.", KmpInt32Ty),
3946         std::make_pair(".part_id.", KmpInt32PtrTy),
3947         std::make_pair(".privates.", VoidPtrTy),
3948         std::make_pair(
3949             ".copy_fn.",
3950             Context.getPointerType(CopyFnType).withConst().withRestrict()),
3951         std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
3952         std::make_pair(StringRef(), QualType()) // __context with shared vars
3953     };
3954     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3955                              Params, /*OpenMPCaptureLevel=*/0);
3956     // Mark this captured region as inlined, because we don't use outlined
3957     // function directly.
3958     getCurCapturedRegion()->TheCapturedDecl->addAttr(
3959         AlwaysInlineAttr::CreateImplicit(
3960             Context, {}, AttributeCommonInfo::AS_Keyword,
3961             AlwaysInlineAttr::Keyword_forceinline));
3962     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3963                              std::make_pair(StringRef(), QualType()),
3964                              /*OpenMPCaptureLevel=*/1);
3965     break;
3966   }
3967   case OMPD_atomic:
3968   case OMPD_critical:
3969   case OMPD_section:
3970   case OMPD_master:
3971   case OMPD_tile:
3972     break;
3973   case OMPD_simd:
3974   case OMPD_for:
3975   case OMPD_for_simd:
3976   case OMPD_sections:
3977   case OMPD_single:
3978   case OMPD_taskgroup:
3979   case OMPD_distribute:
3980   case OMPD_distribute_simd:
3981   case OMPD_ordered:
3982   case OMPD_target_data:
3983   case OMPD_dispatch: {
3984     Sema::CapturedParamNameType Params[] = {
3985         std::make_pair(StringRef(), QualType()) // __context with shared vars
3986     };
3987     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3988                              Params);
3989     break;
3990   }
3991   case OMPD_task: {
3992     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
3993     QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
3994     QualType KmpInt32PtrTy =
3995         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3996     QualType Args[] = {VoidPtrTy};
3997     FunctionProtoType::ExtProtoInfo EPI;
3998     EPI.Variadic = true;
3999     QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
4000     Sema::CapturedParamNameType Params[] = {
4001         std::make_pair(".global_tid.", KmpInt32Ty),
4002         std::make_pair(".part_id.", KmpInt32PtrTy),
4003         std::make_pair(".privates.", VoidPtrTy),
4004         std::make_pair(
4005             ".copy_fn.",
4006             Context.getPointerType(CopyFnType).withConst().withRestrict()),
4007         std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
4008         std::make_pair(StringRef(), QualType()) // __context with shared vars
4009     };
4010     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
4011                              Params);
4012     // Mark this captured region as inlined, because we don't use outlined
4013     // function directly.
4014     getCurCapturedRegion()->TheCapturedDecl->addAttr(
4015         AlwaysInlineAttr::CreateImplicit(
4016             Context, {}, AttributeCommonInfo::AS_Keyword,
4017             AlwaysInlineAttr::Keyword_forceinline));
4018     break;
4019   }
4020   case OMPD_taskloop:
4021   case OMPD_taskloop_simd:
4022   case OMPD_master_taskloop:
4023   case OMPD_master_taskloop_simd: {
4024     QualType KmpInt32Ty =
4025         Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1)
4026             .withConst();
4027     QualType KmpUInt64Ty =
4028         Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0)
4029             .withConst();
4030     QualType KmpInt64Ty =
4031         Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1)
4032             .withConst();
4033     QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
4034     QualType KmpInt32PtrTy =
4035         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
4036     QualType Args[] = {VoidPtrTy};
4037     FunctionProtoType::ExtProtoInfo EPI;
4038     EPI.Variadic = true;
4039     QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
4040     Sema::CapturedParamNameType Params[] = {
4041         std::make_pair(".global_tid.", KmpInt32Ty),
4042         std::make_pair(".part_id.", KmpInt32PtrTy),
4043         std::make_pair(".privates.", VoidPtrTy),
4044         std::make_pair(
4045             ".copy_fn.",
4046             Context.getPointerType(CopyFnType).withConst().withRestrict()),
4047         std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
4048         std::make_pair(".lb.", KmpUInt64Ty),
4049         std::make_pair(".ub.", KmpUInt64Ty),
4050         std::make_pair(".st.", KmpInt64Ty),
4051         std::make_pair(".liter.", KmpInt32Ty),
4052         std::make_pair(".reductions.", VoidPtrTy),
4053         std::make_pair(StringRef(), QualType()) // __context with shared vars
4054     };
4055     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
4056                              Params);
4057     // Mark this captured region as inlined, because we don't use outlined
4058     // function directly.
4059     getCurCapturedRegion()->TheCapturedDecl->addAttr(
4060         AlwaysInlineAttr::CreateImplicit(
4061             Context, {}, AttributeCommonInfo::AS_Keyword,
4062             AlwaysInlineAttr::Keyword_forceinline));
4063     break;
4064   }
4065   case OMPD_parallel_master_taskloop:
4066   case OMPD_parallel_master_taskloop_simd: {
4067     QualType KmpInt32Ty =
4068         Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1)
4069             .withConst();
4070     QualType KmpUInt64Ty =
4071         Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0)
4072             .withConst();
4073     QualType KmpInt64Ty =
4074         Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1)
4075             .withConst();
4076     QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
4077     QualType KmpInt32PtrTy =
4078         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
4079     Sema::CapturedParamNameType ParamsParallel[] = {
4080         std::make_pair(".global_tid.", KmpInt32PtrTy),
4081         std::make_pair(".bound_tid.", KmpInt32PtrTy),
4082         std::make_pair(StringRef(), QualType()) // __context with shared vars
4083     };
4084     // Start a captured region for 'parallel'.
4085     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
4086                              ParamsParallel, /*OpenMPCaptureLevel=*/0);
4087     QualType Args[] = {VoidPtrTy};
4088     FunctionProtoType::ExtProtoInfo EPI;
4089     EPI.Variadic = true;
4090     QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
4091     Sema::CapturedParamNameType Params[] = {
4092         std::make_pair(".global_tid.", KmpInt32Ty),
4093         std::make_pair(".part_id.", KmpInt32PtrTy),
4094         std::make_pair(".privates.", VoidPtrTy),
4095         std::make_pair(
4096             ".copy_fn.",
4097             Context.getPointerType(CopyFnType).withConst().withRestrict()),
4098         std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
4099         std::make_pair(".lb.", KmpUInt64Ty),
4100         std::make_pair(".ub.", KmpUInt64Ty),
4101         std::make_pair(".st.", KmpInt64Ty),
4102         std::make_pair(".liter.", KmpInt32Ty),
4103         std::make_pair(".reductions.", VoidPtrTy),
4104         std::make_pair(StringRef(), QualType()) // __context with shared vars
4105     };
4106     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
4107                              Params, /*OpenMPCaptureLevel=*/1);
4108     // Mark this captured region as inlined, because we don't use outlined
4109     // function directly.
4110     getCurCapturedRegion()->TheCapturedDecl->addAttr(
4111         AlwaysInlineAttr::CreateImplicit(
4112             Context, {}, AttributeCommonInfo::AS_Keyword,
4113             AlwaysInlineAttr::Keyword_forceinline));
4114     break;
4115   }
4116   case OMPD_distribute_parallel_for_simd:
4117   case OMPD_distribute_parallel_for: {
4118     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
4119     QualType KmpInt32PtrTy =
4120         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
4121     Sema::CapturedParamNameType Params[] = {
4122         std::make_pair(".global_tid.", KmpInt32PtrTy),
4123         std::make_pair(".bound_tid.", KmpInt32PtrTy),
4124         std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
4125         std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
4126         std::make_pair(StringRef(), QualType()) // __context with shared vars
4127     };
4128     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
4129                              Params);
4130     break;
4131   }
4132   case OMPD_target_teams_distribute_parallel_for:
4133   case OMPD_target_teams_distribute_parallel_for_simd: {
4134     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
4135     QualType KmpInt32PtrTy =
4136         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
4137     QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
4138 
4139     QualType Args[] = {VoidPtrTy};
4140     FunctionProtoType::ExtProtoInfo EPI;
4141     EPI.Variadic = true;
4142     QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
4143     Sema::CapturedParamNameType Params[] = {
4144         std::make_pair(".global_tid.", KmpInt32Ty),
4145         std::make_pair(".part_id.", KmpInt32PtrTy),
4146         std::make_pair(".privates.", VoidPtrTy),
4147         std::make_pair(
4148             ".copy_fn.",
4149             Context.getPointerType(CopyFnType).withConst().withRestrict()),
4150         std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
4151         std::make_pair(StringRef(), QualType()) // __context with shared vars
4152     };
4153     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
4154                              Params, /*OpenMPCaptureLevel=*/0);
4155     // Mark this captured region as inlined, because we don't use outlined
4156     // function directly.
4157     getCurCapturedRegion()->TheCapturedDecl->addAttr(
4158         AlwaysInlineAttr::CreateImplicit(
4159             Context, {}, AttributeCommonInfo::AS_Keyword,
4160             AlwaysInlineAttr::Keyword_forceinline));
4161     Sema::CapturedParamNameType ParamsTarget[] = {
4162         std::make_pair(StringRef(), QualType()) // __context with shared vars
4163     };
4164     // Start a captured region for 'target' with no implicit parameters.
4165     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
4166                              ParamsTarget, /*OpenMPCaptureLevel=*/1);
4167 
4168     Sema::CapturedParamNameType ParamsTeams[] = {
4169         std::make_pair(".global_tid.", KmpInt32PtrTy),
4170         std::make_pair(".bound_tid.", KmpInt32PtrTy),
4171         std::make_pair(StringRef(), QualType()) // __context with shared vars
4172     };
4173     // Start a captured region for 'target' with no implicit parameters.
4174     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
4175                              ParamsTeams, /*OpenMPCaptureLevel=*/2);
4176 
4177     Sema::CapturedParamNameType ParamsParallel[] = {
4178         std::make_pair(".global_tid.", KmpInt32PtrTy),
4179         std::make_pair(".bound_tid.", KmpInt32PtrTy),
4180         std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
4181         std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
4182         std::make_pair(StringRef(), QualType()) // __context with shared vars
4183     };
4184     // Start a captured region for 'teams' or 'parallel'.  Both regions have
4185     // the same implicit parameters.
4186     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
4187                              ParamsParallel, /*OpenMPCaptureLevel=*/3);
4188     break;
4189   }
4190 
4191   case OMPD_teams_distribute_parallel_for:
4192   case OMPD_teams_distribute_parallel_for_simd: {
4193     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
4194     QualType KmpInt32PtrTy =
4195         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
4196 
4197     Sema::CapturedParamNameType ParamsTeams[] = {
4198         std::make_pair(".global_tid.", KmpInt32PtrTy),
4199         std::make_pair(".bound_tid.", KmpInt32PtrTy),
4200         std::make_pair(StringRef(), QualType()) // __context with shared vars
4201     };
4202     // Start a captured region for 'target' with no implicit parameters.
4203     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
4204                              ParamsTeams, /*OpenMPCaptureLevel=*/0);
4205 
4206     Sema::CapturedParamNameType ParamsParallel[] = {
4207         std::make_pair(".global_tid.", KmpInt32PtrTy),
4208         std::make_pair(".bound_tid.", KmpInt32PtrTy),
4209         std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
4210         std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
4211         std::make_pair(StringRef(), QualType()) // __context with shared vars
4212     };
4213     // Start a captured region for 'teams' or 'parallel'.  Both regions have
4214     // the same implicit parameters.
4215     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
4216                              ParamsParallel, /*OpenMPCaptureLevel=*/1);
4217     break;
4218   }
4219   case OMPD_target_update:
4220   case OMPD_target_enter_data:
4221   case OMPD_target_exit_data: {
4222     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
4223     QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
4224     QualType KmpInt32PtrTy =
4225         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
4226     QualType Args[] = {VoidPtrTy};
4227     FunctionProtoType::ExtProtoInfo EPI;
4228     EPI.Variadic = true;
4229     QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
4230     Sema::CapturedParamNameType Params[] = {
4231         std::make_pair(".global_tid.", KmpInt32Ty),
4232         std::make_pair(".part_id.", KmpInt32PtrTy),
4233         std::make_pair(".privates.", VoidPtrTy),
4234         std::make_pair(
4235             ".copy_fn.",
4236             Context.getPointerType(CopyFnType).withConst().withRestrict()),
4237         std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
4238         std::make_pair(StringRef(), QualType()) // __context with shared vars
4239     };
4240     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
4241                              Params);
4242     // Mark this captured region as inlined, because we don't use outlined
4243     // function directly.
4244     getCurCapturedRegion()->TheCapturedDecl->addAttr(
4245         AlwaysInlineAttr::CreateImplicit(
4246             Context, {}, AttributeCommonInfo::AS_Keyword,
4247             AlwaysInlineAttr::Keyword_forceinline));
4248     break;
4249   }
4250   case OMPD_threadprivate:
4251   case OMPD_allocate:
4252   case OMPD_taskyield:
4253   case OMPD_barrier:
4254   case OMPD_taskwait:
4255   case OMPD_cancellation_point:
4256   case OMPD_cancel:
4257   case OMPD_flush:
4258   case OMPD_depobj:
4259   case OMPD_scan:
4260   case OMPD_declare_reduction:
4261   case OMPD_declare_mapper:
4262   case OMPD_declare_simd:
4263   case OMPD_declare_target:
4264   case OMPD_end_declare_target:
4265   case OMPD_requires:
4266   case OMPD_declare_variant:
4267   case OMPD_begin_declare_variant:
4268   case OMPD_end_declare_variant:
4269     llvm_unreachable("OpenMP Directive is not allowed");
4270   case OMPD_unknown:
4271   default:
4272     llvm_unreachable("Unknown OpenMP directive");
4273   }
4274   DSAStack->setContext(CurContext);
4275 }
4276 
4277 int Sema::getNumberOfConstructScopes(unsigned Level) const {
4278   return getOpenMPCaptureLevels(DSAStack->getDirective(Level));
4279 }
4280 
4281 int Sema::getOpenMPCaptureLevels(OpenMPDirectiveKind DKind) {
4282   SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
4283   getOpenMPCaptureRegions(CaptureRegions, DKind);
4284   return CaptureRegions.size();
4285 }
4286 
4287 static OMPCapturedExprDecl *buildCaptureDecl(Sema &S, IdentifierInfo *Id,
4288                                              Expr *CaptureExpr, bool WithInit,
4289                                              bool AsExpression) {
4290   assert(CaptureExpr);
4291   ASTContext &C = S.getASTContext();
4292   Expr *Init = AsExpression ? CaptureExpr : CaptureExpr->IgnoreImpCasts();
4293   QualType Ty = Init->getType();
4294   if (CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue()) {
4295     if (S.getLangOpts().CPlusPlus) {
4296       Ty = C.getLValueReferenceType(Ty);
4297     } else {
4298       Ty = C.getPointerType(Ty);
4299       ExprResult Res =
4300           S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_AddrOf, Init);
4301       if (!Res.isUsable())
4302         return nullptr;
4303       Init = Res.get();
4304     }
4305     WithInit = true;
4306   }
4307   auto *CED = OMPCapturedExprDecl::Create(C, S.CurContext, Id, Ty,
4308                                           CaptureExpr->getBeginLoc());
4309   if (!WithInit)
4310     CED->addAttr(OMPCaptureNoInitAttr::CreateImplicit(C));
4311   S.CurContext->addHiddenDecl(CED);
4312   Sema::TentativeAnalysisScope Trap(S);
4313   S.AddInitializerToDecl(CED, Init, /*DirectInit=*/false);
4314   return CED;
4315 }
4316 
4317 static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr,
4318                                  bool WithInit) {
4319   OMPCapturedExprDecl *CD;
4320   if (VarDecl *VD = S.isOpenMPCapturedDecl(D))
4321     CD = cast<OMPCapturedExprDecl>(VD);
4322   else
4323     CD = buildCaptureDecl(S, D->getIdentifier(), CaptureExpr, WithInit,
4324                           /*AsExpression=*/false);
4325   return buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
4326                           CaptureExpr->getExprLoc());
4327 }
4328 
4329 static ExprResult buildCapture(Sema &S, Expr *CaptureExpr, DeclRefExpr *&Ref) {
4330   CaptureExpr = S.DefaultLvalueConversion(CaptureExpr).get();
4331   if (!Ref) {
4332     OMPCapturedExprDecl *CD = buildCaptureDecl(
4333         S, &S.getASTContext().Idents.get(".capture_expr."), CaptureExpr,
4334         /*WithInit=*/true, /*AsExpression=*/true);
4335     Ref = buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
4336                            CaptureExpr->getExprLoc());
4337   }
4338   ExprResult Res = Ref;
4339   if (!S.getLangOpts().CPlusPlus &&
4340       CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue() &&
4341       Ref->getType()->isPointerType()) {
4342     Res = S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_Deref, Ref);
4343     if (!Res.isUsable())
4344       return ExprError();
4345   }
4346   return S.DefaultLvalueConversion(Res.get());
4347 }
4348 
4349 namespace {
4350 // OpenMP directives parsed in this section are represented as a
4351 // CapturedStatement with an associated statement.  If a syntax error
4352 // is detected during the parsing of the associated statement, the
4353 // compiler must abort processing and close the CapturedStatement.
4354 //
4355 // Combined directives such as 'target parallel' have more than one
4356 // nested CapturedStatements.  This RAII ensures that we unwind out
4357 // of all the nested CapturedStatements when an error is found.
4358 class CaptureRegionUnwinderRAII {
4359 private:
4360   Sema &S;
4361   bool &ErrorFound;
4362   OpenMPDirectiveKind DKind = OMPD_unknown;
4363 
4364 public:
4365   CaptureRegionUnwinderRAII(Sema &S, bool &ErrorFound,
4366                             OpenMPDirectiveKind DKind)
4367       : S(S), ErrorFound(ErrorFound), DKind(DKind) {}
4368   ~CaptureRegionUnwinderRAII() {
4369     if (ErrorFound) {
4370       int ThisCaptureLevel = S.getOpenMPCaptureLevels(DKind);
4371       while (--ThisCaptureLevel >= 0)
4372         S.ActOnCapturedRegionError();
4373     }
4374   }
4375 };
4376 } // namespace
4377 
4378 void Sema::tryCaptureOpenMPLambdas(ValueDecl *V) {
4379   // Capture variables captured by reference in lambdas for target-based
4380   // directives.
4381   if (!CurContext->isDependentContext() &&
4382       (isOpenMPTargetExecutionDirective(DSAStack->getCurrentDirective()) ||
4383        isOpenMPTargetDataManagementDirective(
4384            DSAStack->getCurrentDirective()))) {
4385     QualType Type = V->getType();
4386     if (const auto *RD = Type.getCanonicalType()
4387                              .getNonReferenceType()
4388                              ->getAsCXXRecordDecl()) {
4389       bool SavedForceCaptureByReferenceInTargetExecutable =
4390           DSAStack->isForceCaptureByReferenceInTargetExecutable();
4391       DSAStack->setForceCaptureByReferenceInTargetExecutable(
4392           /*V=*/true);
4393       if (RD->isLambda()) {
4394         llvm::DenseMap<const VarDecl *, FieldDecl *> Captures;
4395         FieldDecl *ThisCapture;
4396         RD->getCaptureFields(Captures, ThisCapture);
4397         for (const LambdaCapture &LC : RD->captures()) {
4398           if (LC.getCaptureKind() == LCK_ByRef) {
4399             VarDecl *VD = LC.getCapturedVar();
4400             DeclContext *VDC = VD->getDeclContext();
4401             if (!VDC->Encloses(CurContext))
4402               continue;
4403             MarkVariableReferenced(LC.getLocation(), VD);
4404           } else if (LC.getCaptureKind() == LCK_This) {
4405             QualType ThisTy = getCurrentThisType();
4406             if (!ThisTy.isNull() &&
4407                 Context.typesAreCompatible(ThisTy, ThisCapture->getType()))
4408               CheckCXXThisCapture(LC.getLocation());
4409           }
4410         }
4411       }
4412       DSAStack->setForceCaptureByReferenceInTargetExecutable(
4413           SavedForceCaptureByReferenceInTargetExecutable);
4414     }
4415   }
4416 }
4417 
4418 static bool checkOrderedOrderSpecified(Sema &S,
4419                                        const ArrayRef<OMPClause *> Clauses) {
4420   const OMPOrderedClause *Ordered = nullptr;
4421   const OMPOrderClause *Order = nullptr;
4422 
4423   for (const OMPClause *Clause : Clauses) {
4424     if (Clause->getClauseKind() == OMPC_ordered)
4425       Ordered = cast<OMPOrderedClause>(Clause);
4426     else if (Clause->getClauseKind() == OMPC_order) {
4427       Order = cast<OMPOrderClause>(Clause);
4428       if (Order->getKind() != OMPC_ORDER_concurrent)
4429         Order = nullptr;
4430     }
4431     if (Ordered && Order)
4432       break;
4433   }
4434 
4435   if (Ordered && Order) {
4436     S.Diag(Order->getKindKwLoc(),
4437            diag::err_omp_simple_clause_incompatible_with_ordered)
4438         << getOpenMPClauseName(OMPC_order)
4439         << getOpenMPSimpleClauseTypeName(OMPC_order, OMPC_ORDER_concurrent)
4440         << SourceRange(Order->getBeginLoc(), Order->getEndLoc());
4441     S.Diag(Ordered->getBeginLoc(), diag::note_omp_ordered_param)
4442         << 0 << SourceRange(Ordered->getBeginLoc(), Ordered->getEndLoc());
4443     return true;
4444   }
4445   return false;
4446 }
4447 
4448 StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S,
4449                                       ArrayRef<OMPClause *> Clauses) {
4450   if (DSAStack->getCurrentDirective() == OMPD_atomic ||
4451       DSAStack->getCurrentDirective() == OMPD_critical ||
4452       DSAStack->getCurrentDirective() == OMPD_section ||
4453       DSAStack->getCurrentDirective() == OMPD_master)
4454     return S;
4455 
4456   bool ErrorFound = false;
4457   CaptureRegionUnwinderRAII CaptureRegionUnwinder(
4458       *this, ErrorFound, DSAStack->getCurrentDirective());
4459   if (!S.isUsable()) {
4460     ErrorFound = true;
4461     return StmtError();
4462   }
4463 
4464   SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
4465   getOpenMPCaptureRegions(CaptureRegions, DSAStack->getCurrentDirective());
4466   OMPOrderedClause *OC = nullptr;
4467   OMPScheduleClause *SC = nullptr;
4468   SmallVector<const OMPLinearClause *, 4> LCs;
4469   SmallVector<const OMPClauseWithPreInit *, 4> PICs;
4470   // This is required for proper codegen.
4471   for (OMPClause *Clause : Clauses) {
4472     if (!LangOpts.OpenMPSimd &&
4473         isOpenMPTaskingDirective(DSAStack->getCurrentDirective()) &&
4474         Clause->getClauseKind() == OMPC_in_reduction) {
4475       // Capture taskgroup task_reduction descriptors inside the tasking regions
4476       // with the corresponding in_reduction items.
4477       auto *IRC = cast<OMPInReductionClause>(Clause);
4478       for (Expr *E : IRC->taskgroup_descriptors())
4479         if (E)
4480           MarkDeclarationsReferencedInExpr(E);
4481     }
4482     if (isOpenMPPrivate(Clause->getClauseKind()) ||
4483         Clause->getClauseKind() == OMPC_copyprivate ||
4484         (getLangOpts().OpenMPUseTLS &&
4485          getASTContext().getTargetInfo().isTLSSupported() &&
4486          Clause->getClauseKind() == OMPC_copyin)) {
4487       DSAStack->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin);
4488       // Mark all variables in private list clauses as used in inner region.
4489       for (Stmt *VarRef : Clause->children()) {
4490         if (auto *E = cast_or_null<Expr>(VarRef)) {
4491           MarkDeclarationsReferencedInExpr(E);
4492         }
4493       }
4494       DSAStack->setForceVarCapturing(/*V=*/false);
4495     } else if (isOpenMPLoopTransformationDirective(
4496                    DSAStack->getCurrentDirective())) {
4497       assert(CaptureRegions.empty() &&
4498              "No captured regions in loop transformation directives.");
4499     } else if (CaptureRegions.size() > 1 ||
4500                CaptureRegions.back() != OMPD_unknown) {
4501       if (auto *C = OMPClauseWithPreInit::get(Clause))
4502         PICs.push_back(C);
4503       if (auto *C = OMPClauseWithPostUpdate::get(Clause)) {
4504         if (Expr *E = C->getPostUpdateExpr())
4505           MarkDeclarationsReferencedInExpr(E);
4506       }
4507     }
4508     if (Clause->getClauseKind() == OMPC_schedule)
4509       SC = cast<OMPScheduleClause>(Clause);
4510     else if (Clause->getClauseKind() == OMPC_ordered)
4511       OC = cast<OMPOrderedClause>(Clause);
4512     else if (Clause->getClauseKind() == OMPC_linear)
4513       LCs.push_back(cast<OMPLinearClause>(Clause));
4514   }
4515   // Capture allocator expressions if used.
4516   for (Expr *E : DSAStack->getInnerAllocators())
4517     MarkDeclarationsReferencedInExpr(E);
4518   // OpenMP, 2.7.1 Loop Construct, Restrictions
4519   // The nonmonotonic modifier cannot be specified if an ordered clause is
4520   // specified.
4521   if (SC &&
4522       (SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
4523        SC->getSecondScheduleModifier() ==
4524            OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
4525       OC) {
4526     Diag(SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic
4527              ? SC->getFirstScheduleModifierLoc()
4528              : SC->getSecondScheduleModifierLoc(),
4529          diag::err_omp_simple_clause_incompatible_with_ordered)
4530         << getOpenMPClauseName(OMPC_schedule)
4531         << getOpenMPSimpleClauseTypeName(OMPC_schedule,
4532                                          OMPC_SCHEDULE_MODIFIER_nonmonotonic)
4533         << SourceRange(OC->getBeginLoc(), OC->getEndLoc());
4534     ErrorFound = true;
4535   }
4536   // OpenMP 5.0, 2.9.2 Worksharing-Loop Construct, Restrictions.
4537   // If an order(concurrent) clause is present, an ordered clause may not appear
4538   // on the same directive.
4539   if (checkOrderedOrderSpecified(*this, Clauses))
4540     ErrorFound = true;
4541   if (!LCs.empty() && OC && OC->getNumForLoops()) {
4542     for (const OMPLinearClause *C : LCs) {
4543       Diag(C->getBeginLoc(), diag::err_omp_linear_ordered)
4544           << SourceRange(OC->getBeginLoc(), OC->getEndLoc());
4545     }
4546     ErrorFound = true;
4547   }
4548   if (isOpenMPWorksharingDirective(DSAStack->getCurrentDirective()) &&
4549       isOpenMPSimdDirective(DSAStack->getCurrentDirective()) && OC &&
4550       OC->getNumForLoops()) {
4551     Diag(OC->getBeginLoc(), diag::err_omp_ordered_simd)
4552         << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
4553     ErrorFound = true;
4554   }
4555   if (ErrorFound) {
4556     return StmtError();
4557   }
4558   StmtResult SR = S;
4559   unsigned CompletedRegions = 0;
4560   for (OpenMPDirectiveKind ThisCaptureRegion : llvm::reverse(CaptureRegions)) {
4561     // Mark all variables in private list clauses as used in inner region.
4562     // Required for proper codegen of combined directives.
4563     // TODO: add processing for other clauses.
4564     if (ThisCaptureRegion != OMPD_unknown) {
4565       for (const clang::OMPClauseWithPreInit *C : PICs) {
4566         OpenMPDirectiveKind CaptureRegion = C->getCaptureRegion();
4567         // Find the particular capture region for the clause if the
4568         // directive is a combined one with multiple capture regions.
4569         // If the directive is not a combined one, the capture region
4570         // associated with the clause is OMPD_unknown and is generated
4571         // only once.
4572         if (CaptureRegion == ThisCaptureRegion ||
4573             CaptureRegion == OMPD_unknown) {
4574           if (auto *DS = cast_or_null<DeclStmt>(C->getPreInitStmt())) {
4575             for (Decl *D : DS->decls())
4576               MarkVariableReferenced(D->getLocation(), cast<VarDecl>(D));
4577           }
4578         }
4579       }
4580     }
4581     if (ThisCaptureRegion == OMPD_target) {
4582       // Capture allocator traits in the target region. They are used implicitly
4583       // and, thus, are not captured by default.
4584       for (OMPClause *C : Clauses) {
4585         if (const auto *UAC = dyn_cast<OMPUsesAllocatorsClause>(C)) {
4586           for (unsigned I = 0, End = UAC->getNumberOfAllocators(); I < End;
4587                ++I) {
4588             OMPUsesAllocatorsClause::Data D = UAC->getAllocatorData(I);
4589             if (Expr *E = D.AllocatorTraits)
4590               MarkDeclarationsReferencedInExpr(E);
4591           }
4592           continue;
4593         }
4594       }
4595     }
4596     if (++CompletedRegions == CaptureRegions.size())
4597       DSAStack->setBodyComplete();
4598     SR = ActOnCapturedRegionEnd(SR.get());
4599   }
4600   return SR;
4601 }
4602 
4603 static bool checkCancelRegion(Sema &SemaRef, OpenMPDirectiveKind CurrentRegion,
4604                               OpenMPDirectiveKind CancelRegion,
4605                               SourceLocation StartLoc) {
4606   // CancelRegion is only needed for cancel and cancellation_point.
4607   if (CurrentRegion != OMPD_cancel && CurrentRegion != OMPD_cancellation_point)
4608     return false;
4609 
4610   if (CancelRegion == OMPD_parallel || CancelRegion == OMPD_for ||
4611       CancelRegion == OMPD_sections || CancelRegion == OMPD_taskgroup)
4612     return false;
4613 
4614   SemaRef.Diag(StartLoc, diag::err_omp_wrong_cancel_region)
4615       << getOpenMPDirectiveName(CancelRegion);
4616   return true;
4617 }
4618 
4619 static bool checkNestingOfRegions(Sema &SemaRef, const DSAStackTy *Stack,
4620                                   OpenMPDirectiveKind CurrentRegion,
4621                                   const DeclarationNameInfo &CurrentName,
4622                                   OpenMPDirectiveKind CancelRegion,
4623                                   SourceLocation StartLoc) {
4624   if (Stack->getCurScope()) {
4625     OpenMPDirectiveKind ParentRegion = Stack->getParentDirective();
4626     OpenMPDirectiveKind OffendingRegion = ParentRegion;
4627     bool NestingProhibited = false;
4628     bool CloseNesting = true;
4629     bool OrphanSeen = false;
4630     enum {
4631       NoRecommend,
4632       ShouldBeInParallelRegion,
4633       ShouldBeInOrderedRegion,
4634       ShouldBeInTargetRegion,
4635       ShouldBeInTeamsRegion,
4636       ShouldBeInLoopSimdRegion,
4637     } Recommend = NoRecommend;
4638     if (isOpenMPSimdDirective(ParentRegion) &&
4639         ((SemaRef.LangOpts.OpenMP <= 45 && CurrentRegion != OMPD_ordered) ||
4640          (SemaRef.LangOpts.OpenMP >= 50 && CurrentRegion != OMPD_ordered &&
4641           CurrentRegion != OMPD_simd && CurrentRegion != OMPD_atomic &&
4642           CurrentRegion != OMPD_scan))) {
4643       // OpenMP [2.16, Nesting of Regions]
4644       // OpenMP constructs may not be nested inside a simd region.
4645       // OpenMP [2.8.1,simd Construct, Restrictions]
4646       // An ordered construct with the simd clause is the only OpenMP
4647       // construct that can appear in the simd region.
4648       // Allowing a SIMD construct nested in another SIMD construct is an
4649       // extension. The OpenMP 4.5 spec does not allow it. Issue a warning
4650       // message.
4651       // OpenMP 5.0 [2.9.3.1, simd Construct, Restrictions]
4652       // The only OpenMP constructs that can be encountered during execution of
4653       // a simd region are the atomic construct, the loop construct, the simd
4654       // construct and the ordered construct with the simd clause.
4655       SemaRef.Diag(StartLoc, (CurrentRegion != OMPD_simd)
4656                                  ? diag::err_omp_prohibited_region_simd
4657                                  : diag::warn_omp_nesting_simd)
4658           << (SemaRef.LangOpts.OpenMP >= 50 ? 1 : 0);
4659       return CurrentRegion != OMPD_simd;
4660     }
4661     if (ParentRegion == OMPD_atomic) {
4662       // OpenMP [2.16, Nesting of Regions]
4663       // OpenMP constructs may not be nested inside an atomic region.
4664       SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic);
4665       return true;
4666     }
4667     if (CurrentRegion == OMPD_section) {
4668       // OpenMP [2.7.2, sections Construct, Restrictions]
4669       // Orphaned section directives are prohibited. That is, the section
4670       // directives must appear within the sections construct and must not be
4671       // encountered elsewhere in the sections region.
4672       if (ParentRegion != OMPD_sections &&
4673           ParentRegion != OMPD_parallel_sections) {
4674         SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive)
4675             << (ParentRegion != OMPD_unknown)
4676             << getOpenMPDirectiveName(ParentRegion);
4677         return true;
4678       }
4679       return false;
4680     }
4681     // Allow some constructs (except teams and cancellation constructs) to be
4682     // orphaned (they could be used in functions, called from OpenMP regions
4683     // with the required preconditions).
4684     if (ParentRegion == OMPD_unknown &&
4685         !isOpenMPNestingTeamsDirective(CurrentRegion) &&
4686         CurrentRegion != OMPD_cancellation_point &&
4687         CurrentRegion != OMPD_cancel && CurrentRegion != OMPD_scan)
4688       return false;
4689     if (CurrentRegion == OMPD_cancellation_point ||
4690         CurrentRegion == OMPD_cancel) {
4691       // OpenMP [2.16, Nesting of Regions]
4692       // A cancellation point construct for which construct-type-clause is
4693       // taskgroup must be nested inside a task construct. A cancellation
4694       // point construct for which construct-type-clause is not taskgroup must
4695       // be closely nested inside an OpenMP construct that matches the type
4696       // specified in construct-type-clause.
4697       // A cancel construct for which construct-type-clause is taskgroup must be
4698       // nested inside a task construct. A cancel construct for which
4699       // construct-type-clause is not taskgroup must be closely nested inside an
4700       // OpenMP construct that matches the type specified in
4701       // construct-type-clause.
4702       NestingProhibited =
4703           !((CancelRegion == OMPD_parallel &&
4704              (ParentRegion == OMPD_parallel ||
4705               ParentRegion == OMPD_target_parallel)) ||
4706             (CancelRegion == OMPD_for &&
4707              (ParentRegion == OMPD_for || ParentRegion == OMPD_parallel_for ||
4708               ParentRegion == OMPD_target_parallel_for ||
4709               ParentRegion == OMPD_distribute_parallel_for ||
4710               ParentRegion == OMPD_teams_distribute_parallel_for ||
4711               ParentRegion == OMPD_target_teams_distribute_parallel_for)) ||
4712             (CancelRegion == OMPD_taskgroup &&
4713              (ParentRegion == OMPD_task ||
4714               (SemaRef.getLangOpts().OpenMP >= 50 &&
4715                (ParentRegion == OMPD_taskloop ||
4716                 ParentRegion == OMPD_master_taskloop ||
4717                 ParentRegion == OMPD_parallel_master_taskloop)))) ||
4718             (CancelRegion == OMPD_sections &&
4719              (ParentRegion == OMPD_section || ParentRegion == OMPD_sections ||
4720               ParentRegion == OMPD_parallel_sections)));
4721       OrphanSeen = ParentRegion == OMPD_unknown;
4722     } else if (CurrentRegion == OMPD_master) {
4723       // OpenMP [2.16, Nesting of Regions]
4724       // A master region may not be closely nested inside a worksharing,
4725       // atomic, or explicit task region.
4726       NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
4727                           isOpenMPTaskingDirective(ParentRegion);
4728     } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) {
4729       // OpenMP [2.16, Nesting of Regions]
4730       // A critical region may not be nested (closely or otherwise) inside a
4731       // critical region with the same name. Note that this restriction is not
4732       // sufficient to prevent deadlock.
4733       SourceLocation PreviousCriticalLoc;
4734       bool DeadLock = Stack->hasDirective(
4735           [CurrentName, &PreviousCriticalLoc](OpenMPDirectiveKind K,
4736                                               const DeclarationNameInfo &DNI,
4737                                               SourceLocation Loc) {
4738             if (K == OMPD_critical && DNI.getName() == CurrentName.getName()) {
4739               PreviousCriticalLoc = Loc;
4740               return true;
4741             }
4742             return false;
4743           },
4744           false /* skip top directive */);
4745       if (DeadLock) {
4746         SemaRef.Diag(StartLoc,
4747                      diag::err_omp_prohibited_region_critical_same_name)
4748             << CurrentName.getName();
4749         if (PreviousCriticalLoc.isValid())
4750           SemaRef.Diag(PreviousCriticalLoc,
4751                        diag::note_omp_previous_critical_region);
4752         return true;
4753       }
4754     } else if (CurrentRegion == OMPD_barrier) {
4755       // OpenMP [2.16, Nesting of Regions]
4756       // A barrier region may not be closely nested inside a worksharing,
4757       // explicit task, critical, ordered, atomic, or master region.
4758       NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
4759                           isOpenMPTaskingDirective(ParentRegion) ||
4760                           ParentRegion == OMPD_master ||
4761                           ParentRegion == OMPD_parallel_master ||
4762                           ParentRegion == OMPD_critical ||
4763                           ParentRegion == OMPD_ordered;
4764     } else if (isOpenMPWorksharingDirective(CurrentRegion) &&
4765                !isOpenMPParallelDirective(CurrentRegion) &&
4766                !isOpenMPTeamsDirective(CurrentRegion)) {
4767       // OpenMP [2.16, Nesting of Regions]
4768       // A worksharing region may not be closely nested inside a worksharing,
4769       // explicit task, critical, ordered, atomic, or master region.
4770       NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
4771                           isOpenMPTaskingDirective(ParentRegion) ||
4772                           ParentRegion == OMPD_master ||
4773                           ParentRegion == OMPD_parallel_master ||
4774                           ParentRegion == OMPD_critical ||
4775                           ParentRegion == OMPD_ordered;
4776       Recommend = ShouldBeInParallelRegion;
4777     } else if (CurrentRegion == OMPD_ordered) {
4778       // OpenMP [2.16, Nesting of Regions]
4779       // An ordered region may not be closely nested inside a critical,
4780       // atomic, or explicit task region.
4781       // An ordered region must be closely nested inside a loop region (or
4782       // parallel loop region) with an ordered clause.
4783       // OpenMP [2.8.1,simd Construct, Restrictions]
4784       // An ordered construct with the simd clause is the only OpenMP construct
4785       // that can appear in the simd region.
4786       NestingProhibited = ParentRegion == OMPD_critical ||
4787                           isOpenMPTaskingDirective(ParentRegion) ||
4788                           !(isOpenMPSimdDirective(ParentRegion) ||
4789                             Stack->isParentOrderedRegion());
4790       Recommend = ShouldBeInOrderedRegion;
4791     } else if (isOpenMPNestingTeamsDirective(CurrentRegion)) {
4792       // OpenMP [2.16, Nesting of Regions]
4793       // If specified, a teams construct must be contained within a target
4794       // construct.
4795       NestingProhibited =
4796           (SemaRef.LangOpts.OpenMP <= 45 && ParentRegion != OMPD_target) ||
4797           (SemaRef.LangOpts.OpenMP >= 50 && ParentRegion != OMPD_unknown &&
4798            ParentRegion != OMPD_target);
4799       OrphanSeen = ParentRegion == OMPD_unknown;
4800       Recommend = ShouldBeInTargetRegion;
4801     } else if (CurrentRegion == OMPD_scan) {
4802       // OpenMP [2.16, Nesting of Regions]
4803       // If specified, a teams construct must be contained within a target
4804       // construct.
4805       NestingProhibited =
4806           SemaRef.LangOpts.OpenMP < 50 ||
4807           (ParentRegion != OMPD_simd && ParentRegion != OMPD_for &&
4808            ParentRegion != OMPD_for_simd && ParentRegion != OMPD_parallel_for &&
4809            ParentRegion != OMPD_parallel_for_simd);
4810       OrphanSeen = ParentRegion == OMPD_unknown;
4811       Recommend = ShouldBeInLoopSimdRegion;
4812     }
4813     if (!NestingProhibited &&
4814         !isOpenMPTargetExecutionDirective(CurrentRegion) &&
4815         !isOpenMPTargetDataManagementDirective(CurrentRegion) &&
4816         (ParentRegion == OMPD_teams || ParentRegion == OMPD_target_teams)) {
4817       // OpenMP [2.16, Nesting of Regions]
4818       // distribute, parallel, parallel sections, parallel workshare, and the
4819       // parallel loop and parallel loop SIMD constructs are the only OpenMP
4820       // constructs that can be closely nested in the teams region.
4821       NestingProhibited = !isOpenMPParallelDirective(CurrentRegion) &&
4822                           !isOpenMPDistributeDirective(CurrentRegion);
4823       Recommend = ShouldBeInParallelRegion;
4824     }
4825     if (!NestingProhibited &&
4826         isOpenMPNestingDistributeDirective(CurrentRegion)) {
4827       // OpenMP 4.5 [2.17 Nesting of Regions]
4828       // The region associated with the distribute construct must be strictly
4829       // nested inside a teams region
4830       NestingProhibited =
4831           (ParentRegion != OMPD_teams && ParentRegion != OMPD_target_teams);
4832       Recommend = ShouldBeInTeamsRegion;
4833     }
4834     if (!NestingProhibited &&
4835         (isOpenMPTargetExecutionDirective(CurrentRegion) ||
4836          isOpenMPTargetDataManagementDirective(CurrentRegion))) {
4837       // OpenMP 4.5 [2.17 Nesting of Regions]
4838       // If a target, target update, target data, target enter data, or
4839       // target exit data construct is encountered during execution of a
4840       // target region, the behavior is unspecified.
4841       NestingProhibited = Stack->hasDirective(
4842           [&OffendingRegion](OpenMPDirectiveKind K, const DeclarationNameInfo &,
4843                              SourceLocation) {
4844             if (isOpenMPTargetExecutionDirective(K)) {
4845               OffendingRegion = K;
4846               return true;
4847             }
4848             return false;
4849           },
4850           false /* don't skip top directive */);
4851       CloseNesting = false;
4852     }
4853     if (NestingProhibited) {
4854       if (OrphanSeen) {
4855         SemaRef.Diag(StartLoc, diag::err_omp_orphaned_device_directive)
4856             << getOpenMPDirectiveName(CurrentRegion) << Recommend;
4857       } else {
4858         SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region)
4859             << CloseNesting << getOpenMPDirectiveName(OffendingRegion)
4860             << Recommend << getOpenMPDirectiveName(CurrentRegion);
4861       }
4862       return true;
4863     }
4864   }
4865   return false;
4866 }
4867 
4868 struct Kind2Unsigned {
4869   using argument_type = OpenMPDirectiveKind;
4870   unsigned operator()(argument_type DK) { return unsigned(DK); }
4871 };
4872 static bool checkIfClauses(Sema &S, OpenMPDirectiveKind Kind,
4873                            ArrayRef<OMPClause *> Clauses,
4874                            ArrayRef<OpenMPDirectiveKind> AllowedNameModifiers) {
4875   bool ErrorFound = false;
4876   unsigned NamedModifiersNumber = 0;
4877   llvm::IndexedMap<const OMPIfClause *, Kind2Unsigned> FoundNameModifiers;
4878   FoundNameModifiers.resize(llvm::omp::Directive_enumSize + 1);
4879   SmallVector<SourceLocation, 4> NameModifierLoc;
4880   for (const OMPClause *C : Clauses) {
4881     if (const auto *IC = dyn_cast_or_null<OMPIfClause>(C)) {
4882       // At most one if clause without a directive-name-modifier can appear on
4883       // the directive.
4884       OpenMPDirectiveKind CurNM = IC->getNameModifier();
4885       if (FoundNameModifiers[CurNM]) {
4886         S.Diag(C->getBeginLoc(), diag::err_omp_more_one_clause)
4887             << getOpenMPDirectiveName(Kind) << getOpenMPClauseName(OMPC_if)
4888             << (CurNM != OMPD_unknown) << getOpenMPDirectiveName(CurNM);
4889         ErrorFound = true;
4890       } else if (CurNM != OMPD_unknown) {
4891         NameModifierLoc.push_back(IC->getNameModifierLoc());
4892         ++NamedModifiersNumber;
4893       }
4894       FoundNameModifiers[CurNM] = IC;
4895       if (CurNM == OMPD_unknown)
4896         continue;
4897       // Check if the specified name modifier is allowed for the current
4898       // directive.
4899       // At most one if clause with the particular directive-name-modifier can
4900       // appear on the directive.
4901       bool MatchFound = false;
4902       for (auto NM : AllowedNameModifiers) {
4903         if (CurNM == NM) {
4904           MatchFound = true;
4905           break;
4906         }
4907       }
4908       if (!MatchFound) {
4909         S.Diag(IC->getNameModifierLoc(),
4910                diag::err_omp_wrong_if_directive_name_modifier)
4911             << getOpenMPDirectiveName(CurNM) << getOpenMPDirectiveName(Kind);
4912         ErrorFound = true;
4913       }
4914     }
4915   }
4916   // If any if clause on the directive includes a directive-name-modifier then
4917   // all if clauses on the directive must include a directive-name-modifier.
4918   if (FoundNameModifiers[OMPD_unknown] && NamedModifiersNumber > 0) {
4919     if (NamedModifiersNumber == AllowedNameModifiers.size()) {
4920       S.Diag(FoundNameModifiers[OMPD_unknown]->getBeginLoc(),
4921              diag::err_omp_no_more_if_clause);
4922     } else {
4923       std::string Values;
4924       std::string Sep(", ");
4925       unsigned AllowedCnt = 0;
4926       unsigned TotalAllowedNum =
4927           AllowedNameModifiers.size() - NamedModifiersNumber;
4928       for (unsigned Cnt = 0, End = AllowedNameModifiers.size(); Cnt < End;
4929            ++Cnt) {
4930         OpenMPDirectiveKind NM = AllowedNameModifiers[Cnt];
4931         if (!FoundNameModifiers[NM]) {
4932           Values += "'";
4933           Values += getOpenMPDirectiveName(NM);
4934           Values += "'";
4935           if (AllowedCnt + 2 == TotalAllowedNum)
4936             Values += " or ";
4937           else if (AllowedCnt + 1 != TotalAllowedNum)
4938             Values += Sep;
4939           ++AllowedCnt;
4940         }
4941       }
4942       S.Diag(FoundNameModifiers[OMPD_unknown]->getCondition()->getBeginLoc(),
4943              diag::err_omp_unnamed_if_clause)
4944           << (TotalAllowedNum > 1) << Values;
4945     }
4946     for (SourceLocation Loc : NameModifierLoc) {
4947       S.Diag(Loc, diag::note_omp_previous_named_if_clause);
4948     }
4949     ErrorFound = true;
4950   }
4951   return ErrorFound;
4952 }
4953 
4954 static std::pair<ValueDecl *, bool> getPrivateItem(Sema &S, Expr *&RefExpr,
4955                                                    SourceLocation &ELoc,
4956                                                    SourceRange &ERange,
4957                                                    bool AllowArraySection) {
4958   if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() ||
4959       RefExpr->containsUnexpandedParameterPack())
4960     return std::make_pair(nullptr, true);
4961 
4962   // OpenMP [3.1, C/C++]
4963   //  A list item is a variable name.
4964   // OpenMP  [2.9.3.3, Restrictions, p.1]
4965   //  A variable that is part of another variable (as an array or
4966   //  structure element) cannot appear in a private clause.
4967   RefExpr = RefExpr->IgnoreParens();
4968   enum {
4969     NoArrayExpr = -1,
4970     ArraySubscript = 0,
4971     OMPArraySection = 1
4972   } IsArrayExpr = NoArrayExpr;
4973   if (AllowArraySection) {
4974     if (auto *ASE = dyn_cast_or_null<ArraySubscriptExpr>(RefExpr)) {
4975       Expr *Base = ASE->getBase()->IgnoreParenImpCasts();
4976       while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
4977         Base = TempASE->getBase()->IgnoreParenImpCasts();
4978       RefExpr = Base;
4979       IsArrayExpr = ArraySubscript;
4980     } else if (auto *OASE = dyn_cast_or_null<OMPArraySectionExpr>(RefExpr)) {
4981       Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
4982       while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
4983         Base = TempOASE->getBase()->IgnoreParenImpCasts();
4984       while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
4985         Base = TempASE->getBase()->IgnoreParenImpCasts();
4986       RefExpr = Base;
4987       IsArrayExpr = OMPArraySection;
4988     }
4989   }
4990   ELoc = RefExpr->getExprLoc();
4991   ERange = RefExpr->getSourceRange();
4992   RefExpr = RefExpr->IgnoreParenImpCasts();
4993   auto *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
4994   auto *ME = dyn_cast_or_null<MemberExpr>(RefExpr);
4995   if ((!DE || !isa<VarDecl>(DE->getDecl())) &&
4996       (S.getCurrentThisType().isNull() || !ME ||
4997        !isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()) ||
4998        !isa<FieldDecl>(ME->getMemberDecl()))) {
4999     if (IsArrayExpr != NoArrayExpr) {
5000       S.Diag(ELoc, diag::err_omp_expected_base_var_name) << IsArrayExpr
5001                                                          << ERange;
5002     } else {
5003       S.Diag(ELoc,
5004              AllowArraySection
5005                  ? diag::err_omp_expected_var_name_member_expr_or_array_item
5006                  : diag::err_omp_expected_var_name_member_expr)
5007           << (S.getCurrentThisType().isNull() ? 0 : 1) << ERange;
5008     }
5009     return std::make_pair(nullptr, false);
5010   }
5011   return std::make_pair(
5012       getCanonicalDecl(DE ? DE->getDecl() : ME->getMemberDecl()), false);
5013 }
5014 
5015 namespace {
5016 /// Checks if the allocator is used in uses_allocators clause to be allowed in
5017 /// target regions.
5018 class AllocatorChecker final : public ConstStmtVisitor<AllocatorChecker, bool> {
5019   DSAStackTy *S = nullptr;
5020 
5021 public:
5022   bool VisitDeclRefExpr(const DeclRefExpr *E) {
5023     return S->isUsesAllocatorsDecl(E->getDecl())
5024                .getValueOr(
5025                    DSAStackTy::UsesAllocatorsDeclKind::AllocatorTrait) ==
5026            DSAStackTy::UsesAllocatorsDeclKind::AllocatorTrait;
5027   }
5028   bool VisitStmt(const Stmt *S) {
5029     for (const Stmt *Child : S->children()) {
5030       if (Child && Visit(Child))
5031         return true;
5032     }
5033     return false;
5034   }
5035   explicit AllocatorChecker(DSAStackTy *S) : S(S) {}
5036 };
5037 } // namespace
5038 
5039 static void checkAllocateClauses(Sema &S, DSAStackTy *Stack,
5040                                  ArrayRef<OMPClause *> Clauses) {
5041   assert(!S.CurContext->isDependentContext() &&
5042          "Expected non-dependent context.");
5043   auto AllocateRange =
5044       llvm::make_filter_range(Clauses, OMPAllocateClause::classof);
5045   llvm::DenseMap<CanonicalDeclPtr<Decl>, CanonicalDeclPtr<VarDecl>>
5046       DeclToCopy;
5047   auto PrivateRange = llvm::make_filter_range(Clauses, [](const OMPClause *C) {
5048     return isOpenMPPrivate(C->getClauseKind());
5049   });
5050   for (OMPClause *Cl : PrivateRange) {
5051     MutableArrayRef<Expr *>::iterator I, It, Et;
5052     if (Cl->getClauseKind() == OMPC_private) {
5053       auto *PC = cast<OMPPrivateClause>(Cl);
5054       I = PC->private_copies().begin();
5055       It = PC->varlist_begin();
5056       Et = PC->varlist_end();
5057     } else if (Cl->getClauseKind() == OMPC_firstprivate) {
5058       auto *PC = cast<OMPFirstprivateClause>(Cl);
5059       I = PC->private_copies().begin();
5060       It = PC->varlist_begin();
5061       Et = PC->varlist_end();
5062     } else if (Cl->getClauseKind() == OMPC_lastprivate) {
5063       auto *PC = cast<OMPLastprivateClause>(Cl);
5064       I = PC->private_copies().begin();
5065       It = PC->varlist_begin();
5066       Et = PC->varlist_end();
5067     } else if (Cl->getClauseKind() == OMPC_linear) {
5068       auto *PC = cast<OMPLinearClause>(Cl);
5069       I = PC->privates().begin();
5070       It = PC->varlist_begin();
5071       Et = PC->varlist_end();
5072     } else if (Cl->getClauseKind() == OMPC_reduction) {
5073       auto *PC = cast<OMPReductionClause>(Cl);
5074       I = PC->privates().begin();
5075       It = PC->varlist_begin();
5076       Et = PC->varlist_end();
5077     } else if (Cl->getClauseKind() == OMPC_task_reduction) {
5078       auto *PC = cast<OMPTaskReductionClause>(Cl);
5079       I = PC->privates().begin();
5080       It = PC->varlist_begin();
5081       Et = PC->varlist_end();
5082     } else if (Cl->getClauseKind() == OMPC_in_reduction) {
5083       auto *PC = cast<OMPInReductionClause>(Cl);
5084       I = PC->privates().begin();
5085       It = PC->varlist_begin();
5086       Et = PC->varlist_end();
5087     } else {
5088       llvm_unreachable("Expected private clause.");
5089     }
5090     for (Expr *E : llvm::make_range(It, Et)) {
5091       if (!*I) {
5092         ++I;
5093         continue;
5094       }
5095       SourceLocation ELoc;
5096       SourceRange ERange;
5097       Expr *SimpleRefExpr = E;
5098       auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange,
5099                                 /*AllowArraySection=*/true);
5100       DeclToCopy.try_emplace(Res.first,
5101                              cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()));
5102       ++I;
5103     }
5104   }
5105   for (OMPClause *C : AllocateRange) {
5106     auto *AC = cast<OMPAllocateClause>(C);
5107     if (S.getLangOpts().OpenMP >= 50 &&
5108         !Stack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>() &&
5109         isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()) &&
5110         AC->getAllocator()) {
5111       Expr *Allocator = AC->getAllocator();
5112       // OpenMP, 2.12.5 target Construct
5113       // Memory allocators that do not appear in a uses_allocators clause cannot
5114       // appear as an allocator in an allocate clause or be used in the target
5115       // region unless a requires directive with the dynamic_allocators clause
5116       // is present in the same compilation unit.
5117       AllocatorChecker Checker(Stack);
5118       if (Checker.Visit(Allocator))
5119         S.Diag(Allocator->getExprLoc(),
5120                diag::err_omp_allocator_not_in_uses_allocators)
5121             << Allocator->getSourceRange();
5122     }
5123     OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind =
5124         getAllocatorKind(S, Stack, AC->getAllocator());
5125     // OpenMP, 2.11.4 allocate Clause, Restrictions.
5126     // For task, taskloop or target directives, allocation requests to memory
5127     // allocators with the trait access set to thread result in unspecified
5128     // behavior.
5129     if (AllocatorKind == OMPAllocateDeclAttr::OMPThreadMemAlloc &&
5130         (isOpenMPTaskingDirective(Stack->getCurrentDirective()) ||
5131          isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()))) {
5132       S.Diag(AC->getAllocator()->getExprLoc(),
5133              diag::warn_omp_allocate_thread_on_task_target_directive)
5134           << getOpenMPDirectiveName(Stack->getCurrentDirective());
5135     }
5136     for (Expr *E : AC->varlists()) {
5137       SourceLocation ELoc;
5138       SourceRange ERange;
5139       Expr *SimpleRefExpr = E;
5140       auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange);
5141       ValueDecl *VD = Res.first;
5142       DSAStackTy::DSAVarData Data = Stack->getTopDSA(VD, /*FromParent=*/false);
5143       if (!isOpenMPPrivate(Data.CKind)) {
5144         S.Diag(E->getExprLoc(),
5145                diag::err_omp_expected_private_copy_for_allocate);
5146         continue;
5147       }
5148       VarDecl *PrivateVD = DeclToCopy[VD];
5149       if (checkPreviousOMPAllocateAttribute(S, Stack, E, PrivateVD,
5150                                             AllocatorKind, AC->getAllocator()))
5151         continue;
5152       applyOMPAllocateAttribute(S, PrivateVD, AllocatorKind, AC->getAllocator(),
5153                                 E->getSourceRange());
5154     }
5155   }
5156 }
5157 
5158 namespace {
5159 /// Rewrite statements and expressions for Sema \p Actions CurContext.
5160 ///
5161 /// Used to wrap already parsed statements/expressions into a new CapturedStmt
5162 /// context. DeclRefExpr used inside the new context are changed to refer to the
5163 /// captured variable instead.
5164 class CaptureVars : public TreeTransform<CaptureVars> {
5165   using BaseTransform = TreeTransform<CaptureVars>;
5166 
5167 public:
5168   CaptureVars(Sema &Actions) : BaseTransform(Actions) {}
5169 
5170   bool AlwaysRebuild() { return true; }
5171 };
5172 } // namespace
5173 
5174 static VarDecl *precomputeExpr(Sema &Actions,
5175                                SmallVectorImpl<Stmt *> &BodyStmts, Expr *E,
5176                                StringRef Name) {
5177   Expr *NewE = AssertSuccess(CaptureVars(Actions).TransformExpr(E));
5178   VarDecl *NewVar = buildVarDecl(Actions, {}, NewE->getType(), Name, nullptr,
5179                                  dyn_cast<DeclRefExpr>(E->IgnoreImplicit()));
5180   auto *NewDeclStmt = cast<DeclStmt>(AssertSuccess(
5181       Actions.ActOnDeclStmt(Actions.ConvertDeclToDeclGroup(NewVar), {}, {})));
5182   Actions.AddInitializerToDecl(NewDeclStmt->getSingleDecl(), NewE, false);
5183   BodyStmts.push_back(NewDeclStmt);
5184   return NewVar;
5185 }
5186 
5187 /// Create a closure that computes the number of iterations of a loop.
5188 ///
5189 /// \param Actions   The Sema object.
5190 /// \param LogicalTy Type for the logical iteration number.
5191 /// \param Rel       Comparison operator of the loop condition.
5192 /// \param StartExpr Value of the loop counter at the first iteration.
5193 /// \param StopExpr  Expression the loop counter is compared against in the loop
5194 /// condition. \param StepExpr      Amount of increment after each iteration.
5195 ///
5196 /// \return Closure (CapturedStmt) of the distance calculation.
5197 static CapturedStmt *buildDistanceFunc(Sema &Actions, QualType LogicalTy,
5198                                        BinaryOperator::Opcode Rel,
5199                                        Expr *StartExpr, Expr *StopExpr,
5200                                        Expr *StepExpr) {
5201   ASTContext &Ctx = Actions.getASTContext();
5202   TypeSourceInfo *LogicalTSI = Ctx.getTrivialTypeSourceInfo(LogicalTy);
5203 
5204   // Captured regions currently don't support return values, we use an
5205   // out-parameter instead. All inputs are implicit captures.
5206   // TODO: Instead of capturing each DeclRefExpr occurring in
5207   // StartExpr/StopExpr/Step, these could also be passed as a value capture.
5208   QualType ResultTy = Ctx.getLValueReferenceType(LogicalTy);
5209   Sema::CapturedParamNameType Params[] = {{"Distance", ResultTy},
5210                                           {StringRef(), QualType()}};
5211   Actions.ActOnCapturedRegionStart({}, nullptr, CR_Default, Params);
5212 
5213   Stmt *Body;
5214   {
5215     Sema::CompoundScopeRAII CompoundScope(Actions);
5216     CapturedDecl *CS = cast<CapturedDecl>(Actions.CurContext);
5217 
5218     // Get the LValue expression for the result.
5219     ImplicitParamDecl *DistParam = CS->getParam(0);
5220     DeclRefExpr *DistRef = Actions.BuildDeclRefExpr(
5221         DistParam, LogicalTy, VK_LValue, {}, nullptr, nullptr, {}, nullptr);
5222 
5223     SmallVector<Stmt *, 4> BodyStmts;
5224 
5225     // Capture all referenced variable references.
5226     // TODO: Instead of computing NewStart/NewStop/NewStep inside the
5227     // CapturedStmt, we could compute them before and capture the result, to be
5228     // used jointly with the LoopVar function.
5229     VarDecl *NewStart = precomputeExpr(Actions, BodyStmts, StartExpr, ".start");
5230     VarDecl *NewStop = precomputeExpr(Actions, BodyStmts, StopExpr, ".stop");
5231     VarDecl *NewStep = precomputeExpr(Actions, BodyStmts, StepExpr, ".step");
5232     auto BuildVarRef = [&](VarDecl *VD) {
5233       return buildDeclRefExpr(Actions, VD, VD->getType(), {});
5234     };
5235 
5236     IntegerLiteral *Zero = IntegerLiteral::Create(
5237         Ctx, llvm::APInt(Ctx.getIntWidth(LogicalTy), 0), LogicalTy, {});
5238     Expr *Dist;
5239     if (Rel == BO_NE) {
5240       // When using a != comparison, the increment can be +1 or -1. This can be
5241       // dynamic at runtime, so we need to check for the direction.
5242       Expr *IsNegStep = AssertSuccess(
5243           Actions.BuildBinOp(nullptr, {}, BO_LT, BuildVarRef(NewStep), Zero));
5244 
5245       // Positive increment.
5246       Expr *ForwardRange = AssertSuccess(Actions.BuildBinOp(
5247           nullptr, {}, BO_Sub, BuildVarRef(NewStop), BuildVarRef(NewStart)));
5248       ForwardRange = AssertSuccess(
5249           Actions.BuildCStyleCastExpr({}, LogicalTSI, {}, ForwardRange));
5250       Expr *ForwardDist = AssertSuccess(Actions.BuildBinOp(
5251           nullptr, {}, BO_Div, ForwardRange, BuildVarRef(NewStep)));
5252 
5253       // Negative increment.
5254       Expr *BackwardRange = AssertSuccess(Actions.BuildBinOp(
5255           nullptr, {}, BO_Sub, BuildVarRef(NewStart), BuildVarRef(NewStop)));
5256       BackwardRange = AssertSuccess(
5257           Actions.BuildCStyleCastExpr({}, LogicalTSI, {}, BackwardRange));
5258       Expr *NegIncAmount = AssertSuccess(
5259           Actions.BuildUnaryOp(nullptr, {}, UO_Minus, BuildVarRef(NewStep)));
5260       Expr *BackwardDist = AssertSuccess(
5261           Actions.BuildBinOp(nullptr, {}, BO_Div, BackwardRange, NegIncAmount));
5262 
5263       // Use the appropriate case.
5264       Dist = AssertSuccess(Actions.ActOnConditionalOp(
5265           {}, {}, IsNegStep, BackwardDist, ForwardDist));
5266     } else {
5267       assert((Rel == BO_LT || Rel == BO_LE || Rel == BO_GE || Rel == BO_GT) &&
5268              "Expected one of these relational operators");
5269 
5270       // We can derive the direction from any other comparison operator. It is
5271       // non well-formed OpenMP if Step increments/decrements in the other
5272       // directions. Whether at least the first iteration passes the loop
5273       // condition.
5274       Expr *HasAnyIteration = AssertSuccess(Actions.BuildBinOp(
5275           nullptr, {}, Rel, BuildVarRef(NewStart), BuildVarRef(NewStop)));
5276 
5277       // Compute the range between first and last counter value.
5278       Expr *Range;
5279       if (Rel == BO_GE || Rel == BO_GT)
5280         Range = AssertSuccess(Actions.BuildBinOp(
5281             nullptr, {}, BO_Sub, BuildVarRef(NewStart), BuildVarRef(NewStop)));
5282       else
5283         Range = AssertSuccess(Actions.BuildBinOp(
5284             nullptr, {}, BO_Sub, BuildVarRef(NewStop), BuildVarRef(NewStart)));
5285 
5286       // Ensure unsigned range space.
5287       Range =
5288           AssertSuccess(Actions.BuildCStyleCastExpr({}, LogicalTSI, {}, Range));
5289 
5290       if (Rel == BO_LE || Rel == BO_GE) {
5291         // Add one to the range if the relational operator is inclusive.
5292         Range =
5293             AssertSuccess(Actions.BuildUnaryOp(nullptr, {}, UO_PreInc, Range));
5294       }
5295 
5296       // Divide by the absolute step amount.
5297       Expr *Divisor = BuildVarRef(NewStep);
5298       if (Rel == BO_GE || Rel == BO_GT)
5299         Divisor =
5300             AssertSuccess(Actions.BuildUnaryOp(nullptr, {}, UO_Minus, Divisor));
5301       Dist = AssertSuccess(
5302           Actions.BuildBinOp(nullptr, {}, BO_Div, Range, Divisor));
5303 
5304       // If there is not at least one iteration, the range contains garbage. Fix
5305       // to zero in this case.
5306       Dist = AssertSuccess(
5307           Actions.ActOnConditionalOp({}, {}, HasAnyIteration, Dist, Zero));
5308     }
5309 
5310     // Assign the result to the out-parameter.
5311     Stmt *ResultAssign = AssertSuccess(Actions.BuildBinOp(
5312         Actions.getCurScope(), {}, BO_Assign, DistRef, Dist));
5313     BodyStmts.push_back(ResultAssign);
5314 
5315     Body = AssertSuccess(Actions.ActOnCompoundStmt({}, {}, BodyStmts, false));
5316   }
5317 
5318   return cast<CapturedStmt>(
5319       AssertSuccess(Actions.ActOnCapturedRegionEnd(Body)));
5320 }
5321 
5322 /// Create a closure that computes the loop variable from the logical iteration
5323 /// number.
5324 ///
5325 /// \param Actions   The Sema object.
5326 /// \param LoopVarTy Type for the loop variable used for result value.
5327 /// \param LogicalTy Type for the logical iteration number.
5328 /// \param StartExpr Value of the loop counter at the first iteration.
5329 /// \param Step      Amount of increment after each iteration.
5330 /// \param Deref     Whether the loop variable is a dereference of the loop
5331 /// counter variable.
5332 ///
5333 /// \return Closure (CapturedStmt) of the loop value calculation.
5334 static CapturedStmt *buildLoopVarFunc(Sema &Actions, QualType LoopVarTy,
5335                                       QualType LogicalTy,
5336                                       DeclRefExpr *StartExpr, Expr *Step,
5337                                       bool Deref) {
5338   ASTContext &Ctx = Actions.getASTContext();
5339 
5340   // Pass the result as an out-parameter. Passing as return value would require
5341   // the OpenMPIRBuilder to know additional C/C++ semantics, such as how to
5342   // invoke a copy constructor.
5343   QualType TargetParamTy = Ctx.getLValueReferenceType(LoopVarTy);
5344   Sema::CapturedParamNameType Params[] = {{"LoopVar", TargetParamTy},
5345                                           {"Logical", LogicalTy},
5346                                           {StringRef(), QualType()}};
5347   Actions.ActOnCapturedRegionStart({}, nullptr, CR_Default, Params);
5348 
5349   // Capture the initial iterator which represents the LoopVar value at the
5350   // zero's logical iteration. Since the original ForStmt/CXXForRangeStmt update
5351   // it in every iteration, capture it by value before it is modified.
5352   VarDecl *StartVar = cast<VarDecl>(StartExpr->getDecl());
5353   bool Invalid = Actions.tryCaptureVariable(StartVar, {},
5354                                             Sema::TryCapture_ExplicitByVal, {});
5355   (void)Invalid;
5356   assert(!Invalid && "Expecting capture-by-value to work.");
5357 
5358   Expr *Body;
5359   {
5360     Sema::CompoundScopeRAII CompoundScope(Actions);
5361     auto *CS = cast<CapturedDecl>(Actions.CurContext);
5362 
5363     ImplicitParamDecl *TargetParam = CS->getParam(0);
5364     DeclRefExpr *TargetRef = Actions.BuildDeclRefExpr(
5365         TargetParam, LoopVarTy, VK_LValue, {}, nullptr, nullptr, {}, nullptr);
5366     ImplicitParamDecl *IndvarParam = CS->getParam(1);
5367     DeclRefExpr *LogicalRef = Actions.BuildDeclRefExpr(
5368         IndvarParam, LogicalTy, VK_LValue, {}, nullptr, nullptr, {}, nullptr);
5369 
5370     // Capture the Start expression.
5371     CaptureVars Recap(Actions);
5372     Expr *NewStart = AssertSuccess(Recap.TransformExpr(StartExpr));
5373     Expr *NewStep = AssertSuccess(Recap.TransformExpr(Step));
5374 
5375     Expr *Skip = AssertSuccess(
5376         Actions.BuildBinOp(nullptr, {}, BO_Mul, NewStep, LogicalRef));
5377     // TODO: Explicitly cast to the iterator's difference_type instead of
5378     // relying on implicit conversion.
5379     Expr *Advanced =
5380         AssertSuccess(Actions.BuildBinOp(nullptr, {}, BO_Add, NewStart, Skip));
5381 
5382     if (Deref) {
5383       // For range-based for-loops convert the loop counter value to a concrete
5384       // loop variable value by dereferencing the iterator.
5385       Advanced =
5386           AssertSuccess(Actions.BuildUnaryOp(nullptr, {}, UO_Deref, Advanced));
5387     }
5388 
5389     // Assign the result to the output parameter.
5390     Body = AssertSuccess(Actions.BuildBinOp(Actions.getCurScope(), {},
5391                                             BO_Assign, TargetRef, Advanced));
5392   }
5393   return cast<CapturedStmt>(
5394       AssertSuccess(Actions.ActOnCapturedRegionEnd(Body)));
5395 }
5396 
5397 StmtResult Sema::ActOnOpenMPCanonicalLoop(Stmt *AStmt) {
5398   ASTContext &Ctx = getASTContext();
5399 
5400   // Extract the common elements of ForStmt and CXXForRangeStmt:
5401   // Loop variable, repeat condition, increment
5402   Expr *Cond, *Inc;
5403   VarDecl *LIVDecl, *LUVDecl;
5404   if (auto *For = dyn_cast<ForStmt>(AStmt)) {
5405     Stmt *Init = For->getInit();
5406     if (auto *LCVarDeclStmt = dyn_cast<DeclStmt>(Init)) {
5407       // For statement declares loop variable.
5408       LIVDecl = cast<VarDecl>(LCVarDeclStmt->getSingleDecl());
5409     } else if (auto *LCAssign = dyn_cast<BinaryOperator>(Init)) {
5410       // For statement reuses variable.
5411       assert(LCAssign->getOpcode() == BO_Assign &&
5412              "init part must be a loop variable assignment");
5413       auto *CounterRef = cast<DeclRefExpr>(LCAssign->getLHS());
5414       LIVDecl = cast<VarDecl>(CounterRef->getDecl());
5415     } else
5416       llvm_unreachable("Cannot determine loop variable");
5417     LUVDecl = LIVDecl;
5418 
5419     Cond = For->getCond();
5420     Inc = For->getInc();
5421   } else if (auto *RangeFor = dyn_cast<CXXForRangeStmt>(AStmt)) {
5422     DeclStmt *BeginStmt = RangeFor->getBeginStmt();
5423     LIVDecl = cast<VarDecl>(BeginStmt->getSingleDecl());
5424     LUVDecl = RangeFor->getLoopVariable();
5425 
5426     Cond = RangeFor->getCond();
5427     Inc = RangeFor->getInc();
5428   } else
5429     llvm_unreachable("unhandled kind of loop");
5430 
5431   QualType CounterTy = LIVDecl->getType();
5432   QualType LVTy = LUVDecl->getType();
5433 
5434   // Analyze the loop condition.
5435   Expr *LHS, *RHS;
5436   BinaryOperator::Opcode CondRel;
5437   Cond = Cond->IgnoreImplicit();
5438   if (auto *CondBinExpr = dyn_cast<BinaryOperator>(Cond)) {
5439     LHS = CondBinExpr->getLHS();
5440     RHS = CondBinExpr->getRHS();
5441     CondRel = CondBinExpr->getOpcode();
5442   } else if (auto *CondCXXOp = dyn_cast<CXXOperatorCallExpr>(Cond)) {
5443     assert(CondCXXOp->getNumArgs() == 2 && "Comparison should have 2 operands");
5444     LHS = CondCXXOp->getArg(0);
5445     RHS = CondCXXOp->getArg(1);
5446     switch (CondCXXOp->getOperator()) {
5447     case OO_ExclaimEqual:
5448       CondRel = BO_NE;
5449       break;
5450     case OO_Less:
5451       CondRel = BO_LT;
5452       break;
5453     case OO_LessEqual:
5454       CondRel = BO_LE;
5455       break;
5456     case OO_Greater:
5457       CondRel = BO_GT;
5458       break;
5459     case OO_GreaterEqual:
5460       CondRel = BO_GE;
5461       break;
5462     default:
5463       llvm_unreachable("unexpected iterator operator");
5464     }
5465   } else
5466     llvm_unreachable("unexpected loop condition");
5467 
5468   // Normalize such that the loop counter is on the LHS.
5469   if (!isa<DeclRefExpr>(LHS->IgnoreImplicit()) ||
5470       cast<DeclRefExpr>(LHS->IgnoreImplicit())->getDecl() != LIVDecl) {
5471     std::swap(LHS, RHS);
5472     CondRel = BinaryOperator::reverseComparisonOp(CondRel);
5473   }
5474   auto *CounterRef = cast<DeclRefExpr>(LHS->IgnoreImplicit());
5475 
5476   // Decide the bit width for the logical iteration counter. By default use the
5477   // unsigned ptrdiff_t integer size (for iterators and pointers).
5478   // TODO: For iterators, use iterator::difference_type,
5479   // std::iterator_traits<>::difference_type or decltype(it - end).
5480   QualType LogicalTy = Ctx.getUnsignedPointerDiffType();
5481   if (CounterTy->isIntegerType()) {
5482     unsigned BitWidth = Ctx.getIntWidth(CounterTy);
5483     LogicalTy = Ctx.getIntTypeForBitwidth(BitWidth, false);
5484   }
5485 
5486   // Analyze the loop increment.
5487   Expr *Step;
5488   if (auto *IncUn = dyn_cast<UnaryOperator>(Inc)) {
5489     int Direction;
5490     switch (IncUn->getOpcode()) {
5491     case UO_PreInc:
5492     case UO_PostInc:
5493       Direction = 1;
5494       break;
5495     case UO_PreDec:
5496     case UO_PostDec:
5497       Direction = -1;
5498       break;
5499     default:
5500       llvm_unreachable("unhandled unary increment operator");
5501     }
5502     Step = IntegerLiteral::Create(
5503         Ctx, llvm::APInt(Ctx.getIntWidth(LogicalTy), Direction), LogicalTy, {});
5504   } else if (auto *IncBin = dyn_cast<BinaryOperator>(Inc)) {
5505     if (IncBin->getOpcode() == BO_AddAssign) {
5506       Step = IncBin->getRHS();
5507     } else if (IncBin->getOpcode() == BO_SubAssign) {
5508       Step =
5509           AssertSuccess(BuildUnaryOp(nullptr, {}, UO_Minus, IncBin->getRHS()));
5510     } else
5511       llvm_unreachable("unhandled binary increment operator");
5512   } else if (auto *CondCXXOp = dyn_cast<CXXOperatorCallExpr>(Inc)) {
5513     switch (CondCXXOp->getOperator()) {
5514     case OO_PlusPlus:
5515       Step = IntegerLiteral::Create(
5516           Ctx, llvm::APInt(Ctx.getIntWidth(LogicalTy), 1), LogicalTy, {});
5517       break;
5518     case OO_MinusMinus:
5519       Step = IntegerLiteral::Create(
5520           Ctx, llvm::APInt(Ctx.getIntWidth(LogicalTy), -1), LogicalTy, {});
5521       break;
5522     case OO_PlusEqual:
5523       Step = CondCXXOp->getArg(1);
5524       break;
5525     case OO_MinusEqual:
5526       Step = AssertSuccess(
5527           BuildUnaryOp(nullptr, {}, UO_Minus, CondCXXOp->getArg(1)));
5528       break;
5529     default:
5530       llvm_unreachable("unhandled overloaded increment operator");
5531     }
5532   } else
5533     llvm_unreachable("unknown increment expression");
5534 
5535   CapturedStmt *DistanceFunc =
5536       buildDistanceFunc(*this, LogicalTy, CondRel, LHS, RHS, Step);
5537   CapturedStmt *LoopVarFunc = buildLoopVarFunc(
5538       *this, LVTy, LogicalTy, CounterRef, Step, isa<CXXForRangeStmt>(AStmt));
5539   DeclRefExpr *LVRef = BuildDeclRefExpr(LUVDecl, LUVDecl->getType(), VK_LValue,
5540                                         {}, nullptr, nullptr, {}, nullptr);
5541   return OMPCanonicalLoop::create(getASTContext(), AStmt, DistanceFunc,
5542                                   LoopVarFunc, LVRef);
5543 }
5544 
5545 static ExprResult buildUserDefinedMapperRef(Sema &SemaRef, Scope *S,
5546                                             CXXScopeSpec &MapperIdScopeSpec,
5547                                             const DeclarationNameInfo &MapperId,
5548                                             QualType Type,
5549                                             Expr *UnresolvedMapper);
5550 
5551 /// Perform DFS through the structure/class data members trying to find
5552 /// member(s) with user-defined 'default' mapper and generate implicit map
5553 /// clauses for such members with the found 'default' mapper.
5554 static void
5555 processImplicitMapsWithDefaultMappers(Sema &S, DSAStackTy *Stack,
5556                                       SmallVectorImpl<OMPClause *> &Clauses) {
5557   // Check for the deault mapper for data members.
5558   if (S.getLangOpts().OpenMP < 50)
5559     return;
5560   SmallVector<OMPClause *, 4> ImplicitMaps;
5561   DeclarationNameInfo DefaultMapperId;
5562   DefaultMapperId.setName(S.Context.DeclarationNames.getIdentifier(
5563       &S.Context.Idents.get("default")));
5564   for (int Cnt = 0, EndCnt = Clauses.size(); Cnt < EndCnt; ++Cnt) {
5565     auto *C = dyn_cast<OMPMapClause>(Clauses[Cnt]);
5566     if (!C)
5567       continue;
5568     SmallVector<Expr *, 4> SubExprs;
5569     auto *MI = C->mapperlist_begin();
5570     for (auto I = C->varlist_begin(), End = C->varlist_end(); I != End;
5571          ++I, ++MI) {
5572       // Expression is mapped using mapper - skip it.
5573       if (*MI)
5574         continue;
5575       Expr *E = *I;
5576       // Expression is dependent - skip it, build the mapper when it gets
5577       // instantiated.
5578       if (E->isTypeDependent() || E->isValueDependent() ||
5579           E->containsUnexpandedParameterPack())
5580         continue;
5581       // Array section - need to check for the mapping of the array section
5582       // element.
5583       QualType CanonType = E->getType().getCanonicalType();
5584       if (CanonType->isSpecificBuiltinType(BuiltinType::OMPArraySection)) {
5585         const auto *OASE = cast<OMPArraySectionExpr>(E->IgnoreParenImpCasts());
5586         QualType BaseType =
5587             OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
5588         QualType ElemType;
5589         if (const auto *ATy = BaseType->getAsArrayTypeUnsafe())
5590           ElemType = ATy->getElementType();
5591         else
5592           ElemType = BaseType->getPointeeType();
5593         CanonType = ElemType;
5594       }
5595 
5596       // DFS over data members in structures/classes.
5597       SmallVector<std::pair<QualType, FieldDecl *>, 4> Types(
5598           1, {CanonType, nullptr});
5599       llvm::DenseMap<const Type *, Expr *> Visited;
5600       SmallVector<std::pair<FieldDecl *, unsigned>, 4> ParentChain(
5601           1, {nullptr, 1});
5602       while (!Types.empty()) {
5603         QualType BaseType;
5604         FieldDecl *CurFD;
5605         std::tie(BaseType, CurFD) = Types.pop_back_val();
5606         while (ParentChain.back().second == 0)
5607           ParentChain.pop_back();
5608         --ParentChain.back().second;
5609         if (BaseType.isNull())
5610           continue;
5611         // Only structs/classes are allowed to have mappers.
5612         const RecordDecl *RD = BaseType.getCanonicalType()->getAsRecordDecl();
5613         if (!RD)
5614           continue;
5615         auto It = Visited.find(BaseType.getTypePtr());
5616         if (It == Visited.end()) {
5617           // Try to find the associated user-defined mapper.
5618           CXXScopeSpec MapperIdScopeSpec;
5619           ExprResult ER = buildUserDefinedMapperRef(
5620               S, Stack->getCurScope(), MapperIdScopeSpec, DefaultMapperId,
5621               BaseType, /*UnresolvedMapper=*/nullptr);
5622           if (ER.isInvalid())
5623             continue;
5624           It = Visited.try_emplace(BaseType.getTypePtr(), ER.get()).first;
5625         }
5626         // Found default mapper.
5627         if (It->second) {
5628           auto *OE = new (S.Context) OpaqueValueExpr(E->getExprLoc(), CanonType,
5629                                                      VK_LValue, OK_Ordinary, E);
5630           OE->setIsUnique(/*V=*/true);
5631           Expr *BaseExpr = OE;
5632           for (const auto &P : ParentChain) {
5633             if (P.first) {
5634               BaseExpr = S.BuildMemberExpr(
5635                   BaseExpr, /*IsArrow=*/false, E->getExprLoc(),
5636                   NestedNameSpecifierLoc(), SourceLocation(), P.first,
5637                   DeclAccessPair::make(P.first, P.first->getAccess()),
5638                   /*HadMultipleCandidates=*/false, DeclarationNameInfo(),
5639                   P.first->getType(), VK_LValue, OK_Ordinary);
5640               BaseExpr = S.DefaultLvalueConversion(BaseExpr).get();
5641             }
5642           }
5643           if (CurFD)
5644             BaseExpr = S.BuildMemberExpr(
5645                 BaseExpr, /*IsArrow=*/false, E->getExprLoc(),
5646                 NestedNameSpecifierLoc(), SourceLocation(), CurFD,
5647                 DeclAccessPair::make(CurFD, CurFD->getAccess()),
5648                 /*HadMultipleCandidates=*/false, DeclarationNameInfo(),
5649                 CurFD->getType(), VK_LValue, OK_Ordinary);
5650           SubExprs.push_back(BaseExpr);
5651           continue;
5652         }
5653         // Check for the "default" mapper for data memebers.
5654         bool FirstIter = true;
5655         for (FieldDecl *FD : RD->fields()) {
5656           if (!FD)
5657             continue;
5658           QualType FieldTy = FD->getType();
5659           if (FieldTy.isNull() ||
5660               !(FieldTy->isStructureOrClassType() || FieldTy->isUnionType()))
5661             continue;
5662           if (FirstIter) {
5663             FirstIter = false;
5664             ParentChain.emplace_back(CurFD, 1);
5665           } else {
5666             ++ParentChain.back().second;
5667           }
5668           Types.emplace_back(FieldTy, FD);
5669         }
5670       }
5671     }
5672     if (SubExprs.empty())
5673       continue;
5674     CXXScopeSpec MapperIdScopeSpec;
5675     DeclarationNameInfo MapperId;
5676     if (OMPClause *NewClause = S.ActOnOpenMPMapClause(
5677             C->getMapTypeModifiers(), C->getMapTypeModifiersLoc(),
5678             MapperIdScopeSpec, MapperId, C->getMapType(),
5679             /*IsMapTypeImplicit=*/true, SourceLocation(), SourceLocation(),
5680             SubExprs, OMPVarListLocTy()))
5681       Clauses.push_back(NewClause);
5682   }
5683 }
5684 
5685 StmtResult Sema::ActOnOpenMPExecutableDirective(
5686     OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
5687     OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
5688     Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
5689   StmtResult Res = StmtError();
5690   // First check CancelRegion which is then used in checkNestingOfRegions.
5691   if (checkCancelRegion(*this, Kind, CancelRegion, StartLoc) ||
5692       checkNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion,
5693                             StartLoc))
5694     return StmtError();
5695 
5696   llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit;
5697   VarsWithInheritedDSAType VarsWithInheritedDSA;
5698   bool ErrorFound = false;
5699   ClausesWithImplicit.append(Clauses.begin(), Clauses.end());
5700   if (AStmt && !CurContext->isDependentContext() && Kind != OMPD_atomic &&
5701       Kind != OMPD_critical && Kind != OMPD_section && Kind != OMPD_master &&
5702       !isOpenMPLoopTransformationDirective(Kind)) {
5703     assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5704 
5705     // Check default data sharing attributes for referenced variables.
5706     DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt));
5707     int ThisCaptureLevel = getOpenMPCaptureLevels(Kind);
5708     Stmt *S = AStmt;
5709     while (--ThisCaptureLevel >= 0)
5710       S = cast<CapturedStmt>(S)->getCapturedStmt();
5711     DSAChecker.Visit(S);
5712     if (!isOpenMPTargetDataManagementDirective(Kind) &&
5713         !isOpenMPTaskingDirective(Kind)) {
5714       // Visit subcaptures to generate implicit clauses for captured vars.
5715       auto *CS = cast<CapturedStmt>(AStmt);
5716       SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
5717       getOpenMPCaptureRegions(CaptureRegions, Kind);
5718       // Ignore outer tasking regions for target directives.
5719       if (CaptureRegions.size() > 1 && CaptureRegions.front() == OMPD_task)
5720         CS = cast<CapturedStmt>(CS->getCapturedStmt());
5721       DSAChecker.visitSubCaptures(CS);
5722     }
5723     if (DSAChecker.isErrorFound())
5724       return StmtError();
5725     // Generate list of implicitly defined firstprivate variables.
5726     VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA();
5727 
5728     SmallVector<Expr *, 4> ImplicitFirstprivates(
5729         DSAChecker.getImplicitFirstprivate().begin(),
5730         DSAChecker.getImplicitFirstprivate().end());
5731     const unsigned DefaultmapKindNum = OMPC_DEFAULTMAP_pointer + 1;
5732     SmallVector<Expr *, 4> ImplicitMaps[DefaultmapKindNum][OMPC_MAP_delete];
5733     SmallVector<OpenMPMapModifierKind, NumberOfOMPMapClauseModifiers>
5734         ImplicitMapModifiers[DefaultmapKindNum];
5735     SmallVector<SourceLocation, NumberOfOMPMapClauseModifiers>
5736         ImplicitMapModifiersLoc[DefaultmapKindNum];
5737     // Get the original location of present modifier from Defaultmap clause.
5738     SourceLocation PresentModifierLocs[DefaultmapKindNum];
5739     for (OMPClause *C : Clauses) {
5740       if (auto *DMC = dyn_cast<OMPDefaultmapClause>(C))
5741         if (DMC->getDefaultmapModifier() == OMPC_DEFAULTMAP_MODIFIER_present)
5742           PresentModifierLocs[DMC->getDefaultmapKind()] =
5743               DMC->getDefaultmapModifierLoc();
5744     }
5745     for (unsigned VC = 0; VC < DefaultmapKindNum; ++VC) {
5746       auto Kind = static_cast<OpenMPDefaultmapClauseKind>(VC);
5747       for (unsigned I = 0; I < OMPC_MAP_delete; ++I) {
5748         ArrayRef<Expr *> ImplicitMap = DSAChecker.getImplicitMap(
5749             Kind, static_cast<OpenMPMapClauseKind>(I));
5750         ImplicitMaps[VC][I].append(ImplicitMap.begin(), ImplicitMap.end());
5751       }
5752       ArrayRef<OpenMPMapModifierKind> ImplicitModifier =
5753           DSAChecker.getImplicitMapModifier(Kind);
5754       ImplicitMapModifiers[VC].append(ImplicitModifier.begin(),
5755                                       ImplicitModifier.end());
5756       std::fill_n(std::back_inserter(ImplicitMapModifiersLoc[VC]),
5757                   ImplicitModifier.size(), PresentModifierLocs[VC]);
5758     }
5759     // Mark taskgroup task_reduction descriptors as implicitly firstprivate.
5760     for (OMPClause *C : Clauses) {
5761       if (auto *IRC = dyn_cast<OMPInReductionClause>(C)) {
5762         for (Expr *E : IRC->taskgroup_descriptors())
5763           if (E)
5764             ImplicitFirstprivates.emplace_back(E);
5765       }
5766       // OpenMP 5.0, 2.10.1 task Construct
5767       // [detach clause]... The event-handle will be considered as if it was
5768       // specified on a firstprivate clause.
5769       if (auto *DC = dyn_cast<OMPDetachClause>(C))
5770         ImplicitFirstprivates.push_back(DC->getEventHandler());
5771     }
5772     if (!ImplicitFirstprivates.empty()) {
5773       if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause(
5774               ImplicitFirstprivates, SourceLocation(), SourceLocation(),
5775               SourceLocation())) {
5776         ClausesWithImplicit.push_back(Implicit);
5777         ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() !=
5778                      ImplicitFirstprivates.size();
5779       } else {
5780         ErrorFound = true;
5781       }
5782     }
5783     for (unsigned I = 0, E = DefaultmapKindNum; I < E; ++I) {
5784       int ClauseKindCnt = -1;
5785       for (ArrayRef<Expr *> ImplicitMap : ImplicitMaps[I]) {
5786         ++ClauseKindCnt;
5787         if (ImplicitMap.empty())
5788           continue;
5789         CXXScopeSpec MapperIdScopeSpec;
5790         DeclarationNameInfo MapperId;
5791         auto Kind = static_cast<OpenMPMapClauseKind>(ClauseKindCnt);
5792         if (OMPClause *Implicit = ActOnOpenMPMapClause(
5793                 ImplicitMapModifiers[I], ImplicitMapModifiersLoc[I],
5794                 MapperIdScopeSpec, MapperId, Kind, /*IsMapTypeImplicit=*/true,
5795                 SourceLocation(), SourceLocation(), ImplicitMap,
5796                 OMPVarListLocTy())) {
5797           ClausesWithImplicit.emplace_back(Implicit);
5798           ErrorFound |= cast<OMPMapClause>(Implicit)->varlist_size() !=
5799                         ImplicitMap.size();
5800         } else {
5801           ErrorFound = true;
5802         }
5803       }
5804     }
5805     // Build expressions for implicit maps of data members with 'default'
5806     // mappers.
5807     if (LangOpts.OpenMP >= 50)
5808       processImplicitMapsWithDefaultMappers(*this, DSAStack,
5809                                             ClausesWithImplicit);
5810   }
5811 
5812   llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers;
5813   switch (Kind) {
5814   case OMPD_parallel:
5815     Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc,
5816                                        EndLoc);
5817     AllowedNameModifiers.push_back(OMPD_parallel);
5818     break;
5819   case OMPD_simd:
5820     Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
5821                                    VarsWithInheritedDSA);
5822     if (LangOpts.OpenMP >= 50)
5823       AllowedNameModifiers.push_back(OMPD_simd);
5824     break;
5825   case OMPD_tile:
5826     Res =
5827         ActOnOpenMPTileDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
5828     break;
5829   case OMPD_for:
5830     Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
5831                                   VarsWithInheritedDSA);
5832     break;
5833   case OMPD_for_simd:
5834     Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
5835                                       EndLoc, VarsWithInheritedDSA);
5836     if (LangOpts.OpenMP >= 50)
5837       AllowedNameModifiers.push_back(OMPD_simd);
5838     break;
5839   case OMPD_sections:
5840     Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc,
5841                                        EndLoc);
5842     break;
5843   case OMPD_section:
5844     assert(ClausesWithImplicit.empty() &&
5845            "No clauses are allowed for 'omp section' directive");
5846     Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc);
5847     break;
5848   case OMPD_single:
5849     Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc,
5850                                      EndLoc);
5851     break;
5852   case OMPD_master:
5853     assert(ClausesWithImplicit.empty() &&
5854            "No clauses are allowed for 'omp master' directive");
5855     Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc);
5856     break;
5857   case OMPD_critical:
5858     Res = ActOnOpenMPCriticalDirective(DirName, ClausesWithImplicit, AStmt,
5859                                        StartLoc, EndLoc);
5860     break;
5861   case OMPD_parallel_for:
5862     Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc,
5863                                           EndLoc, VarsWithInheritedDSA);
5864     AllowedNameModifiers.push_back(OMPD_parallel);
5865     break;
5866   case OMPD_parallel_for_simd:
5867     Res = ActOnOpenMPParallelForSimdDirective(
5868         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
5869     AllowedNameModifiers.push_back(OMPD_parallel);
5870     if (LangOpts.OpenMP >= 50)
5871       AllowedNameModifiers.push_back(OMPD_simd);
5872     break;
5873   case OMPD_parallel_master:
5874     Res = ActOnOpenMPParallelMasterDirective(ClausesWithImplicit, AStmt,
5875                                                StartLoc, EndLoc);
5876     AllowedNameModifiers.push_back(OMPD_parallel);
5877     break;
5878   case OMPD_parallel_sections:
5879     Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt,
5880                                                StartLoc, EndLoc);
5881     AllowedNameModifiers.push_back(OMPD_parallel);
5882     break;
5883   case OMPD_task:
5884     Res =
5885         ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
5886     AllowedNameModifiers.push_back(OMPD_task);
5887     break;
5888   case OMPD_taskyield:
5889     assert(ClausesWithImplicit.empty() &&
5890            "No clauses are allowed for 'omp taskyield' directive");
5891     assert(AStmt == nullptr &&
5892            "No associated statement allowed for 'omp taskyield' directive");
5893     Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc);
5894     break;
5895   case OMPD_barrier:
5896     assert(ClausesWithImplicit.empty() &&
5897            "No clauses are allowed for 'omp barrier' directive");
5898     assert(AStmt == nullptr &&
5899            "No associated statement allowed for 'omp barrier' directive");
5900     Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc);
5901     break;
5902   case OMPD_taskwait:
5903     assert(ClausesWithImplicit.empty() &&
5904            "No clauses are allowed for 'omp taskwait' directive");
5905     assert(AStmt == nullptr &&
5906            "No associated statement allowed for 'omp taskwait' directive");
5907     Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc);
5908     break;
5909   case OMPD_taskgroup:
5910     Res = ActOnOpenMPTaskgroupDirective(ClausesWithImplicit, AStmt, StartLoc,
5911                                         EndLoc);
5912     break;
5913   case OMPD_flush:
5914     assert(AStmt == nullptr &&
5915            "No associated statement allowed for 'omp flush' directive");
5916     Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc);
5917     break;
5918   case OMPD_depobj:
5919     assert(AStmt == nullptr &&
5920            "No associated statement allowed for 'omp depobj' directive");
5921     Res = ActOnOpenMPDepobjDirective(ClausesWithImplicit, StartLoc, EndLoc);
5922     break;
5923   case OMPD_scan:
5924     assert(AStmt == nullptr &&
5925            "No associated statement allowed for 'omp scan' directive");
5926     Res = ActOnOpenMPScanDirective(ClausesWithImplicit, StartLoc, EndLoc);
5927     break;
5928   case OMPD_ordered:
5929     Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc,
5930                                       EndLoc);
5931     break;
5932   case OMPD_atomic:
5933     Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc,
5934                                      EndLoc);
5935     break;
5936   case OMPD_teams:
5937     Res =
5938         ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
5939     break;
5940   case OMPD_target:
5941     Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc,
5942                                      EndLoc);
5943     AllowedNameModifiers.push_back(OMPD_target);
5944     break;
5945   case OMPD_target_parallel:
5946     Res = ActOnOpenMPTargetParallelDirective(ClausesWithImplicit, AStmt,
5947                                              StartLoc, EndLoc);
5948     AllowedNameModifiers.push_back(OMPD_target);
5949     AllowedNameModifiers.push_back(OMPD_parallel);
5950     break;
5951   case OMPD_target_parallel_for:
5952     Res = ActOnOpenMPTargetParallelForDirective(
5953         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
5954     AllowedNameModifiers.push_back(OMPD_target);
5955     AllowedNameModifiers.push_back(OMPD_parallel);
5956     break;
5957   case OMPD_cancellation_point:
5958     assert(ClausesWithImplicit.empty() &&
5959            "No clauses are allowed for 'omp cancellation point' directive");
5960     assert(AStmt == nullptr && "No associated statement allowed for 'omp "
5961                                "cancellation point' directive");
5962     Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion);
5963     break;
5964   case OMPD_cancel:
5965     assert(AStmt == nullptr &&
5966            "No associated statement allowed for 'omp cancel' directive");
5967     Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc,
5968                                      CancelRegion);
5969     AllowedNameModifiers.push_back(OMPD_cancel);
5970     break;
5971   case OMPD_target_data:
5972     Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc,
5973                                          EndLoc);
5974     AllowedNameModifiers.push_back(OMPD_target_data);
5975     break;
5976   case OMPD_target_enter_data:
5977     Res = ActOnOpenMPTargetEnterDataDirective(ClausesWithImplicit, StartLoc,
5978                                               EndLoc, AStmt);
5979     AllowedNameModifiers.push_back(OMPD_target_enter_data);
5980     break;
5981   case OMPD_target_exit_data:
5982     Res = ActOnOpenMPTargetExitDataDirective(ClausesWithImplicit, StartLoc,
5983                                              EndLoc, AStmt);
5984     AllowedNameModifiers.push_back(OMPD_target_exit_data);
5985     break;
5986   case OMPD_taskloop:
5987     Res = ActOnOpenMPTaskLoopDirective(ClausesWithImplicit, AStmt, StartLoc,
5988                                        EndLoc, VarsWithInheritedDSA);
5989     AllowedNameModifiers.push_back(OMPD_taskloop);
5990     break;
5991   case OMPD_taskloop_simd:
5992     Res = ActOnOpenMPTaskLoopSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
5993                                            EndLoc, VarsWithInheritedDSA);
5994     AllowedNameModifiers.push_back(OMPD_taskloop);
5995     if (LangOpts.OpenMP >= 50)
5996       AllowedNameModifiers.push_back(OMPD_simd);
5997     break;
5998   case OMPD_master_taskloop:
5999     Res = ActOnOpenMPMasterTaskLoopDirective(
6000         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6001     AllowedNameModifiers.push_back(OMPD_taskloop);
6002     break;
6003   case OMPD_master_taskloop_simd:
6004     Res = ActOnOpenMPMasterTaskLoopSimdDirective(
6005         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6006     AllowedNameModifiers.push_back(OMPD_taskloop);
6007     if (LangOpts.OpenMP >= 50)
6008       AllowedNameModifiers.push_back(OMPD_simd);
6009     break;
6010   case OMPD_parallel_master_taskloop:
6011     Res = ActOnOpenMPParallelMasterTaskLoopDirective(
6012         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6013     AllowedNameModifiers.push_back(OMPD_taskloop);
6014     AllowedNameModifiers.push_back(OMPD_parallel);
6015     break;
6016   case OMPD_parallel_master_taskloop_simd:
6017     Res = ActOnOpenMPParallelMasterTaskLoopSimdDirective(
6018         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6019     AllowedNameModifiers.push_back(OMPD_taskloop);
6020     AllowedNameModifiers.push_back(OMPD_parallel);
6021     if (LangOpts.OpenMP >= 50)
6022       AllowedNameModifiers.push_back(OMPD_simd);
6023     break;
6024   case OMPD_distribute:
6025     Res = ActOnOpenMPDistributeDirective(ClausesWithImplicit, AStmt, StartLoc,
6026                                          EndLoc, VarsWithInheritedDSA);
6027     break;
6028   case OMPD_target_update:
6029     Res = ActOnOpenMPTargetUpdateDirective(ClausesWithImplicit, StartLoc,
6030                                            EndLoc, AStmt);
6031     AllowedNameModifiers.push_back(OMPD_target_update);
6032     break;
6033   case OMPD_distribute_parallel_for:
6034     Res = ActOnOpenMPDistributeParallelForDirective(
6035         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6036     AllowedNameModifiers.push_back(OMPD_parallel);
6037     break;
6038   case OMPD_distribute_parallel_for_simd:
6039     Res = ActOnOpenMPDistributeParallelForSimdDirective(
6040         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6041     AllowedNameModifiers.push_back(OMPD_parallel);
6042     if (LangOpts.OpenMP >= 50)
6043       AllowedNameModifiers.push_back(OMPD_simd);
6044     break;
6045   case OMPD_distribute_simd:
6046     Res = ActOnOpenMPDistributeSimdDirective(
6047         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6048     if (LangOpts.OpenMP >= 50)
6049       AllowedNameModifiers.push_back(OMPD_simd);
6050     break;
6051   case OMPD_target_parallel_for_simd:
6052     Res = ActOnOpenMPTargetParallelForSimdDirective(
6053         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6054     AllowedNameModifiers.push_back(OMPD_target);
6055     AllowedNameModifiers.push_back(OMPD_parallel);
6056     if (LangOpts.OpenMP >= 50)
6057       AllowedNameModifiers.push_back(OMPD_simd);
6058     break;
6059   case OMPD_target_simd:
6060     Res = ActOnOpenMPTargetSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
6061                                          EndLoc, VarsWithInheritedDSA);
6062     AllowedNameModifiers.push_back(OMPD_target);
6063     if (LangOpts.OpenMP >= 50)
6064       AllowedNameModifiers.push_back(OMPD_simd);
6065     break;
6066   case OMPD_teams_distribute:
6067     Res = ActOnOpenMPTeamsDistributeDirective(
6068         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6069     break;
6070   case OMPD_teams_distribute_simd:
6071     Res = ActOnOpenMPTeamsDistributeSimdDirective(
6072         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6073     if (LangOpts.OpenMP >= 50)
6074       AllowedNameModifiers.push_back(OMPD_simd);
6075     break;
6076   case OMPD_teams_distribute_parallel_for_simd:
6077     Res = ActOnOpenMPTeamsDistributeParallelForSimdDirective(
6078         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6079     AllowedNameModifiers.push_back(OMPD_parallel);
6080     if (LangOpts.OpenMP >= 50)
6081       AllowedNameModifiers.push_back(OMPD_simd);
6082     break;
6083   case OMPD_teams_distribute_parallel_for:
6084     Res = ActOnOpenMPTeamsDistributeParallelForDirective(
6085         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6086     AllowedNameModifiers.push_back(OMPD_parallel);
6087     break;
6088   case OMPD_target_teams:
6089     Res = ActOnOpenMPTargetTeamsDirective(ClausesWithImplicit, AStmt, StartLoc,
6090                                           EndLoc);
6091     AllowedNameModifiers.push_back(OMPD_target);
6092     break;
6093   case OMPD_target_teams_distribute:
6094     Res = ActOnOpenMPTargetTeamsDistributeDirective(
6095         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6096     AllowedNameModifiers.push_back(OMPD_target);
6097     break;
6098   case OMPD_target_teams_distribute_parallel_for:
6099     Res = ActOnOpenMPTargetTeamsDistributeParallelForDirective(
6100         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6101     AllowedNameModifiers.push_back(OMPD_target);
6102     AllowedNameModifiers.push_back(OMPD_parallel);
6103     break;
6104   case OMPD_target_teams_distribute_parallel_for_simd:
6105     Res = ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
6106         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6107     AllowedNameModifiers.push_back(OMPD_target);
6108     AllowedNameModifiers.push_back(OMPD_parallel);
6109     if (LangOpts.OpenMP >= 50)
6110       AllowedNameModifiers.push_back(OMPD_simd);
6111     break;
6112   case OMPD_target_teams_distribute_simd:
6113     Res = ActOnOpenMPTargetTeamsDistributeSimdDirective(
6114         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6115     AllowedNameModifiers.push_back(OMPD_target);
6116     if (LangOpts.OpenMP >= 50)
6117       AllowedNameModifiers.push_back(OMPD_simd);
6118     break;
6119   case OMPD_interop:
6120     assert(AStmt == nullptr &&
6121            "No associated statement allowed for 'omp interop' directive");
6122     Res = ActOnOpenMPInteropDirective(ClausesWithImplicit, StartLoc, EndLoc);
6123     break;
6124   case OMPD_dispatch:
6125     Res = ActOnOpenMPDispatchDirective(ClausesWithImplicit, AStmt, StartLoc,
6126                                        EndLoc);
6127     break;
6128   case OMPD_declare_target:
6129   case OMPD_end_declare_target:
6130   case OMPD_threadprivate:
6131   case OMPD_allocate:
6132   case OMPD_declare_reduction:
6133   case OMPD_declare_mapper:
6134   case OMPD_declare_simd:
6135   case OMPD_requires:
6136   case OMPD_declare_variant:
6137   case OMPD_begin_declare_variant:
6138   case OMPD_end_declare_variant:
6139     llvm_unreachable("OpenMP Directive is not allowed");
6140   case OMPD_unknown:
6141   default:
6142     llvm_unreachable("Unknown OpenMP directive");
6143   }
6144 
6145   ErrorFound = Res.isInvalid() || ErrorFound;
6146 
6147   // Check variables in the clauses if default(none) or
6148   // default(firstprivate) was specified.
6149   if (DSAStack->getDefaultDSA() == DSA_none ||
6150       DSAStack->getDefaultDSA() == DSA_firstprivate) {
6151     DSAAttrChecker DSAChecker(DSAStack, *this, nullptr);
6152     for (OMPClause *C : Clauses) {
6153       switch (C->getClauseKind()) {
6154       case OMPC_num_threads:
6155       case OMPC_dist_schedule:
6156         // Do not analyse if no parent teams directive.
6157         if (isOpenMPTeamsDirective(Kind))
6158           break;
6159         continue;
6160       case OMPC_if:
6161         if (isOpenMPTeamsDirective(Kind) &&
6162             cast<OMPIfClause>(C)->getNameModifier() != OMPD_target)
6163           break;
6164         if (isOpenMPParallelDirective(Kind) &&
6165             isOpenMPTaskLoopDirective(Kind) &&
6166             cast<OMPIfClause>(C)->getNameModifier() != OMPD_parallel)
6167           break;
6168         continue;
6169       case OMPC_schedule:
6170       case OMPC_detach:
6171         break;
6172       case OMPC_grainsize:
6173       case OMPC_num_tasks:
6174       case OMPC_final:
6175       case OMPC_priority:
6176       case OMPC_novariants:
6177       case OMPC_nocontext:
6178         // Do not analyze if no parent parallel directive.
6179         if (isOpenMPParallelDirective(Kind))
6180           break;
6181         continue;
6182       case OMPC_ordered:
6183       case OMPC_device:
6184       case OMPC_num_teams:
6185       case OMPC_thread_limit:
6186       case OMPC_hint:
6187       case OMPC_collapse:
6188       case OMPC_safelen:
6189       case OMPC_simdlen:
6190       case OMPC_sizes:
6191       case OMPC_default:
6192       case OMPC_proc_bind:
6193       case OMPC_private:
6194       case OMPC_firstprivate:
6195       case OMPC_lastprivate:
6196       case OMPC_shared:
6197       case OMPC_reduction:
6198       case OMPC_task_reduction:
6199       case OMPC_in_reduction:
6200       case OMPC_linear:
6201       case OMPC_aligned:
6202       case OMPC_copyin:
6203       case OMPC_copyprivate:
6204       case OMPC_nowait:
6205       case OMPC_untied:
6206       case OMPC_mergeable:
6207       case OMPC_allocate:
6208       case OMPC_read:
6209       case OMPC_write:
6210       case OMPC_update:
6211       case OMPC_capture:
6212       case OMPC_seq_cst:
6213       case OMPC_acq_rel:
6214       case OMPC_acquire:
6215       case OMPC_release:
6216       case OMPC_relaxed:
6217       case OMPC_depend:
6218       case OMPC_threads:
6219       case OMPC_simd:
6220       case OMPC_map:
6221       case OMPC_nogroup:
6222       case OMPC_defaultmap:
6223       case OMPC_to:
6224       case OMPC_from:
6225       case OMPC_use_device_ptr:
6226       case OMPC_use_device_addr:
6227       case OMPC_is_device_ptr:
6228       case OMPC_nontemporal:
6229       case OMPC_order:
6230       case OMPC_destroy:
6231       case OMPC_inclusive:
6232       case OMPC_exclusive:
6233       case OMPC_uses_allocators:
6234       case OMPC_affinity:
6235         continue;
6236       case OMPC_allocator:
6237       case OMPC_flush:
6238       case OMPC_depobj:
6239       case OMPC_threadprivate:
6240       case OMPC_uniform:
6241       case OMPC_unknown:
6242       case OMPC_unified_address:
6243       case OMPC_unified_shared_memory:
6244       case OMPC_reverse_offload:
6245       case OMPC_dynamic_allocators:
6246       case OMPC_atomic_default_mem_order:
6247       case OMPC_device_type:
6248       case OMPC_match:
6249       default:
6250         llvm_unreachable("Unexpected clause");
6251       }
6252       for (Stmt *CC : C->children()) {
6253         if (CC)
6254           DSAChecker.Visit(CC);
6255       }
6256     }
6257     for (const auto &P : DSAChecker.getVarsWithInheritedDSA())
6258       VarsWithInheritedDSA[P.getFirst()] = P.getSecond();
6259   }
6260   for (const auto &P : VarsWithInheritedDSA) {
6261     if (P.getFirst()->isImplicit() || isa<OMPCapturedExprDecl>(P.getFirst()))
6262       continue;
6263     ErrorFound = true;
6264     if (DSAStack->getDefaultDSA() == DSA_none ||
6265         DSAStack->getDefaultDSA() == DSA_firstprivate) {
6266       Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable)
6267           << P.first << P.second->getSourceRange();
6268       Diag(DSAStack->getDefaultDSALocation(), diag::note_omp_default_dsa_none);
6269     } else if (getLangOpts().OpenMP >= 50) {
6270       Diag(P.second->getExprLoc(),
6271            diag::err_omp_defaultmap_no_attr_for_variable)
6272           << P.first << P.second->getSourceRange();
6273       Diag(DSAStack->getDefaultDSALocation(),
6274            diag::note_omp_defaultmap_attr_none);
6275     }
6276   }
6277 
6278   if (!AllowedNameModifiers.empty())
6279     ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) ||
6280                  ErrorFound;
6281 
6282   if (ErrorFound)
6283     return StmtError();
6284 
6285   if (!CurContext->isDependentContext() &&
6286       isOpenMPTargetExecutionDirective(Kind) &&
6287       !(DSAStack->hasRequiresDeclWithClause<OMPUnifiedSharedMemoryClause>() ||
6288         DSAStack->hasRequiresDeclWithClause<OMPUnifiedAddressClause>() ||
6289         DSAStack->hasRequiresDeclWithClause<OMPReverseOffloadClause>() ||
6290         DSAStack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>())) {
6291     // Register target to DSA Stack.
6292     DSAStack->addTargetDirLocation(StartLoc);
6293   }
6294 
6295   return Res;
6296 }
6297 
6298 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareSimdDirective(
6299     DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen,
6300     ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
6301     ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
6302     ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR) {
6303   assert(Aligneds.size() == Alignments.size());
6304   assert(Linears.size() == LinModifiers.size());
6305   assert(Linears.size() == Steps.size());
6306   if (!DG || DG.get().isNull())
6307     return DeclGroupPtrTy();
6308 
6309   const int SimdId = 0;
6310   if (!DG.get().isSingleDecl()) {
6311     Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd_variant)
6312         << SimdId;
6313     return DG;
6314   }
6315   Decl *ADecl = DG.get().getSingleDecl();
6316   if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
6317     ADecl = FTD->getTemplatedDecl();
6318 
6319   auto *FD = dyn_cast<FunctionDecl>(ADecl);
6320   if (!FD) {
6321     Diag(ADecl->getLocation(), diag::err_omp_function_expected) << SimdId;
6322     return DeclGroupPtrTy();
6323   }
6324 
6325   // OpenMP [2.8.2, declare simd construct, Description]
6326   // The parameter of the simdlen clause must be a constant positive integer
6327   // expression.
6328   ExprResult SL;
6329   if (Simdlen)
6330     SL = VerifyPositiveIntegerConstantInClause(Simdlen, OMPC_simdlen);
6331   // OpenMP [2.8.2, declare simd construct, Description]
6332   // The special this pointer can be used as if was one of the arguments to the
6333   // function in any of the linear, aligned, or uniform clauses.
6334   // The uniform clause declares one or more arguments to have an invariant
6335   // value for all concurrent invocations of the function in the execution of a
6336   // single SIMD loop.
6337   llvm::DenseMap<const Decl *, const Expr *> UniformedArgs;
6338   const Expr *UniformedLinearThis = nullptr;
6339   for (const Expr *E : Uniforms) {
6340     E = E->IgnoreParenImpCasts();
6341     if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
6342       if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
6343         if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
6344             FD->getParamDecl(PVD->getFunctionScopeIndex())
6345                     ->getCanonicalDecl() == PVD->getCanonicalDecl()) {
6346           UniformedArgs.try_emplace(PVD->getCanonicalDecl(), E);
6347           continue;
6348         }
6349     if (isa<CXXThisExpr>(E)) {
6350       UniformedLinearThis = E;
6351       continue;
6352     }
6353     Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
6354         << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
6355   }
6356   // OpenMP [2.8.2, declare simd construct, Description]
6357   // The aligned clause declares that the object to which each list item points
6358   // is aligned to the number of bytes expressed in the optional parameter of
6359   // the aligned clause.
6360   // The special this pointer can be used as if was one of the arguments to the
6361   // function in any of the linear, aligned, or uniform clauses.
6362   // The type of list items appearing in the aligned clause must be array,
6363   // pointer, reference to array, or reference to pointer.
6364   llvm::DenseMap<const Decl *, const Expr *> AlignedArgs;
6365   const Expr *AlignedThis = nullptr;
6366   for (const Expr *E : Aligneds) {
6367     E = E->IgnoreParenImpCasts();
6368     if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
6369       if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
6370         const VarDecl *CanonPVD = PVD->getCanonicalDecl();
6371         if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
6372             FD->getParamDecl(PVD->getFunctionScopeIndex())
6373                     ->getCanonicalDecl() == CanonPVD) {
6374           // OpenMP  [2.8.1, simd construct, Restrictions]
6375           // A list-item cannot appear in more than one aligned clause.
6376           if (AlignedArgs.count(CanonPVD) > 0) {
6377             Diag(E->getExprLoc(), diag::err_omp_used_in_clause_twice)
6378                 << 1 << getOpenMPClauseName(OMPC_aligned)
6379                 << E->getSourceRange();
6380             Diag(AlignedArgs[CanonPVD]->getExprLoc(),
6381                  diag::note_omp_explicit_dsa)
6382                 << getOpenMPClauseName(OMPC_aligned);
6383             continue;
6384           }
6385           AlignedArgs[CanonPVD] = E;
6386           QualType QTy = PVD->getType()
6387                              .getNonReferenceType()
6388                              .getUnqualifiedType()
6389                              .getCanonicalType();
6390           const Type *Ty = QTy.getTypePtrOrNull();
6391           if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
6392             Diag(E->getExprLoc(), diag::err_omp_aligned_expected_array_or_ptr)
6393                 << QTy << getLangOpts().CPlusPlus << E->getSourceRange();
6394             Diag(PVD->getLocation(), diag::note_previous_decl) << PVD;
6395           }
6396           continue;
6397         }
6398       }
6399     if (isa<CXXThisExpr>(E)) {
6400       if (AlignedThis) {
6401         Diag(E->getExprLoc(), diag::err_omp_used_in_clause_twice)
6402             << 2 << getOpenMPClauseName(OMPC_aligned) << E->getSourceRange();
6403         Diag(AlignedThis->getExprLoc(), diag::note_omp_explicit_dsa)
6404             << getOpenMPClauseName(OMPC_aligned);
6405       }
6406       AlignedThis = E;
6407       continue;
6408     }
6409     Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
6410         << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
6411   }
6412   // The optional parameter of the aligned clause, alignment, must be a constant
6413   // positive integer expression. If no optional parameter is specified,
6414   // implementation-defined default alignments for SIMD instructions on the
6415   // target platforms are assumed.
6416   SmallVector<const Expr *, 4> NewAligns;
6417   for (Expr *E : Alignments) {
6418     ExprResult Align;
6419     if (E)
6420       Align = VerifyPositiveIntegerConstantInClause(E, OMPC_aligned);
6421     NewAligns.push_back(Align.get());
6422   }
6423   // OpenMP [2.8.2, declare simd construct, Description]
6424   // The linear clause declares one or more list items to be private to a SIMD
6425   // lane and to have a linear relationship with respect to the iteration space
6426   // of a loop.
6427   // The special this pointer can be used as if was one of the arguments to the
6428   // function in any of the linear, aligned, or uniform clauses.
6429   // When a linear-step expression is specified in a linear clause it must be
6430   // either a constant integer expression or an integer-typed parameter that is
6431   // specified in a uniform clause on the directive.
6432   llvm::DenseMap<const Decl *, const Expr *> LinearArgs;
6433   const bool IsUniformedThis = UniformedLinearThis != nullptr;
6434   auto MI = LinModifiers.begin();
6435   for (const Expr *E : Linears) {
6436     auto LinKind = static_cast<OpenMPLinearClauseKind>(*MI);
6437     ++MI;
6438     E = E->IgnoreParenImpCasts();
6439     if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
6440       if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
6441         const VarDecl *CanonPVD = PVD->getCanonicalDecl();
6442         if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
6443             FD->getParamDecl(PVD->getFunctionScopeIndex())
6444                     ->getCanonicalDecl() == CanonPVD) {
6445           // OpenMP  [2.15.3.7, linear Clause, Restrictions]
6446           // A list-item cannot appear in more than one linear clause.
6447           if (LinearArgs.count(CanonPVD) > 0) {
6448             Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
6449                 << getOpenMPClauseName(OMPC_linear)
6450                 << getOpenMPClauseName(OMPC_linear) << E->getSourceRange();
6451             Diag(LinearArgs[CanonPVD]->getExprLoc(),
6452                  diag::note_omp_explicit_dsa)
6453                 << getOpenMPClauseName(OMPC_linear);
6454             continue;
6455           }
6456           // Each argument can appear in at most one uniform or linear clause.
6457           if (UniformedArgs.count(CanonPVD) > 0) {
6458             Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
6459                 << getOpenMPClauseName(OMPC_linear)
6460                 << getOpenMPClauseName(OMPC_uniform) << E->getSourceRange();
6461             Diag(UniformedArgs[CanonPVD]->getExprLoc(),
6462                  diag::note_omp_explicit_dsa)
6463                 << getOpenMPClauseName(OMPC_uniform);
6464             continue;
6465           }
6466           LinearArgs[CanonPVD] = E;
6467           if (E->isValueDependent() || E->isTypeDependent() ||
6468               E->isInstantiationDependent() ||
6469               E->containsUnexpandedParameterPack())
6470             continue;
6471           (void)CheckOpenMPLinearDecl(CanonPVD, E->getExprLoc(), LinKind,
6472                                       PVD->getOriginalType(),
6473                                       /*IsDeclareSimd=*/true);
6474           continue;
6475         }
6476       }
6477     if (isa<CXXThisExpr>(E)) {
6478       if (UniformedLinearThis) {
6479         Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
6480             << getOpenMPClauseName(OMPC_linear)
6481             << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform : OMPC_linear)
6482             << E->getSourceRange();
6483         Diag(UniformedLinearThis->getExprLoc(), diag::note_omp_explicit_dsa)
6484             << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform
6485                                                    : OMPC_linear);
6486         continue;
6487       }
6488       UniformedLinearThis = E;
6489       if (E->isValueDependent() || E->isTypeDependent() ||
6490           E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
6491         continue;
6492       (void)CheckOpenMPLinearDecl(/*D=*/nullptr, E->getExprLoc(), LinKind,
6493                                   E->getType(), /*IsDeclareSimd=*/true);
6494       continue;
6495     }
6496     Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
6497         << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
6498   }
6499   Expr *Step = nullptr;
6500   Expr *NewStep = nullptr;
6501   SmallVector<Expr *, 4> NewSteps;
6502   for (Expr *E : Steps) {
6503     // Skip the same step expression, it was checked already.
6504     if (Step == E || !E) {
6505       NewSteps.push_back(E ? NewStep : nullptr);
6506       continue;
6507     }
6508     Step = E;
6509     if (const auto *DRE = dyn_cast<DeclRefExpr>(Step))
6510       if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
6511         const VarDecl *CanonPVD = PVD->getCanonicalDecl();
6512         if (UniformedArgs.count(CanonPVD) == 0) {
6513           Diag(Step->getExprLoc(), diag::err_omp_expected_uniform_param)
6514               << Step->getSourceRange();
6515         } else if (E->isValueDependent() || E->isTypeDependent() ||
6516                    E->isInstantiationDependent() ||
6517                    E->containsUnexpandedParameterPack() ||
6518                    CanonPVD->getType()->hasIntegerRepresentation()) {
6519           NewSteps.push_back(Step);
6520         } else {
6521           Diag(Step->getExprLoc(), diag::err_omp_expected_int_param)
6522               << Step->getSourceRange();
6523         }
6524         continue;
6525       }
6526     NewStep = Step;
6527     if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
6528         !Step->isInstantiationDependent() &&
6529         !Step->containsUnexpandedParameterPack()) {
6530       NewStep = PerformOpenMPImplicitIntegerConversion(Step->getExprLoc(), Step)
6531                     .get();
6532       if (NewStep)
6533         NewStep =
6534             VerifyIntegerConstantExpression(NewStep, /*FIXME*/ AllowFold).get();
6535     }
6536     NewSteps.push_back(NewStep);
6537   }
6538   auto *NewAttr = OMPDeclareSimdDeclAttr::CreateImplicit(
6539       Context, BS, SL.get(), const_cast<Expr **>(Uniforms.data()),
6540       Uniforms.size(), const_cast<Expr **>(Aligneds.data()), Aligneds.size(),
6541       const_cast<Expr **>(NewAligns.data()), NewAligns.size(),
6542       const_cast<Expr **>(Linears.data()), Linears.size(),
6543       const_cast<unsigned *>(LinModifiers.data()), LinModifiers.size(),
6544       NewSteps.data(), NewSteps.size(), SR);
6545   ADecl->addAttr(NewAttr);
6546   return DG;
6547 }
6548 
6549 static void setPrototype(Sema &S, FunctionDecl *FD, FunctionDecl *FDWithProto,
6550                          QualType NewType) {
6551   assert(NewType->isFunctionProtoType() &&
6552          "Expected function type with prototype.");
6553   assert(FD->getType()->isFunctionNoProtoType() &&
6554          "Expected function with type with no prototype.");
6555   assert(FDWithProto->getType()->isFunctionProtoType() &&
6556          "Expected function with prototype.");
6557   // Synthesize parameters with the same types.
6558   FD->setType(NewType);
6559   SmallVector<ParmVarDecl *, 16> Params;
6560   for (const ParmVarDecl *P : FDWithProto->parameters()) {
6561     auto *Param = ParmVarDecl::Create(S.getASTContext(), FD, SourceLocation(),
6562                                       SourceLocation(), nullptr, P->getType(),
6563                                       /*TInfo=*/nullptr, SC_None, nullptr);
6564     Param->setScopeInfo(0, Params.size());
6565     Param->setImplicit();
6566     Params.push_back(Param);
6567   }
6568 
6569   FD->setParams(Params);
6570 }
6571 
6572 void Sema::ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(Decl *D) {
6573   if (D->isInvalidDecl())
6574     return;
6575   FunctionDecl *FD = nullptr;
6576   if (auto *UTemplDecl = dyn_cast<FunctionTemplateDecl>(D))
6577     FD = UTemplDecl->getTemplatedDecl();
6578   else
6579     FD = cast<FunctionDecl>(D);
6580   assert(FD && "Expected a function declaration!");
6581 
6582   // If we are intantiating templates we do *not* apply scoped assumptions but
6583   // only global ones. We apply scoped assumption to the template definition
6584   // though.
6585   if (!inTemplateInstantiation()) {
6586     for (AssumptionAttr *AA : OMPAssumeScoped)
6587       FD->addAttr(AA);
6588   }
6589   for (AssumptionAttr *AA : OMPAssumeGlobal)
6590     FD->addAttr(AA);
6591 }
6592 
6593 Sema::OMPDeclareVariantScope::OMPDeclareVariantScope(OMPTraitInfo &TI)
6594     : TI(&TI), NameSuffix(TI.getMangledName()) {}
6595 
6596 void Sema::ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(
6597     Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParamLists,
6598     SmallVectorImpl<FunctionDecl *> &Bases) {
6599   if (!D.getIdentifier())
6600     return;
6601 
6602   OMPDeclareVariantScope &DVScope = OMPDeclareVariantScopes.back();
6603 
6604   // Template specialization is an extension, check if we do it.
6605   bool IsTemplated = !TemplateParamLists.empty();
6606   if (IsTemplated &
6607       !DVScope.TI->isExtensionActive(
6608           llvm::omp::TraitProperty::implementation_extension_allow_templates))
6609     return;
6610 
6611   IdentifierInfo *BaseII = D.getIdentifier();
6612   LookupResult Lookup(*this, DeclarationName(BaseII), D.getIdentifierLoc(),
6613                       LookupOrdinaryName);
6614   LookupParsedName(Lookup, S, &D.getCXXScopeSpec());
6615 
6616   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
6617   QualType FType = TInfo->getType();
6618 
6619   bool IsConstexpr =
6620       D.getDeclSpec().getConstexprSpecifier() == ConstexprSpecKind::Constexpr;
6621   bool IsConsteval =
6622       D.getDeclSpec().getConstexprSpecifier() == ConstexprSpecKind::Consteval;
6623 
6624   for (auto *Candidate : Lookup) {
6625     auto *CandidateDecl = Candidate->getUnderlyingDecl();
6626     FunctionDecl *UDecl = nullptr;
6627     if (IsTemplated && isa<FunctionTemplateDecl>(CandidateDecl))
6628       UDecl = cast<FunctionTemplateDecl>(CandidateDecl)->getTemplatedDecl();
6629     else if (!IsTemplated)
6630       UDecl = dyn_cast<FunctionDecl>(CandidateDecl);
6631     if (!UDecl)
6632       continue;
6633 
6634     // Don't specialize constexpr/consteval functions with
6635     // non-constexpr/consteval functions.
6636     if (UDecl->isConstexpr() && !IsConstexpr)
6637       continue;
6638     if (UDecl->isConsteval() && !IsConsteval)
6639       continue;
6640 
6641     QualType UDeclTy = UDecl->getType();
6642     if (!UDeclTy->isDependentType()) {
6643       QualType NewType = Context.mergeFunctionTypes(
6644           FType, UDeclTy, /* OfBlockPointer */ false,
6645           /* Unqualified */ false, /* AllowCXX */ true);
6646       if (NewType.isNull())
6647         continue;
6648     }
6649 
6650     // Found a base!
6651     Bases.push_back(UDecl);
6652   }
6653 
6654   bool UseImplicitBase = !DVScope.TI->isExtensionActive(
6655       llvm::omp::TraitProperty::implementation_extension_disable_implicit_base);
6656   // If no base was found we create a declaration that we use as base.
6657   if (Bases.empty() && UseImplicitBase) {
6658     D.setFunctionDefinitionKind(FunctionDefinitionKind::Declaration);
6659     Decl *BaseD = HandleDeclarator(S, D, TemplateParamLists);
6660     BaseD->setImplicit(true);
6661     if (auto *BaseTemplD = dyn_cast<FunctionTemplateDecl>(BaseD))
6662       Bases.push_back(BaseTemplD->getTemplatedDecl());
6663     else
6664       Bases.push_back(cast<FunctionDecl>(BaseD));
6665   }
6666 
6667   std::string MangledName;
6668   MangledName += D.getIdentifier()->getName();
6669   MangledName += getOpenMPVariantManglingSeparatorStr();
6670   MangledName += DVScope.NameSuffix;
6671   IdentifierInfo &VariantII = Context.Idents.get(MangledName);
6672 
6673   VariantII.setMangledOpenMPVariantName(true);
6674   D.SetIdentifier(&VariantII, D.getBeginLoc());
6675 }
6676 
6677 void Sema::ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(
6678     Decl *D, SmallVectorImpl<FunctionDecl *> &Bases) {
6679   // Do not mark function as is used to prevent its emission if this is the
6680   // only place where it is used.
6681   EnterExpressionEvaluationContext Unevaluated(
6682       *this, Sema::ExpressionEvaluationContext::Unevaluated);
6683 
6684   FunctionDecl *FD = nullptr;
6685   if (auto *UTemplDecl = dyn_cast<FunctionTemplateDecl>(D))
6686     FD = UTemplDecl->getTemplatedDecl();
6687   else
6688     FD = cast<FunctionDecl>(D);
6689   auto *VariantFuncRef = DeclRefExpr::Create(
6690       Context, NestedNameSpecifierLoc(), SourceLocation(), FD,
6691       /* RefersToEnclosingVariableOrCapture */ false,
6692       /* NameLoc */ FD->getLocation(), FD->getType(), ExprValueKind::VK_RValue);
6693 
6694   OMPDeclareVariantScope &DVScope = OMPDeclareVariantScopes.back();
6695   auto *OMPDeclareVariantA = OMPDeclareVariantAttr::CreateImplicit(
6696       Context, VariantFuncRef, DVScope.TI);
6697   for (FunctionDecl *BaseFD : Bases)
6698     BaseFD->addAttr(OMPDeclareVariantA);
6699 }
6700 
6701 ExprResult Sema::ActOnOpenMPCall(ExprResult Call, Scope *Scope,
6702                                  SourceLocation LParenLoc,
6703                                  MultiExprArg ArgExprs,
6704                                  SourceLocation RParenLoc, Expr *ExecConfig) {
6705   // The common case is a regular call we do not want to specialize at all. Try
6706   // to make that case fast by bailing early.
6707   CallExpr *CE = dyn_cast<CallExpr>(Call.get());
6708   if (!CE)
6709     return Call;
6710 
6711   FunctionDecl *CalleeFnDecl = CE->getDirectCallee();
6712   if (!CalleeFnDecl)
6713     return Call;
6714 
6715   if (!CalleeFnDecl->hasAttr<OMPDeclareVariantAttr>())
6716     return Call;
6717 
6718   ASTContext &Context = getASTContext();
6719   std::function<void(StringRef)> DiagUnknownTrait = [this,
6720                                                      CE](StringRef ISATrait) {
6721     // TODO Track the selector locations in a way that is accessible here to
6722     // improve the diagnostic location.
6723     Diag(CE->getBeginLoc(), diag::warn_unknown_declare_variant_isa_trait)
6724         << ISATrait;
6725   };
6726   TargetOMPContext OMPCtx(Context, std::move(DiagUnknownTrait),
6727                           getCurFunctionDecl());
6728 
6729   QualType CalleeFnType = CalleeFnDecl->getType();
6730 
6731   SmallVector<Expr *, 4> Exprs;
6732   SmallVector<VariantMatchInfo, 4> VMIs;
6733   while (CalleeFnDecl) {
6734     for (OMPDeclareVariantAttr *A :
6735          CalleeFnDecl->specific_attrs<OMPDeclareVariantAttr>()) {
6736       Expr *VariantRef = A->getVariantFuncRef();
6737 
6738       VariantMatchInfo VMI;
6739       OMPTraitInfo &TI = A->getTraitInfo();
6740       TI.getAsVariantMatchInfo(Context, VMI);
6741       if (!isVariantApplicableInContext(VMI, OMPCtx,
6742                                         /* DeviceSetOnly */ false))
6743         continue;
6744 
6745       VMIs.push_back(VMI);
6746       Exprs.push_back(VariantRef);
6747     }
6748 
6749     CalleeFnDecl = CalleeFnDecl->getPreviousDecl();
6750   }
6751 
6752   ExprResult NewCall;
6753   do {
6754     int BestIdx = getBestVariantMatchForContext(VMIs, OMPCtx);
6755     if (BestIdx < 0)
6756       return Call;
6757     Expr *BestExpr = cast<DeclRefExpr>(Exprs[BestIdx]);
6758     Decl *BestDecl = cast<DeclRefExpr>(BestExpr)->getDecl();
6759 
6760     {
6761       // Try to build a (member) call expression for the current best applicable
6762       // variant expression. We allow this to fail in which case we continue
6763       // with the next best variant expression. The fail case is part of the
6764       // implementation defined behavior in the OpenMP standard when it talks
6765       // about what differences in the function prototypes: "Any differences
6766       // that the specific OpenMP context requires in the prototype of the
6767       // variant from the base function prototype are implementation defined."
6768       // This wording is there to allow the specialized variant to have a
6769       // different type than the base function. This is intended and OK but if
6770       // we cannot create a call the difference is not in the "implementation
6771       // defined range" we allow.
6772       Sema::TentativeAnalysisScope Trap(*this);
6773 
6774       if (auto *SpecializedMethod = dyn_cast<CXXMethodDecl>(BestDecl)) {
6775         auto *MemberCall = dyn_cast<CXXMemberCallExpr>(CE);
6776         BestExpr = MemberExpr::CreateImplicit(
6777             Context, MemberCall->getImplicitObjectArgument(),
6778             /* IsArrow */ false, SpecializedMethod, Context.BoundMemberTy,
6779             MemberCall->getValueKind(), MemberCall->getObjectKind());
6780       }
6781       NewCall = BuildCallExpr(Scope, BestExpr, LParenLoc, ArgExprs, RParenLoc,
6782                               ExecConfig);
6783       if (NewCall.isUsable()) {
6784         if (CallExpr *NCE = dyn_cast<CallExpr>(NewCall.get())) {
6785           FunctionDecl *NewCalleeFnDecl = NCE->getDirectCallee();
6786           QualType NewType = Context.mergeFunctionTypes(
6787               CalleeFnType, NewCalleeFnDecl->getType(),
6788               /* OfBlockPointer */ false,
6789               /* Unqualified */ false, /* AllowCXX */ true);
6790           if (!NewType.isNull())
6791             break;
6792           // Don't use the call if the function type was not compatible.
6793           NewCall = nullptr;
6794         }
6795       }
6796     }
6797 
6798     VMIs.erase(VMIs.begin() + BestIdx);
6799     Exprs.erase(Exprs.begin() + BestIdx);
6800   } while (!VMIs.empty());
6801 
6802   if (!NewCall.isUsable())
6803     return Call;
6804   return PseudoObjectExpr::Create(Context, CE, {NewCall.get()}, 0);
6805 }
6806 
6807 Optional<std::pair<FunctionDecl *, Expr *>>
6808 Sema::checkOpenMPDeclareVariantFunction(Sema::DeclGroupPtrTy DG,
6809                                         Expr *VariantRef, OMPTraitInfo &TI,
6810                                         SourceRange SR) {
6811   if (!DG || DG.get().isNull())
6812     return None;
6813 
6814   const int VariantId = 1;
6815   // Must be applied only to single decl.
6816   if (!DG.get().isSingleDecl()) {
6817     Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd_variant)
6818         << VariantId << SR;
6819     return None;
6820   }
6821   Decl *ADecl = DG.get().getSingleDecl();
6822   if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
6823     ADecl = FTD->getTemplatedDecl();
6824 
6825   // Decl must be a function.
6826   auto *FD = dyn_cast<FunctionDecl>(ADecl);
6827   if (!FD) {
6828     Diag(ADecl->getLocation(), diag::err_omp_function_expected)
6829         << VariantId << SR;
6830     return None;
6831   }
6832 
6833   auto &&HasMultiVersionAttributes = [](const FunctionDecl *FD) {
6834     return FD->hasAttrs() &&
6835            (FD->hasAttr<CPUDispatchAttr>() || FD->hasAttr<CPUSpecificAttr>() ||
6836             FD->hasAttr<TargetAttr>());
6837   };
6838   // OpenMP is not compatible with CPU-specific attributes.
6839   if (HasMultiVersionAttributes(FD)) {
6840     Diag(FD->getLocation(), diag::err_omp_declare_variant_incompat_attributes)
6841         << SR;
6842     return None;
6843   }
6844 
6845   // Allow #pragma omp declare variant only if the function is not used.
6846   if (FD->isUsed(false))
6847     Diag(SR.getBegin(), diag::warn_omp_declare_variant_after_used)
6848         << FD->getLocation();
6849 
6850   // Check if the function was emitted already.
6851   const FunctionDecl *Definition;
6852   if (!FD->isThisDeclarationADefinition() && FD->isDefined(Definition) &&
6853       (LangOpts.EmitAllDecls || Context.DeclMustBeEmitted(Definition)))
6854     Diag(SR.getBegin(), diag::warn_omp_declare_variant_after_emitted)
6855         << FD->getLocation();
6856 
6857   // The VariantRef must point to function.
6858   if (!VariantRef) {
6859     Diag(SR.getBegin(), diag::err_omp_function_expected) << VariantId;
6860     return None;
6861   }
6862 
6863   auto ShouldDelayChecks = [](Expr *&E, bool) {
6864     return E && (E->isTypeDependent() || E->isValueDependent() ||
6865                  E->containsUnexpandedParameterPack() ||
6866                  E->isInstantiationDependent());
6867   };
6868   // Do not check templates, wait until instantiation.
6869   if (FD->isDependentContext() || ShouldDelayChecks(VariantRef, false) ||
6870       TI.anyScoreOrCondition(ShouldDelayChecks))
6871     return std::make_pair(FD, VariantRef);
6872 
6873   // Deal with non-constant score and user condition expressions.
6874   auto HandleNonConstantScoresAndConditions = [this](Expr *&E,
6875                                                      bool IsScore) -> bool {
6876     if (!E || E->isIntegerConstantExpr(Context))
6877       return false;
6878 
6879     if (IsScore) {
6880       // We warn on non-constant scores and pretend they were not present.
6881       Diag(E->getExprLoc(), diag::warn_omp_declare_variant_score_not_constant)
6882           << E;
6883       E = nullptr;
6884     } else {
6885       // We could replace a non-constant user condition with "false" but we
6886       // will soon need to handle these anyway for the dynamic version of
6887       // OpenMP context selectors.
6888       Diag(E->getExprLoc(),
6889            diag::err_omp_declare_variant_user_condition_not_constant)
6890           << E;
6891     }
6892     return true;
6893   };
6894   if (TI.anyScoreOrCondition(HandleNonConstantScoresAndConditions))
6895     return None;
6896 
6897   // Convert VariantRef expression to the type of the original function to
6898   // resolve possible conflicts.
6899   ExprResult VariantRefCast = VariantRef;
6900   if (LangOpts.CPlusPlus) {
6901     QualType FnPtrType;
6902     auto *Method = dyn_cast<CXXMethodDecl>(FD);
6903     if (Method && !Method->isStatic()) {
6904       const Type *ClassType =
6905           Context.getTypeDeclType(Method->getParent()).getTypePtr();
6906       FnPtrType = Context.getMemberPointerType(FD->getType(), ClassType);
6907       ExprResult ER;
6908       {
6909         // Build adrr_of unary op to correctly handle type checks for member
6910         // functions.
6911         Sema::TentativeAnalysisScope Trap(*this);
6912         ER = CreateBuiltinUnaryOp(VariantRef->getBeginLoc(), UO_AddrOf,
6913                                   VariantRef);
6914       }
6915       if (!ER.isUsable()) {
6916         Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected)
6917             << VariantId << VariantRef->getSourceRange();
6918         return None;
6919       }
6920       VariantRef = ER.get();
6921     } else {
6922       FnPtrType = Context.getPointerType(FD->getType());
6923     }
6924     QualType VarianPtrType = Context.getPointerType(VariantRef->getType());
6925     if (VarianPtrType.getUnqualifiedType() != FnPtrType.getUnqualifiedType()) {
6926       ImplicitConversionSequence ICS = TryImplicitConversion(
6927           VariantRef, FnPtrType.getUnqualifiedType(),
6928           /*SuppressUserConversions=*/false, AllowedExplicit::None,
6929           /*InOverloadResolution=*/false,
6930           /*CStyle=*/false,
6931           /*AllowObjCWritebackConversion=*/false);
6932       if (ICS.isFailure()) {
6933         Diag(VariantRef->getExprLoc(),
6934              diag::err_omp_declare_variant_incompat_types)
6935             << VariantRef->getType()
6936             << ((Method && !Method->isStatic()) ? FnPtrType : FD->getType())
6937             << VariantRef->getSourceRange();
6938         return None;
6939       }
6940       VariantRefCast = PerformImplicitConversion(
6941           VariantRef, FnPtrType.getUnqualifiedType(), AA_Converting);
6942       if (!VariantRefCast.isUsable())
6943         return None;
6944     }
6945     // Drop previously built artificial addr_of unary op for member functions.
6946     if (Method && !Method->isStatic()) {
6947       Expr *PossibleAddrOfVariantRef = VariantRefCast.get();
6948       if (auto *UO = dyn_cast<UnaryOperator>(
6949               PossibleAddrOfVariantRef->IgnoreImplicit()))
6950         VariantRefCast = UO->getSubExpr();
6951     }
6952   }
6953 
6954   ExprResult ER = CheckPlaceholderExpr(VariantRefCast.get());
6955   if (!ER.isUsable() ||
6956       !ER.get()->IgnoreParenImpCasts()->getType()->isFunctionType()) {
6957     Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected)
6958         << VariantId << VariantRef->getSourceRange();
6959     return None;
6960   }
6961 
6962   // The VariantRef must point to function.
6963   auto *DRE = dyn_cast<DeclRefExpr>(ER.get()->IgnoreParenImpCasts());
6964   if (!DRE) {
6965     Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected)
6966         << VariantId << VariantRef->getSourceRange();
6967     return None;
6968   }
6969   auto *NewFD = dyn_cast_or_null<FunctionDecl>(DRE->getDecl());
6970   if (!NewFD) {
6971     Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected)
6972         << VariantId << VariantRef->getSourceRange();
6973     return None;
6974   }
6975 
6976   // Check if function types are compatible in C.
6977   if (!LangOpts.CPlusPlus) {
6978     QualType NewType =
6979         Context.mergeFunctionTypes(FD->getType(), NewFD->getType());
6980     if (NewType.isNull()) {
6981       Diag(VariantRef->getExprLoc(),
6982            diag::err_omp_declare_variant_incompat_types)
6983           << NewFD->getType() << FD->getType() << VariantRef->getSourceRange();
6984       return None;
6985     }
6986     if (NewType->isFunctionProtoType()) {
6987       if (FD->getType()->isFunctionNoProtoType())
6988         setPrototype(*this, FD, NewFD, NewType);
6989       else if (NewFD->getType()->isFunctionNoProtoType())
6990         setPrototype(*this, NewFD, FD, NewType);
6991     }
6992   }
6993 
6994   // Check if variant function is not marked with declare variant directive.
6995   if (NewFD->hasAttrs() && NewFD->hasAttr<OMPDeclareVariantAttr>()) {
6996     Diag(VariantRef->getExprLoc(),
6997          diag::warn_omp_declare_variant_marked_as_declare_variant)
6998         << VariantRef->getSourceRange();
6999     SourceRange SR =
7000         NewFD->specific_attr_begin<OMPDeclareVariantAttr>()->getRange();
7001     Diag(SR.getBegin(), diag::note_omp_marked_declare_variant_here) << SR;
7002     return None;
7003   }
7004 
7005   enum DoesntSupport {
7006     VirtFuncs = 1,
7007     Constructors = 3,
7008     Destructors = 4,
7009     DeletedFuncs = 5,
7010     DefaultedFuncs = 6,
7011     ConstexprFuncs = 7,
7012     ConstevalFuncs = 8,
7013   };
7014   if (const auto *CXXFD = dyn_cast<CXXMethodDecl>(FD)) {
7015     if (CXXFD->isVirtual()) {
7016       Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
7017           << VirtFuncs;
7018       return None;
7019     }
7020 
7021     if (isa<CXXConstructorDecl>(FD)) {
7022       Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
7023           << Constructors;
7024       return None;
7025     }
7026 
7027     if (isa<CXXDestructorDecl>(FD)) {
7028       Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
7029           << Destructors;
7030       return None;
7031     }
7032   }
7033 
7034   if (FD->isDeleted()) {
7035     Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
7036         << DeletedFuncs;
7037     return None;
7038   }
7039 
7040   if (FD->isDefaulted()) {
7041     Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
7042         << DefaultedFuncs;
7043     return None;
7044   }
7045 
7046   if (FD->isConstexpr()) {
7047     Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
7048         << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
7049     return None;
7050   }
7051 
7052   // Check general compatibility.
7053   if (areMultiversionVariantFunctionsCompatible(
7054           FD, NewFD, PartialDiagnostic::NullDiagnostic(),
7055           PartialDiagnosticAt(SourceLocation(),
7056                               PartialDiagnostic::NullDiagnostic()),
7057           PartialDiagnosticAt(
7058               VariantRef->getExprLoc(),
7059               PDiag(diag::err_omp_declare_variant_doesnt_support)),
7060           PartialDiagnosticAt(VariantRef->getExprLoc(),
7061                               PDiag(diag::err_omp_declare_variant_diff)
7062                                   << FD->getLocation()),
7063           /*TemplatesSupported=*/true, /*ConstexprSupported=*/false,
7064           /*CLinkageMayDiffer=*/true))
7065     return None;
7066   return std::make_pair(FD, cast<Expr>(DRE));
7067 }
7068 
7069 void Sema::ActOnOpenMPDeclareVariantDirective(FunctionDecl *FD,
7070                                               Expr *VariantRef,
7071                                               OMPTraitInfo &TI,
7072                                               SourceRange SR) {
7073   auto *NewAttr =
7074       OMPDeclareVariantAttr::CreateImplicit(Context, VariantRef, &TI, SR);
7075   FD->addAttr(NewAttr);
7076 }
7077 
7078 StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
7079                                               Stmt *AStmt,
7080                                               SourceLocation StartLoc,
7081                                               SourceLocation EndLoc) {
7082   if (!AStmt)
7083     return StmtError();
7084 
7085   auto *CS = cast<CapturedStmt>(AStmt);
7086   // 1.2.2 OpenMP Language Terminology
7087   // Structured block - An executable statement with a single entry at the
7088   // top and a single exit at the bottom.
7089   // The point of exit cannot be a branch out of the structured block.
7090   // longjmp() and throw() must not violate the entry/exit criteria.
7091   CS->getCapturedDecl()->setNothrow();
7092 
7093   setFunctionHasBranchProtectedScope();
7094 
7095   return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
7096                                       DSAStack->getTaskgroupReductionRef(),
7097                                       DSAStack->isCancelRegion());
7098 }
7099 
7100 namespace {
7101 /// Iteration space of a single for loop.
7102 struct LoopIterationSpace final {
7103   /// True if the condition operator is the strict compare operator (<, > or
7104   /// !=).
7105   bool IsStrictCompare = false;
7106   /// Condition of the loop.
7107   Expr *PreCond = nullptr;
7108   /// This expression calculates the number of iterations in the loop.
7109   /// It is always possible to calculate it before starting the loop.
7110   Expr *NumIterations = nullptr;
7111   /// The loop counter variable.
7112   Expr *CounterVar = nullptr;
7113   /// Private loop counter variable.
7114   Expr *PrivateCounterVar = nullptr;
7115   /// This is initializer for the initial value of #CounterVar.
7116   Expr *CounterInit = nullptr;
7117   /// This is step for the #CounterVar used to generate its update:
7118   /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration.
7119   Expr *CounterStep = nullptr;
7120   /// Should step be subtracted?
7121   bool Subtract = false;
7122   /// Source range of the loop init.
7123   SourceRange InitSrcRange;
7124   /// Source range of the loop condition.
7125   SourceRange CondSrcRange;
7126   /// Source range of the loop increment.
7127   SourceRange IncSrcRange;
7128   /// Minimum value that can have the loop control variable. Used to support
7129   /// non-rectangular loops. Applied only for LCV with the non-iterator types,
7130   /// since only such variables can be used in non-loop invariant expressions.
7131   Expr *MinValue = nullptr;
7132   /// Maximum value that can have the loop control variable. Used to support
7133   /// non-rectangular loops. Applied only for LCV with the non-iterator type,
7134   /// since only such variables can be used in non-loop invariant expressions.
7135   Expr *MaxValue = nullptr;
7136   /// true, if the lower bound depends on the outer loop control var.
7137   bool IsNonRectangularLB = false;
7138   /// true, if the upper bound depends on the outer loop control var.
7139   bool IsNonRectangularUB = false;
7140   /// Index of the loop this loop depends on and forms non-rectangular loop
7141   /// nest.
7142   unsigned LoopDependentIdx = 0;
7143   /// Final condition for the non-rectangular loop nest support. It is used to
7144   /// check that the number of iterations for this particular counter must be
7145   /// finished.
7146   Expr *FinalCondition = nullptr;
7147 };
7148 
7149 /// Helper class for checking canonical form of the OpenMP loops and
7150 /// extracting iteration space of each loop in the loop nest, that will be used
7151 /// for IR generation.
7152 class OpenMPIterationSpaceChecker {
7153   /// Reference to Sema.
7154   Sema &SemaRef;
7155   /// Does the loop associated directive support non-rectangular loops?
7156   bool SupportsNonRectangular;
7157   /// Data-sharing stack.
7158   DSAStackTy &Stack;
7159   /// A location for diagnostics (when there is no some better location).
7160   SourceLocation DefaultLoc;
7161   /// A location for diagnostics (when increment is not compatible).
7162   SourceLocation ConditionLoc;
7163   /// A source location for referring to loop init later.
7164   SourceRange InitSrcRange;
7165   /// A source location for referring to condition later.
7166   SourceRange ConditionSrcRange;
7167   /// A source location for referring to increment later.
7168   SourceRange IncrementSrcRange;
7169   /// Loop variable.
7170   ValueDecl *LCDecl = nullptr;
7171   /// Reference to loop variable.
7172   Expr *LCRef = nullptr;
7173   /// Lower bound (initializer for the var).
7174   Expr *LB = nullptr;
7175   /// Upper bound.
7176   Expr *UB = nullptr;
7177   /// Loop step (increment).
7178   Expr *Step = nullptr;
7179   /// This flag is true when condition is one of:
7180   ///   Var <  UB
7181   ///   Var <= UB
7182   ///   UB  >  Var
7183   ///   UB  >= Var
7184   /// This will have no value when the condition is !=
7185   llvm::Optional<bool> TestIsLessOp;
7186   /// This flag is true when condition is strict ( < or > ).
7187   bool TestIsStrictOp = false;
7188   /// This flag is true when step is subtracted on each iteration.
7189   bool SubtractStep = false;
7190   /// The outer loop counter this loop depends on (if any).
7191   const ValueDecl *DepDecl = nullptr;
7192   /// Contains number of loop (starts from 1) on which loop counter init
7193   /// expression of this loop depends on.
7194   Optional<unsigned> InitDependOnLC;
7195   /// Contains number of loop (starts from 1) on which loop counter condition
7196   /// expression of this loop depends on.
7197   Optional<unsigned> CondDependOnLC;
7198   /// Checks if the provide statement depends on the loop counter.
7199   Optional<unsigned> doesDependOnLoopCounter(const Stmt *S, bool IsInitializer);
7200   /// Original condition required for checking of the exit condition for
7201   /// non-rectangular loop.
7202   Expr *Condition = nullptr;
7203 
7204 public:
7205   OpenMPIterationSpaceChecker(Sema &SemaRef, bool SupportsNonRectangular,
7206                               DSAStackTy &Stack, SourceLocation DefaultLoc)
7207       : SemaRef(SemaRef), SupportsNonRectangular(SupportsNonRectangular),
7208         Stack(Stack), DefaultLoc(DefaultLoc), ConditionLoc(DefaultLoc) {}
7209   /// Check init-expr for canonical loop form and save loop counter
7210   /// variable - #Var and its initialization value - #LB.
7211   bool checkAndSetInit(Stmt *S, bool EmitDiags = true);
7212   /// Check test-expr for canonical form, save upper-bound (#UB), flags
7213   /// for less/greater and for strict/non-strict comparison.
7214   bool checkAndSetCond(Expr *S);
7215   /// Check incr-expr for canonical loop form and return true if it
7216   /// does not conform, otherwise save loop step (#Step).
7217   bool checkAndSetInc(Expr *S);
7218   /// Return the loop counter variable.
7219   ValueDecl *getLoopDecl() const { return LCDecl; }
7220   /// Return the reference expression to loop counter variable.
7221   Expr *getLoopDeclRefExpr() const { return LCRef; }
7222   /// Source range of the loop init.
7223   SourceRange getInitSrcRange() const { return InitSrcRange; }
7224   /// Source range of the loop condition.
7225   SourceRange getConditionSrcRange() const { return ConditionSrcRange; }
7226   /// Source range of the loop increment.
7227   SourceRange getIncrementSrcRange() const { return IncrementSrcRange; }
7228   /// True if the step should be subtracted.
7229   bool shouldSubtractStep() const { return SubtractStep; }
7230   /// True, if the compare operator is strict (<, > or !=).
7231   bool isStrictTestOp() const { return TestIsStrictOp; }
7232   /// Build the expression to calculate the number of iterations.
7233   Expr *buildNumIterations(
7234       Scope *S, ArrayRef<LoopIterationSpace> ResultIterSpaces, bool LimitedType,
7235       llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
7236   /// Build the precondition expression for the loops.
7237   Expr *
7238   buildPreCond(Scope *S, Expr *Cond,
7239                llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
7240   /// Build reference expression to the counter be used for codegen.
7241   DeclRefExpr *
7242   buildCounterVar(llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
7243                   DSAStackTy &DSA) const;
7244   /// Build reference expression to the private counter be used for
7245   /// codegen.
7246   Expr *buildPrivateCounterVar() const;
7247   /// Build initialization of the counter be used for codegen.
7248   Expr *buildCounterInit() const;
7249   /// Build step of the counter be used for codegen.
7250   Expr *buildCounterStep() const;
7251   /// Build loop data with counter value for depend clauses in ordered
7252   /// directives.
7253   Expr *
7254   buildOrderedLoopData(Scope *S, Expr *Counter,
7255                        llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
7256                        SourceLocation Loc, Expr *Inc = nullptr,
7257                        OverloadedOperatorKind OOK = OO_Amp);
7258   /// Builds the minimum value for the loop counter.
7259   std::pair<Expr *, Expr *> buildMinMaxValues(
7260       Scope *S, llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
7261   /// Builds final condition for the non-rectangular loops.
7262   Expr *buildFinalCondition(Scope *S) const;
7263   /// Return true if any expression is dependent.
7264   bool dependent() const;
7265   /// Returns true if the initializer forms non-rectangular loop.
7266   bool doesInitDependOnLC() const { return InitDependOnLC.hasValue(); }
7267   /// Returns true if the condition forms non-rectangular loop.
7268   bool doesCondDependOnLC() const { return CondDependOnLC.hasValue(); }
7269   /// Returns index of the loop we depend on (starting from 1), or 0 otherwise.
7270   unsigned getLoopDependentIdx() const {
7271     return InitDependOnLC.getValueOr(CondDependOnLC.getValueOr(0));
7272   }
7273 
7274 private:
7275   /// Check the right-hand side of an assignment in the increment
7276   /// expression.
7277   bool checkAndSetIncRHS(Expr *RHS);
7278   /// Helper to set loop counter variable and its initializer.
7279   bool setLCDeclAndLB(ValueDecl *NewLCDecl, Expr *NewDeclRefExpr, Expr *NewLB,
7280                       bool EmitDiags);
7281   /// Helper to set upper bound.
7282   bool setUB(Expr *NewUB, llvm::Optional<bool> LessOp, bool StrictOp,
7283              SourceRange SR, SourceLocation SL);
7284   /// Helper to set loop increment.
7285   bool setStep(Expr *NewStep, bool Subtract);
7286 };
7287 
7288 bool OpenMPIterationSpaceChecker::dependent() const {
7289   if (!LCDecl) {
7290     assert(!LB && !UB && !Step);
7291     return false;
7292   }
7293   return LCDecl->getType()->isDependentType() ||
7294          (LB && LB->isValueDependent()) || (UB && UB->isValueDependent()) ||
7295          (Step && Step->isValueDependent());
7296 }
7297 
7298 bool OpenMPIterationSpaceChecker::setLCDeclAndLB(ValueDecl *NewLCDecl,
7299                                                  Expr *NewLCRefExpr,
7300                                                  Expr *NewLB, bool EmitDiags) {
7301   // State consistency checking to ensure correct usage.
7302   assert(LCDecl == nullptr && LB == nullptr && LCRef == nullptr &&
7303          UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
7304   if (!NewLCDecl || !NewLB)
7305     return true;
7306   LCDecl = getCanonicalDecl(NewLCDecl);
7307   LCRef = NewLCRefExpr;
7308   if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB))
7309     if (const CXXConstructorDecl *Ctor = CE->getConstructor())
7310       if ((Ctor->isCopyOrMoveConstructor() ||
7311            Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
7312           CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
7313         NewLB = CE->getArg(0)->IgnoreParenImpCasts();
7314   LB = NewLB;
7315   if (EmitDiags)
7316     InitDependOnLC = doesDependOnLoopCounter(LB, /*IsInitializer=*/true);
7317   return false;
7318 }
7319 
7320 bool OpenMPIterationSpaceChecker::setUB(Expr *NewUB,
7321                                         llvm::Optional<bool> LessOp,
7322                                         bool StrictOp, SourceRange SR,
7323                                         SourceLocation SL) {
7324   // State consistency checking to ensure correct usage.
7325   assert(LCDecl != nullptr && LB != nullptr && UB == nullptr &&
7326          Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
7327   if (!NewUB)
7328     return true;
7329   UB = NewUB;
7330   if (LessOp)
7331     TestIsLessOp = LessOp;
7332   TestIsStrictOp = StrictOp;
7333   ConditionSrcRange = SR;
7334   ConditionLoc = SL;
7335   CondDependOnLC = doesDependOnLoopCounter(UB, /*IsInitializer=*/false);
7336   return false;
7337 }
7338 
7339 bool OpenMPIterationSpaceChecker::setStep(Expr *NewStep, bool Subtract) {
7340   // State consistency checking to ensure correct usage.
7341   assert(LCDecl != nullptr && LB != nullptr && Step == nullptr);
7342   if (!NewStep)
7343     return true;
7344   if (!NewStep->isValueDependent()) {
7345     // Check that the step is integer expression.
7346     SourceLocation StepLoc = NewStep->getBeginLoc();
7347     ExprResult Val = SemaRef.PerformOpenMPImplicitIntegerConversion(
7348         StepLoc, getExprAsWritten(NewStep));
7349     if (Val.isInvalid())
7350       return true;
7351     NewStep = Val.get();
7352 
7353     // OpenMP [2.6, Canonical Loop Form, Restrictions]
7354     //  If test-expr is of form var relational-op b and relational-op is < or
7355     //  <= then incr-expr must cause var to increase on each iteration of the
7356     //  loop. If test-expr is of form var relational-op b and relational-op is
7357     //  > or >= then incr-expr must cause var to decrease on each iteration of
7358     //  the loop.
7359     //  If test-expr is of form b relational-op var and relational-op is < or
7360     //  <= then incr-expr must cause var to decrease on each iteration of the
7361     //  loop. If test-expr is of form b relational-op var and relational-op is
7362     //  > or >= then incr-expr must cause var to increase on each iteration of
7363     //  the loop.
7364     Optional<llvm::APSInt> Result =
7365         NewStep->getIntegerConstantExpr(SemaRef.Context);
7366     bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation();
7367     bool IsConstNeg =
7368         Result && Result->isSigned() && (Subtract != Result->isNegative());
7369     bool IsConstPos =
7370         Result && Result->isSigned() && (Subtract == Result->isNegative());
7371     bool IsConstZero = Result && !Result->getBoolValue();
7372 
7373     // != with increment is treated as <; != with decrement is treated as >
7374     if (!TestIsLessOp.hasValue())
7375       TestIsLessOp = IsConstPos || (IsUnsigned && !Subtract);
7376     if (UB && (IsConstZero ||
7377                (TestIsLessOp.getValue() ?
7378                   (IsConstNeg || (IsUnsigned && Subtract)) :
7379                   (IsConstPos || (IsUnsigned && !Subtract))))) {
7380       SemaRef.Diag(NewStep->getExprLoc(),
7381                    diag::err_omp_loop_incr_not_compatible)
7382           << LCDecl << TestIsLessOp.getValue() << NewStep->getSourceRange();
7383       SemaRef.Diag(ConditionLoc,
7384                    diag::note_omp_loop_cond_requres_compatible_incr)
7385           << TestIsLessOp.getValue() << ConditionSrcRange;
7386       return true;
7387     }
7388     if (TestIsLessOp.getValue() == Subtract) {
7389       NewStep =
7390           SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus, NewStep)
7391               .get();
7392       Subtract = !Subtract;
7393     }
7394   }
7395 
7396   Step = NewStep;
7397   SubtractStep = Subtract;
7398   return false;
7399 }
7400 
7401 namespace {
7402 /// Checker for the non-rectangular loops. Checks if the initializer or
7403 /// condition expression references loop counter variable.
7404 class LoopCounterRefChecker final
7405     : public ConstStmtVisitor<LoopCounterRefChecker, bool> {
7406   Sema &SemaRef;
7407   DSAStackTy &Stack;
7408   const ValueDecl *CurLCDecl = nullptr;
7409   const ValueDecl *DepDecl = nullptr;
7410   const ValueDecl *PrevDepDecl = nullptr;
7411   bool IsInitializer = true;
7412   bool SupportsNonRectangular;
7413   unsigned BaseLoopId = 0;
7414   bool checkDecl(const Expr *E, const ValueDecl *VD) {
7415     if (getCanonicalDecl(VD) == getCanonicalDecl(CurLCDecl)) {
7416       SemaRef.Diag(E->getExprLoc(), diag::err_omp_stmt_depends_on_loop_counter)
7417           << (IsInitializer ? 0 : 1);
7418       return false;
7419     }
7420     const auto &&Data = Stack.isLoopControlVariable(VD);
7421     // OpenMP, 2.9.1 Canonical Loop Form, Restrictions.
7422     // The type of the loop iterator on which we depend may not have a random
7423     // access iterator type.
7424     if (Data.first && VD->getType()->isRecordType()) {
7425       SmallString<128> Name;
7426       llvm::raw_svector_ostream OS(Name);
7427       VD->getNameForDiagnostic(OS, SemaRef.getPrintingPolicy(),
7428                                /*Qualified=*/true);
7429       SemaRef.Diag(E->getExprLoc(),
7430                    diag::err_omp_wrong_dependency_iterator_type)
7431           << OS.str();
7432       SemaRef.Diag(VD->getLocation(), diag::note_previous_decl) << VD;
7433       return false;
7434     }
7435     if (Data.first && !SupportsNonRectangular) {
7436       SemaRef.Diag(E->getExprLoc(), diag::err_omp_invariant_dependency);
7437       return false;
7438     }
7439     if (Data.first &&
7440         (DepDecl || (PrevDepDecl &&
7441                      getCanonicalDecl(VD) != getCanonicalDecl(PrevDepDecl)))) {
7442       if (!DepDecl && PrevDepDecl)
7443         DepDecl = PrevDepDecl;
7444       SmallString<128> Name;
7445       llvm::raw_svector_ostream OS(Name);
7446       DepDecl->getNameForDiagnostic(OS, SemaRef.getPrintingPolicy(),
7447                                     /*Qualified=*/true);
7448       SemaRef.Diag(E->getExprLoc(),
7449                    diag::err_omp_invariant_or_linear_dependency)
7450           << OS.str();
7451       return false;
7452     }
7453     if (Data.first) {
7454       DepDecl = VD;
7455       BaseLoopId = Data.first;
7456     }
7457     return Data.first;
7458   }
7459 
7460 public:
7461   bool VisitDeclRefExpr(const DeclRefExpr *E) {
7462     const ValueDecl *VD = E->getDecl();
7463     if (isa<VarDecl>(VD))
7464       return checkDecl(E, VD);
7465     return false;
7466   }
7467   bool VisitMemberExpr(const MemberExpr *E) {
7468     if (isa<CXXThisExpr>(E->getBase()->IgnoreParens())) {
7469       const ValueDecl *VD = E->getMemberDecl();
7470       if (isa<VarDecl>(VD) || isa<FieldDecl>(VD))
7471         return checkDecl(E, VD);
7472     }
7473     return false;
7474   }
7475   bool VisitStmt(const Stmt *S) {
7476     bool Res = false;
7477     for (const Stmt *Child : S->children())
7478       Res = (Child && Visit(Child)) || Res;
7479     return Res;
7480   }
7481   explicit LoopCounterRefChecker(Sema &SemaRef, DSAStackTy &Stack,
7482                                  const ValueDecl *CurLCDecl, bool IsInitializer,
7483                                  const ValueDecl *PrevDepDecl = nullptr,
7484                                  bool SupportsNonRectangular = true)
7485       : SemaRef(SemaRef), Stack(Stack), CurLCDecl(CurLCDecl),
7486         PrevDepDecl(PrevDepDecl), IsInitializer(IsInitializer),
7487         SupportsNonRectangular(SupportsNonRectangular) {}
7488   unsigned getBaseLoopId() const {
7489     assert(CurLCDecl && "Expected loop dependency.");
7490     return BaseLoopId;
7491   }
7492   const ValueDecl *getDepDecl() const {
7493     assert(CurLCDecl && "Expected loop dependency.");
7494     return DepDecl;
7495   }
7496 };
7497 } // namespace
7498 
7499 Optional<unsigned>
7500 OpenMPIterationSpaceChecker::doesDependOnLoopCounter(const Stmt *S,
7501                                                      bool IsInitializer) {
7502   // Check for the non-rectangular loops.
7503   LoopCounterRefChecker LoopStmtChecker(SemaRef, Stack, LCDecl, IsInitializer,
7504                                         DepDecl, SupportsNonRectangular);
7505   if (LoopStmtChecker.Visit(S)) {
7506     DepDecl = LoopStmtChecker.getDepDecl();
7507     return LoopStmtChecker.getBaseLoopId();
7508   }
7509   return llvm::None;
7510 }
7511 
7512 bool OpenMPIterationSpaceChecker::checkAndSetInit(Stmt *S, bool EmitDiags) {
7513   // Check init-expr for canonical loop form and save loop counter
7514   // variable - #Var and its initialization value - #LB.
7515   // OpenMP [2.6] Canonical loop form. init-expr may be one of the following:
7516   //   var = lb
7517   //   integer-type var = lb
7518   //   random-access-iterator-type var = lb
7519   //   pointer-type var = lb
7520   //
7521   if (!S) {
7522     if (EmitDiags) {
7523       SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init);
7524     }
7525     return true;
7526   }
7527   if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
7528     if (!ExprTemp->cleanupsHaveSideEffects())
7529       S = ExprTemp->getSubExpr();
7530 
7531   InitSrcRange = S->getSourceRange();
7532   if (Expr *E = dyn_cast<Expr>(S))
7533     S = E->IgnoreParens();
7534   if (auto *BO = dyn_cast<BinaryOperator>(S)) {
7535     if (BO->getOpcode() == BO_Assign) {
7536       Expr *LHS = BO->getLHS()->IgnoreParens();
7537       if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
7538         if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
7539           if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
7540             return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
7541                                   EmitDiags);
7542         return setLCDeclAndLB(DRE->getDecl(), DRE, BO->getRHS(), EmitDiags);
7543       }
7544       if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
7545         if (ME->isArrow() &&
7546             isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
7547           return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
7548                                 EmitDiags);
7549       }
7550     }
7551   } else if (auto *DS = dyn_cast<DeclStmt>(S)) {
7552     if (DS->isSingleDecl()) {
7553       if (auto *Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) {
7554         if (Var->hasInit() && !Var->getType()->isReferenceType()) {
7555           // Accept non-canonical init form here but emit ext. warning.
7556           if (Var->getInitStyle() != VarDecl::CInit && EmitDiags)
7557             SemaRef.Diag(S->getBeginLoc(),
7558                          diag::ext_omp_loop_not_canonical_init)
7559                 << S->getSourceRange();
7560           return setLCDeclAndLB(
7561               Var,
7562               buildDeclRefExpr(SemaRef, Var,
7563                                Var->getType().getNonReferenceType(),
7564                                DS->getBeginLoc()),
7565               Var->getInit(), EmitDiags);
7566         }
7567       }
7568     }
7569   } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
7570     if (CE->getOperator() == OO_Equal) {
7571       Expr *LHS = CE->getArg(0);
7572       if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
7573         if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
7574           if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
7575             return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
7576                                   EmitDiags);
7577         return setLCDeclAndLB(DRE->getDecl(), DRE, CE->getArg(1), EmitDiags);
7578       }
7579       if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
7580         if (ME->isArrow() &&
7581             isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
7582           return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
7583                                 EmitDiags);
7584       }
7585     }
7586   }
7587 
7588   if (dependent() || SemaRef.CurContext->isDependentContext())
7589     return false;
7590   if (EmitDiags) {
7591     SemaRef.Diag(S->getBeginLoc(), diag::err_omp_loop_not_canonical_init)
7592         << S->getSourceRange();
7593   }
7594   return true;
7595 }
7596 
7597 /// Ignore parenthesizes, implicit casts, copy constructor and return the
7598 /// variable (which may be the loop variable) if possible.
7599 static const ValueDecl *getInitLCDecl(const Expr *E) {
7600   if (!E)
7601     return nullptr;
7602   E = getExprAsWritten(E);
7603   if (const auto *CE = dyn_cast_or_null<CXXConstructExpr>(E))
7604     if (const CXXConstructorDecl *Ctor = CE->getConstructor())
7605       if ((Ctor->isCopyOrMoveConstructor() ||
7606            Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
7607           CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
7608         E = CE->getArg(0)->IgnoreParenImpCasts();
7609   if (const auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) {
7610     if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
7611       return getCanonicalDecl(VD);
7612   }
7613   if (const auto *ME = dyn_cast_or_null<MemberExpr>(E))
7614     if (ME->isArrow() && isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
7615       return getCanonicalDecl(ME->getMemberDecl());
7616   return nullptr;
7617 }
7618 
7619 bool OpenMPIterationSpaceChecker::checkAndSetCond(Expr *S) {
7620   // Check test-expr for canonical form, save upper-bound UB, flags for
7621   // less/greater and for strict/non-strict comparison.
7622   // OpenMP [2.9] Canonical loop form. Test-expr may be one of the following:
7623   //   var relational-op b
7624   //   b relational-op var
7625   //
7626   bool IneqCondIsCanonical = SemaRef.getLangOpts().OpenMP >= 50;
7627   if (!S) {
7628     SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond)
7629         << (IneqCondIsCanonical ? 1 : 0) << LCDecl;
7630     return true;
7631   }
7632   Condition = S;
7633   S = getExprAsWritten(S);
7634   SourceLocation CondLoc = S->getBeginLoc();
7635   if (auto *BO = dyn_cast<BinaryOperator>(S)) {
7636     if (BO->isRelationalOp()) {
7637       if (getInitLCDecl(BO->getLHS()) == LCDecl)
7638         return setUB(BO->getRHS(),
7639                      (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE),
7640                      (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
7641                      BO->getSourceRange(), BO->getOperatorLoc());
7642       if (getInitLCDecl(BO->getRHS()) == LCDecl)
7643         return setUB(BO->getLHS(),
7644                      (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE),
7645                      (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
7646                      BO->getSourceRange(), BO->getOperatorLoc());
7647     } else if (IneqCondIsCanonical && BO->getOpcode() == BO_NE)
7648       return setUB(
7649           getInitLCDecl(BO->getLHS()) == LCDecl ? BO->getRHS() : BO->getLHS(),
7650           /*LessOp=*/llvm::None,
7651           /*StrictOp=*/true, BO->getSourceRange(), BO->getOperatorLoc());
7652   } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
7653     if (CE->getNumArgs() == 2) {
7654       auto Op = CE->getOperator();
7655       switch (Op) {
7656       case OO_Greater:
7657       case OO_GreaterEqual:
7658       case OO_Less:
7659       case OO_LessEqual:
7660         if (getInitLCDecl(CE->getArg(0)) == LCDecl)
7661           return setUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual,
7662                        Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
7663                        CE->getOperatorLoc());
7664         if (getInitLCDecl(CE->getArg(1)) == LCDecl)
7665           return setUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual,
7666                        Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
7667                        CE->getOperatorLoc());
7668         break;
7669       case OO_ExclaimEqual:
7670         if (IneqCondIsCanonical)
7671           return setUB(getInitLCDecl(CE->getArg(0)) == LCDecl ? CE->getArg(1)
7672                                                               : CE->getArg(0),
7673                        /*LessOp=*/llvm::None,
7674                        /*StrictOp=*/true, CE->getSourceRange(),
7675                        CE->getOperatorLoc());
7676         break;
7677       default:
7678         break;
7679       }
7680     }
7681   }
7682   if (dependent() || SemaRef.CurContext->isDependentContext())
7683     return false;
7684   SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond)
7685       << (IneqCondIsCanonical ? 1 : 0) << S->getSourceRange() << LCDecl;
7686   return true;
7687 }
7688 
7689 bool OpenMPIterationSpaceChecker::checkAndSetIncRHS(Expr *RHS) {
7690   // RHS of canonical loop form increment can be:
7691   //   var + incr
7692   //   incr + var
7693   //   var - incr
7694   //
7695   RHS = RHS->IgnoreParenImpCasts();
7696   if (auto *BO = dyn_cast<BinaryOperator>(RHS)) {
7697     if (BO->isAdditiveOp()) {
7698       bool IsAdd = BO->getOpcode() == BO_Add;
7699       if (getInitLCDecl(BO->getLHS()) == LCDecl)
7700         return setStep(BO->getRHS(), !IsAdd);
7701       if (IsAdd && getInitLCDecl(BO->getRHS()) == LCDecl)
7702         return setStep(BO->getLHS(), /*Subtract=*/false);
7703     }
7704   } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(RHS)) {
7705     bool IsAdd = CE->getOperator() == OO_Plus;
7706     if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) {
7707       if (getInitLCDecl(CE->getArg(0)) == LCDecl)
7708         return setStep(CE->getArg(1), !IsAdd);
7709       if (IsAdd && getInitLCDecl(CE->getArg(1)) == LCDecl)
7710         return setStep(CE->getArg(0), /*Subtract=*/false);
7711     }
7712   }
7713   if (dependent() || SemaRef.CurContext->isDependentContext())
7714     return false;
7715   SemaRef.Diag(RHS->getBeginLoc(), diag::err_omp_loop_not_canonical_incr)
7716       << RHS->getSourceRange() << LCDecl;
7717   return true;
7718 }
7719 
7720 bool OpenMPIterationSpaceChecker::checkAndSetInc(Expr *S) {
7721   // Check incr-expr for canonical loop form and return true if it
7722   // does not conform.
7723   // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
7724   //   ++var
7725   //   var++
7726   //   --var
7727   //   var--
7728   //   var += incr
7729   //   var -= incr
7730   //   var = var + incr
7731   //   var = incr + var
7732   //   var = var - incr
7733   //
7734   if (!S) {
7735     SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << LCDecl;
7736     return true;
7737   }
7738   if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
7739     if (!ExprTemp->cleanupsHaveSideEffects())
7740       S = ExprTemp->getSubExpr();
7741 
7742   IncrementSrcRange = S->getSourceRange();
7743   S = S->IgnoreParens();
7744   if (auto *UO = dyn_cast<UnaryOperator>(S)) {
7745     if (UO->isIncrementDecrementOp() &&
7746         getInitLCDecl(UO->getSubExpr()) == LCDecl)
7747       return setStep(SemaRef
7748                          .ActOnIntegerConstant(UO->getBeginLoc(),
7749                                                (UO->isDecrementOp() ? -1 : 1))
7750                          .get(),
7751                      /*Subtract=*/false);
7752   } else if (auto *BO = dyn_cast<BinaryOperator>(S)) {
7753     switch (BO->getOpcode()) {
7754     case BO_AddAssign:
7755     case BO_SubAssign:
7756       if (getInitLCDecl(BO->getLHS()) == LCDecl)
7757         return setStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign);
7758       break;
7759     case BO_Assign:
7760       if (getInitLCDecl(BO->getLHS()) == LCDecl)
7761         return checkAndSetIncRHS(BO->getRHS());
7762       break;
7763     default:
7764       break;
7765     }
7766   } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
7767     switch (CE->getOperator()) {
7768     case OO_PlusPlus:
7769     case OO_MinusMinus:
7770       if (getInitLCDecl(CE->getArg(0)) == LCDecl)
7771         return setStep(SemaRef
7772                            .ActOnIntegerConstant(
7773                                CE->getBeginLoc(),
7774                                ((CE->getOperator() == OO_MinusMinus) ? -1 : 1))
7775                            .get(),
7776                        /*Subtract=*/false);
7777       break;
7778     case OO_PlusEqual:
7779     case OO_MinusEqual:
7780       if (getInitLCDecl(CE->getArg(0)) == LCDecl)
7781         return setStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual);
7782       break;
7783     case OO_Equal:
7784       if (getInitLCDecl(CE->getArg(0)) == LCDecl)
7785         return checkAndSetIncRHS(CE->getArg(1));
7786       break;
7787     default:
7788       break;
7789     }
7790   }
7791   if (dependent() || SemaRef.CurContext->isDependentContext())
7792     return false;
7793   SemaRef.Diag(S->getBeginLoc(), diag::err_omp_loop_not_canonical_incr)
7794       << S->getSourceRange() << LCDecl;
7795   return true;
7796 }
7797 
7798 static ExprResult
7799 tryBuildCapture(Sema &SemaRef, Expr *Capture,
7800                 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
7801   if (SemaRef.CurContext->isDependentContext() || Capture->containsErrors())
7802     return Capture;
7803   if (Capture->isEvaluatable(SemaRef.Context, Expr::SE_AllowSideEffects))
7804     return SemaRef.PerformImplicitConversion(
7805         Capture->IgnoreImpCasts(), Capture->getType(), Sema::AA_Converting,
7806         /*AllowExplicit=*/true);
7807   auto I = Captures.find(Capture);
7808   if (I != Captures.end())
7809     return buildCapture(SemaRef, Capture, I->second);
7810   DeclRefExpr *Ref = nullptr;
7811   ExprResult Res = buildCapture(SemaRef, Capture, Ref);
7812   Captures[Capture] = Ref;
7813   return Res;
7814 }
7815 
7816 /// Calculate number of iterations, transforming to unsigned, if number of
7817 /// iterations may be larger than the original type.
7818 static Expr *
7819 calculateNumIters(Sema &SemaRef, Scope *S, SourceLocation DefaultLoc,
7820                   Expr *Lower, Expr *Upper, Expr *Step, QualType LCTy,
7821                   bool TestIsStrictOp, bool RoundToStep,
7822                   llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
7823   ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures);
7824   if (!NewStep.isUsable())
7825     return nullptr;
7826   llvm::APSInt LRes, SRes;
7827   bool IsLowerConst = false, IsStepConst = false;
7828   if (Optional<llvm::APSInt> Res = Lower->getIntegerConstantExpr(SemaRef.Context)) {
7829     LRes = *Res;
7830     IsLowerConst = true;
7831   }
7832   if (Optional<llvm::APSInt> Res = Step->getIntegerConstantExpr(SemaRef.Context)) {
7833     SRes = *Res;
7834     IsStepConst = true;
7835   }
7836   bool NoNeedToConvert = IsLowerConst && !RoundToStep &&
7837                          ((!TestIsStrictOp && LRes.isNonNegative()) ||
7838                           (TestIsStrictOp && LRes.isStrictlyPositive()));
7839   bool NeedToReorganize = false;
7840   // Check if any subexpressions in Lower -Step [+ 1] lead to overflow.
7841   if (!NoNeedToConvert && IsLowerConst &&
7842       (TestIsStrictOp || (RoundToStep && IsStepConst))) {
7843     NoNeedToConvert = true;
7844     if (RoundToStep) {
7845       unsigned BW = LRes.getBitWidth() > SRes.getBitWidth()
7846                         ? LRes.getBitWidth()
7847                         : SRes.getBitWidth();
7848       LRes = LRes.extend(BW + 1);
7849       LRes.setIsSigned(true);
7850       SRes = SRes.extend(BW + 1);
7851       SRes.setIsSigned(true);
7852       LRes -= SRes;
7853       NoNeedToConvert = LRes.trunc(BW).extend(BW + 1) == LRes;
7854       LRes = LRes.trunc(BW);
7855     }
7856     if (TestIsStrictOp) {
7857       unsigned BW = LRes.getBitWidth();
7858       LRes = LRes.extend(BW + 1);
7859       LRes.setIsSigned(true);
7860       ++LRes;
7861       NoNeedToConvert =
7862           NoNeedToConvert && LRes.trunc(BW).extend(BW + 1) == LRes;
7863       // truncate to the original bitwidth.
7864       LRes = LRes.trunc(BW);
7865     }
7866     NeedToReorganize = NoNeedToConvert;
7867   }
7868   llvm::APSInt URes;
7869   bool IsUpperConst = false;
7870   if (Optional<llvm::APSInt> Res = Upper->getIntegerConstantExpr(SemaRef.Context)) {
7871     URes = *Res;
7872     IsUpperConst = true;
7873   }
7874   if (NoNeedToConvert && IsLowerConst && IsUpperConst &&
7875       (!RoundToStep || IsStepConst)) {
7876     unsigned BW = LRes.getBitWidth() > URes.getBitWidth() ? LRes.getBitWidth()
7877                                                           : URes.getBitWidth();
7878     LRes = LRes.extend(BW + 1);
7879     LRes.setIsSigned(true);
7880     URes = URes.extend(BW + 1);
7881     URes.setIsSigned(true);
7882     URes -= LRes;
7883     NoNeedToConvert = URes.trunc(BW).extend(BW + 1) == URes;
7884     NeedToReorganize = NoNeedToConvert;
7885   }
7886   // If the boundaries are not constant or (Lower - Step [+ 1]) is not constant
7887   // or less than zero (Upper - (Lower - Step [+ 1]) may overflow) - promote to
7888   // unsigned.
7889   if ((!NoNeedToConvert || (LRes.isNegative() && !IsUpperConst)) &&
7890       !LCTy->isDependentType() && LCTy->isIntegerType()) {
7891     QualType LowerTy = Lower->getType();
7892     QualType UpperTy = Upper->getType();
7893     uint64_t LowerSize = SemaRef.Context.getTypeSize(LowerTy);
7894     uint64_t UpperSize = SemaRef.Context.getTypeSize(UpperTy);
7895     if ((LowerSize <= UpperSize && UpperTy->hasSignedIntegerRepresentation()) ||
7896         (LowerSize > UpperSize && LowerTy->hasSignedIntegerRepresentation())) {
7897       QualType CastType = SemaRef.Context.getIntTypeForBitwidth(
7898           LowerSize > UpperSize ? LowerSize : UpperSize, /*Signed=*/0);
7899       Upper =
7900           SemaRef
7901               .PerformImplicitConversion(
7902                   SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Upper).get(),
7903                   CastType, Sema::AA_Converting)
7904               .get();
7905       Lower = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Lower).get();
7906       NewStep = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, NewStep.get());
7907     }
7908   }
7909   if (!Lower || !Upper || NewStep.isInvalid())
7910     return nullptr;
7911 
7912   ExprResult Diff;
7913   // If need to reorganize, then calculate the form as Upper - (Lower - Step [+
7914   // 1]).
7915   if (NeedToReorganize) {
7916     Diff = Lower;
7917 
7918     if (RoundToStep) {
7919       // Lower - Step
7920       Diff =
7921           SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Diff.get(), NewStep.get());
7922       if (!Diff.isUsable())
7923         return nullptr;
7924     }
7925 
7926     // Lower - Step [+ 1]
7927     if (TestIsStrictOp)
7928       Diff = SemaRef.BuildBinOp(
7929           S, DefaultLoc, BO_Add, Diff.get(),
7930           SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
7931     if (!Diff.isUsable())
7932       return nullptr;
7933 
7934     Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
7935     if (!Diff.isUsable())
7936       return nullptr;
7937 
7938     // Upper - (Lower - Step [+ 1]).
7939     Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Diff.get());
7940     if (!Diff.isUsable())
7941       return nullptr;
7942   } else {
7943     Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
7944 
7945     if (!Diff.isUsable() && LCTy->getAsCXXRecordDecl()) {
7946       // BuildBinOp already emitted error, this one is to point user to upper
7947       // and lower bound, and to tell what is passed to 'operator-'.
7948       SemaRef.Diag(Upper->getBeginLoc(), diag::err_omp_loop_diff_cxx)
7949           << Upper->getSourceRange() << Lower->getSourceRange();
7950       return nullptr;
7951     }
7952 
7953     if (!Diff.isUsable())
7954       return nullptr;
7955 
7956     // Upper - Lower [- 1]
7957     if (TestIsStrictOp)
7958       Diff = SemaRef.BuildBinOp(
7959           S, DefaultLoc, BO_Sub, Diff.get(),
7960           SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
7961     if (!Diff.isUsable())
7962       return nullptr;
7963 
7964     if (RoundToStep) {
7965       // Upper - Lower [- 1] + Step
7966       Diff =
7967           SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get());
7968       if (!Diff.isUsable())
7969         return nullptr;
7970     }
7971   }
7972 
7973   // Parentheses (for dumping/debugging purposes only).
7974   Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
7975   if (!Diff.isUsable())
7976     return nullptr;
7977 
7978   // (Upper - Lower [- 1] + Step) / Step or (Upper - Lower) / Step
7979   Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
7980   if (!Diff.isUsable())
7981     return nullptr;
7982 
7983   return Diff.get();
7984 }
7985 
7986 /// Build the expression to calculate the number of iterations.
7987 Expr *OpenMPIterationSpaceChecker::buildNumIterations(
7988     Scope *S, ArrayRef<LoopIterationSpace> ResultIterSpaces, bool LimitedType,
7989     llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
7990   QualType VarType = LCDecl->getType().getNonReferenceType();
7991   if (!VarType->isIntegerType() && !VarType->isPointerType() &&
7992       !SemaRef.getLangOpts().CPlusPlus)
7993     return nullptr;
7994   Expr *LBVal = LB;
7995   Expr *UBVal = UB;
7996   // LB = TestIsLessOp.getValue() ? min(LB(MinVal), LB(MaxVal)) :
7997   // max(LB(MinVal), LB(MaxVal))
7998   if (InitDependOnLC) {
7999     const LoopIterationSpace &IS = ResultIterSpaces[*InitDependOnLC - 1];
8000     if (!IS.MinValue || !IS.MaxValue)
8001       return nullptr;
8002     // OuterVar = Min
8003     ExprResult MinValue =
8004         SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MinValue);
8005     if (!MinValue.isUsable())
8006       return nullptr;
8007 
8008     ExprResult LBMinVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign,
8009                                              IS.CounterVar, MinValue.get());
8010     if (!LBMinVal.isUsable())
8011       return nullptr;
8012     // OuterVar = Min, LBVal
8013     LBMinVal =
8014         SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, LBMinVal.get(), LBVal);
8015     if (!LBMinVal.isUsable())
8016       return nullptr;
8017     // (OuterVar = Min, LBVal)
8018     LBMinVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, LBMinVal.get());
8019     if (!LBMinVal.isUsable())
8020       return nullptr;
8021 
8022     // OuterVar = Max
8023     ExprResult MaxValue =
8024         SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MaxValue);
8025     if (!MaxValue.isUsable())
8026       return nullptr;
8027 
8028     ExprResult LBMaxVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign,
8029                                              IS.CounterVar, MaxValue.get());
8030     if (!LBMaxVal.isUsable())
8031       return nullptr;
8032     // OuterVar = Max, LBVal
8033     LBMaxVal =
8034         SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, LBMaxVal.get(), LBVal);
8035     if (!LBMaxVal.isUsable())
8036       return nullptr;
8037     // (OuterVar = Max, LBVal)
8038     LBMaxVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, LBMaxVal.get());
8039     if (!LBMaxVal.isUsable())
8040       return nullptr;
8041 
8042     Expr *LBMin = tryBuildCapture(SemaRef, LBMinVal.get(), Captures).get();
8043     Expr *LBMax = tryBuildCapture(SemaRef, LBMaxVal.get(), Captures).get();
8044     if (!LBMin || !LBMax)
8045       return nullptr;
8046     // LB(MinVal) < LB(MaxVal)
8047     ExprResult MinLessMaxRes =
8048         SemaRef.BuildBinOp(S, DefaultLoc, BO_LT, LBMin, LBMax);
8049     if (!MinLessMaxRes.isUsable())
8050       return nullptr;
8051     Expr *MinLessMax =
8052         tryBuildCapture(SemaRef, MinLessMaxRes.get(), Captures).get();
8053     if (!MinLessMax)
8054       return nullptr;
8055     if (TestIsLessOp.getValue()) {
8056       // LB(MinVal) < LB(MaxVal) ? LB(MinVal) : LB(MaxVal) - min(LB(MinVal),
8057       // LB(MaxVal))
8058       ExprResult MinLB = SemaRef.ActOnConditionalOp(DefaultLoc, DefaultLoc,
8059                                                     MinLessMax, LBMin, LBMax);
8060       if (!MinLB.isUsable())
8061         return nullptr;
8062       LBVal = MinLB.get();
8063     } else {
8064       // LB(MinVal) < LB(MaxVal) ? LB(MaxVal) : LB(MinVal) - max(LB(MinVal),
8065       // LB(MaxVal))
8066       ExprResult MaxLB = SemaRef.ActOnConditionalOp(DefaultLoc, DefaultLoc,
8067                                                     MinLessMax, LBMax, LBMin);
8068       if (!MaxLB.isUsable())
8069         return nullptr;
8070       LBVal = MaxLB.get();
8071     }
8072   }
8073   // UB = TestIsLessOp.getValue() ? max(UB(MinVal), UB(MaxVal)) :
8074   // min(UB(MinVal), UB(MaxVal))
8075   if (CondDependOnLC) {
8076     const LoopIterationSpace &IS = ResultIterSpaces[*CondDependOnLC - 1];
8077     if (!IS.MinValue || !IS.MaxValue)
8078       return nullptr;
8079     // OuterVar = Min
8080     ExprResult MinValue =
8081         SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MinValue);
8082     if (!MinValue.isUsable())
8083       return nullptr;
8084 
8085     ExprResult UBMinVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign,
8086                                              IS.CounterVar, MinValue.get());
8087     if (!UBMinVal.isUsable())
8088       return nullptr;
8089     // OuterVar = Min, UBVal
8090     UBMinVal =
8091         SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, UBMinVal.get(), UBVal);
8092     if (!UBMinVal.isUsable())
8093       return nullptr;
8094     // (OuterVar = Min, UBVal)
8095     UBMinVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, UBMinVal.get());
8096     if (!UBMinVal.isUsable())
8097       return nullptr;
8098 
8099     // OuterVar = Max
8100     ExprResult MaxValue =
8101         SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MaxValue);
8102     if (!MaxValue.isUsable())
8103       return nullptr;
8104 
8105     ExprResult UBMaxVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign,
8106                                              IS.CounterVar, MaxValue.get());
8107     if (!UBMaxVal.isUsable())
8108       return nullptr;
8109     // OuterVar = Max, UBVal
8110     UBMaxVal =
8111         SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, UBMaxVal.get(), UBVal);
8112     if (!UBMaxVal.isUsable())
8113       return nullptr;
8114     // (OuterVar = Max, UBVal)
8115     UBMaxVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, UBMaxVal.get());
8116     if (!UBMaxVal.isUsable())
8117       return nullptr;
8118 
8119     Expr *UBMin = tryBuildCapture(SemaRef, UBMinVal.get(), Captures).get();
8120     Expr *UBMax = tryBuildCapture(SemaRef, UBMaxVal.get(), Captures).get();
8121     if (!UBMin || !UBMax)
8122       return nullptr;
8123     // UB(MinVal) > UB(MaxVal)
8124     ExprResult MinGreaterMaxRes =
8125         SemaRef.BuildBinOp(S, DefaultLoc, BO_GT, UBMin, UBMax);
8126     if (!MinGreaterMaxRes.isUsable())
8127       return nullptr;
8128     Expr *MinGreaterMax =
8129         tryBuildCapture(SemaRef, MinGreaterMaxRes.get(), Captures).get();
8130     if (!MinGreaterMax)
8131       return nullptr;
8132     if (TestIsLessOp.getValue()) {
8133       // UB(MinVal) > UB(MaxVal) ? UB(MinVal) : UB(MaxVal) - max(UB(MinVal),
8134       // UB(MaxVal))
8135       ExprResult MaxUB = SemaRef.ActOnConditionalOp(
8136           DefaultLoc, DefaultLoc, MinGreaterMax, UBMin, UBMax);
8137       if (!MaxUB.isUsable())
8138         return nullptr;
8139       UBVal = MaxUB.get();
8140     } else {
8141       // UB(MinVal) > UB(MaxVal) ? UB(MaxVal) : UB(MinVal) - min(UB(MinVal),
8142       // UB(MaxVal))
8143       ExprResult MinUB = SemaRef.ActOnConditionalOp(
8144           DefaultLoc, DefaultLoc, MinGreaterMax, UBMax, UBMin);
8145       if (!MinUB.isUsable())
8146         return nullptr;
8147       UBVal = MinUB.get();
8148     }
8149   }
8150   Expr *UBExpr = TestIsLessOp.getValue() ? UBVal : LBVal;
8151   Expr *LBExpr = TestIsLessOp.getValue() ? LBVal : UBVal;
8152   Expr *Upper = tryBuildCapture(SemaRef, UBExpr, Captures).get();
8153   Expr *Lower = tryBuildCapture(SemaRef, LBExpr, Captures).get();
8154   if (!Upper || !Lower)
8155     return nullptr;
8156 
8157   ExprResult Diff = calculateNumIters(SemaRef, S, DefaultLoc, Lower, Upper,
8158                                       Step, VarType, TestIsStrictOp,
8159                                       /*RoundToStep=*/true, Captures);
8160   if (!Diff.isUsable())
8161     return nullptr;
8162 
8163   // OpenMP runtime requires 32-bit or 64-bit loop variables.
8164   QualType Type = Diff.get()->getType();
8165   ASTContext &C = SemaRef.Context;
8166   bool UseVarType = VarType->hasIntegerRepresentation() &&
8167                     C.getTypeSize(Type) > C.getTypeSize(VarType);
8168   if (!Type->isIntegerType() || UseVarType) {
8169     unsigned NewSize =
8170         UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type);
8171     bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation()
8172                                : Type->hasSignedIntegerRepresentation();
8173     Type = C.getIntTypeForBitwidth(NewSize, IsSigned);
8174     if (!SemaRef.Context.hasSameType(Diff.get()->getType(), Type)) {
8175       Diff = SemaRef.PerformImplicitConversion(
8176           Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true);
8177       if (!Diff.isUsable())
8178         return nullptr;
8179     }
8180   }
8181   if (LimitedType) {
8182     unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32;
8183     if (NewSize != C.getTypeSize(Type)) {
8184       if (NewSize < C.getTypeSize(Type)) {
8185         assert(NewSize == 64 && "incorrect loop var size");
8186         SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var)
8187             << InitSrcRange << ConditionSrcRange;
8188       }
8189       QualType NewType = C.getIntTypeForBitwidth(
8190           NewSize, Type->hasSignedIntegerRepresentation() ||
8191                        C.getTypeSize(Type) < NewSize);
8192       if (!SemaRef.Context.hasSameType(Diff.get()->getType(), NewType)) {
8193         Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType,
8194                                                  Sema::AA_Converting, true);
8195         if (!Diff.isUsable())
8196           return nullptr;
8197       }
8198     }
8199   }
8200 
8201   return Diff.get();
8202 }
8203 
8204 std::pair<Expr *, Expr *> OpenMPIterationSpaceChecker::buildMinMaxValues(
8205     Scope *S, llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
8206   // Do not build for iterators, they cannot be used in non-rectangular loop
8207   // nests.
8208   if (LCDecl->getType()->isRecordType())
8209     return std::make_pair(nullptr, nullptr);
8210   // If we subtract, the min is in the condition, otherwise the min is in the
8211   // init value.
8212   Expr *MinExpr = nullptr;
8213   Expr *MaxExpr = nullptr;
8214   Expr *LBExpr = TestIsLessOp.getValue() ? LB : UB;
8215   Expr *UBExpr = TestIsLessOp.getValue() ? UB : LB;
8216   bool LBNonRect = TestIsLessOp.getValue() ? InitDependOnLC.hasValue()
8217                                            : CondDependOnLC.hasValue();
8218   bool UBNonRect = TestIsLessOp.getValue() ? CondDependOnLC.hasValue()
8219                                            : InitDependOnLC.hasValue();
8220   Expr *Lower =
8221       LBNonRect ? LBExpr : tryBuildCapture(SemaRef, LBExpr, Captures).get();
8222   Expr *Upper =
8223       UBNonRect ? UBExpr : tryBuildCapture(SemaRef, UBExpr, Captures).get();
8224   if (!Upper || !Lower)
8225     return std::make_pair(nullptr, nullptr);
8226 
8227   if (TestIsLessOp.getValue())
8228     MinExpr = Lower;
8229   else
8230     MaxExpr = Upper;
8231 
8232   // Build minimum/maximum value based on number of iterations.
8233   QualType VarType = LCDecl->getType().getNonReferenceType();
8234 
8235   ExprResult Diff = calculateNumIters(SemaRef, S, DefaultLoc, Lower, Upper,
8236                                       Step, VarType, TestIsStrictOp,
8237                                       /*RoundToStep=*/false, Captures);
8238   if (!Diff.isUsable())
8239     return std::make_pair(nullptr, nullptr);
8240 
8241   // ((Upper - Lower [- 1]) / Step) * Step
8242   // Parentheses (for dumping/debugging purposes only).
8243   Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
8244   if (!Diff.isUsable())
8245     return std::make_pair(nullptr, nullptr);
8246 
8247   ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures);
8248   if (!NewStep.isUsable())
8249     return std::make_pair(nullptr, nullptr);
8250   Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Mul, Diff.get(), NewStep.get());
8251   if (!Diff.isUsable())
8252     return std::make_pair(nullptr, nullptr);
8253 
8254   // Parentheses (for dumping/debugging purposes only).
8255   Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
8256   if (!Diff.isUsable())
8257     return std::make_pair(nullptr, nullptr);
8258 
8259   // Convert to the ptrdiff_t, if original type is pointer.
8260   if (VarType->isAnyPointerType() &&
8261       !SemaRef.Context.hasSameType(
8262           Diff.get()->getType(),
8263           SemaRef.Context.getUnsignedPointerDiffType())) {
8264     Diff = SemaRef.PerformImplicitConversion(
8265         Diff.get(), SemaRef.Context.getUnsignedPointerDiffType(),
8266         Sema::AA_Converting, /*AllowExplicit=*/true);
8267   }
8268   if (!Diff.isUsable())
8269     return std::make_pair(nullptr, nullptr);
8270 
8271   if (TestIsLessOp.getValue()) {
8272     // MinExpr = Lower;
8273     // MaxExpr = Lower + (((Upper - Lower [- 1]) / Step) * Step)
8274     Diff = SemaRef.BuildBinOp(
8275         S, DefaultLoc, BO_Add,
8276         SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Lower).get(),
8277         Diff.get());
8278     if (!Diff.isUsable())
8279       return std::make_pair(nullptr, nullptr);
8280   } else {
8281     // MaxExpr = Upper;
8282     // MinExpr = Upper - (((Upper - Lower [- 1]) / Step) * Step)
8283     Diff = SemaRef.BuildBinOp(
8284         S, DefaultLoc, BO_Sub,
8285         SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Upper).get(),
8286         Diff.get());
8287     if (!Diff.isUsable())
8288       return std::make_pair(nullptr, nullptr);
8289   }
8290 
8291   // Convert to the original type.
8292   if (SemaRef.Context.hasSameType(Diff.get()->getType(), VarType))
8293     Diff = SemaRef.PerformImplicitConversion(Diff.get(), VarType,
8294                                              Sema::AA_Converting,
8295                                              /*AllowExplicit=*/true);
8296   if (!Diff.isUsable())
8297     return std::make_pair(nullptr, nullptr);
8298 
8299   Sema::TentativeAnalysisScope Trap(SemaRef);
8300   Diff = SemaRef.ActOnFinishFullExpr(Diff.get(), /*DiscardedValue=*/false);
8301   if (!Diff.isUsable())
8302     return std::make_pair(nullptr, nullptr);
8303 
8304   if (TestIsLessOp.getValue())
8305     MaxExpr = Diff.get();
8306   else
8307     MinExpr = Diff.get();
8308 
8309   return std::make_pair(MinExpr, MaxExpr);
8310 }
8311 
8312 Expr *OpenMPIterationSpaceChecker::buildFinalCondition(Scope *S) const {
8313   if (InitDependOnLC || CondDependOnLC)
8314     return Condition;
8315   return nullptr;
8316 }
8317 
8318 Expr *OpenMPIterationSpaceChecker::buildPreCond(
8319     Scope *S, Expr *Cond,
8320     llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
8321   // Do not build a precondition when the condition/initialization is dependent
8322   // to prevent pessimistic early loop exit.
8323   // TODO: this can be improved by calculating min/max values but not sure that
8324   // it will be very effective.
8325   if (CondDependOnLC || InitDependOnLC)
8326     return SemaRef.PerformImplicitConversion(
8327         SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get(),
8328         SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
8329         /*AllowExplicit=*/true).get();
8330 
8331   // Try to build LB <op> UB, where <op> is <, >, <=, or >=.
8332   Sema::TentativeAnalysisScope Trap(SemaRef);
8333 
8334   ExprResult NewLB = tryBuildCapture(SemaRef, LB, Captures);
8335   ExprResult NewUB = tryBuildCapture(SemaRef, UB, Captures);
8336   if (!NewLB.isUsable() || !NewUB.isUsable())
8337     return nullptr;
8338 
8339   ExprResult CondExpr =
8340       SemaRef.BuildBinOp(S, DefaultLoc,
8341                          TestIsLessOp.getValue() ?
8342                            (TestIsStrictOp ? BO_LT : BO_LE) :
8343                            (TestIsStrictOp ? BO_GT : BO_GE),
8344                          NewLB.get(), NewUB.get());
8345   if (CondExpr.isUsable()) {
8346     if (!SemaRef.Context.hasSameUnqualifiedType(CondExpr.get()->getType(),
8347                                                 SemaRef.Context.BoolTy))
8348       CondExpr = SemaRef.PerformImplicitConversion(
8349           CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
8350           /*AllowExplicit=*/true);
8351   }
8352 
8353   // Otherwise use original loop condition and evaluate it in runtime.
8354   return CondExpr.isUsable() ? CondExpr.get() : Cond;
8355 }
8356 
8357 /// Build reference expression to the counter be used for codegen.
8358 DeclRefExpr *OpenMPIterationSpaceChecker::buildCounterVar(
8359     llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
8360     DSAStackTy &DSA) const {
8361   auto *VD = dyn_cast<VarDecl>(LCDecl);
8362   if (!VD) {
8363     VD = SemaRef.isOpenMPCapturedDecl(LCDecl);
8364     DeclRefExpr *Ref = buildDeclRefExpr(
8365         SemaRef, VD, VD->getType().getNonReferenceType(), DefaultLoc);
8366     const DSAStackTy::DSAVarData Data =
8367         DSA.getTopDSA(LCDecl, /*FromParent=*/false);
8368     // If the loop control decl is explicitly marked as private, do not mark it
8369     // as captured again.
8370     if (!isOpenMPPrivate(Data.CKind) || !Data.RefExpr)
8371       Captures.insert(std::make_pair(LCRef, Ref));
8372     return Ref;
8373   }
8374   return cast<DeclRefExpr>(LCRef);
8375 }
8376 
8377 Expr *OpenMPIterationSpaceChecker::buildPrivateCounterVar() const {
8378   if (LCDecl && !LCDecl->isInvalidDecl()) {
8379     QualType Type = LCDecl->getType().getNonReferenceType();
8380     VarDecl *PrivateVar = buildVarDecl(
8381         SemaRef, DefaultLoc, Type, LCDecl->getName(),
8382         LCDecl->hasAttrs() ? &LCDecl->getAttrs() : nullptr,
8383         isa<VarDecl>(LCDecl)
8384             ? buildDeclRefExpr(SemaRef, cast<VarDecl>(LCDecl), Type, DefaultLoc)
8385             : nullptr);
8386     if (PrivateVar->isInvalidDecl())
8387       return nullptr;
8388     return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc);
8389   }
8390   return nullptr;
8391 }
8392 
8393 /// Build initialization of the counter to be used for codegen.
8394 Expr *OpenMPIterationSpaceChecker::buildCounterInit() const { return LB; }
8395 
8396 /// Build step of the counter be used for codegen.
8397 Expr *OpenMPIterationSpaceChecker::buildCounterStep() const { return Step; }
8398 
8399 Expr *OpenMPIterationSpaceChecker::buildOrderedLoopData(
8400     Scope *S, Expr *Counter,
8401     llvm::MapVector<const Expr *, DeclRefExpr *> &Captures, SourceLocation Loc,
8402     Expr *Inc, OverloadedOperatorKind OOK) {
8403   Expr *Cnt = SemaRef.DefaultLvalueConversion(Counter).get();
8404   if (!Cnt)
8405     return nullptr;
8406   if (Inc) {
8407     assert((OOK == OO_Plus || OOK == OO_Minus) &&
8408            "Expected only + or - operations for depend clauses.");
8409     BinaryOperatorKind BOK = (OOK == OO_Plus) ? BO_Add : BO_Sub;
8410     Cnt = SemaRef.BuildBinOp(S, Loc, BOK, Cnt, Inc).get();
8411     if (!Cnt)
8412       return nullptr;
8413   }
8414   QualType VarType = LCDecl->getType().getNonReferenceType();
8415   if (!VarType->isIntegerType() && !VarType->isPointerType() &&
8416       !SemaRef.getLangOpts().CPlusPlus)
8417     return nullptr;
8418   // Upper - Lower
8419   Expr *Upper = TestIsLessOp.getValue()
8420                     ? Cnt
8421                     : tryBuildCapture(SemaRef, LB, Captures).get();
8422   Expr *Lower = TestIsLessOp.getValue()
8423                     ? tryBuildCapture(SemaRef, LB, Captures).get()
8424                     : Cnt;
8425   if (!Upper || !Lower)
8426     return nullptr;
8427 
8428   ExprResult Diff = calculateNumIters(
8429       SemaRef, S, DefaultLoc, Lower, Upper, Step, VarType,
8430       /*TestIsStrictOp=*/false, /*RoundToStep=*/false, Captures);
8431   if (!Diff.isUsable())
8432     return nullptr;
8433 
8434   return Diff.get();
8435 }
8436 } // namespace
8437 
8438 void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) {
8439   assert(getLangOpts().OpenMP && "OpenMP is not active.");
8440   assert(Init && "Expected loop in canonical form.");
8441   unsigned AssociatedLoops = DSAStack->getAssociatedLoops();
8442   if (AssociatedLoops > 0 &&
8443       isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
8444     DSAStack->loopStart();
8445     OpenMPIterationSpaceChecker ISC(*this, /*SupportsNonRectangular=*/true,
8446                                     *DSAStack, ForLoc);
8447     if (!ISC.checkAndSetInit(Init, /*EmitDiags=*/false)) {
8448       if (ValueDecl *D = ISC.getLoopDecl()) {
8449         auto *VD = dyn_cast<VarDecl>(D);
8450         DeclRefExpr *PrivateRef = nullptr;
8451         if (!VD) {
8452           if (VarDecl *Private = isOpenMPCapturedDecl(D)) {
8453             VD = Private;
8454           } else {
8455             PrivateRef = buildCapture(*this, D, ISC.getLoopDeclRefExpr(),
8456                                       /*WithInit=*/false);
8457             VD = cast<VarDecl>(PrivateRef->getDecl());
8458           }
8459         }
8460         DSAStack->addLoopControlVariable(D, VD);
8461         const Decl *LD = DSAStack->getPossiblyLoopCunter();
8462         if (LD != D->getCanonicalDecl()) {
8463           DSAStack->resetPossibleLoopCounter();
8464           if (auto *Var = dyn_cast_or_null<VarDecl>(LD))
8465             MarkDeclarationsReferencedInExpr(
8466                 buildDeclRefExpr(*this, const_cast<VarDecl *>(Var),
8467                                  Var->getType().getNonLValueExprType(Context),
8468                                  ForLoc, /*RefersToCapture=*/true));
8469         }
8470         OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
8471         // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables
8472         // Referenced in a Construct, C/C++]. The loop iteration variable in the
8473         // associated for-loop of a simd construct with just one associated
8474         // for-loop may be listed in a linear clause with a constant-linear-step
8475         // that is the increment of the associated for-loop. The loop iteration
8476         // variable(s) in the associated for-loop(s) of a for or parallel for
8477         // construct may be listed in a private or lastprivate clause.
8478         DSAStackTy::DSAVarData DVar =
8479             DSAStack->getTopDSA(D, /*FromParent=*/false);
8480         // If LoopVarRefExpr is nullptr it means the corresponding loop variable
8481         // is declared in the loop and it is predetermined as a private.
8482         Expr *LoopDeclRefExpr = ISC.getLoopDeclRefExpr();
8483         OpenMPClauseKind PredeterminedCKind =
8484             isOpenMPSimdDirective(DKind)
8485                 ? (DSAStack->hasMutipleLoops() ? OMPC_lastprivate : OMPC_linear)
8486                 : OMPC_private;
8487         if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
8488               DVar.CKind != PredeterminedCKind && DVar.RefExpr &&
8489               (LangOpts.OpenMP <= 45 || (DVar.CKind != OMPC_lastprivate &&
8490                                          DVar.CKind != OMPC_private))) ||
8491              ((isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop ||
8492                DKind == OMPD_master_taskloop ||
8493                DKind == OMPD_parallel_master_taskloop ||
8494                isOpenMPDistributeDirective(DKind)) &&
8495               !isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
8496               DVar.CKind != OMPC_private && DVar.CKind != OMPC_lastprivate)) &&
8497             (DVar.CKind != OMPC_private || DVar.RefExpr)) {
8498           Diag(Init->getBeginLoc(), diag::err_omp_loop_var_dsa)
8499               << getOpenMPClauseName(DVar.CKind)
8500               << getOpenMPDirectiveName(DKind)
8501               << getOpenMPClauseName(PredeterminedCKind);
8502           if (DVar.RefExpr == nullptr)
8503             DVar.CKind = PredeterminedCKind;
8504           reportOriginalDsa(*this, DSAStack, D, DVar,
8505                             /*IsLoopIterVar=*/true);
8506         } else if (LoopDeclRefExpr) {
8507           // Make the loop iteration variable private (for worksharing
8508           // constructs), linear (for simd directives with the only one
8509           // associated loop) or lastprivate (for simd directives with several
8510           // collapsed or ordered loops).
8511           if (DVar.CKind == OMPC_unknown)
8512             DSAStack->addDSA(D, LoopDeclRefExpr, PredeterminedCKind,
8513                              PrivateRef);
8514         }
8515       }
8516     }
8517     DSAStack->setAssociatedLoops(AssociatedLoops - 1);
8518   }
8519 }
8520 
8521 /// Called on a for stmt to check and extract its iteration space
8522 /// for further processing (such as collapsing).
8523 static bool checkOpenMPIterationSpace(
8524     OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA,
8525     unsigned CurrentNestedLoopCount, unsigned NestedLoopCount,
8526     unsigned TotalNestedLoopCount, Expr *CollapseLoopCountExpr,
8527     Expr *OrderedLoopCountExpr,
8528     Sema::VarsWithInheritedDSAType &VarsWithImplicitDSA,
8529     llvm::MutableArrayRef<LoopIterationSpace> ResultIterSpaces,
8530     llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
8531   bool SupportsNonRectangular = !isOpenMPLoopTransformationDirective(DKind);
8532   // OpenMP [2.9.1, Canonical Loop Form]
8533   //   for (init-expr; test-expr; incr-expr) structured-block
8534   //   for (range-decl: range-expr) structured-block
8535   if (auto *CanonLoop = dyn_cast_or_null<OMPCanonicalLoop>(S))
8536     S = CanonLoop->getLoopStmt();
8537   auto *For = dyn_cast_or_null<ForStmt>(S);
8538   auto *CXXFor = dyn_cast_or_null<CXXForRangeStmt>(S);
8539   // Ranged for is supported only in OpenMP 5.0.
8540   if (!For && (SemaRef.LangOpts.OpenMP <= 45 || !CXXFor)) {
8541     SemaRef.Diag(S->getBeginLoc(), diag::err_omp_not_for)
8542         << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr)
8543         << getOpenMPDirectiveName(DKind) << TotalNestedLoopCount
8544         << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount;
8545     if (TotalNestedLoopCount > 1) {
8546       if (CollapseLoopCountExpr && OrderedLoopCountExpr)
8547         SemaRef.Diag(DSA.getConstructLoc(),
8548                      diag::note_omp_collapse_ordered_expr)
8549             << 2 << CollapseLoopCountExpr->getSourceRange()
8550             << OrderedLoopCountExpr->getSourceRange();
8551       else if (CollapseLoopCountExpr)
8552         SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
8553                      diag::note_omp_collapse_ordered_expr)
8554             << 0 << CollapseLoopCountExpr->getSourceRange();
8555       else
8556         SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
8557                      diag::note_omp_collapse_ordered_expr)
8558             << 1 << OrderedLoopCountExpr->getSourceRange();
8559     }
8560     return true;
8561   }
8562   assert(((For && For->getBody()) || (CXXFor && CXXFor->getBody())) &&
8563          "No loop body.");
8564 
8565   OpenMPIterationSpaceChecker ISC(SemaRef, SupportsNonRectangular, DSA,
8566                                   For ? For->getForLoc() : CXXFor->getForLoc());
8567 
8568   // Check init.
8569   Stmt *Init = For ? For->getInit() : CXXFor->getBeginStmt();
8570   if (ISC.checkAndSetInit(Init))
8571     return true;
8572 
8573   bool HasErrors = false;
8574 
8575   // Check loop variable's type.
8576   if (ValueDecl *LCDecl = ISC.getLoopDecl()) {
8577     // OpenMP [2.6, Canonical Loop Form]
8578     // Var is one of the following:
8579     //   A variable of signed or unsigned integer type.
8580     //   For C++, a variable of a random access iterator type.
8581     //   For C, a variable of a pointer type.
8582     QualType VarType = LCDecl->getType().getNonReferenceType();
8583     if (!VarType->isDependentType() && !VarType->isIntegerType() &&
8584         !VarType->isPointerType() &&
8585         !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) {
8586       SemaRef.Diag(Init->getBeginLoc(), diag::err_omp_loop_variable_type)
8587           << SemaRef.getLangOpts().CPlusPlus;
8588       HasErrors = true;
8589     }
8590 
8591     // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in
8592     // a Construct
8593     // The loop iteration variable(s) in the associated for-loop(s) of a for or
8594     // parallel for construct is (are) private.
8595     // The loop iteration variable in the associated for-loop of a simd
8596     // construct with just one associated for-loop is linear with a
8597     // constant-linear-step that is the increment of the associated for-loop.
8598     // Exclude loop var from the list of variables with implicitly defined data
8599     // sharing attributes.
8600     VarsWithImplicitDSA.erase(LCDecl);
8601 
8602     assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars");
8603 
8604     // Check test-expr.
8605     HasErrors |= ISC.checkAndSetCond(For ? For->getCond() : CXXFor->getCond());
8606 
8607     // Check incr-expr.
8608     HasErrors |= ISC.checkAndSetInc(For ? For->getInc() : CXXFor->getInc());
8609   }
8610 
8611   if (ISC.dependent() || SemaRef.CurContext->isDependentContext() || HasErrors)
8612     return HasErrors;
8613 
8614   // Build the loop's iteration space representation.
8615   ResultIterSpaces[CurrentNestedLoopCount].PreCond = ISC.buildPreCond(
8616       DSA.getCurScope(), For ? For->getCond() : CXXFor->getCond(), Captures);
8617   ResultIterSpaces[CurrentNestedLoopCount].NumIterations =
8618       ISC.buildNumIterations(DSA.getCurScope(), ResultIterSpaces,
8619                              (isOpenMPWorksharingDirective(DKind) ||
8620                               isOpenMPTaskLoopDirective(DKind) ||
8621                               isOpenMPDistributeDirective(DKind) ||
8622                               isOpenMPLoopTransformationDirective(DKind)),
8623                              Captures);
8624   ResultIterSpaces[CurrentNestedLoopCount].CounterVar =
8625       ISC.buildCounterVar(Captures, DSA);
8626   ResultIterSpaces[CurrentNestedLoopCount].PrivateCounterVar =
8627       ISC.buildPrivateCounterVar();
8628   ResultIterSpaces[CurrentNestedLoopCount].CounterInit = ISC.buildCounterInit();
8629   ResultIterSpaces[CurrentNestedLoopCount].CounterStep = ISC.buildCounterStep();
8630   ResultIterSpaces[CurrentNestedLoopCount].InitSrcRange = ISC.getInitSrcRange();
8631   ResultIterSpaces[CurrentNestedLoopCount].CondSrcRange =
8632       ISC.getConditionSrcRange();
8633   ResultIterSpaces[CurrentNestedLoopCount].IncSrcRange =
8634       ISC.getIncrementSrcRange();
8635   ResultIterSpaces[CurrentNestedLoopCount].Subtract = ISC.shouldSubtractStep();
8636   ResultIterSpaces[CurrentNestedLoopCount].IsStrictCompare =
8637       ISC.isStrictTestOp();
8638   std::tie(ResultIterSpaces[CurrentNestedLoopCount].MinValue,
8639            ResultIterSpaces[CurrentNestedLoopCount].MaxValue) =
8640       ISC.buildMinMaxValues(DSA.getCurScope(), Captures);
8641   ResultIterSpaces[CurrentNestedLoopCount].FinalCondition =
8642       ISC.buildFinalCondition(DSA.getCurScope());
8643   ResultIterSpaces[CurrentNestedLoopCount].IsNonRectangularLB =
8644       ISC.doesInitDependOnLC();
8645   ResultIterSpaces[CurrentNestedLoopCount].IsNonRectangularUB =
8646       ISC.doesCondDependOnLC();
8647   ResultIterSpaces[CurrentNestedLoopCount].LoopDependentIdx =
8648       ISC.getLoopDependentIdx();
8649 
8650   HasErrors |=
8651       (ResultIterSpaces[CurrentNestedLoopCount].PreCond == nullptr ||
8652        ResultIterSpaces[CurrentNestedLoopCount].NumIterations == nullptr ||
8653        ResultIterSpaces[CurrentNestedLoopCount].CounterVar == nullptr ||
8654        ResultIterSpaces[CurrentNestedLoopCount].PrivateCounterVar == nullptr ||
8655        ResultIterSpaces[CurrentNestedLoopCount].CounterInit == nullptr ||
8656        ResultIterSpaces[CurrentNestedLoopCount].CounterStep == nullptr);
8657   if (!HasErrors && DSA.isOrderedRegion()) {
8658     if (DSA.getOrderedRegionParam().second->getNumForLoops()) {
8659       if (CurrentNestedLoopCount <
8660           DSA.getOrderedRegionParam().second->getLoopNumIterations().size()) {
8661         DSA.getOrderedRegionParam().second->setLoopNumIterations(
8662             CurrentNestedLoopCount,
8663             ResultIterSpaces[CurrentNestedLoopCount].NumIterations);
8664         DSA.getOrderedRegionParam().second->setLoopCounter(
8665             CurrentNestedLoopCount,
8666             ResultIterSpaces[CurrentNestedLoopCount].CounterVar);
8667       }
8668     }
8669     for (auto &Pair : DSA.getDoacrossDependClauses()) {
8670       if (CurrentNestedLoopCount >= Pair.first->getNumLoops()) {
8671         // Erroneous case - clause has some problems.
8672         continue;
8673       }
8674       if (Pair.first->getDependencyKind() == OMPC_DEPEND_sink &&
8675           Pair.second.size() <= CurrentNestedLoopCount) {
8676         // Erroneous case - clause has some problems.
8677         Pair.first->setLoopData(CurrentNestedLoopCount, nullptr);
8678         continue;
8679       }
8680       Expr *CntValue;
8681       if (Pair.first->getDependencyKind() == OMPC_DEPEND_source)
8682         CntValue = ISC.buildOrderedLoopData(
8683             DSA.getCurScope(),
8684             ResultIterSpaces[CurrentNestedLoopCount].CounterVar, Captures,
8685             Pair.first->getDependencyLoc());
8686       else
8687         CntValue = ISC.buildOrderedLoopData(
8688             DSA.getCurScope(),
8689             ResultIterSpaces[CurrentNestedLoopCount].CounterVar, Captures,
8690             Pair.first->getDependencyLoc(),
8691             Pair.second[CurrentNestedLoopCount].first,
8692             Pair.second[CurrentNestedLoopCount].second);
8693       Pair.first->setLoopData(CurrentNestedLoopCount, CntValue);
8694     }
8695   }
8696 
8697   return HasErrors;
8698 }
8699 
8700 /// Build 'VarRef = Start.
8701 static ExprResult
8702 buildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
8703                  ExprResult Start, bool IsNonRectangularLB,
8704                  llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
8705   // Build 'VarRef = Start.
8706   ExprResult NewStart = IsNonRectangularLB
8707                             ? Start.get()
8708                             : tryBuildCapture(SemaRef, Start.get(), Captures);
8709   if (!NewStart.isUsable())
8710     return ExprError();
8711   if (!SemaRef.Context.hasSameType(NewStart.get()->getType(),
8712                                    VarRef.get()->getType())) {
8713     NewStart = SemaRef.PerformImplicitConversion(
8714         NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting,
8715         /*AllowExplicit=*/true);
8716     if (!NewStart.isUsable())
8717       return ExprError();
8718   }
8719 
8720   ExprResult Init =
8721       SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
8722   return Init;
8723 }
8724 
8725 /// Build 'VarRef = Start + Iter * Step'.
8726 static ExprResult buildCounterUpdate(
8727     Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
8728     ExprResult Start, ExprResult Iter, ExprResult Step, bool Subtract,
8729     bool IsNonRectangularLB,
8730     llvm::MapVector<const Expr *, DeclRefExpr *> *Captures = nullptr) {
8731   // Add parentheses (for debugging purposes only).
8732   Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get());
8733   if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() ||
8734       !Step.isUsable())
8735     return ExprError();
8736 
8737   ExprResult NewStep = Step;
8738   if (Captures)
8739     NewStep = tryBuildCapture(SemaRef, Step.get(), *Captures);
8740   if (NewStep.isInvalid())
8741     return ExprError();
8742   ExprResult Update =
8743       SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get());
8744   if (!Update.isUsable())
8745     return ExprError();
8746 
8747   // Try to build 'VarRef = Start, VarRef (+|-)= Iter * Step' or
8748   // 'VarRef = Start (+|-) Iter * Step'.
8749   if (!Start.isUsable())
8750     return ExprError();
8751   ExprResult NewStart = SemaRef.ActOnParenExpr(Loc, Loc, Start.get());
8752   if (!NewStart.isUsable())
8753     return ExprError();
8754   if (Captures && !IsNonRectangularLB)
8755     NewStart = tryBuildCapture(SemaRef, Start.get(), *Captures);
8756   if (NewStart.isInvalid())
8757     return ExprError();
8758 
8759   // First attempt: try to build 'VarRef = Start, VarRef += Iter * Step'.
8760   ExprResult SavedUpdate = Update;
8761   ExprResult UpdateVal;
8762   if (VarRef.get()->getType()->isOverloadableType() ||
8763       NewStart.get()->getType()->isOverloadableType() ||
8764       Update.get()->getType()->isOverloadableType()) {
8765     Sema::TentativeAnalysisScope Trap(SemaRef);
8766 
8767     Update =
8768         SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
8769     if (Update.isUsable()) {
8770       UpdateVal =
8771           SemaRef.BuildBinOp(S, Loc, Subtract ? BO_SubAssign : BO_AddAssign,
8772                              VarRef.get(), SavedUpdate.get());
8773       if (UpdateVal.isUsable()) {
8774         Update = SemaRef.CreateBuiltinBinOp(Loc, BO_Comma, Update.get(),
8775                                             UpdateVal.get());
8776       }
8777     }
8778   }
8779 
8780   // Second attempt: try to build 'VarRef = Start (+|-) Iter * Step'.
8781   if (!Update.isUsable() || !UpdateVal.isUsable()) {
8782     Update = SemaRef.BuildBinOp(S, Loc, Subtract ? BO_Sub : BO_Add,
8783                                 NewStart.get(), SavedUpdate.get());
8784     if (!Update.isUsable())
8785       return ExprError();
8786 
8787     if (!SemaRef.Context.hasSameType(Update.get()->getType(),
8788                                      VarRef.get()->getType())) {
8789       Update = SemaRef.PerformImplicitConversion(
8790           Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true);
8791       if (!Update.isUsable())
8792         return ExprError();
8793     }
8794 
8795     Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get());
8796   }
8797   return Update;
8798 }
8799 
8800 /// Convert integer expression \a E to make it have at least \a Bits
8801 /// bits.
8802 static ExprResult widenIterationCount(unsigned Bits, Expr *E, Sema &SemaRef) {
8803   if (E == nullptr)
8804     return ExprError();
8805   ASTContext &C = SemaRef.Context;
8806   QualType OldType = E->getType();
8807   unsigned HasBits = C.getTypeSize(OldType);
8808   if (HasBits >= Bits)
8809     return ExprResult(E);
8810   // OK to convert to signed, because new type has more bits than old.
8811   QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true);
8812   return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting,
8813                                            true);
8814 }
8815 
8816 /// Check if the given expression \a E is a constant integer that fits
8817 /// into \a Bits bits.
8818 static bool fitsInto(unsigned Bits, bool Signed, const Expr *E, Sema &SemaRef) {
8819   if (E == nullptr)
8820     return false;
8821   if (Optional<llvm::APSInt> Result =
8822           E->getIntegerConstantExpr(SemaRef.Context))
8823     return Signed ? Result->isSignedIntN(Bits) : Result->isIntN(Bits);
8824   return false;
8825 }
8826 
8827 /// Build preinits statement for the given declarations.
8828 static Stmt *buildPreInits(ASTContext &Context,
8829                            MutableArrayRef<Decl *> PreInits) {
8830   if (!PreInits.empty()) {
8831     return new (Context) DeclStmt(
8832         DeclGroupRef::Create(Context, PreInits.begin(), PreInits.size()),
8833         SourceLocation(), SourceLocation());
8834   }
8835   return nullptr;
8836 }
8837 
8838 /// Build preinits statement for the given declarations.
8839 static Stmt *
8840 buildPreInits(ASTContext &Context,
8841               const llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
8842   if (!Captures.empty()) {
8843     SmallVector<Decl *, 16> PreInits;
8844     for (const auto &Pair : Captures)
8845       PreInits.push_back(Pair.second->getDecl());
8846     return buildPreInits(Context, PreInits);
8847   }
8848   return nullptr;
8849 }
8850 
8851 /// Build postupdate expression for the given list of postupdates expressions.
8852 static Expr *buildPostUpdate(Sema &S, ArrayRef<Expr *> PostUpdates) {
8853   Expr *PostUpdate = nullptr;
8854   if (!PostUpdates.empty()) {
8855     for (Expr *E : PostUpdates) {
8856       Expr *ConvE = S.BuildCStyleCastExpr(
8857                          E->getExprLoc(),
8858                          S.Context.getTrivialTypeSourceInfo(S.Context.VoidTy),
8859                          E->getExprLoc(), E)
8860                         .get();
8861       PostUpdate = PostUpdate
8862                        ? S.CreateBuiltinBinOp(ConvE->getExprLoc(), BO_Comma,
8863                                               PostUpdate, ConvE)
8864                              .get()
8865                        : ConvE;
8866     }
8867   }
8868   return PostUpdate;
8869 }
8870 
8871 /// Called on a for stmt to check itself and nested loops (if any).
8872 /// \return Returns 0 if one of the collapsed stmts is not canonical for loop,
8873 /// number of collapsed loops otherwise.
8874 static unsigned
8875 checkOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr,
8876                 Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef,
8877                 DSAStackTy &DSA,
8878                 Sema::VarsWithInheritedDSAType &VarsWithImplicitDSA,
8879                 OMPLoopBasedDirective::HelperExprs &Built) {
8880   unsigned NestedLoopCount = 1;
8881   bool SupportsNonPerfectlyNested = (SemaRef.LangOpts.OpenMP >= 50) &&
8882                                     !isOpenMPLoopTransformationDirective(DKind);
8883 
8884   if (CollapseLoopCountExpr) {
8885     // Found 'collapse' clause - calculate collapse number.
8886     Expr::EvalResult Result;
8887     if (!CollapseLoopCountExpr->isValueDependent() &&
8888         CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext())) {
8889       NestedLoopCount = Result.Val.getInt().getLimitedValue();
8890     } else {
8891       Built.clear(/*Size=*/1);
8892       return 1;
8893     }
8894   }
8895   unsigned OrderedLoopCount = 1;
8896   if (OrderedLoopCountExpr) {
8897     // Found 'ordered' clause - calculate collapse number.
8898     Expr::EvalResult EVResult;
8899     if (!OrderedLoopCountExpr->isValueDependent() &&
8900         OrderedLoopCountExpr->EvaluateAsInt(EVResult,
8901                                             SemaRef.getASTContext())) {
8902       llvm::APSInt Result = EVResult.Val.getInt();
8903       if (Result.getLimitedValue() < NestedLoopCount) {
8904         SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
8905                      diag::err_omp_wrong_ordered_loop_count)
8906             << OrderedLoopCountExpr->getSourceRange();
8907         SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
8908                      diag::note_collapse_loop_count)
8909             << CollapseLoopCountExpr->getSourceRange();
8910       }
8911       OrderedLoopCount = Result.getLimitedValue();
8912     } else {
8913       Built.clear(/*Size=*/1);
8914       return 1;
8915     }
8916   }
8917   // This is helper routine for loop directives (e.g., 'for', 'simd',
8918   // 'for simd', etc.).
8919   llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
8920   unsigned NumLoops = std::max(OrderedLoopCount, NestedLoopCount);
8921   SmallVector<LoopIterationSpace, 4> IterSpaces(NumLoops);
8922   if (!OMPLoopBasedDirective::doForAllLoops(
8923           AStmt->IgnoreContainers(!isOpenMPLoopTransformationDirective(DKind)),
8924           SupportsNonPerfectlyNested, NumLoops,
8925           [DKind, &SemaRef, &DSA, NumLoops, NestedLoopCount,
8926            CollapseLoopCountExpr, OrderedLoopCountExpr, &VarsWithImplicitDSA,
8927            &IterSpaces, &Captures](unsigned Cnt, Stmt *CurStmt) {
8928             if (checkOpenMPIterationSpace(
8929                     DKind, CurStmt, SemaRef, DSA, Cnt, NestedLoopCount,
8930                     NumLoops, CollapseLoopCountExpr, OrderedLoopCountExpr,
8931                     VarsWithImplicitDSA, IterSpaces, Captures))
8932               return true;
8933             if (Cnt > 0 && Cnt >= NestedLoopCount &&
8934                 IterSpaces[Cnt].CounterVar) {
8935               // Handle initialization of captured loop iterator variables.
8936               auto *DRE = cast<DeclRefExpr>(IterSpaces[Cnt].CounterVar);
8937               if (isa<OMPCapturedExprDecl>(DRE->getDecl())) {
8938                 Captures[DRE] = DRE;
8939               }
8940             }
8941             return false;
8942           }))
8943     return 0;
8944 
8945   Built.clear(/* size */ NestedLoopCount);
8946 
8947   if (SemaRef.CurContext->isDependentContext())
8948     return NestedLoopCount;
8949 
8950   // An example of what is generated for the following code:
8951   //
8952   //   #pragma omp simd collapse(2) ordered(2)
8953   //   for (i = 0; i < NI; ++i)
8954   //     for (k = 0; k < NK; ++k)
8955   //       for (j = J0; j < NJ; j+=2) {
8956   //         <loop body>
8957   //       }
8958   //
8959   // We generate the code below.
8960   // Note: the loop body may be outlined in CodeGen.
8961   // Note: some counters may be C++ classes, operator- is used to find number of
8962   // iterations and operator+= to calculate counter value.
8963   // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32
8964   // or i64 is currently supported).
8965   //
8966   //   #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2))
8967   //   for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) {
8968   //     .local.i = IV / ((NJ - J0 - 1 + 2) / 2);
8969   //     .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2;
8970   //     // similar updates for vars in clauses (e.g. 'linear')
8971   //     <loop body (using local i and j)>
8972   //   }
8973   //   i = NI; // assign final values of counters
8974   //   j = NJ;
8975   //
8976 
8977   // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are
8978   // the iteration counts of the collapsed for loops.
8979   // Precondition tests if there is at least one iteration (all conditions are
8980   // true).
8981   auto PreCond = ExprResult(IterSpaces[0].PreCond);
8982   Expr *N0 = IterSpaces[0].NumIterations;
8983   ExprResult LastIteration32 =
8984       widenIterationCount(/*Bits=*/32,
8985                           SemaRef
8986                               .PerformImplicitConversion(
8987                                   N0->IgnoreImpCasts(), N0->getType(),
8988                                   Sema::AA_Converting, /*AllowExplicit=*/true)
8989                               .get(),
8990                           SemaRef);
8991   ExprResult LastIteration64 = widenIterationCount(
8992       /*Bits=*/64,
8993       SemaRef
8994           .PerformImplicitConversion(N0->IgnoreImpCasts(), N0->getType(),
8995                                      Sema::AA_Converting,
8996                                      /*AllowExplicit=*/true)
8997           .get(),
8998       SemaRef);
8999 
9000   if (!LastIteration32.isUsable() || !LastIteration64.isUsable())
9001     return NestedLoopCount;
9002 
9003   ASTContext &C = SemaRef.Context;
9004   bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32;
9005 
9006   Scope *CurScope = DSA.getCurScope();
9007   for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) {
9008     if (PreCond.isUsable()) {
9009       PreCond =
9010           SemaRef.BuildBinOp(CurScope, PreCond.get()->getExprLoc(), BO_LAnd,
9011                              PreCond.get(), IterSpaces[Cnt].PreCond);
9012     }
9013     Expr *N = IterSpaces[Cnt].NumIterations;
9014     SourceLocation Loc = N->getExprLoc();
9015     AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32;
9016     if (LastIteration32.isUsable())
9017       LastIteration32 = SemaRef.BuildBinOp(
9018           CurScope, Loc, BO_Mul, LastIteration32.get(),
9019           SemaRef
9020               .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
9021                                          Sema::AA_Converting,
9022                                          /*AllowExplicit=*/true)
9023               .get());
9024     if (LastIteration64.isUsable())
9025       LastIteration64 = SemaRef.BuildBinOp(
9026           CurScope, Loc, BO_Mul, LastIteration64.get(),
9027           SemaRef
9028               .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
9029                                          Sema::AA_Converting,
9030                                          /*AllowExplicit=*/true)
9031               .get());
9032   }
9033 
9034   // Choose either the 32-bit or 64-bit version.
9035   ExprResult LastIteration = LastIteration64;
9036   if (SemaRef.getLangOpts().OpenMPOptimisticCollapse ||
9037       (LastIteration32.isUsable() &&
9038        C.getTypeSize(LastIteration32.get()->getType()) == 32 &&
9039        (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 ||
9040         fitsInto(
9041             /*Bits=*/32,
9042             LastIteration32.get()->getType()->hasSignedIntegerRepresentation(),
9043             LastIteration64.get(), SemaRef))))
9044     LastIteration = LastIteration32;
9045   QualType VType = LastIteration.get()->getType();
9046   QualType RealVType = VType;
9047   QualType StrideVType = VType;
9048   if (isOpenMPTaskLoopDirective(DKind)) {
9049     VType =
9050         SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
9051     StrideVType =
9052         SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
9053   }
9054 
9055   if (!LastIteration.isUsable())
9056     return 0;
9057 
9058   // Save the number of iterations.
9059   ExprResult NumIterations = LastIteration;
9060   {
9061     LastIteration = SemaRef.BuildBinOp(
9062         CurScope, LastIteration.get()->getExprLoc(), BO_Sub,
9063         LastIteration.get(),
9064         SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
9065     if (!LastIteration.isUsable())
9066       return 0;
9067   }
9068 
9069   // Calculate the last iteration number beforehand instead of doing this on
9070   // each iteration. Do not do this if the number of iterations may be kfold-ed.
9071   bool IsConstant = LastIteration.get()->isIntegerConstantExpr(SemaRef.Context);
9072   ExprResult CalcLastIteration;
9073   if (!IsConstant) {
9074     ExprResult SaveRef =
9075         tryBuildCapture(SemaRef, LastIteration.get(), Captures);
9076     LastIteration = SaveRef;
9077 
9078     // Prepare SaveRef + 1.
9079     NumIterations = SemaRef.BuildBinOp(
9080         CurScope, SaveRef.get()->getExprLoc(), BO_Add, SaveRef.get(),
9081         SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
9082     if (!NumIterations.isUsable())
9083       return 0;
9084   }
9085 
9086   SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin();
9087 
9088   // Build variables passed into runtime, necessary for worksharing directives.
9089   ExprResult LB, UB, IL, ST, EUB, CombLB, CombUB, PrevLB, PrevUB, CombEUB;
9090   if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
9091       isOpenMPDistributeDirective(DKind) ||
9092       isOpenMPLoopTransformationDirective(DKind)) {
9093     // Lower bound variable, initialized with zero.
9094     VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb");
9095     LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc);
9096     SemaRef.AddInitializerToDecl(LBDecl,
9097                                  SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
9098                                  /*DirectInit*/ false);
9099 
9100     // Upper bound variable, initialized with last iteration number.
9101     VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub");
9102     UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc);
9103     SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(),
9104                                  /*DirectInit*/ false);
9105 
9106     // A 32-bit variable-flag where runtime returns 1 for the last iteration.
9107     // This will be used to implement clause 'lastprivate'.
9108     QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true);
9109     VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last");
9110     IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc);
9111     SemaRef.AddInitializerToDecl(ILDecl,
9112                                  SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
9113                                  /*DirectInit*/ false);
9114 
9115     // Stride variable returned by runtime (we initialize it to 1 by default).
9116     VarDecl *STDecl =
9117         buildVarDecl(SemaRef, InitLoc, StrideVType, ".omp.stride");
9118     ST = buildDeclRefExpr(SemaRef, STDecl, StrideVType, InitLoc);
9119     SemaRef.AddInitializerToDecl(STDecl,
9120                                  SemaRef.ActOnIntegerConstant(InitLoc, 1).get(),
9121                                  /*DirectInit*/ false);
9122 
9123     // Build expression: UB = min(UB, LastIteration)
9124     // It is necessary for CodeGen of directives with static scheduling.
9125     ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT,
9126                                                 UB.get(), LastIteration.get());
9127     ExprResult CondOp = SemaRef.ActOnConditionalOp(
9128         LastIteration.get()->getExprLoc(), InitLoc, IsUBGreater.get(),
9129         LastIteration.get(), UB.get());
9130     EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(),
9131                              CondOp.get());
9132     EUB = SemaRef.ActOnFinishFullExpr(EUB.get(), /*DiscardedValue*/ false);
9133 
9134     // If we have a combined directive that combines 'distribute', 'for' or
9135     // 'simd' we need to be able to access the bounds of the schedule of the
9136     // enclosing region. E.g. in 'distribute parallel for' the bounds obtained
9137     // by scheduling 'distribute' have to be passed to the schedule of 'for'.
9138     if (isOpenMPLoopBoundSharingDirective(DKind)) {
9139       // Lower bound variable, initialized with zero.
9140       VarDecl *CombLBDecl =
9141           buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.lb");
9142       CombLB = buildDeclRefExpr(SemaRef, CombLBDecl, VType, InitLoc);
9143       SemaRef.AddInitializerToDecl(
9144           CombLBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
9145           /*DirectInit*/ false);
9146 
9147       // Upper bound variable, initialized with last iteration number.
9148       VarDecl *CombUBDecl =
9149           buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.ub");
9150       CombUB = buildDeclRefExpr(SemaRef, CombUBDecl, VType, InitLoc);
9151       SemaRef.AddInitializerToDecl(CombUBDecl, LastIteration.get(),
9152                                    /*DirectInit*/ false);
9153 
9154       ExprResult CombIsUBGreater = SemaRef.BuildBinOp(
9155           CurScope, InitLoc, BO_GT, CombUB.get(), LastIteration.get());
9156       ExprResult CombCondOp =
9157           SemaRef.ActOnConditionalOp(InitLoc, InitLoc, CombIsUBGreater.get(),
9158                                      LastIteration.get(), CombUB.get());
9159       CombEUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, CombUB.get(),
9160                                    CombCondOp.get());
9161       CombEUB =
9162           SemaRef.ActOnFinishFullExpr(CombEUB.get(), /*DiscardedValue*/ false);
9163 
9164       const CapturedDecl *CD = cast<CapturedStmt>(AStmt)->getCapturedDecl();
9165       // We expect to have at least 2 more parameters than the 'parallel'
9166       // directive does - the lower and upper bounds of the previous schedule.
9167       assert(CD->getNumParams() >= 4 &&
9168              "Unexpected number of parameters in loop combined directive");
9169 
9170       // Set the proper type for the bounds given what we learned from the
9171       // enclosed loops.
9172       ImplicitParamDecl *PrevLBDecl = CD->getParam(/*PrevLB=*/2);
9173       ImplicitParamDecl *PrevUBDecl = CD->getParam(/*PrevUB=*/3);
9174 
9175       // Previous lower and upper bounds are obtained from the region
9176       // parameters.
9177       PrevLB =
9178           buildDeclRefExpr(SemaRef, PrevLBDecl, PrevLBDecl->getType(), InitLoc);
9179       PrevUB =
9180           buildDeclRefExpr(SemaRef, PrevUBDecl, PrevUBDecl->getType(), InitLoc);
9181     }
9182   }
9183 
9184   // Build the iteration variable and its initialization before loop.
9185   ExprResult IV;
9186   ExprResult Init, CombInit;
9187   {
9188     VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, RealVType, ".omp.iv");
9189     IV = buildDeclRefExpr(SemaRef, IVDecl, RealVType, InitLoc);
9190     Expr *RHS = (isOpenMPWorksharingDirective(DKind) ||
9191                  isOpenMPTaskLoopDirective(DKind) ||
9192                  isOpenMPDistributeDirective(DKind) ||
9193                  isOpenMPLoopTransformationDirective(DKind))
9194                     ? LB.get()
9195                     : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
9196     Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS);
9197     Init = SemaRef.ActOnFinishFullExpr(Init.get(), /*DiscardedValue*/ false);
9198 
9199     if (isOpenMPLoopBoundSharingDirective(DKind)) {
9200       Expr *CombRHS =
9201           (isOpenMPWorksharingDirective(DKind) ||
9202            isOpenMPTaskLoopDirective(DKind) ||
9203            isOpenMPDistributeDirective(DKind))
9204               ? CombLB.get()
9205               : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
9206       CombInit =
9207           SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), CombRHS);
9208       CombInit =
9209           SemaRef.ActOnFinishFullExpr(CombInit.get(), /*DiscardedValue*/ false);
9210     }
9211   }
9212 
9213   bool UseStrictCompare =
9214       RealVType->hasUnsignedIntegerRepresentation() &&
9215       llvm::all_of(IterSpaces, [](const LoopIterationSpace &LIS) {
9216         return LIS.IsStrictCompare;
9217       });
9218   // Loop condition (IV < NumIterations) or (IV <= UB or IV < UB + 1 (for
9219   // unsigned IV)) for worksharing loops.
9220   SourceLocation CondLoc = AStmt->getBeginLoc();
9221   Expr *BoundUB = UB.get();
9222   if (UseStrictCompare) {
9223     BoundUB =
9224         SemaRef
9225             .BuildBinOp(CurScope, CondLoc, BO_Add, BoundUB,
9226                         SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
9227             .get();
9228     BoundUB =
9229         SemaRef.ActOnFinishFullExpr(BoundUB, /*DiscardedValue*/ false).get();
9230   }
9231   ExprResult Cond =
9232       (isOpenMPWorksharingDirective(DKind) ||
9233        isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind) ||
9234        isOpenMPLoopTransformationDirective(DKind))
9235           ? SemaRef.BuildBinOp(CurScope, CondLoc,
9236                                UseStrictCompare ? BO_LT : BO_LE, IV.get(),
9237                                BoundUB)
9238           : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
9239                                NumIterations.get());
9240   ExprResult CombDistCond;
9241   if (isOpenMPLoopBoundSharingDirective(DKind)) {
9242     CombDistCond = SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
9243                                       NumIterations.get());
9244   }
9245 
9246   ExprResult CombCond;
9247   if (isOpenMPLoopBoundSharingDirective(DKind)) {
9248     Expr *BoundCombUB = CombUB.get();
9249     if (UseStrictCompare) {
9250       BoundCombUB =
9251           SemaRef
9252               .BuildBinOp(
9253                   CurScope, CondLoc, BO_Add, BoundCombUB,
9254                   SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
9255               .get();
9256       BoundCombUB =
9257           SemaRef.ActOnFinishFullExpr(BoundCombUB, /*DiscardedValue*/ false)
9258               .get();
9259     }
9260     CombCond =
9261         SemaRef.BuildBinOp(CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE,
9262                            IV.get(), BoundCombUB);
9263   }
9264   // Loop increment (IV = IV + 1)
9265   SourceLocation IncLoc = AStmt->getBeginLoc();
9266   ExprResult Inc =
9267       SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(),
9268                          SemaRef.ActOnIntegerConstant(IncLoc, 1).get());
9269   if (!Inc.isUsable())
9270     return 0;
9271   Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get());
9272   Inc = SemaRef.ActOnFinishFullExpr(Inc.get(), /*DiscardedValue*/ false);
9273   if (!Inc.isUsable())
9274     return 0;
9275 
9276   // Increments for worksharing loops (LB = LB + ST; UB = UB + ST).
9277   // Used for directives with static scheduling.
9278   // In combined construct, add combined version that use CombLB and CombUB
9279   // base variables for the update
9280   ExprResult NextLB, NextUB, CombNextLB, CombNextUB;
9281   if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
9282       isOpenMPDistributeDirective(DKind) ||
9283       isOpenMPLoopTransformationDirective(DKind)) {
9284     // LB + ST
9285     NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get());
9286     if (!NextLB.isUsable())
9287       return 0;
9288     // LB = LB + ST
9289     NextLB =
9290         SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get());
9291     NextLB =
9292         SemaRef.ActOnFinishFullExpr(NextLB.get(), /*DiscardedValue*/ false);
9293     if (!NextLB.isUsable())
9294       return 0;
9295     // UB + ST
9296     NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get());
9297     if (!NextUB.isUsable())
9298       return 0;
9299     // UB = UB + ST
9300     NextUB =
9301         SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get());
9302     NextUB =
9303         SemaRef.ActOnFinishFullExpr(NextUB.get(), /*DiscardedValue*/ false);
9304     if (!NextUB.isUsable())
9305       return 0;
9306     if (isOpenMPLoopBoundSharingDirective(DKind)) {
9307       CombNextLB =
9308           SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombLB.get(), ST.get());
9309       if (!NextLB.isUsable())
9310         return 0;
9311       // LB = LB + ST
9312       CombNextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombLB.get(),
9313                                       CombNextLB.get());
9314       CombNextLB = SemaRef.ActOnFinishFullExpr(CombNextLB.get(),
9315                                                /*DiscardedValue*/ false);
9316       if (!CombNextLB.isUsable())
9317         return 0;
9318       // UB + ST
9319       CombNextUB =
9320           SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombUB.get(), ST.get());
9321       if (!CombNextUB.isUsable())
9322         return 0;
9323       // UB = UB + ST
9324       CombNextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombUB.get(),
9325                                       CombNextUB.get());
9326       CombNextUB = SemaRef.ActOnFinishFullExpr(CombNextUB.get(),
9327                                                /*DiscardedValue*/ false);
9328       if (!CombNextUB.isUsable())
9329         return 0;
9330     }
9331   }
9332 
9333   // Create increment expression for distribute loop when combined in a same
9334   // directive with for as IV = IV + ST; ensure upper bound expression based
9335   // on PrevUB instead of NumIterations - used to implement 'for' when found
9336   // in combination with 'distribute', like in 'distribute parallel for'
9337   SourceLocation DistIncLoc = AStmt->getBeginLoc();
9338   ExprResult DistCond, DistInc, PrevEUB, ParForInDistCond;
9339   if (isOpenMPLoopBoundSharingDirective(DKind)) {
9340     DistCond = SemaRef.BuildBinOp(
9341         CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE, IV.get(), BoundUB);
9342     assert(DistCond.isUsable() && "distribute cond expr was not built");
9343 
9344     DistInc =
9345         SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Add, IV.get(), ST.get());
9346     assert(DistInc.isUsable() && "distribute inc expr was not built");
9347     DistInc = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, IV.get(),
9348                                  DistInc.get());
9349     DistInc =
9350         SemaRef.ActOnFinishFullExpr(DistInc.get(), /*DiscardedValue*/ false);
9351     assert(DistInc.isUsable() && "distribute inc expr was not built");
9352 
9353     // Build expression: UB = min(UB, prevUB) for #for in composite or combined
9354     // construct
9355     SourceLocation DistEUBLoc = AStmt->getBeginLoc();
9356     ExprResult IsUBGreater =
9357         SemaRef.BuildBinOp(CurScope, DistEUBLoc, BO_GT, UB.get(), PrevUB.get());
9358     ExprResult CondOp = SemaRef.ActOnConditionalOp(
9359         DistEUBLoc, DistEUBLoc, IsUBGreater.get(), PrevUB.get(), UB.get());
9360     PrevEUB = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, UB.get(),
9361                                  CondOp.get());
9362     PrevEUB =
9363         SemaRef.ActOnFinishFullExpr(PrevEUB.get(), /*DiscardedValue*/ false);
9364 
9365     // Build IV <= PrevUB or IV < PrevUB + 1 for unsigned IV to be used in
9366     // parallel for is in combination with a distribute directive with
9367     // schedule(static, 1)
9368     Expr *BoundPrevUB = PrevUB.get();
9369     if (UseStrictCompare) {
9370       BoundPrevUB =
9371           SemaRef
9372               .BuildBinOp(
9373                   CurScope, CondLoc, BO_Add, BoundPrevUB,
9374                   SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
9375               .get();
9376       BoundPrevUB =
9377           SemaRef.ActOnFinishFullExpr(BoundPrevUB, /*DiscardedValue*/ false)
9378               .get();
9379     }
9380     ParForInDistCond =
9381         SemaRef.BuildBinOp(CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE,
9382                            IV.get(), BoundPrevUB);
9383   }
9384 
9385   // Build updates and final values of the loop counters.
9386   bool HasErrors = false;
9387   Built.Counters.resize(NestedLoopCount);
9388   Built.Inits.resize(NestedLoopCount);
9389   Built.Updates.resize(NestedLoopCount);
9390   Built.Finals.resize(NestedLoopCount);
9391   Built.DependentCounters.resize(NestedLoopCount);
9392   Built.DependentInits.resize(NestedLoopCount);
9393   Built.FinalsConditions.resize(NestedLoopCount);
9394   {
9395     // We implement the following algorithm for obtaining the
9396     // original loop iteration variable values based on the
9397     // value of the collapsed loop iteration variable IV.
9398     //
9399     // Let n+1 be the number of collapsed loops in the nest.
9400     // Iteration variables (I0, I1, .... In)
9401     // Iteration counts (N0, N1, ... Nn)
9402     //
9403     // Acc = IV;
9404     //
9405     // To compute Ik for loop k, 0 <= k <= n, generate:
9406     //    Prod = N(k+1) * N(k+2) * ... * Nn;
9407     //    Ik = Acc / Prod;
9408     //    Acc -= Ik * Prod;
9409     //
9410     ExprResult Acc = IV;
9411     for (unsigned int Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
9412       LoopIterationSpace &IS = IterSpaces[Cnt];
9413       SourceLocation UpdLoc = IS.IncSrcRange.getBegin();
9414       ExprResult Iter;
9415 
9416       // Compute prod
9417       ExprResult Prod =
9418           SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
9419       for (unsigned int K = Cnt+1; K < NestedLoopCount; ++K)
9420         Prod = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Prod.get(),
9421                                   IterSpaces[K].NumIterations);
9422 
9423       // Iter = Acc / Prod
9424       // If there is at least one more inner loop to avoid
9425       // multiplication by 1.
9426       if (Cnt + 1 < NestedLoopCount)
9427         Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div,
9428                                   Acc.get(), Prod.get());
9429       else
9430         Iter = Acc;
9431       if (!Iter.isUsable()) {
9432         HasErrors = true;
9433         break;
9434       }
9435 
9436       // Update Acc:
9437       // Acc -= Iter * Prod
9438       // Check if there is at least one more inner loop to avoid
9439       // multiplication by 1.
9440       if (Cnt + 1 < NestedLoopCount)
9441         Prod = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul,
9442                                   Iter.get(), Prod.get());
9443       else
9444         Prod = Iter;
9445       Acc = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Sub,
9446                                Acc.get(), Prod.get());
9447 
9448       // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step
9449       auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl());
9450       DeclRefExpr *CounterVar = buildDeclRefExpr(
9451           SemaRef, VD, IS.CounterVar->getType(), IS.CounterVar->getExprLoc(),
9452           /*RefersToCapture=*/true);
9453       ExprResult Init =
9454           buildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar,
9455                            IS.CounterInit, IS.IsNonRectangularLB, Captures);
9456       if (!Init.isUsable()) {
9457         HasErrors = true;
9458         break;
9459       }
9460       ExprResult Update = buildCounterUpdate(
9461           SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, Iter,
9462           IS.CounterStep, IS.Subtract, IS.IsNonRectangularLB, &Captures);
9463       if (!Update.isUsable()) {
9464         HasErrors = true;
9465         break;
9466       }
9467 
9468       // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step
9469       ExprResult Final =
9470           buildCounterUpdate(SemaRef, CurScope, UpdLoc, CounterVar,
9471                              IS.CounterInit, IS.NumIterations, IS.CounterStep,
9472                              IS.Subtract, IS.IsNonRectangularLB, &Captures);
9473       if (!Final.isUsable()) {
9474         HasErrors = true;
9475         break;
9476       }
9477 
9478       if (!Update.isUsable() || !Final.isUsable()) {
9479         HasErrors = true;
9480         break;
9481       }
9482       // Save results
9483       Built.Counters[Cnt] = IS.CounterVar;
9484       Built.PrivateCounters[Cnt] = IS.PrivateCounterVar;
9485       Built.Inits[Cnt] = Init.get();
9486       Built.Updates[Cnt] = Update.get();
9487       Built.Finals[Cnt] = Final.get();
9488       Built.DependentCounters[Cnt] = nullptr;
9489       Built.DependentInits[Cnt] = nullptr;
9490       Built.FinalsConditions[Cnt] = nullptr;
9491       if (IS.IsNonRectangularLB || IS.IsNonRectangularUB) {
9492         Built.DependentCounters[Cnt] =
9493             Built.Counters[NestedLoopCount - 1 - IS.LoopDependentIdx];
9494         Built.DependentInits[Cnt] =
9495             Built.Inits[NestedLoopCount - 1 - IS.LoopDependentIdx];
9496         Built.FinalsConditions[Cnt] = IS.FinalCondition;
9497       }
9498     }
9499   }
9500 
9501   if (HasErrors)
9502     return 0;
9503 
9504   // Save results
9505   Built.IterationVarRef = IV.get();
9506   Built.LastIteration = LastIteration.get();
9507   Built.NumIterations = NumIterations.get();
9508   Built.CalcLastIteration = SemaRef
9509                                 .ActOnFinishFullExpr(CalcLastIteration.get(),
9510                                                      /*DiscardedValue=*/false)
9511                                 .get();
9512   Built.PreCond = PreCond.get();
9513   Built.PreInits = buildPreInits(C, Captures);
9514   Built.Cond = Cond.get();
9515   Built.Init = Init.get();
9516   Built.Inc = Inc.get();
9517   Built.LB = LB.get();
9518   Built.UB = UB.get();
9519   Built.IL = IL.get();
9520   Built.ST = ST.get();
9521   Built.EUB = EUB.get();
9522   Built.NLB = NextLB.get();
9523   Built.NUB = NextUB.get();
9524   Built.PrevLB = PrevLB.get();
9525   Built.PrevUB = PrevUB.get();
9526   Built.DistInc = DistInc.get();
9527   Built.PrevEUB = PrevEUB.get();
9528   Built.DistCombinedFields.LB = CombLB.get();
9529   Built.DistCombinedFields.UB = CombUB.get();
9530   Built.DistCombinedFields.EUB = CombEUB.get();
9531   Built.DistCombinedFields.Init = CombInit.get();
9532   Built.DistCombinedFields.Cond = CombCond.get();
9533   Built.DistCombinedFields.NLB = CombNextLB.get();
9534   Built.DistCombinedFields.NUB = CombNextUB.get();
9535   Built.DistCombinedFields.DistCond = CombDistCond.get();
9536   Built.DistCombinedFields.ParForInDistCond = ParForInDistCond.get();
9537 
9538   return NestedLoopCount;
9539 }
9540 
9541 static Expr *getCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) {
9542   auto CollapseClauses =
9543       OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses);
9544   if (CollapseClauses.begin() != CollapseClauses.end())
9545     return (*CollapseClauses.begin())->getNumForLoops();
9546   return nullptr;
9547 }
9548 
9549 static Expr *getOrderedNumberExpr(ArrayRef<OMPClause *> Clauses) {
9550   auto OrderedClauses =
9551       OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses);
9552   if (OrderedClauses.begin() != OrderedClauses.end())
9553     return (*OrderedClauses.begin())->getNumForLoops();
9554   return nullptr;
9555 }
9556 
9557 static bool checkSimdlenSafelenSpecified(Sema &S,
9558                                          const ArrayRef<OMPClause *> Clauses) {
9559   const OMPSafelenClause *Safelen = nullptr;
9560   const OMPSimdlenClause *Simdlen = nullptr;
9561 
9562   for (const OMPClause *Clause : Clauses) {
9563     if (Clause->getClauseKind() == OMPC_safelen)
9564       Safelen = cast<OMPSafelenClause>(Clause);
9565     else if (Clause->getClauseKind() == OMPC_simdlen)
9566       Simdlen = cast<OMPSimdlenClause>(Clause);
9567     if (Safelen && Simdlen)
9568       break;
9569   }
9570 
9571   if (Simdlen && Safelen) {
9572     const Expr *SimdlenLength = Simdlen->getSimdlen();
9573     const Expr *SafelenLength = Safelen->getSafelen();
9574     if (SimdlenLength->isValueDependent() || SimdlenLength->isTypeDependent() ||
9575         SimdlenLength->isInstantiationDependent() ||
9576         SimdlenLength->containsUnexpandedParameterPack())
9577       return false;
9578     if (SafelenLength->isValueDependent() || SafelenLength->isTypeDependent() ||
9579         SafelenLength->isInstantiationDependent() ||
9580         SafelenLength->containsUnexpandedParameterPack())
9581       return false;
9582     Expr::EvalResult SimdlenResult, SafelenResult;
9583     SimdlenLength->EvaluateAsInt(SimdlenResult, S.Context);
9584     SafelenLength->EvaluateAsInt(SafelenResult, S.Context);
9585     llvm::APSInt SimdlenRes = SimdlenResult.Val.getInt();
9586     llvm::APSInt SafelenRes = SafelenResult.Val.getInt();
9587     // OpenMP 4.5 [2.8.1, simd Construct, Restrictions]
9588     // If both simdlen and safelen clauses are specified, the value of the
9589     // simdlen parameter must be less than or equal to the value of the safelen
9590     // parameter.
9591     if (SimdlenRes > SafelenRes) {
9592       S.Diag(SimdlenLength->getExprLoc(),
9593              diag::err_omp_wrong_simdlen_safelen_values)
9594           << SimdlenLength->getSourceRange() << SafelenLength->getSourceRange();
9595       return true;
9596     }
9597   }
9598   return false;
9599 }
9600 
9601 StmtResult
9602 Sema::ActOnOpenMPSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
9603                                SourceLocation StartLoc, SourceLocation EndLoc,
9604                                VarsWithInheritedDSAType &VarsWithImplicitDSA) {
9605   if (!AStmt)
9606     return StmtError();
9607 
9608   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
9609   OMPLoopBasedDirective::HelperExprs B;
9610   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
9611   // define the nested loops number.
9612   unsigned NestedLoopCount = checkOpenMPLoop(
9613       OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
9614       AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
9615   if (NestedLoopCount == 0)
9616     return StmtError();
9617 
9618   assert((CurContext->isDependentContext() || B.builtAll()) &&
9619          "omp simd loop exprs were not built");
9620 
9621   if (!CurContext->isDependentContext()) {
9622     // Finalize the clauses that need pre-built expressions for CodeGen.
9623     for (OMPClause *C : Clauses) {
9624       if (auto *LC = dyn_cast<OMPLinearClause>(C))
9625         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
9626                                      B.NumIterations, *this, CurScope,
9627                                      DSAStack))
9628           return StmtError();
9629     }
9630   }
9631 
9632   if (checkSimdlenSafelenSpecified(*this, Clauses))
9633     return StmtError();
9634 
9635   setFunctionHasBranchProtectedScope();
9636   return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
9637                                   Clauses, AStmt, B);
9638 }
9639 
9640 StmtResult
9641 Sema::ActOnOpenMPForDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
9642                               SourceLocation StartLoc, SourceLocation EndLoc,
9643                               VarsWithInheritedDSAType &VarsWithImplicitDSA) {
9644   if (!AStmt)
9645     return StmtError();
9646 
9647   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
9648   OMPLoopBasedDirective::HelperExprs B;
9649   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
9650   // define the nested loops number.
9651   unsigned NestedLoopCount = checkOpenMPLoop(
9652       OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
9653       AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
9654   if (NestedLoopCount == 0)
9655     return StmtError();
9656 
9657   assert((CurContext->isDependentContext() || B.builtAll()) &&
9658          "omp for loop exprs were not built");
9659 
9660   if (!CurContext->isDependentContext()) {
9661     // Finalize the clauses that need pre-built expressions for CodeGen.
9662     for (OMPClause *C : Clauses) {
9663       if (auto *LC = dyn_cast<OMPLinearClause>(C))
9664         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
9665                                      B.NumIterations, *this, CurScope,
9666                                      DSAStack))
9667           return StmtError();
9668     }
9669   }
9670 
9671   setFunctionHasBranchProtectedScope();
9672   return OMPForDirective::Create(
9673       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
9674       DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion());
9675 }
9676 
9677 StmtResult Sema::ActOnOpenMPForSimdDirective(
9678     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
9679     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
9680   if (!AStmt)
9681     return StmtError();
9682 
9683   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
9684   OMPLoopBasedDirective::HelperExprs B;
9685   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
9686   // define the nested loops number.
9687   unsigned NestedLoopCount =
9688       checkOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses),
9689                       getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
9690                       VarsWithImplicitDSA, B);
9691   if (NestedLoopCount == 0)
9692     return StmtError();
9693 
9694   assert((CurContext->isDependentContext() || B.builtAll()) &&
9695          "omp for simd loop exprs were not built");
9696 
9697   if (!CurContext->isDependentContext()) {
9698     // Finalize the clauses that need pre-built expressions for CodeGen.
9699     for (OMPClause *C : Clauses) {
9700       if (auto *LC = dyn_cast<OMPLinearClause>(C))
9701         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
9702                                      B.NumIterations, *this, CurScope,
9703                                      DSAStack))
9704           return StmtError();
9705     }
9706   }
9707 
9708   if (checkSimdlenSafelenSpecified(*this, Clauses))
9709     return StmtError();
9710 
9711   setFunctionHasBranchProtectedScope();
9712   return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
9713                                      Clauses, AStmt, B);
9714 }
9715 
9716 StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
9717                                               Stmt *AStmt,
9718                                               SourceLocation StartLoc,
9719                                               SourceLocation EndLoc) {
9720   if (!AStmt)
9721     return StmtError();
9722 
9723   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
9724   auto BaseStmt = AStmt;
9725   while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
9726     BaseStmt = CS->getCapturedStmt();
9727   if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
9728     auto S = C->children();
9729     if (S.begin() == S.end())
9730       return StmtError();
9731     // All associated statements must be '#pragma omp section' except for
9732     // the first one.
9733     for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
9734       if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
9735         if (SectionStmt)
9736           Diag(SectionStmt->getBeginLoc(),
9737                diag::err_omp_sections_substmt_not_section);
9738         return StmtError();
9739       }
9740       cast<OMPSectionDirective>(SectionStmt)
9741           ->setHasCancel(DSAStack->isCancelRegion());
9742     }
9743   } else {
9744     Diag(AStmt->getBeginLoc(), diag::err_omp_sections_not_compound_stmt);
9745     return StmtError();
9746   }
9747 
9748   setFunctionHasBranchProtectedScope();
9749 
9750   return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
9751                                       DSAStack->getTaskgroupReductionRef(),
9752                                       DSAStack->isCancelRegion());
9753 }
9754 
9755 StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt,
9756                                              SourceLocation StartLoc,
9757                                              SourceLocation EndLoc) {
9758   if (!AStmt)
9759     return StmtError();
9760 
9761   setFunctionHasBranchProtectedScope();
9762   DSAStack->setParentCancelRegion(DSAStack->isCancelRegion());
9763 
9764   return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt,
9765                                      DSAStack->isCancelRegion());
9766 }
9767 
9768 static Expr *getDirectCallExpr(Expr *E) {
9769   E = E->IgnoreParenCasts()->IgnoreImplicit();
9770   if (auto *CE = dyn_cast<CallExpr>(E))
9771     if (CE->getDirectCallee())
9772       return E;
9773   return nullptr;
9774 }
9775 
9776 StmtResult Sema::ActOnOpenMPDispatchDirective(ArrayRef<OMPClause *> Clauses,
9777                                               Stmt *AStmt,
9778                                               SourceLocation StartLoc,
9779                                               SourceLocation EndLoc) {
9780   if (!AStmt)
9781     return StmtError();
9782 
9783   Stmt *S = cast<CapturedStmt>(AStmt)->getCapturedStmt();
9784 
9785   // 5.1 OpenMP
9786   // expression-stmt : an expression statement with one of the following forms:
9787   //   expression = target-call ( [expression-list] );
9788   //   target-call ( [expression-list] );
9789 
9790   SourceLocation TargetCallLoc;
9791 
9792   if (!CurContext->isDependentContext()) {
9793     Expr *TargetCall = nullptr;
9794 
9795     auto *E = dyn_cast<Expr>(S);
9796     if (!E) {
9797       Diag(S->getBeginLoc(), diag::err_omp_dispatch_statement_call);
9798       return StmtError();
9799     }
9800 
9801     E = E->IgnoreParenCasts()->IgnoreImplicit();
9802 
9803     if (auto *BO = dyn_cast<BinaryOperator>(E)) {
9804       if (BO->getOpcode() == BO_Assign)
9805         TargetCall = getDirectCallExpr(BO->getRHS());
9806     } else {
9807       if (auto *COCE = dyn_cast<CXXOperatorCallExpr>(E))
9808         if (COCE->getOperator() == OO_Equal)
9809           TargetCall = getDirectCallExpr(COCE->getArg(1));
9810       if (!TargetCall)
9811         TargetCall = getDirectCallExpr(E);
9812     }
9813     if (!TargetCall) {
9814       Diag(E->getBeginLoc(), diag::err_omp_dispatch_statement_call);
9815       return StmtError();
9816     }
9817     TargetCallLoc = TargetCall->getExprLoc();
9818   }
9819 
9820   setFunctionHasBranchProtectedScope();
9821 
9822   return OMPDispatchDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
9823                                       TargetCallLoc);
9824 }
9825 
9826 StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
9827                                             Stmt *AStmt,
9828                                             SourceLocation StartLoc,
9829                                             SourceLocation EndLoc) {
9830   if (!AStmt)
9831     return StmtError();
9832 
9833   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
9834 
9835   setFunctionHasBranchProtectedScope();
9836 
9837   // OpenMP [2.7.3, single Construct, Restrictions]
9838   // The copyprivate clause must not be used with the nowait clause.
9839   const OMPClause *Nowait = nullptr;
9840   const OMPClause *Copyprivate = nullptr;
9841   for (const OMPClause *Clause : Clauses) {
9842     if (Clause->getClauseKind() == OMPC_nowait)
9843       Nowait = Clause;
9844     else if (Clause->getClauseKind() == OMPC_copyprivate)
9845       Copyprivate = Clause;
9846     if (Copyprivate && Nowait) {
9847       Diag(Copyprivate->getBeginLoc(),
9848            diag::err_omp_single_copyprivate_with_nowait);
9849       Diag(Nowait->getBeginLoc(), diag::note_omp_nowait_clause_here);
9850       return StmtError();
9851     }
9852   }
9853 
9854   return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
9855 }
9856 
9857 StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt,
9858                                             SourceLocation StartLoc,
9859                                             SourceLocation EndLoc) {
9860   if (!AStmt)
9861     return StmtError();
9862 
9863   setFunctionHasBranchProtectedScope();
9864 
9865   return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt);
9866 }
9867 
9868 StmtResult Sema::ActOnOpenMPCriticalDirective(
9869     const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses,
9870     Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
9871   if (!AStmt)
9872     return StmtError();
9873 
9874   bool ErrorFound = false;
9875   llvm::APSInt Hint;
9876   SourceLocation HintLoc;
9877   bool DependentHint = false;
9878   for (const OMPClause *C : Clauses) {
9879     if (C->getClauseKind() == OMPC_hint) {
9880       if (!DirName.getName()) {
9881         Diag(C->getBeginLoc(), diag::err_omp_hint_clause_no_name);
9882         ErrorFound = true;
9883       }
9884       Expr *E = cast<OMPHintClause>(C)->getHint();
9885       if (E->isTypeDependent() || E->isValueDependent() ||
9886           E->isInstantiationDependent()) {
9887         DependentHint = true;
9888       } else {
9889         Hint = E->EvaluateKnownConstInt(Context);
9890         HintLoc = C->getBeginLoc();
9891       }
9892     }
9893   }
9894   if (ErrorFound)
9895     return StmtError();
9896   const auto Pair = DSAStack->getCriticalWithHint(DirName);
9897   if (Pair.first && DirName.getName() && !DependentHint) {
9898     if (llvm::APSInt::compareValues(Hint, Pair.second) != 0) {
9899       Diag(StartLoc, diag::err_omp_critical_with_hint);
9900       if (HintLoc.isValid())
9901         Diag(HintLoc, diag::note_omp_critical_hint_here)
9902             << 0 << Hint.toString(/*Radix=*/10, /*Signed=*/false);
9903       else
9904         Diag(StartLoc, diag::note_omp_critical_no_hint) << 0;
9905       if (const auto *C = Pair.first->getSingleClause<OMPHintClause>()) {
9906         Diag(C->getBeginLoc(), diag::note_omp_critical_hint_here)
9907             << 1
9908             << C->getHint()->EvaluateKnownConstInt(Context).toString(
9909                    /*Radix=*/10, /*Signed=*/false);
9910       } else {
9911         Diag(Pair.first->getBeginLoc(), diag::note_omp_critical_no_hint) << 1;
9912       }
9913     }
9914   }
9915 
9916   setFunctionHasBranchProtectedScope();
9917 
9918   auto *Dir = OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc,
9919                                            Clauses, AStmt);
9920   if (!Pair.first && DirName.getName() && !DependentHint)
9921     DSAStack->addCriticalWithHint(Dir, Hint);
9922   return Dir;
9923 }
9924 
9925 StmtResult Sema::ActOnOpenMPParallelForDirective(
9926     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
9927     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
9928   if (!AStmt)
9929     return StmtError();
9930 
9931   auto *CS = cast<CapturedStmt>(AStmt);
9932   // 1.2.2 OpenMP Language Terminology
9933   // Structured block - An executable statement with a single entry at the
9934   // top and a single exit at the bottom.
9935   // The point of exit cannot be a branch out of the structured block.
9936   // longjmp() and throw() must not violate the entry/exit criteria.
9937   CS->getCapturedDecl()->setNothrow();
9938 
9939   OMPLoopBasedDirective::HelperExprs B;
9940   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
9941   // define the nested loops number.
9942   unsigned NestedLoopCount =
9943       checkOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses),
9944                       getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
9945                       VarsWithImplicitDSA, B);
9946   if (NestedLoopCount == 0)
9947     return StmtError();
9948 
9949   assert((CurContext->isDependentContext() || B.builtAll()) &&
9950          "omp parallel for loop exprs were not built");
9951 
9952   if (!CurContext->isDependentContext()) {
9953     // Finalize the clauses that need pre-built expressions for CodeGen.
9954     for (OMPClause *C : Clauses) {
9955       if (auto *LC = dyn_cast<OMPLinearClause>(C))
9956         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
9957                                      B.NumIterations, *this, CurScope,
9958                                      DSAStack))
9959           return StmtError();
9960     }
9961   }
9962 
9963   setFunctionHasBranchProtectedScope();
9964   return OMPParallelForDirective::Create(
9965       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
9966       DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion());
9967 }
9968 
9969 StmtResult Sema::ActOnOpenMPParallelForSimdDirective(
9970     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
9971     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
9972   if (!AStmt)
9973     return StmtError();
9974 
9975   auto *CS = cast<CapturedStmt>(AStmt);
9976   // 1.2.2 OpenMP Language Terminology
9977   // Structured block - An executable statement with a single entry at the
9978   // top and a single exit at the bottom.
9979   // The point of exit cannot be a branch out of the structured block.
9980   // longjmp() and throw() must not violate the entry/exit criteria.
9981   CS->getCapturedDecl()->setNothrow();
9982 
9983   OMPLoopBasedDirective::HelperExprs B;
9984   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
9985   // define the nested loops number.
9986   unsigned NestedLoopCount =
9987       checkOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses),
9988                       getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
9989                       VarsWithImplicitDSA, B);
9990   if (NestedLoopCount == 0)
9991     return StmtError();
9992 
9993   if (!CurContext->isDependentContext()) {
9994     // Finalize the clauses that need pre-built expressions for CodeGen.
9995     for (OMPClause *C : Clauses) {
9996       if (auto *LC = dyn_cast<OMPLinearClause>(C))
9997         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
9998                                      B.NumIterations, *this, CurScope,
9999                                      DSAStack))
10000           return StmtError();
10001     }
10002   }
10003 
10004   if (checkSimdlenSafelenSpecified(*this, Clauses))
10005     return StmtError();
10006 
10007   setFunctionHasBranchProtectedScope();
10008   return OMPParallelForSimdDirective::Create(
10009       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
10010 }
10011 
10012 StmtResult
10013 Sema::ActOnOpenMPParallelMasterDirective(ArrayRef<OMPClause *> Clauses,
10014                                          Stmt *AStmt, SourceLocation StartLoc,
10015                                          SourceLocation EndLoc) {
10016   if (!AStmt)
10017     return StmtError();
10018 
10019   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
10020   auto *CS = cast<CapturedStmt>(AStmt);
10021   // 1.2.2 OpenMP Language Terminology
10022   // Structured block - An executable statement with a single entry at the
10023   // top and a single exit at the bottom.
10024   // The point of exit cannot be a branch out of the structured block.
10025   // longjmp() and throw() must not violate the entry/exit criteria.
10026   CS->getCapturedDecl()->setNothrow();
10027 
10028   setFunctionHasBranchProtectedScope();
10029 
10030   return OMPParallelMasterDirective::Create(
10031       Context, StartLoc, EndLoc, Clauses, AStmt,
10032       DSAStack->getTaskgroupReductionRef());
10033 }
10034 
10035 StmtResult
10036 Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
10037                                            Stmt *AStmt, SourceLocation StartLoc,
10038                                            SourceLocation EndLoc) {
10039   if (!AStmt)
10040     return StmtError();
10041 
10042   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
10043   auto BaseStmt = AStmt;
10044   while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
10045     BaseStmt = CS->getCapturedStmt();
10046   if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
10047     auto S = C->children();
10048     if (S.begin() == S.end())
10049       return StmtError();
10050     // All associated statements must be '#pragma omp section' except for
10051     // the first one.
10052     for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
10053       if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
10054         if (SectionStmt)
10055           Diag(SectionStmt->getBeginLoc(),
10056                diag::err_omp_parallel_sections_substmt_not_section);
10057         return StmtError();
10058       }
10059       cast<OMPSectionDirective>(SectionStmt)
10060           ->setHasCancel(DSAStack->isCancelRegion());
10061     }
10062   } else {
10063     Diag(AStmt->getBeginLoc(),
10064          diag::err_omp_parallel_sections_not_compound_stmt);
10065     return StmtError();
10066   }
10067 
10068   setFunctionHasBranchProtectedScope();
10069 
10070   return OMPParallelSectionsDirective::Create(
10071       Context, StartLoc, EndLoc, Clauses, AStmt,
10072       DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion());
10073 }
10074 
10075 /// detach and mergeable clauses are mutially exclusive, check for it.
10076 static bool checkDetachMergeableClauses(Sema &S,
10077                                         ArrayRef<OMPClause *> Clauses) {
10078   const OMPClause *PrevClause = nullptr;
10079   bool ErrorFound = false;
10080   for (const OMPClause *C : Clauses) {
10081     if (C->getClauseKind() == OMPC_detach ||
10082         C->getClauseKind() == OMPC_mergeable) {
10083       if (!PrevClause) {
10084         PrevClause = C;
10085       } else if (PrevClause->getClauseKind() != C->getClauseKind()) {
10086         S.Diag(C->getBeginLoc(), diag::err_omp_clauses_mutually_exclusive)
10087             << getOpenMPClauseName(C->getClauseKind())
10088             << getOpenMPClauseName(PrevClause->getClauseKind());
10089         S.Diag(PrevClause->getBeginLoc(), diag::note_omp_previous_clause)
10090             << getOpenMPClauseName(PrevClause->getClauseKind());
10091         ErrorFound = true;
10092       }
10093     }
10094   }
10095   return ErrorFound;
10096 }
10097 
10098 StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
10099                                           Stmt *AStmt, SourceLocation StartLoc,
10100                                           SourceLocation EndLoc) {
10101   if (!AStmt)
10102     return StmtError();
10103 
10104   // OpenMP 5.0, 2.10.1 task Construct
10105   // If a detach clause appears on the directive, then a mergeable clause cannot
10106   // appear on the same directive.
10107   if (checkDetachMergeableClauses(*this, Clauses))
10108     return StmtError();
10109 
10110   auto *CS = cast<CapturedStmt>(AStmt);
10111   // 1.2.2 OpenMP Language Terminology
10112   // Structured block - An executable statement with a single entry at the
10113   // top and a single exit at the bottom.
10114   // The point of exit cannot be a branch out of the structured block.
10115   // longjmp() and throw() must not violate the entry/exit criteria.
10116   CS->getCapturedDecl()->setNothrow();
10117 
10118   setFunctionHasBranchProtectedScope();
10119 
10120   return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
10121                                   DSAStack->isCancelRegion());
10122 }
10123 
10124 StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
10125                                                SourceLocation EndLoc) {
10126   return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc);
10127 }
10128 
10129 StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
10130                                              SourceLocation EndLoc) {
10131   return OMPBarrierDirective::Create(Context, StartLoc, EndLoc);
10132 }
10133 
10134 StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
10135                                               SourceLocation EndLoc) {
10136   return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc);
10137 }
10138 
10139 StmtResult Sema::ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses,
10140                                                Stmt *AStmt,
10141                                                SourceLocation StartLoc,
10142                                                SourceLocation EndLoc) {
10143   if (!AStmt)
10144     return StmtError();
10145 
10146   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
10147 
10148   setFunctionHasBranchProtectedScope();
10149 
10150   return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, Clauses,
10151                                        AStmt,
10152                                        DSAStack->getTaskgroupReductionRef());
10153 }
10154 
10155 StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
10156                                            SourceLocation StartLoc,
10157                                            SourceLocation EndLoc) {
10158   OMPFlushClause *FC = nullptr;
10159   OMPClause *OrderClause = nullptr;
10160   for (OMPClause *C : Clauses) {
10161     if (C->getClauseKind() == OMPC_flush)
10162       FC = cast<OMPFlushClause>(C);
10163     else
10164       OrderClause = C;
10165   }
10166   OpenMPClauseKind MemOrderKind = OMPC_unknown;
10167   SourceLocation MemOrderLoc;
10168   for (const OMPClause *C : Clauses) {
10169     if (C->getClauseKind() == OMPC_acq_rel ||
10170         C->getClauseKind() == OMPC_acquire ||
10171         C->getClauseKind() == OMPC_release) {
10172       if (MemOrderKind != OMPC_unknown) {
10173         Diag(C->getBeginLoc(), diag::err_omp_several_mem_order_clauses)
10174             << getOpenMPDirectiveName(OMPD_flush) << 1
10175             << SourceRange(C->getBeginLoc(), C->getEndLoc());
10176         Diag(MemOrderLoc, diag::note_omp_previous_mem_order_clause)
10177             << getOpenMPClauseName(MemOrderKind);
10178       } else {
10179         MemOrderKind = C->getClauseKind();
10180         MemOrderLoc = C->getBeginLoc();
10181       }
10182     }
10183   }
10184   if (FC && OrderClause) {
10185     Diag(FC->getLParenLoc(), diag::err_omp_flush_order_clause_and_list)
10186         << getOpenMPClauseName(OrderClause->getClauseKind());
10187     Diag(OrderClause->getBeginLoc(), diag::note_omp_flush_order_clause_here)
10188         << getOpenMPClauseName(OrderClause->getClauseKind());
10189     return StmtError();
10190   }
10191   return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses);
10192 }
10193 
10194 StmtResult Sema::ActOnOpenMPDepobjDirective(ArrayRef<OMPClause *> Clauses,
10195                                             SourceLocation StartLoc,
10196                                             SourceLocation EndLoc) {
10197   if (Clauses.empty()) {
10198     Diag(StartLoc, diag::err_omp_depobj_expected);
10199     return StmtError();
10200   } else if (Clauses[0]->getClauseKind() != OMPC_depobj) {
10201     Diag(Clauses[0]->getBeginLoc(), diag::err_omp_depobj_expected);
10202     return StmtError();
10203   }
10204   // Only depobj expression and another single clause is allowed.
10205   if (Clauses.size() > 2) {
10206     Diag(Clauses[2]->getBeginLoc(),
10207          diag::err_omp_depobj_single_clause_expected);
10208     return StmtError();
10209   } else if (Clauses.size() < 1) {
10210     Diag(Clauses[0]->getEndLoc(), diag::err_omp_depobj_single_clause_expected);
10211     return StmtError();
10212   }
10213   return OMPDepobjDirective::Create(Context, StartLoc, EndLoc, Clauses);
10214 }
10215 
10216 StmtResult Sema::ActOnOpenMPScanDirective(ArrayRef<OMPClause *> Clauses,
10217                                           SourceLocation StartLoc,
10218                                           SourceLocation EndLoc) {
10219   // Check that exactly one clause is specified.
10220   if (Clauses.size() != 1) {
10221     Diag(Clauses.empty() ? EndLoc : Clauses[1]->getBeginLoc(),
10222          diag::err_omp_scan_single_clause_expected);
10223     return StmtError();
10224   }
10225   // Check that scan directive is used in the scopeof the OpenMP loop body.
10226   if (Scope *S = DSAStack->getCurScope()) {
10227     Scope *ParentS = S->getParent();
10228     if (!ParentS || ParentS->getParent() != ParentS->getBreakParent() ||
10229         !ParentS->getBreakParent()->isOpenMPLoopScope())
10230       return StmtError(Diag(StartLoc, diag::err_omp_orphaned_device_directive)
10231                        << getOpenMPDirectiveName(OMPD_scan) << 5);
10232   }
10233   // Check that only one instance of scan directives is used in the same outer
10234   // region.
10235   if (DSAStack->doesParentHasScanDirective()) {
10236     Diag(StartLoc, diag::err_omp_several_directives_in_region) << "scan";
10237     Diag(DSAStack->getParentScanDirectiveLoc(),
10238          diag::note_omp_previous_directive)
10239         << "scan";
10240     return StmtError();
10241   }
10242   DSAStack->setParentHasScanDirective(StartLoc);
10243   return OMPScanDirective::Create(Context, StartLoc, EndLoc, Clauses);
10244 }
10245 
10246 StmtResult Sema::ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
10247                                              Stmt *AStmt,
10248                                              SourceLocation StartLoc,
10249                                              SourceLocation EndLoc) {
10250   const OMPClause *DependFound = nullptr;
10251   const OMPClause *DependSourceClause = nullptr;
10252   const OMPClause *DependSinkClause = nullptr;
10253   bool ErrorFound = false;
10254   const OMPThreadsClause *TC = nullptr;
10255   const OMPSIMDClause *SC = nullptr;
10256   for (const OMPClause *C : Clauses) {
10257     if (auto *DC = dyn_cast<OMPDependClause>(C)) {
10258       DependFound = C;
10259       if (DC->getDependencyKind() == OMPC_DEPEND_source) {
10260         if (DependSourceClause) {
10261           Diag(C->getBeginLoc(), diag::err_omp_more_one_clause)
10262               << getOpenMPDirectiveName(OMPD_ordered)
10263               << getOpenMPClauseName(OMPC_depend) << 2;
10264           ErrorFound = true;
10265         } else {
10266           DependSourceClause = C;
10267         }
10268         if (DependSinkClause) {
10269           Diag(C->getBeginLoc(), diag::err_omp_depend_sink_source_not_allowed)
10270               << 0;
10271           ErrorFound = true;
10272         }
10273       } else if (DC->getDependencyKind() == OMPC_DEPEND_sink) {
10274         if (DependSourceClause) {
10275           Diag(C->getBeginLoc(), diag::err_omp_depend_sink_source_not_allowed)
10276               << 1;
10277           ErrorFound = true;
10278         }
10279         DependSinkClause = C;
10280       }
10281     } else if (C->getClauseKind() == OMPC_threads) {
10282       TC = cast<OMPThreadsClause>(C);
10283     } else if (C->getClauseKind() == OMPC_simd) {
10284       SC = cast<OMPSIMDClause>(C);
10285     }
10286   }
10287   if (!ErrorFound && !SC &&
10288       isOpenMPSimdDirective(DSAStack->getParentDirective())) {
10289     // OpenMP [2.8.1,simd Construct, Restrictions]
10290     // An ordered construct with the simd clause is the only OpenMP construct
10291     // that can appear in the simd region.
10292     Diag(StartLoc, diag::err_omp_prohibited_region_simd)
10293         << (LangOpts.OpenMP >= 50 ? 1 : 0);
10294     ErrorFound = true;
10295   } else if (DependFound && (TC || SC)) {
10296     Diag(DependFound->getBeginLoc(), diag::err_omp_depend_clause_thread_simd)
10297         << getOpenMPClauseName(TC ? TC->getClauseKind() : SC->getClauseKind());
10298     ErrorFound = true;
10299   } else if (DependFound && !DSAStack->getParentOrderedRegionParam().first) {
10300     Diag(DependFound->getBeginLoc(),
10301          diag::err_omp_ordered_directive_without_param);
10302     ErrorFound = true;
10303   } else if (TC || Clauses.empty()) {
10304     if (const Expr *Param = DSAStack->getParentOrderedRegionParam().first) {
10305       SourceLocation ErrLoc = TC ? TC->getBeginLoc() : StartLoc;
10306       Diag(ErrLoc, diag::err_omp_ordered_directive_with_param)
10307           << (TC != nullptr);
10308       Diag(Param->getBeginLoc(), diag::note_omp_ordered_param) << 1;
10309       ErrorFound = true;
10310     }
10311   }
10312   if ((!AStmt && !DependFound) || ErrorFound)
10313     return StmtError();
10314 
10315   // OpenMP 5.0, 2.17.9, ordered Construct, Restrictions.
10316   // During execution of an iteration of a worksharing-loop or a loop nest
10317   // within a worksharing-loop, simd, or worksharing-loop SIMD region, a thread
10318   // must not execute more than one ordered region corresponding to an ordered
10319   // construct without a depend clause.
10320   if (!DependFound) {
10321     if (DSAStack->doesParentHasOrderedDirective()) {
10322       Diag(StartLoc, diag::err_omp_several_directives_in_region) << "ordered";
10323       Diag(DSAStack->getParentOrderedDirectiveLoc(),
10324            diag::note_omp_previous_directive)
10325           << "ordered";
10326       return StmtError();
10327     }
10328     DSAStack->setParentHasOrderedDirective(StartLoc);
10329   }
10330 
10331   if (AStmt) {
10332     assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
10333 
10334     setFunctionHasBranchProtectedScope();
10335   }
10336 
10337   return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
10338 }
10339 
10340 namespace {
10341 /// Helper class for checking expression in 'omp atomic [update]'
10342 /// construct.
10343 class OpenMPAtomicUpdateChecker {
10344   /// Error results for atomic update expressions.
10345   enum ExprAnalysisErrorCode {
10346     /// A statement is not an expression statement.
10347     NotAnExpression,
10348     /// Expression is not builtin binary or unary operation.
10349     NotABinaryOrUnaryExpression,
10350     /// Unary operation is not post-/pre- increment/decrement operation.
10351     NotAnUnaryIncDecExpression,
10352     /// An expression is not of scalar type.
10353     NotAScalarType,
10354     /// A binary operation is not an assignment operation.
10355     NotAnAssignmentOp,
10356     /// RHS part of the binary operation is not a binary expression.
10357     NotABinaryExpression,
10358     /// RHS part is not additive/multiplicative/shift/biwise binary
10359     /// expression.
10360     NotABinaryOperator,
10361     /// RHS binary operation does not have reference to the updated LHS
10362     /// part.
10363     NotAnUpdateExpression,
10364     /// No errors is found.
10365     NoError
10366   };
10367   /// Reference to Sema.
10368   Sema &SemaRef;
10369   /// A location for note diagnostics (when error is found).
10370   SourceLocation NoteLoc;
10371   /// 'x' lvalue part of the source atomic expression.
10372   Expr *X;
10373   /// 'expr' rvalue part of the source atomic expression.
10374   Expr *E;
10375   /// Helper expression of the form
10376   /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
10377   /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
10378   Expr *UpdateExpr;
10379   /// Is 'x' a LHS in a RHS part of full update expression. It is
10380   /// important for non-associative operations.
10381   bool IsXLHSInRHSPart;
10382   BinaryOperatorKind Op;
10383   SourceLocation OpLoc;
10384   /// true if the source expression is a postfix unary operation, false
10385   /// if it is a prefix unary operation.
10386   bool IsPostfixUpdate;
10387 
10388 public:
10389   OpenMPAtomicUpdateChecker(Sema &SemaRef)
10390       : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr),
10391         IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {}
10392   /// Check specified statement that it is suitable for 'atomic update'
10393   /// constructs and extract 'x', 'expr' and Operation from the original
10394   /// expression. If DiagId and NoteId == 0, then only check is performed
10395   /// without error notification.
10396   /// \param DiagId Diagnostic which should be emitted if error is found.
10397   /// \param NoteId Diagnostic note for the main error message.
10398   /// \return true if statement is not an update expression, false otherwise.
10399   bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0);
10400   /// Return the 'x' lvalue part of the source atomic expression.
10401   Expr *getX() const { return X; }
10402   /// Return the 'expr' rvalue part of the source atomic expression.
10403   Expr *getExpr() const { return E; }
10404   /// Return the update expression used in calculation of the updated
10405   /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
10406   /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
10407   Expr *getUpdateExpr() const { return UpdateExpr; }
10408   /// Return true if 'x' is LHS in RHS part of full update expression,
10409   /// false otherwise.
10410   bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; }
10411 
10412   /// true if the source expression is a postfix unary operation, false
10413   /// if it is a prefix unary operation.
10414   bool isPostfixUpdate() const { return IsPostfixUpdate; }
10415 
10416 private:
10417   bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0,
10418                             unsigned NoteId = 0);
10419 };
10420 } // namespace
10421 
10422 bool OpenMPAtomicUpdateChecker::checkBinaryOperation(
10423     BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) {
10424   ExprAnalysisErrorCode ErrorFound = NoError;
10425   SourceLocation ErrorLoc, NoteLoc;
10426   SourceRange ErrorRange, NoteRange;
10427   // Allowed constructs are:
10428   //  x = x binop expr;
10429   //  x = expr binop x;
10430   if (AtomicBinOp->getOpcode() == BO_Assign) {
10431     X = AtomicBinOp->getLHS();
10432     if (const auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>(
10433             AtomicBinOp->getRHS()->IgnoreParenImpCasts())) {
10434       if (AtomicInnerBinOp->isMultiplicativeOp() ||
10435           AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() ||
10436           AtomicInnerBinOp->isBitwiseOp()) {
10437         Op = AtomicInnerBinOp->getOpcode();
10438         OpLoc = AtomicInnerBinOp->getOperatorLoc();
10439         Expr *LHS = AtomicInnerBinOp->getLHS();
10440         Expr *RHS = AtomicInnerBinOp->getRHS();
10441         llvm::FoldingSetNodeID XId, LHSId, RHSId;
10442         X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(),
10443                                           /*Canonical=*/true);
10444         LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(),
10445                                             /*Canonical=*/true);
10446         RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(),
10447                                             /*Canonical=*/true);
10448         if (XId == LHSId) {
10449           E = RHS;
10450           IsXLHSInRHSPart = true;
10451         } else if (XId == RHSId) {
10452           E = LHS;
10453           IsXLHSInRHSPart = false;
10454         } else {
10455           ErrorLoc = AtomicInnerBinOp->getExprLoc();
10456           ErrorRange = AtomicInnerBinOp->getSourceRange();
10457           NoteLoc = X->getExprLoc();
10458           NoteRange = X->getSourceRange();
10459           ErrorFound = NotAnUpdateExpression;
10460         }
10461       } else {
10462         ErrorLoc = AtomicInnerBinOp->getExprLoc();
10463         ErrorRange = AtomicInnerBinOp->getSourceRange();
10464         NoteLoc = AtomicInnerBinOp->getOperatorLoc();
10465         NoteRange = SourceRange(NoteLoc, NoteLoc);
10466         ErrorFound = NotABinaryOperator;
10467       }
10468     } else {
10469       NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc();
10470       NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange();
10471       ErrorFound = NotABinaryExpression;
10472     }
10473   } else {
10474     ErrorLoc = AtomicBinOp->getExprLoc();
10475     ErrorRange = AtomicBinOp->getSourceRange();
10476     NoteLoc = AtomicBinOp->getOperatorLoc();
10477     NoteRange = SourceRange(NoteLoc, NoteLoc);
10478     ErrorFound = NotAnAssignmentOp;
10479   }
10480   if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
10481     SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
10482     SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
10483     return true;
10484   }
10485   if (SemaRef.CurContext->isDependentContext())
10486     E = X = UpdateExpr = nullptr;
10487   return ErrorFound != NoError;
10488 }
10489 
10490 bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId,
10491                                                unsigned NoteId) {
10492   ExprAnalysisErrorCode ErrorFound = NoError;
10493   SourceLocation ErrorLoc, NoteLoc;
10494   SourceRange ErrorRange, NoteRange;
10495   // Allowed constructs are:
10496   //  x++;
10497   //  x--;
10498   //  ++x;
10499   //  --x;
10500   //  x binop= expr;
10501   //  x = x binop expr;
10502   //  x = expr binop x;
10503   if (auto *AtomicBody = dyn_cast<Expr>(S)) {
10504     AtomicBody = AtomicBody->IgnoreParenImpCasts();
10505     if (AtomicBody->getType()->isScalarType() ||
10506         AtomicBody->isInstantiationDependent()) {
10507       if (const auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>(
10508               AtomicBody->IgnoreParenImpCasts())) {
10509         // Check for Compound Assignment Operation
10510         Op = BinaryOperator::getOpForCompoundAssignment(
10511             AtomicCompAssignOp->getOpcode());
10512         OpLoc = AtomicCompAssignOp->getOperatorLoc();
10513         E = AtomicCompAssignOp->getRHS();
10514         X = AtomicCompAssignOp->getLHS()->IgnoreParens();
10515         IsXLHSInRHSPart = true;
10516       } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>(
10517                      AtomicBody->IgnoreParenImpCasts())) {
10518         // Check for Binary Operation
10519         if (checkBinaryOperation(AtomicBinOp, DiagId, NoteId))
10520           return true;
10521       } else if (const auto *AtomicUnaryOp = dyn_cast<UnaryOperator>(
10522                      AtomicBody->IgnoreParenImpCasts())) {
10523         // Check for Unary Operation
10524         if (AtomicUnaryOp->isIncrementDecrementOp()) {
10525           IsPostfixUpdate = AtomicUnaryOp->isPostfix();
10526           Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub;
10527           OpLoc = AtomicUnaryOp->getOperatorLoc();
10528           X = AtomicUnaryOp->getSubExpr()->IgnoreParens();
10529           E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get();
10530           IsXLHSInRHSPart = true;
10531         } else {
10532           ErrorFound = NotAnUnaryIncDecExpression;
10533           ErrorLoc = AtomicUnaryOp->getExprLoc();
10534           ErrorRange = AtomicUnaryOp->getSourceRange();
10535           NoteLoc = AtomicUnaryOp->getOperatorLoc();
10536           NoteRange = SourceRange(NoteLoc, NoteLoc);
10537         }
10538       } else if (!AtomicBody->isInstantiationDependent()) {
10539         ErrorFound = NotABinaryOrUnaryExpression;
10540         NoteLoc = ErrorLoc = AtomicBody->getExprLoc();
10541         NoteRange = ErrorRange = AtomicBody->getSourceRange();
10542       }
10543     } else {
10544       ErrorFound = NotAScalarType;
10545       NoteLoc = ErrorLoc = AtomicBody->getBeginLoc();
10546       NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
10547     }
10548   } else {
10549     ErrorFound = NotAnExpression;
10550     NoteLoc = ErrorLoc = S->getBeginLoc();
10551     NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
10552   }
10553   if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
10554     SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
10555     SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
10556     return true;
10557   }
10558   if (SemaRef.CurContext->isDependentContext())
10559     E = X = UpdateExpr = nullptr;
10560   if (ErrorFound == NoError && E && X) {
10561     // Build an update expression of form 'OpaqueValueExpr(x) binop
10562     // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop
10563     // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression.
10564     auto *OVEX = new (SemaRef.getASTContext())
10565         OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue);
10566     auto *OVEExpr = new (SemaRef.getASTContext())
10567         OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue);
10568     ExprResult Update =
10569         SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr,
10570                                    IsXLHSInRHSPart ? OVEExpr : OVEX);
10571     if (Update.isInvalid())
10572       return true;
10573     Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(),
10574                                                Sema::AA_Casting);
10575     if (Update.isInvalid())
10576       return true;
10577     UpdateExpr = Update.get();
10578   }
10579   return ErrorFound != NoError;
10580 }
10581 
10582 StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
10583                                             Stmt *AStmt,
10584                                             SourceLocation StartLoc,
10585                                             SourceLocation EndLoc) {
10586   // Register location of the first atomic directive.
10587   DSAStack->addAtomicDirectiveLoc(StartLoc);
10588   if (!AStmt)
10589     return StmtError();
10590 
10591   // 1.2.2 OpenMP Language Terminology
10592   // Structured block - An executable statement with a single entry at the
10593   // top and a single exit at the bottom.
10594   // The point of exit cannot be a branch out of the structured block.
10595   // longjmp() and throw() must not violate the entry/exit criteria.
10596   OpenMPClauseKind AtomicKind = OMPC_unknown;
10597   SourceLocation AtomicKindLoc;
10598   OpenMPClauseKind MemOrderKind = OMPC_unknown;
10599   SourceLocation MemOrderLoc;
10600   for (const OMPClause *C : Clauses) {
10601     if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write ||
10602         C->getClauseKind() == OMPC_update ||
10603         C->getClauseKind() == OMPC_capture) {
10604       if (AtomicKind != OMPC_unknown) {
10605         Diag(C->getBeginLoc(), diag::err_omp_atomic_several_clauses)
10606             << SourceRange(C->getBeginLoc(), C->getEndLoc());
10607         Diag(AtomicKindLoc, diag::note_omp_previous_mem_order_clause)
10608             << getOpenMPClauseName(AtomicKind);
10609       } else {
10610         AtomicKind = C->getClauseKind();
10611         AtomicKindLoc = C->getBeginLoc();
10612       }
10613     }
10614     if (C->getClauseKind() == OMPC_seq_cst ||
10615         C->getClauseKind() == OMPC_acq_rel ||
10616         C->getClauseKind() == OMPC_acquire ||
10617         C->getClauseKind() == OMPC_release ||
10618         C->getClauseKind() == OMPC_relaxed) {
10619       if (MemOrderKind != OMPC_unknown) {
10620         Diag(C->getBeginLoc(), diag::err_omp_several_mem_order_clauses)
10621             << getOpenMPDirectiveName(OMPD_atomic) << 0
10622             << SourceRange(C->getBeginLoc(), C->getEndLoc());
10623         Diag(MemOrderLoc, diag::note_omp_previous_mem_order_clause)
10624             << getOpenMPClauseName(MemOrderKind);
10625       } else {
10626         MemOrderKind = C->getClauseKind();
10627         MemOrderLoc = C->getBeginLoc();
10628       }
10629     }
10630   }
10631   // OpenMP 5.0, 2.17.7 atomic Construct, Restrictions
10632   // If atomic-clause is read then memory-order-clause must not be acq_rel or
10633   // release.
10634   // If atomic-clause is write then memory-order-clause must not be acq_rel or
10635   // acquire.
10636   // If atomic-clause is update or not present then memory-order-clause must not
10637   // be acq_rel or acquire.
10638   if ((AtomicKind == OMPC_read &&
10639        (MemOrderKind == OMPC_acq_rel || MemOrderKind == OMPC_release)) ||
10640       ((AtomicKind == OMPC_write || AtomicKind == OMPC_update ||
10641         AtomicKind == OMPC_unknown) &&
10642        (MemOrderKind == OMPC_acq_rel || MemOrderKind == OMPC_acquire))) {
10643     SourceLocation Loc = AtomicKindLoc;
10644     if (AtomicKind == OMPC_unknown)
10645       Loc = StartLoc;
10646     Diag(Loc, diag::err_omp_atomic_incompatible_mem_order_clause)
10647         << getOpenMPClauseName(AtomicKind)
10648         << (AtomicKind == OMPC_unknown ? 1 : 0)
10649         << getOpenMPClauseName(MemOrderKind);
10650     Diag(MemOrderLoc, diag::note_omp_previous_mem_order_clause)
10651         << getOpenMPClauseName(MemOrderKind);
10652   }
10653 
10654   Stmt *Body = AStmt;
10655   if (auto *EWC = dyn_cast<ExprWithCleanups>(Body))
10656     Body = EWC->getSubExpr();
10657 
10658   Expr *X = nullptr;
10659   Expr *V = nullptr;
10660   Expr *E = nullptr;
10661   Expr *UE = nullptr;
10662   bool IsXLHSInRHSPart = false;
10663   bool IsPostfixUpdate = false;
10664   // OpenMP [2.12.6, atomic Construct]
10665   // In the next expressions:
10666   // * x and v (as applicable) are both l-value expressions with scalar type.
10667   // * During the execution of an atomic region, multiple syntactic
10668   // occurrences of x must designate the same storage location.
10669   // * Neither of v and expr (as applicable) may access the storage location
10670   // designated by x.
10671   // * Neither of x and expr (as applicable) may access the storage location
10672   // designated by v.
10673   // * expr is an expression with scalar type.
10674   // * binop is one of +, *, -, /, &, ^, |, <<, or >>.
10675   // * binop, binop=, ++, and -- are not overloaded operators.
10676   // * The expression x binop expr must be numerically equivalent to x binop
10677   // (expr). This requirement is satisfied if the operators in expr have
10678   // precedence greater than binop, or by using parentheses around expr or
10679   // subexpressions of expr.
10680   // * The expression expr binop x must be numerically equivalent to (expr)
10681   // binop x. This requirement is satisfied if the operators in expr have
10682   // precedence equal to or greater than binop, or by using parentheses around
10683   // expr or subexpressions of expr.
10684   // * For forms that allow multiple occurrences of x, the number of times
10685   // that x is evaluated is unspecified.
10686   if (AtomicKind == OMPC_read) {
10687     enum {
10688       NotAnExpression,
10689       NotAnAssignmentOp,
10690       NotAScalarType,
10691       NotAnLValue,
10692       NoError
10693     } ErrorFound = NoError;
10694     SourceLocation ErrorLoc, NoteLoc;
10695     SourceRange ErrorRange, NoteRange;
10696     // If clause is read:
10697     //  v = x;
10698     if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
10699       const auto *AtomicBinOp =
10700           dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
10701       if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
10702         X = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
10703         V = AtomicBinOp->getLHS()->IgnoreParenImpCasts();
10704         if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
10705             (V->isInstantiationDependent() || V->getType()->isScalarType())) {
10706           if (!X->isLValue() || !V->isLValue()) {
10707             const Expr *NotLValueExpr = X->isLValue() ? V : X;
10708             ErrorFound = NotAnLValue;
10709             ErrorLoc = AtomicBinOp->getExprLoc();
10710             ErrorRange = AtomicBinOp->getSourceRange();
10711             NoteLoc = NotLValueExpr->getExprLoc();
10712             NoteRange = NotLValueExpr->getSourceRange();
10713           }
10714         } else if (!X->isInstantiationDependent() ||
10715                    !V->isInstantiationDependent()) {
10716           const Expr *NotScalarExpr =
10717               (X->isInstantiationDependent() || X->getType()->isScalarType())
10718                   ? V
10719                   : X;
10720           ErrorFound = NotAScalarType;
10721           ErrorLoc = AtomicBinOp->getExprLoc();
10722           ErrorRange = AtomicBinOp->getSourceRange();
10723           NoteLoc = NotScalarExpr->getExprLoc();
10724           NoteRange = NotScalarExpr->getSourceRange();
10725         }
10726       } else if (!AtomicBody->isInstantiationDependent()) {
10727         ErrorFound = NotAnAssignmentOp;
10728         ErrorLoc = AtomicBody->getExprLoc();
10729         ErrorRange = AtomicBody->getSourceRange();
10730         NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
10731                               : AtomicBody->getExprLoc();
10732         NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
10733                                 : AtomicBody->getSourceRange();
10734       }
10735     } else {
10736       ErrorFound = NotAnExpression;
10737       NoteLoc = ErrorLoc = Body->getBeginLoc();
10738       NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
10739     }
10740     if (ErrorFound != NoError) {
10741       Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement)
10742           << ErrorRange;
10743       Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
10744                                                       << NoteRange;
10745       return StmtError();
10746     }
10747     if (CurContext->isDependentContext())
10748       V = X = nullptr;
10749   } else if (AtomicKind == OMPC_write) {
10750     enum {
10751       NotAnExpression,
10752       NotAnAssignmentOp,
10753       NotAScalarType,
10754       NotAnLValue,
10755       NoError
10756     } ErrorFound = NoError;
10757     SourceLocation ErrorLoc, NoteLoc;
10758     SourceRange ErrorRange, NoteRange;
10759     // If clause is write:
10760     //  x = expr;
10761     if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
10762       const auto *AtomicBinOp =
10763           dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
10764       if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
10765         X = AtomicBinOp->getLHS();
10766         E = AtomicBinOp->getRHS();
10767         if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
10768             (E->isInstantiationDependent() || E->getType()->isScalarType())) {
10769           if (!X->isLValue()) {
10770             ErrorFound = NotAnLValue;
10771             ErrorLoc = AtomicBinOp->getExprLoc();
10772             ErrorRange = AtomicBinOp->getSourceRange();
10773             NoteLoc = X->getExprLoc();
10774             NoteRange = X->getSourceRange();
10775           }
10776         } else if (!X->isInstantiationDependent() ||
10777                    !E->isInstantiationDependent()) {
10778           const Expr *NotScalarExpr =
10779               (X->isInstantiationDependent() || X->getType()->isScalarType())
10780                   ? E
10781                   : X;
10782           ErrorFound = NotAScalarType;
10783           ErrorLoc = AtomicBinOp->getExprLoc();
10784           ErrorRange = AtomicBinOp->getSourceRange();
10785           NoteLoc = NotScalarExpr->getExprLoc();
10786           NoteRange = NotScalarExpr->getSourceRange();
10787         }
10788       } else if (!AtomicBody->isInstantiationDependent()) {
10789         ErrorFound = NotAnAssignmentOp;
10790         ErrorLoc = AtomicBody->getExprLoc();
10791         ErrorRange = AtomicBody->getSourceRange();
10792         NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
10793                               : AtomicBody->getExprLoc();
10794         NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
10795                                 : AtomicBody->getSourceRange();
10796       }
10797     } else {
10798       ErrorFound = NotAnExpression;
10799       NoteLoc = ErrorLoc = Body->getBeginLoc();
10800       NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
10801     }
10802     if (ErrorFound != NoError) {
10803       Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement)
10804           << ErrorRange;
10805       Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
10806                                                       << NoteRange;
10807       return StmtError();
10808     }
10809     if (CurContext->isDependentContext())
10810       E = X = nullptr;
10811   } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) {
10812     // If clause is update:
10813     //  x++;
10814     //  x--;
10815     //  ++x;
10816     //  --x;
10817     //  x binop= expr;
10818     //  x = x binop expr;
10819     //  x = expr binop x;
10820     OpenMPAtomicUpdateChecker Checker(*this);
10821     if (Checker.checkStatement(
10822             Body, (AtomicKind == OMPC_update)
10823                       ? diag::err_omp_atomic_update_not_expression_statement
10824                       : diag::err_omp_atomic_not_expression_statement,
10825             diag::note_omp_atomic_update))
10826       return StmtError();
10827     if (!CurContext->isDependentContext()) {
10828       E = Checker.getExpr();
10829       X = Checker.getX();
10830       UE = Checker.getUpdateExpr();
10831       IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
10832     }
10833   } else if (AtomicKind == OMPC_capture) {
10834     enum {
10835       NotAnAssignmentOp,
10836       NotACompoundStatement,
10837       NotTwoSubstatements,
10838       NotASpecificExpression,
10839       NoError
10840     } ErrorFound = NoError;
10841     SourceLocation ErrorLoc, NoteLoc;
10842     SourceRange ErrorRange, NoteRange;
10843     if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
10844       // If clause is a capture:
10845       //  v = x++;
10846       //  v = x--;
10847       //  v = ++x;
10848       //  v = --x;
10849       //  v = x binop= expr;
10850       //  v = x = x binop expr;
10851       //  v = x = expr binop x;
10852       const auto *AtomicBinOp =
10853           dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
10854       if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
10855         V = AtomicBinOp->getLHS();
10856         Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
10857         OpenMPAtomicUpdateChecker Checker(*this);
10858         if (Checker.checkStatement(
10859                 Body, diag::err_omp_atomic_capture_not_expression_statement,
10860                 diag::note_omp_atomic_update))
10861           return StmtError();
10862         E = Checker.getExpr();
10863         X = Checker.getX();
10864         UE = Checker.getUpdateExpr();
10865         IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
10866         IsPostfixUpdate = Checker.isPostfixUpdate();
10867       } else if (!AtomicBody->isInstantiationDependent()) {
10868         ErrorLoc = AtomicBody->getExprLoc();
10869         ErrorRange = AtomicBody->getSourceRange();
10870         NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
10871                               : AtomicBody->getExprLoc();
10872         NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
10873                                 : AtomicBody->getSourceRange();
10874         ErrorFound = NotAnAssignmentOp;
10875       }
10876       if (ErrorFound != NoError) {
10877         Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement)
10878             << ErrorRange;
10879         Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
10880         return StmtError();
10881       }
10882       if (CurContext->isDependentContext())
10883         UE = V = E = X = nullptr;
10884     } else {
10885       // If clause is a capture:
10886       //  { v = x; x = expr; }
10887       //  { v = x; x++; }
10888       //  { v = x; x--; }
10889       //  { v = x; ++x; }
10890       //  { v = x; --x; }
10891       //  { v = x; x binop= expr; }
10892       //  { v = x; x = x binop expr; }
10893       //  { v = x; x = expr binop x; }
10894       //  { x++; v = x; }
10895       //  { x--; v = x; }
10896       //  { ++x; v = x; }
10897       //  { --x; v = x; }
10898       //  { x binop= expr; v = x; }
10899       //  { x = x binop expr; v = x; }
10900       //  { x = expr binop x; v = x; }
10901       if (auto *CS = dyn_cast<CompoundStmt>(Body)) {
10902         // Check that this is { expr1; expr2; }
10903         if (CS->size() == 2) {
10904           Stmt *First = CS->body_front();
10905           Stmt *Second = CS->body_back();
10906           if (auto *EWC = dyn_cast<ExprWithCleanups>(First))
10907             First = EWC->getSubExpr()->IgnoreParenImpCasts();
10908           if (auto *EWC = dyn_cast<ExprWithCleanups>(Second))
10909             Second = EWC->getSubExpr()->IgnoreParenImpCasts();
10910           // Need to find what subexpression is 'v' and what is 'x'.
10911           OpenMPAtomicUpdateChecker Checker(*this);
10912           bool IsUpdateExprFound = !Checker.checkStatement(Second);
10913           BinaryOperator *BinOp = nullptr;
10914           if (IsUpdateExprFound) {
10915             BinOp = dyn_cast<BinaryOperator>(First);
10916             IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
10917           }
10918           if (IsUpdateExprFound && !CurContext->isDependentContext()) {
10919             //  { v = x; x++; }
10920             //  { v = x; x--; }
10921             //  { v = x; ++x; }
10922             //  { v = x; --x; }
10923             //  { v = x; x binop= expr; }
10924             //  { v = x; x = x binop expr; }
10925             //  { v = x; x = expr binop x; }
10926             // Check that the first expression has form v = x.
10927             Expr *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
10928             llvm::FoldingSetNodeID XId, PossibleXId;
10929             Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
10930             PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
10931             IsUpdateExprFound = XId == PossibleXId;
10932             if (IsUpdateExprFound) {
10933               V = BinOp->getLHS();
10934               X = Checker.getX();
10935               E = Checker.getExpr();
10936               UE = Checker.getUpdateExpr();
10937               IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
10938               IsPostfixUpdate = true;
10939             }
10940           }
10941           if (!IsUpdateExprFound) {
10942             IsUpdateExprFound = !Checker.checkStatement(First);
10943             BinOp = nullptr;
10944             if (IsUpdateExprFound) {
10945               BinOp = dyn_cast<BinaryOperator>(Second);
10946               IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
10947             }
10948             if (IsUpdateExprFound && !CurContext->isDependentContext()) {
10949               //  { x++; v = x; }
10950               //  { x--; v = x; }
10951               //  { ++x; v = x; }
10952               //  { --x; v = x; }
10953               //  { x binop= expr; v = x; }
10954               //  { x = x binop expr; v = x; }
10955               //  { x = expr binop x; v = x; }
10956               // Check that the second expression has form v = x.
10957               Expr *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
10958               llvm::FoldingSetNodeID XId, PossibleXId;
10959               Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
10960               PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
10961               IsUpdateExprFound = XId == PossibleXId;
10962               if (IsUpdateExprFound) {
10963                 V = BinOp->getLHS();
10964                 X = Checker.getX();
10965                 E = Checker.getExpr();
10966                 UE = Checker.getUpdateExpr();
10967                 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
10968                 IsPostfixUpdate = false;
10969               }
10970             }
10971           }
10972           if (!IsUpdateExprFound) {
10973             //  { v = x; x = expr; }
10974             auto *FirstExpr = dyn_cast<Expr>(First);
10975             auto *SecondExpr = dyn_cast<Expr>(Second);
10976             if (!FirstExpr || !SecondExpr ||
10977                 !(FirstExpr->isInstantiationDependent() ||
10978                   SecondExpr->isInstantiationDependent())) {
10979               auto *FirstBinOp = dyn_cast<BinaryOperator>(First);
10980               if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) {
10981                 ErrorFound = NotAnAssignmentOp;
10982                 NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc()
10983                                                 : First->getBeginLoc();
10984                 NoteRange = ErrorRange = FirstBinOp
10985                                              ? FirstBinOp->getSourceRange()
10986                                              : SourceRange(ErrorLoc, ErrorLoc);
10987               } else {
10988                 auto *SecondBinOp = dyn_cast<BinaryOperator>(Second);
10989                 if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) {
10990                   ErrorFound = NotAnAssignmentOp;
10991                   NoteLoc = ErrorLoc = SecondBinOp
10992                                            ? SecondBinOp->getOperatorLoc()
10993                                            : Second->getBeginLoc();
10994                   NoteRange = ErrorRange =
10995                       SecondBinOp ? SecondBinOp->getSourceRange()
10996                                   : SourceRange(ErrorLoc, ErrorLoc);
10997                 } else {
10998                   Expr *PossibleXRHSInFirst =
10999                       FirstBinOp->getRHS()->IgnoreParenImpCasts();
11000                   Expr *PossibleXLHSInSecond =
11001                       SecondBinOp->getLHS()->IgnoreParenImpCasts();
11002                   llvm::FoldingSetNodeID X1Id, X2Id;
11003                   PossibleXRHSInFirst->Profile(X1Id, Context,
11004                                                /*Canonical=*/true);
11005                   PossibleXLHSInSecond->Profile(X2Id, Context,
11006                                                 /*Canonical=*/true);
11007                   IsUpdateExprFound = X1Id == X2Id;
11008                   if (IsUpdateExprFound) {
11009                     V = FirstBinOp->getLHS();
11010                     X = SecondBinOp->getLHS();
11011                     E = SecondBinOp->getRHS();
11012                     UE = nullptr;
11013                     IsXLHSInRHSPart = false;
11014                     IsPostfixUpdate = true;
11015                   } else {
11016                     ErrorFound = NotASpecificExpression;
11017                     ErrorLoc = FirstBinOp->getExprLoc();
11018                     ErrorRange = FirstBinOp->getSourceRange();
11019                     NoteLoc = SecondBinOp->getLHS()->getExprLoc();
11020                     NoteRange = SecondBinOp->getRHS()->getSourceRange();
11021                   }
11022                 }
11023               }
11024             }
11025           }
11026         } else {
11027           NoteLoc = ErrorLoc = Body->getBeginLoc();
11028           NoteRange = ErrorRange =
11029               SourceRange(Body->getBeginLoc(), Body->getBeginLoc());
11030           ErrorFound = NotTwoSubstatements;
11031         }
11032       } else {
11033         NoteLoc = ErrorLoc = Body->getBeginLoc();
11034         NoteRange = ErrorRange =
11035             SourceRange(Body->getBeginLoc(), Body->getBeginLoc());
11036         ErrorFound = NotACompoundStatement;
11037       }
11038       if (ErrorFound != NoError) {
11039         Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement)
11040             << ErrorRange;
11041         Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
11042         return StmtError();
11043       }
11044       if (CurContext->isDependentContext())
11045         UE = V = E = X = nullptr;
11046     }
11047   }
11048 
11049   setFunctionHasBranchProtectedScope();
11050 
11051   return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
11052                                     X, V, E, UE, IsXLHSInRHSPart,
11053                                     IsPostfixUpdate);
11054 }
11055 
11056 StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
11057                                             Stmt *AStmt,
11058                                             SourceLocation StartLoc,
11059                                             SourceLocation EndLoc) {
11060   if (!AStmt)
11061     return StmtError();
11062 
11063   auto *CS = cast<CapturedStmt>(AStmt);
11064   // 1.2.2 OpenMP Language Terminology
11065   // Structured block - An executable statement with a single entry at the
11066   // top and a single exit at the bottom.
11067   // The point of exit cannot be a branch out of the structured block.
11068   // longjmp() and throw() must not violate the entry/exit criteria.
11069   CS->getCapturedDecl()->setNothrow();
11070   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target);
11071        ThisCaptureLevel > 1; --ThisCaptureLevel) {
11072     CS = cast<CapturedStmt>(CS->getCapturedStmt());
11073     // 1.2.2 OpenMP Language Terminology
11074     // Structured block - An executable statement with a single entry at the
11075     // top and a single exit at the bottom.
11076     // The point of exit cannot be a branch out of the structured block.
11077     // longjmp() and throw() must not violate the entry/exit criteria.
11078     CS->getCapturedDecl()->setNothrow();
11079   }
11080 
11081   // OpenMP [2.16, Nesting of Regions]
11082   // If specified, a teams construct must be contained within a target
11083   // construct. That target construct must contain no statements or directives
11084   // outside of the teams construct.
11085   if (DSAStack->hasInnerTeamsRegion()) {
11086     const Stmt *S = CS->IgnoreContainers(/*IgnoreCaptured=*/true);
11087     bool OMPTeamsFound = true;
11088     if (const auto *CS = dyn_cast<CompoundStmt>(S)) {
11089       auto I = CS->body_begin();
11090       while (I != CS->body_end()) {
11091         const auto *OED = dyn_cast<OMPExecutableDirective>(*I);
11092         if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind()) ||
11093             OMPTeamsFound) {
11094 
11095           OMPTeamsFound = false;
11096           break;
11097         }
11098         ++I;
11099       }
11100       assert(I != CS->body_end() && "Not found statement");
11101       S = *I;
11102     } else {
11103       const auto *OED = dyn_cast<OMPExecutableDirective>(S);
11104       OMPTeamsFound = OED && isOpenMPTeamsDirective(OED->getDirectiveKind());
11105     }
11106     if (!OMPTeamsFound) {
11107       Diag(StartLoc, diag::err_omp_target_contains_not_only_teams);
11108       Diag(DSAStack->getInnerTeamsRegionLoc(),
11109            diag::note_omp_nested_teams_construct_here);
11110       Diag(S->getBeginLoc(), diag::note_omp_nested_statement_here)
11111           << isa<OMPExecutableDirective>(S);
11112       return StmtError();
11113     }
11114   }
11115 
11116   setFunctionHasBranchProtectedScope();
11117 
11118   return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
11119 }
11120 
11121 StmtResult
11122 Sema::ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
11123                                          Stmt *AStmt, SourceLocation StartLoc,
11124                                          SourceLocation EndLoc) {
11125   if (!AStmt)
11126     return StmtError();
11127 
11128   auto *CS = cast<CapturedStmt>(AStmt);
11129   // 1.2.2 OpenMP Language Terminology
11130   // Structured block - An executable statement with a single entry at the
11131   // top and a single exit at the bottom.
11132   // The point of exit cannot be a branch out of the structured block.
11133   // longjmp() and throw() must not violate the entry/exit criteria.
11134   CS->getCapturedDecl()->setNothrow();
11135   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel);
11136        ThisCaptureLevel > 1; --ThisCaptureLevel) {
11137     CS = cast<CapturedStmt>(CS->getCapturedStmt());
11138     // 1.2.2 OpenMP Language Terminology
11139     // Structured block - An executable statement with a single entry at the
11140     // top and a single exit at the bottom.
11141     // The point of exit cannot be a branch out of the structured block.
11142     // longjmp() and throw() must not violate the entry/exit criteria.
11143     CS->getCapturedDecl()->setNothrow();
11144   }
11145 
11146   setFunctionHasBranchProtectedScope();
11147 
11148   return OMPTargetParallelDirective::Create(
11149       Context, StartLoc, EndLoc, Clauses, AStmt,
11150       DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion());
11151 }
11152 
11153 StmtResult Sema::ActOnOpenMPTargetParallelForDirective(
11154     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11155     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
11156   if (!AStmt)
11157     return StmtError();
11158 
11159   auto *CS = cast<CapturedStmt>(AStmt);
11160   // 1.2.2 OpenMP Language Terminology
11161   // Structured block - An executable statement with a single entry at the
11162   // top and a single exit at the bottom.
11163   // The point of exit cannot be a branch out of the structured block.
11164   // longjmp() and throw() must not violate the entry/exit criteria.
11165   CS->getCapturedDecl()->setNothrow();
11166   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
11167        ThisCaptureLevel > 1; --ThisCaptureLevel) {
11168     CS = cast<CapturedStmt>(CS->getCapturedStmt());
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   }
11176 
11177   OMPLoopBasedDirective::HelperExprs B;
11178   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
11179   // define the nested loops number.
11180   unsigned NestedLoopCount =
11181       checkOpenMPLoop(OMPD_target_parallel_for, getCollapseNumberExpr(Clauses),
11182                       getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
11183                       VarsWithImplicitDSA, B);
11184   if (NestedLoopCount == 0)
11185     return StmtError();
11186 
11187   assert((CurContext->isDependentContext() || B.builtAll()) &&
11188          "omp target parallel for loop exprs were not built");
11189 
11190   if (!CurContext->isDependentContext()) {
11191     // Finalize the clauses that need pre-built expressions for CodeGen.
11192     for (OMPClause *C : Clauses) {
11193       if (auto *LC = dyn_cast<OMPLinearClause>(C))
11194         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
11195                                      B.NumIterations, *this, CurScope,
11196                                      DSAStack))
11197           return StmtError();
11198     }
11199   }
11200 
11201   setFunctionHasBranchProtectedScope();
11202   return OMPTargetParallelForDirective::Create(
11203       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
11204       DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion());
11205 }
11206 
11207 /// Check for existence of a map clause in the list of clauses.
11208 static bool hasClauses(ArrayRef<OMPClause *> Clauses,
11209                        const OpenMPClauseKind K) {
11210   return llvm::any_of(
11211       Clauses, [K](const OMPClause *C) { return C->getClauseKind() == K; });
11212 }
11213 
11214 template <typename... Params>
11215 static bool hasClauses(ArrayRef<OMPClause *> Clauses, const OpenMPClauseKind K,
11216                        const Params... ClauseTypes) {
11217   return hasClauses(Clauses, K) || hasClauses(Clauses, ClauseTypes...);
11218 }
11219 
11220 StmtResult Sema::ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
11221                                                 Stmt *AStmt,
11222                                                 SourceLocation StartLoc,
11223                                                 SourceLocation EndLoc) {
11224   if (!AStmt)
11225     return StmtError();
11226 
11227   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
11228 
11229   // OpenMP [2.12.2, target data Construct, Restrictions]
11230   // At least one map, use_device_addr or use_device_ptr clause must appear on
11231   // the directive.
11232   if (!hasClauses(Clauses, OMPC_map, OMPC_use_device_ptr) &&
11233       (LangOpts.OpenMP < 50 || !hasClauses(Clauses, OMPC_use_device_addr))) {
11234     StringRef Expected;
11235     if (LangOpts.OpenMP < 50)
11236       Expected = "'map' or 'use_device_ptr'";
11237     else
11238       Expected = "'map', 'use_device_ptr', or 'use_device_addr'";
11239     Diag(StartLoc, diag::err_omp_no_clause_for_directive)
11240         << Expected << getOpenMPDirectiveName(OMPD_target_data);
11241     return StmtError();
11242   }
11243 
11244   setFunctionHasBranchProtectedScope();
11245 
11246   return OMPTargetDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
11247                                         AStmt);
11248 }
11249 
11250 StmtResult
11251 Sema::ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
11252                                           SourceLocation StartLoc,
11253                                           SourceLocation EndLoc, Stmt *AStmt) {
11254   if (!AStmt)
11255     return StmtError();
11256 
11257   auto *CS = cast<CapturedStmt>(AStmt);
11258   // 1.2.2 OpenMP Language Terminology
11259   // Structured block - An executable statement with a single entry at the
11260   // top and a single exit at the bottom.
11261   // The point of exit cannot be a branch out of the structured block.
11262   // longjmp() and throw() must not violate the entry/exit criteria.
11263   CS->getCapturedDecl()->setNothrow();
11264   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_enter_data);
11265        ThisCaptureLevel > 1; --ThisCaptureLevel) {
11266     CS = cast<CapturedStmt>(CS->getCapturedStmt());
11267     // 1.2.2 OpenMP Language Terminology
11268     // Structured block - An executable statement with a single entry at the
11269     // top and a single exit at the bottom.
11270     // The point of exit cannot be a branch out of the structured block.
11271     // longjmp() and throw() must not violate the entry/exit criteria.
11272     CS->getCapturedDecl()->setNothrow();
11273   }
11274 
11275   // OpenMP [2.10.2, Restrictions, p. 99]
11276   // At least one map clause must appear on the directive.
11277   if (!hasClauses(Clauses, OMPC_map)) {
11278     Diag(StartLoc, diag::err_omp_no_clause_for_directive)
11279         << "'map'" << getOpenMPDirectiveName(OMPD_target_enter_data);
11280     return StmtError();
11281   }
11282 
11283   return OMPTargetEnterDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
11284                                              AStmt);
11285 }
11286 
11287 StmtResult
11288 Sema::ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
11289                                          SourceLocation StartLoc,
11290                                          SourceLocation EndLoc, Stmt *AStmt) {
11291   if (!AStmt)
11292     return StmtError();
11293 
11294   auto *CS = cast<CapturedStmt>(AStmt);
11295   // 1.2.2 OpenMP Language Terminology
11296   // Structured block - An executable statement with a single entry at the
11297   // top and a single exit at the bottom.
11298   // The point of exit cannot be a branch out of the structured block.
11299   // longjmp() and throw() must not violate the entry/exit criteria.
11300   CS->getCapturedDecl()->setNothrow();
11301   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_exit_data);
11302        ThisCaptureLevel > 1; --ThisCaptureLevel) {
11303     CS = cast<CapturedStmt>(CS->getCapturedStmt());
11304     // 1.2.2 OpenMP Language Terminology
11305     // Structured block - An executable statement with a single entry at the
11306     // top and a single exit at the bottom.
11307     // The point of exit cannot be a branch out of the structured block.
11308     // longjmp() and throw() must not violate the entry/exit criteria.
11309     CS->getCapturedDecl()->setNothrow();
11310   }
11311 
11312   // OpenMP [2.10.3, Restrictions, p. 102]
11313   // At least one map clause must appear on the directive.
11314   if (!hasClauses(Clauses, OMPC_map)) {
11315     Diag(StartLoc, diag::err_omp_no_clause_for_directive)
11316         << "'map'" << getOpenMPDirectiveName(OMPD_target_exit_data);
11317     return StmtError();
11318   }
11319 
11320   return OMPTargetExitDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
11321                                             AStmt);
11322 }
11323 
11324 StmtResult Sema::ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
11325                                                   SourceLocation StartLoc,
11326                                                   SourceLocation EndLoc,
11327                                                   Stmt *AStmt) {
11328   if (!AStmt)
11329     return StmtError();
11330 
11331   auto *CS = cast<CapturedStmt>(AStmt);
11332   // 1.2.2 OpenMP Language Terminology
11333   // Structured block - An executable statement with a single entry at the
11334   // top and a single exit at the bottom.
11335   // The point of exit cannot be a branch out of the structured block.
11336   // longjmp() and throw() must not violate the entry/exit criteria.
11337   CS->getCapturedDecl()->setNothrow();
11338   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_update);
11339        ThisCaptureLevel > 1; --ThisCaptureLevel) {
11340     CS = cast<CapturedStmt>(CS->getCapturedStmt());
11341     // 1.2.2 OpenMP Language Terminology
11342     // Structured block - An executable statement with a single entry at the
11343     // top and a single exit at the bottom.
11344     // The point of exit cannot be a branch out of the structured block.
11345     // longjmp() and throw() must not violate the entry/exit criteria.
11346     CS->getCapturedDecl()->setNothrow();
11347   }
11348 
11349   if (!hasClauses(Clauses, OMPC_to, OMPC_from)) {
11350     Diag(StartLoc, diag::err_omp_at_least_one_motion_clause_required);
11351     return StmtError();
11352   }
11353   return OMPTargetUpdateDirective::Create(Context, StartLoc, EndLoc, Clauses,
11354                                           AStmt);
11355 }
11356 
11357 StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
11358                                            Stmt *AStmt, SourceLocation StartLoc,
11359                                            SourceLocation EndLoc) {
11360   if (!AStmt)
11361     return StmtError();
11362 
11363   auto *CS = cast<CapturedStmt>(AStmt);
11364   // 1.2.2 OpenMP Language Terminology
11365   // Structured block - An executable statement with a single entry at the
11366   // top and a single exit at the bottom.
11367   // The point of exit cannot be a branch out of the structured block.
11368   // longjmp() and throw() must not violate the entry/exit criteria.
11369   CS->getCapturedDecl()->setNothrow();
11370 
11371   setFunctionHasBranchProtectedScope();
11372 
11373   DSAStack->setParentTeamsRegionLoc(StartLoc);
11374 
11375   return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
11376 }
11377 
11378 StmtResult
11379 Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
11380                                             SourceLocation EndLoc,
11381                                             OpenMPDirectiveKind CancelRegion) {
11382   if (DSAStack->isParentNowaitRegion()) {
11383     Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0;
11384     return StmtError();
11385   }
11386   if (DSAStack->isParentOrderedRegion()) {
11387     Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0;
11388     return StmtError();
11389   }
11390   return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc,
11391                                                CancelRegion);
11392 }
11393 
11394 StmtResult Sema::ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
11395                                             SourceLocation StartLoc,
11396                                             SourceLocation EndLoc,
11397                                             OpenMPDirectiveKind CancelRegion) {
11398   if (DSAStack->isParentNowaitRegion()) {
11399     Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1;
11400     return StmtError();
11401   }
11402   if (DSAStack->isParentOrderedRegion()) {
11403     Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1;
11404     return StmtError();
11405   }
11406   DSAStack->setParentCancelRegion(/*Cancel=*/true);
11407   return OMPCancelDirective::Create(Context, StartLoc, EndLoc, Clauses,
11408                                     CancelRegion);
11409 }
11410 
11411 static bool checkGrainsizeNumTasksClauses(Sema &S,
11412                                           ArrayRef<OMPClause *> Clauses) {
11413   const OMPClause *PrevClause = nullptr;
11414   bool ErrorFound = false;
11415   for (const OMPClause *C : Clauses) {
11416     if (C->getClauseKind() == OMPC_grainsize ||
11417         C->getClauseKind() == OMPC_num_tasks) {
11418       if (!PrevClause)
11419         PrevClause = C;
11420       else if (PrevClause->getClauseKind() != C->getClauseKind()) {
11421         S.Diag(C->getBeginLoc(), diag::err_omp_clauses_mutually_exclusive)
11422             << getOpenMPClauseName(C->getClauseKind())
11423             << getOpenMPClauseName(PrevClause->getClauseKind());
11424         S.Diag(PrevClause->getBeginLoc(), diag::note_omp_previous_clause)
11425             << getOpenMPClauseName(PrevClause->getClauseKind());
11426         ErrorFound = true;
11427       }
11428     }
11429   }
11430   return ErrorFound;
11431 }
11432 
11433 static bool checkReductionClauseWithNogroup(Sema &S,
11434                                             ArrayRef<OMPClause *> Clauses) {
11435   const OMPClause *ReductionClause = nullptr;
11436   const OMPClause *NogroupClause = nullptr;
11437   for (const OMPClause *C : Clauses) {
11438     if (C->getClauseKind() == OMPC_reduction) {
11439       ReductionClause = C;
11440       if (NogroupClause)
11441         break;
11442       continue;
11443     }
11444     if (C->getClauseKind() == OMPC_nogroup) {
11445       NogroupClause = C;
11446       if (ReductionClause)
11447         break;
11448       continue;
11449     }
11450   }
11451   if (ReductionClause && NogroupClause) {
11452     S.Diag(ReductionClause->getBeginLoc(), diag::err_omp_reduction_with_nogroup)
11453         << SourceRange(NogroupClause->getBeginLoc(),
11454                        NogroupClause->getEndLoc());
11455     return true;
11456   }
11457   return false;
11458 }
11459 
11460 StmtResult Sema::ActOnOpenMPTaskLoopDirective(
11461     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11462     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
11463   if (!AStmt)
11464     return StmtError();
11465 
11466   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
11467   OMPLoopBasedDirective::HelperExprs B;
11468   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
11469   // define the nested loops number.
11470   unsigned NestedLoopCount =
11471       checkOpenMPLoop(OMPD_taskloop, getCollapseNumberExpr(Clauses),
11472                       /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
11473                       VarsWithImplicitDSA, B);
11474   if (NestedLoopCount == 0)
11475     return StmtError();
11476 
11477   assert((CurContext->isDependentContext() || B.builtAll()) &&
11478          "omp for loop exprs were not built");
11479 
11480   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
11481   // The grainsize clause and num_tasks clause are mutually exclusive and may
11482   // not appear on the same taskloop directive.
11483   if (checkGrainsizeNumTasksClauses(*this, Clauses))
11484     return StmtError();
11485   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
11486   // If a reduction clause is present on the taskloop directive, the nogroup
11487   // clause must not be specified.
11488   if (checkReductionClauseWithNogroup(*this, Clauses))
11489     return StmtError();
11490 
11491   setFunctionHasBranchProtectedScope();
11492   return OMPTaskLoopDirective::Create(Context, StartLoc, EndLoc,
11493                                       NestedLoopCount, Clauses, AStmt, B,
11494                                       DSAStack->isCancelRegion());
11495 }
11496 
11497 StmtResult Sema::ActOnOpenMPTaskLoopSimdDirective(
11498     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11499     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
11500   if (!AStmt)
11501     return StmtError();
11502 
11503   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
11504   OMPLoopBasedDirective::HelperExprs B;
11505   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
11506   // define the nested loops number.
11507   unsigned NestedLoopCount =
11508       checkOpenMPLoop(OMPD_taskloop_simd, getCollapseNumberExpr(Clauses),
11509                       /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
11510                       VarsWithImplicitDSA, B);
11511   if (NestedLoopCount == 0)
11512     return StmtError();
11513 
11514   assert((CurContext->isDependentContext() || B.builtAll()) &&
11515          "omp for loop exprs were not built");
11516 
11517   if (!CurContext->isDependentContext()) {
11518     // Finalize the clauses that need pre-built expressions for CodeGen.
11519     for (OMPClause *C : Clauses) {
11520       if (auto *LC = dyn_cast<OMPLinearClause>(C))
11521         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
11522                                      B.NumIterations, *this, CurScope,
11523                                      DSAStack))
11524           return StmtError();
11525     }
11526   }
11527 
11528   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
11529   // The grainsize clause and num_tasks clause are mutually exclusive and may
11530   // not appear on the same taskloop directive.
11531   if (checkGrainsizeNumTasksClauses(*this, Clauses))
11532     return StmtError();
11533   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
11534   // If a reduction clause is present on the taskloop directive, the nogroup
11535   // clause must not be specified.
11536   if (checkReductionClauseWithNogroup(*this, Clauses))
11537     return StmtError();
11538   if (checkSimdlenSafelenSpecified(*this, Clauses))
11539     return StmtError();
11540 
11541   setFunctionHasBranchProtectedScope();
11542   return OMPTaskLoopSimdDirective::Create(Context, StartLoc, EndLoc,
11543                                           NestedLoopCount, Clauses, AStmt, B);
11544 }
11545 
11546 StmtResult Sema::ActOnOpenMPMasterTaskLoopDirective(
11547     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11548     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
11549   if (!AStmt)
11550     return StmtError();
11551 
11552   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
11553   OMPLoopBasedDirective::HelperExprs B;
11554   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
11555   // define the nested loops number.
11556   unsigned NestedLoopCount =
11557       checkOpenMPLoop(OMPD_master_taskloop, getCollapseNumberExpr(Clauses),
11558                       /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
11559                       VarsWithImplicitDSA, B);
11560   if (NestedLoopCount == 0)
11561     return StmtError();
11562 
11563   assert((CurContext->isDependentContext() || B.builtAll()) &&
11564          "omp for loop exprs were not built");
11565 
11566   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
11567   // The grainsize clause and num_tasks clause are mutually exclusive and may
11568   // not appear on the same taskloop directive.
11569   if (checkGrainsizeNumTasksClauses(*this, Clauses))
11570     return StmtError();
11571   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
11572   // If a reduction clause is present on the taskloop directive, the nogroup
11573   // clause must not be specified.
11574   if (checkReductionClauseWithNogroup(*this, Clauses))
11575     return StmtError();
11576 
11577   setFunctionHasBranchProtectedScope();
11578   return OMPMasterTaskLoopDirective::Create(Context, StartLoc, EndLoc,
11579                                             NestedLoopCount, Clauses, AStmt, B,
11580                                             DSAStack->isCancelRegion());
11581 }
11582 
11583 StmtResult Sema::ActOnOpenMPMasterTaskLoopSimdDirective(
11584     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11585     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
11586   if (!AStmt)
11587     return StmtError();
11588 
11589   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
11590   OMPLoopBasedDirective::HelperExprs B;
11591   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
11592   // define the nested loops number.
11593   unsigned NestedLoopCount =
11594       checkOpenMPLoop(OMPD_master_taskloop_simd, getCollapseNumberExpr(Clauses),
11595                       /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
11596                       VarsWithImplicitDSA, B);
11597   if (NestedLoopCount == 0)
11598     return StmtError();
11599 
11600   assert((CurContext->isDependentContext() || B.builtAll()) &&
11601          "omp for loop exprs were not built");
11602 
11603   if (!CurContext->isDependentContext()) {
11604     // Finalize the clauses that need pre-built expressions for CodeGen.
11605     for (OMPClause *C : Clauses) {
11606       if (auto *LC = dyn_cast<OMPLinearClause>(C))
11607         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
11608                                      B.NumIterations, *this, CurScope,
11609                                      DSAStack))
11610           return StmtError();
11611     }
11612   }
11613 
11614   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
11615   // The grainsize clause and num_tasks clause are mutually exclusive and may
11616   // not appear on the same taskloop directive.
11617   if (checkGrainsizeNumTasksClauses(*this, Clauses))
11618     return StmtError();
11619   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
11620   // If a reduction clause is present on the taskloop directive, the nogroup
11621   // clause must not be specified.
11622   if (checkReductionClauseWithNogroup(*this, Clauses))
11623     return StmtError();
11624   if (checkSimdlenSafelenSpecified(*this, Clauses))
11625     return StmtError();
11626 
11627   setFunctionHasBranchProtectedScope();
11628   return OMPMasterTaskLoopSimdDirective::Create(
11629       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
11630 }
11631 
11632 StmtResult Sema::ActOnOpenMPParallelMasterTaskLoopDirective(
11633     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11634     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
11635   if (!AStmt)
11636     return StmtError();
11637 
11638   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
11639   auto *CS = cast<CapturedStmt>(AStmt);
11640   // 1.2.2 OpenMP Language Terminology
11641   // Structured block - An executable statement with a single entry at the
11642   // top and a single exit at the bottom.
11643   // The point of exit cannot be a branch out of the structured block.
11644   // longjmp() and throw() must not violate the entry/exit criteria.
11645   CS->getCapturedDecl()->setNothrow();
11646   for (int ThisCaptureLevel =
11647            getOpenMPCaptureLevels(OMPD_parallel_master_taskloop);
11648        ThisCaptureLevel > 1; --ThisCaptureLevel) {
11649     CS = cast<CapturedStmt>(CS->getCapturedStmt());
11650     // 1.2.2 OpenMP Language Terminology
11651     // Structured block - An executable statement with a single entry at the
11652     // top and a single exit at the bottom.
11653     // The point of exit cannot be a branch out of the structured block.
11654     // longjmp() and throw() must not violate the entry/exit criteria.
11655     CS->getCapturedDecl()->setNothrow();
11656   }
11657 
11658   OMPLoopBasedDirective::HelperExprs B;
11659   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
11660   // define the nested loops number.
11661   unsigned NestedLoopCount = checkOpenMPLoop(
11662       OMPD_parallel_master_taskloop, getCollapseNumberExpr(Clauses),
11663       /*OrderedLoopCountExpr=*/nullptr, CS, *this, *DSAStack,
11664       VarsWithImplicitDSA, B);
11665   if (NestedLoopCount == 0)
11666     return StmtError();
11667 
11668   assert((CurContext->isDependentContext() || B.builtAll()) &&
11669          "omp for loop exprs were not built");
11670 
11671   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
11672   // The grainsize clause and num_tasks clause are mutually exclusive and may
11673   // not appear on the same taskloop directive.
11674   if (checkGrainsizeNumTasksClauses(*this, Clauses))
11675     return StmtError();
11676   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
11677   // If a reduction clause is present on the taskloop directive, the nogroup
11678   // clause must not be specified.
11679   if (checkReductionClauseWithNogroup(*this, Clauses))
11680     return StmtError();
11681 
11682   setFunctionHasBranchProtectedScope();
11683   return OMPParallelMasterTaskLoopDirective::Create(
11684       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
11685       DSAStack->isCancelRegion());
11686 }
11687 
11688 StmtResult Sema::ActOnOpenMPParallelMasterTaskLoopSimdDirective(
11689     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11690     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
11691   if (!AStmt)
11692     return StmtError();
11693 
11694   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
11695   auto *CS = cast<CapturedStmt>(AStmt);
11696   // 1.2.2 OpenMP Language Terminology
11697   // Structured block - An executable statement with a single entry at the
11698   // top and a single exit at the bottom.
11699   // The point of exit cannot be a branch out of the structured block.
11700   // longjmp() and throw() must not violate the entry/exit criteria.
11701   CS->getCapturedDecl()->setNothrow();
11702   for (int ThisCaptureLevel =
11703            getOpenMPCaptureLevels(OMPD_parallel_master_taskloop_simd);
11704        ThisCaptureLevel > 1; --ThisCaptureLevel) {
11705     CS = cast<CapturedStmt>(CS->getCapturedStmt());
11706     // 1.2.2 OpenMP Language Terminology
11707     // Structured block - An executable statement with a single entry at the
11708     // top and a single exit at the bottom.
11709     // The point of exit cannot be a branch out of the structured block.
11710     // longjmp() and throw() must not violate the entry/exit criteria.
11711     CS->getCapturedDecl()->setNothrow();
11712   }
11713 
11714   OMPLoopBasedDirective::HelperExprs B;
11715   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
11716   // define the nested loops number.
11717   unsigned NestedLoopCount = checkOpenMPLoop(
11718       OMPD_parallel_master_taskloop_simd, getCollapseNumberExpr(Clauses),
11719       /*OrderedLoopCountExpr=*/nullptr, CS, *this, *DSAStack,
11720       VarsWithImplicitDSA, B);
11721   if (NestedLoopCount == 0)
11722     return StmtError();
11723 
11724   assert((CurContext->isDependentContext() || B.builtAll()) &&
11725          "omp for loop exprs were not built");
11726 
11727   if (!CurContext->isDependentContext()) {
11728     // Finalize the clauses that need pre-built expressions for CodeGen.
11729     for (OMPClause *C : Clauses) {
11730       if (auto *LC = dyn_cast<OMPLinearClause>(C))
11731         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
11732                                      B.NumIterations, *this, CurScope,
11733                                      DSAStack))
11734           return StmtError();
11735     }
11736   }
11737 
11738   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
11739   // The grainsize clause and num_tasks clause are mutually exclusive and may
11740   // not appear on the same taskloop directive.
11741   if (checkGrainsizeNumTasksClauses(*this, Clauses))
11742     return StmtError();
11743   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
11744   // If a reduction clause is present on the taskloop directive, the nogroup
11745   // clause must not be specified.
11746   if (checkReductionClauseWithNogroup(*this, Clauses))
11747     return StmtError();
11748   if (checkSimdlenSafelenSpecified(*this, Clauses))
11749     return StmtError();
11750 
11751   setFunctionHasBranchProtectedScope();
11752   return OMPParallelMasterTaskLoopSimdDirective::Create(
11753       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
11754 }
11755 
11756 StmtResult Sema::ActOnOpenMPDistributeDirective(
11757     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11758     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
11759   if (!AStmt)
11760     return StmtError();
11761 
11762   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
11763   OMPLoopBasedDirective::HelperExprs B;
11764   // In presence of clause 'collapse' with number of loops, it will
11765   // define the nested loops number.
11766   unsigned NestedLoopCount =
11767       checkOpenMPLoop(OMPD_distribute, getCollapseNumberExpr(Clauses),
11768                       nullptr /*ordered not a clause on distribute*/, AStmt,
11769                       *this, *DSAStack, VarsWithImplicitDSA, B);
11770   if (NestedLoopCount == 0)
11771     return StmtError();
11772 
11773   assert((CurContext->isDependentContext() || B.builtAll()) &&
11774          "omp for loop exprs were not built");
11775 
11776   setFunctionHasBranchProtectedScope();
11777   return OMPDistributeDirective::Create(Context, StartLoc, EndLoc,
11778                                         NestedLoopCount, Clauses, AStmt, B);
11779 }
11780 
11781 StmtResult Sema::ActOnOpenMPDistributeParallelForDirective(
11782     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11783     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
11784   if (!AStmt)
11785     return StmtError();
11786 
11787   auto *CS = cast<CapturedStmt>(AStmt);
11788   // 1.2.2 OpenMP Language Terminology
11789   // Structured block - An executable statement with a single entry at the
11790   // top and a single exit at the bottom.
11791   // The point of exit cannot be a branch out of the structured block.
11792   // longjmp() and throw() must not violate the entry/exit criteria.
11793   CS->getCapturedDecl()->setNothrow();
11794   for (int ThisCaptureLevel =
11795            getOpenMPCaptureLevels(OMPD_distribute_parallel_for);
11796        ThisCaptureLevel > 1; --ThisCaptureLevel) {
11797     CS = cast<CapturedStmt>(CS->getCapturedStmt());
11798     // 1.2.2 OpenMP Language Terminology
11799     // Structured block - An executable statement with a single entry at the
11800     // top and a single exit at the bottom.
11801     // The point of exit cannot be a branch out of the structured block.
11802     // longjmp() and throw() must not violate the entry/exit criteria.
11803     CS->getCapturedDecl()->setNothrow();
11804   }
11805 
11806   OMPLoopBasedDirective::HelperExprs B;
11807   // In presence of clause 'collapse' with number of loops, it will
11808   // define the nested loops number.
11809   unsigned NestedLoopCount = checkOpenMPLoop(
11810       OMPD_distribute_parallel_for, getCollapseNumberExpr(Clauses),
11811       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
11812       VarsWithImplicitDSA, B);
11813   if (NestedLoopCount == 0)
11814     return StmtError();
11815 
11816   assert((CurContext->isDependentContext() || B.builtAll()) &&
11817          "omp for loop exprs were not built");
11818 
11819   setFunctionHasBranchProtectedScope();
11820   return OMPDistributeParallelForDirective::Create(
11821       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
11822       DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion());
11823 }
11824 
11825 StmtResult Sema::ActOnOpenMPDistributeParallelForSimdDirective(
11826     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11827     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
11828   if (!AStmt)
11829     return StmtError();
11830 
11831   auto *CS = cast<CapturedStmt>(AStmt);
11832   // 1.2.2 OpenMP Language Terminology
11833   // Structured block - An executable statement with a single entry at the
11834   // top and a single exit at the bottom.
11835   // The point of exit cannot be a branch out of the structured block.
11836   // longjmp() and throw() must not violate the entry/exit criteria.
11837   CS->getCapturedDecl()->setNothrow();
11838   for (int ThisCaptureLevel =
11839            getOpenMPCaptureLevels(OMPD_distribute_parallel_for_simd);
11840        ThisCaptureLevel > 1; --ThisCaptureLevel) {
11841     CS = cast<CapturedStmt>(CS->getCapturedStmt());
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   }
11849 
11850   OMPLoopBasedDirective::HelperExprs B;
11851   // In presence of clause 'collapse' with number of loops, it will
11852   // define the nested loops number.
11853   unsigned NestedLoopCount = checkOpenMPLoop(
11854       OMPD_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
11855       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
11856       VarsWithImplicitDSA, B);
11857   if (NestedLoopCount == 0)
11858     return StmtError();
11859 
11860   assert((CurContext->isDependentContext() || B.builtAll()) &&
11861          "omp for loop exprs were not built");
11862 
11863   if (!CurContext->isDependentContext()) {
11864     // Finalize the clauses that need pre-built expressions for CodeGen.
11865     for (OMPClause *C : Clauses) {
11866       if (auto *LC = dyn_cast<OMPLinearClause>(C))
11867         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
11868                                      B.NumIterations, *this, CurScope,
11869                                      DSAStack))
11870           return StmtError();
11871     }
11872   }
11873 
11874   if (checkSimdlenSafelenSpecified(*this, Clauses))
11875     return StmtError();
11876 
11877   setFunctionHasBranchProtectedScope();
11878   return OMPDistributeParallelForSimdDirective::Create(
11879       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
11880 }
11881 
11882 StmtResult Sema::ActOnOpenMPDistributeSimdDirective(
11883     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11884     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
11885   if (!AStmt)
11886     return StmtError();
11887 
11888   auto *CS = cast<CapturedStmt>(AStmt);
11889   // 1.2.2 OpenMP Language Terminology
11890   // Structured block - An executable statement with a single entry at the
11891   // top and a single exit at the bottom.
11892   // The point of exit cannot be a branch out of the structured block.
11893   // longjmp() and throw() must not violate the entry/exit criteria.
11894   CS->getCapturedDecl()->setNothrow();
11895   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_distribute_simd);
11896        ThisCaptureLevel > 1; --ThisCaptureLevel) {
11897     CS = cast<CapturedStmt>(CS->getCapturedStmt());
11898     // 1.2.2 OpenMP Language Terminology
11899     // Structured block - An executable statement with a single entry at the
11900     // top and a single exit at the bottom.
11901     // The point of exit cannot be a branch out of the structured block.
11902     // longjmp() and throw() must not violate the entry/exit criteria.
11903     CS->getCapturedDecl()->setNothrow();
11904   }
11905 
11906   OMPLoopBasedDirective::HelperExprs B;
11907   // In presence of clause 'collapse' with number of loops, it will
11908   // define the nested loops number.
11909   unsigned NestedLoopCount =
11910       checkOpenMPLoop(OMPD_distribute_simd, getCollapseNumberExpr(Clauses),
11911                       nullptr /*ordered not a clause on distribute*/, CS, *this,
11912                       *DSAStack, VarsWithImplicitDSA, B);
11913   if (NestedLoopCount == 0)
11914     return StmtError();
11915 
11916   assert((CurContext->isDependentContext() || B.builtAll()) &&
11917          "omp for loop exprs were not built");
11918 
11919   if (!CurContext->isDependentContext()) {
11920     // Finalize the clauses that need pre-built expressions for CodeGen.
11921     for (OMPClause *C : Clauses) {
11922       if (auto *LC = dyn_cast<OMPLinearClause>(C))
11923         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
11924                                      B.NumIterations, *this, CurScope,
11925                                      DSAStack))
11926           return StmtError();
11927     }
11928   }
11929 
11930   if (checkSimdlenSafelenSpecified(*this, Clauses))
11931     return StmtError();
11932 
11933   setFunctionHasBranchProtectedScope();
11934   return OMPDistributeSimdDirective::Create(Context, StartLoc, EndLoc,
11935                                             NestedLoopCount, Clauses, AStmt, B);
11936 }
11937 
11938 StmtResult Sema::ActOnOpenMPTargetParallelForSimdDirective(
11939     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11940     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
11941   if (!AStmt)
11942     return StmtError();
11943 
11944   auto *CS = cast<CapturedStmt>(AStmt);
11945   // 1.2.2 OpenMP Language Terminology
11946   // Structured block - An executable statement with a single entry at the
11947   // top and a single exit at the bottom.
11948   // The point of exit cannot be a branch out of the structured block.
11949   // longjmp() and throw() must not violate the entry/exit criteria.
11950   CS->getCapturedDecl()->setNothrow();
11951   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
11952        ThisCaptureLevel > 1; --ThisCaptureLevel) {
11953     CS = cast<CapturedStmt>(CS->getCapturedStmt());
11954     // 1.2.2 OpenMP Language Terminology
11955     // Structured block - An executable statement with a single entry at the
11956     // top and a single exit at the bottom.
11957     // The point of exit cannot be a branch out of the structured block.
11958     // longjmp() and throw() must not violate the entry/exit criteria.
11959     CS->getCapturedDecl()->setNothrow();
11960   }
11961 
11962   OMPLoopBasedDirective::HelperExprs B;
11963   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
11964   // define the nested loops number.
11965   unsigned NestedLoopCount = checkOpenMPLoop(
11966       OMPD_target_parallel_for_simd, getCollapseNumberExpr(Clauses),
11967       getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
11968       VarsWithImplicitDSA, B);
11969   if (NestedLoopCount == 0)
11970     return StmtError();
11971 
11972   assert((CurContext->isDependentContext() || B.builtAll()) &&
11973          "omp target parallel for simd loop exprs were not built");
11974 
11975   if (!CurContext->isDependentContext()) {
11976     // Finalize the clauses that need pre-built expressions for CodeGen.
11977     for (OMPClause *C : Clauses) {
11978       if (auto *LC = dyn_cast<OMPLinearClause>(C))
11979         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
11980                                      B.NumIterations, *this, CurScope,
11981                                      DSAStack))
11982           return StmtError();
11983     }
11984   }
11985   if (checkSimdlenSafelenSpecified(*this, Clauses))
11986     return StmtError();
11987 
11988   setFunctionHasBranchProtectedScope();
11989   return OMPTargetParallelForSimdDirective::Create(
11990       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
11991 }
11992 
11993 StmtResult Sema::ActOnOpenMPTargetSimdDirective(
11994     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11995     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
11996   if (!AStmt)
11997     return StmtError();
11998 
11999   auto *CS = cast<CapturedStmt>(AStmt);
12000   // 1.2.2 OpenMP Language Terminology
12001   // Structured block - An executable statement with a single entry at the
12002   // top and a single exit at the bottom.
12003   // The point of exit cannot be a branch out of the structured block.
12004   // longjmp() and throw() must not violate the entry/exit criteria.
12005   CS->getCapturedDecl()->setNothrow();
12006   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_simd);
12007        ThisCaptureLevel > 1; --ThisCaptureLevel) {
12008     CS = cast<CapturedStmt>(CS->getCapturedStmt());
12009     // 1.2.2 OpenMP Language Terminology
12010     // Structured block - An executable statement with a single entry at the
12011     // top and a single exit at the bottom.
12012     // The point of exit cannot be a branch out of the structured block.
12013     // longjmp() and throw() must not violate the entry/exit criteria.
12014     CS->getCapturedDecl()->setNothrow();
12015   }
12016 
12017   OMPLoopBasedDirective::HelperExprs B;
12018   // In presence of clause 'collapse' with number of loops, it will define the
12019   // nested loops number.
12020   unsigned NestedLoopCount =
12021       checkOpenMPLoop(OMPD_target_simd, getCollapseNumberExpr(Clauses),
12022                       getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
12023                       VarsWithImplicitDSA, B);
12024   if (NestedLoopCount == 0)
12025     return StmtError();
12026 
12027   assert((CurContext->isDependentContext() || B.builtAll()) &&
12028          "omp target simd loop exprs were not built");
12029 
12030   if (!CurContext->isDependentContext()) {
12031     // Finalize the clauses that need pre-built expressions for CodeGen.
12032     for (OMPClause *C : Clauses) {
12033       if (auto *LC = dyn_cast<OMPLinearClause>(C))
12034         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
12035                                      B.NumIterations, *this, CurScope,
12036                                      DSAStack))
12037           return StmtError();
12038     }
12039   }
12040 
12041   if (checkSimdlenSafelenSpecified(*this, Clauses))
12042     return StmtError();
12043 
12044   setFunctionHasBranchProtectedScope();
12045   return OMPTargetSimdDirective::Create(Context, StartLoc, EndLoc,
12046                                         NestedLoopCount, Clauses, AStmt, B);
12047 }
12048 
12049 StmtResult Sema::ActOnOpenMPTeamsDistributeDirective(
12050     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
12051     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
12052   if (!AStmt)
12053     return StmtError();
12054 
12055   auto *CS = cast<CapturedStmt>(AStmt);
12056   // 1.2.2 OpenMP Language Terminology
12057   // Structured block - An executable statement with a single entry at the
12058   // top and a single exit at the bottom.
12059   // The point of exit cannot be a branch out of the structured block.
12060   // longjmp() and throw() must not violate the entry/exit criteria.
12061   CS->getCapturedDecl()->setNothrow();
12062   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_teams_distribute);
12063        ThisCaptureLevel > 1; --ThisCaptureLevel) {
12064     CS = cast<CapturedStmt>(CS->getCapturedStmt());
12065     // 1.2.2 OpenMP Language Terminology
12066     // Structured block - An executable statement with a single entry at the
12067     // top and a single exit at the bottom.
12068     // The point of exit cannot be a branch out of the structured block.
12069     // longjmp() and throw() must not violate the entry/exit criteria.
12070     CS->getCapturedDecl()->setNothrow();
12071   }
12072 
12073   OMPLoopBasedDirective::HelperExprs B;
12074   // In presence of clause 'collapse' with number of loops, it will
12075   // define the nested loops number.
12076   unsigned NestedLoopCount =
12077       checkOpenMPLoop(OMPD_teams_distribute, getCollapseNumberExpr(Clauses),
12078                       nullptr /*ordered not a clause on distribute*/, CS, *this,
12079                       *DSAStack, VarsWithImplicitDSA, B);
12080   if (NestedLoopCount == 0)
12081     return StmtError();
12082 
12083   assert((CurContext->isDependentContext() || B.builtAll()) &&
12084          "omp teams distribute loop exprs were not built");
12085 
12086   setFunctionHasBranchProtectedScope();
12087 
12088   DSAStack->setParentTeamsRegionLoc(StartLoc);
12089 
12090   return OMPTeamsDistributeDirective::Create(
12091       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
12092 }
12093 
12094 StmtResult Sema::ActOnOpenMPTeamsDistributeSimdDirective(
12095     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
12096     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
12097   if (!AStmt)
12098     return StmtError();
12099 
12100   auto *CS = cast<CapturedStmt>(AStmt);
12101   // 1.2.2 OpenMP Language Terminology
12102   // Structured block - An executable statement with a single entry at the
12103   // top and a single exit at the bottom.
12104   // The point of exit cannot be a branch out of the structured block.
12105   // longjmp() and throw() must not violate the entry/exit criteria.
12106   CS->getCapturedDecl()->setNothrow();
12107   for (int ThisCaptureLevel =
12108            getOpenMPCaptureLevels(OMPD_teams_distribute_simd);
12109        ThisCaptureLevel > 1; --ThisCaptureLevel) {
12110     CS = cast<CapturedStmt>(CS->getCapturedStmt());
12111     // 1.2.2 OpenMP Language Terminology
12112     // Structured block - An executable statement with a single entry at the
12113     // top and a single exit at the bottom.
12114     // The point of exit cannot be a branch out of the structured block.
12115     // longjmp() and throw() must not violate the entry/exit criteria.
12116     CS->getCapturedDecl()->setNothrow();
12117   }
12118 
12119   OMPLoopBasedDirective::HelperExprs B;
12120   // In presence of clause 'collapse' with number of loops, it will
12121   // define the nested loops number.
12122   unsigned NestedLoopCount = checkOpenMPLoop(
12123       OMPD_teams_distribute_simd, getCollapseNumberExpr(Clauses),
12124       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
12125       VarsWithImplicitDSA, B);
12126 
12127   if (NestedLoopCount == 0)
12128     return StmtError();
12129 
12130   assert((CurContext->isDependentContext() || B.builtAll()) &&
12131          "omp teams distribute simd loop exprs were not built");
12132 
12133   if (!CurContext->isDependentContext()) {
12134     // Finalize the clauses that need pre-built expressions for CodeGen.
12135     for (OMPClause *C : Clauses) {
12136       if (auto *LC = dyn_cast<OMPLinearClause>(C))
12137         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
12138                                      B.NumIterations, *this, CurScope,
12139                                      DSAStack))
12140           return StmtError();
12141     }
12142   }
12143 
12144   if (checkSimdlenSafelenSpecified(*this, Clauses))
12145     return StmtError();
12146 
12147   setFunctionHasBranchProtectedScope();
12148 
12149   DSAStack->setParentTeamsRegionLoc(StartLoc);
12150 
12151   return OMPTeamsDistributeSimdDirective::Create(
12152       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
12153 }
12154 
12155 StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForSimdDirective(
12156     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
12157     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
12158   if (!AStmt)
12159     return StmtError();
12160 
12161   auto *CS = cast<CapturedStmt>(AStmt);
12162   // 1.2.2 OpenMP Language Terminology
12163   // Structured block - An executable statement with a single entry at the
12164   // top and a single exit at the bottom.
12165   // The point of exit cannot be a branch out of the structured block.
12166   // longjmp() and throw() must not violate the entry/exit criteria.
12167   CS->getCapturedDecl()->setNothrow();
12168 
12169   for (int ThisCaptureLevel =
12170            getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for_simd);
12171        ThisCaptureLevel > 1; --ThisCaptureLevel) {
12172     CS = cast<CapturedStmt>(CS->getCapturedStmt());
12173     // 1.2.2 OpenMP Language Terminology
12174     // Structured block - An executable statement with a single entry at the
12175     // top and a single exit at the bottom.
12176     // The point of exit cannot be a branch out of the structured block.
12177     // longjmp() and throw() must not violate the entry/exit criteria.
12178     CS->getCapturedDecl()->setNothrow();
12179   }
12180 
12181   OMPLoopBasedDirective::HelperExprs B;
12182   // In presence of clause 'collapse' with number of loops, it will
12183   // define the nested loops number.
12184   unsigned NestedLoopCount = checkOpenMPLoop(
12185       OMPD_teams_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
12186       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
12187       VarsWithImplicitDSA, B);
12188 
12189   if (NestedLoopCount == 0)
12190     return StmtError();
12191 
12192   assert((CurContext->isDependentContext() || B.builtAll()) &&
12193          "omp for loop exprs were not built");
12194 
12195   if (!CurContext->isDependentContext()) {
12196     // Finalize the clauses that need pre-built expressions for CodeGen.
12197     for (OMPClause *C : Clauses) {
12198       if (auto *LC = dyn_cast<OMPLinearClause>(C))
12199         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
12200                                      B.NumIterations, *this, CurScope,
12201                                      DSAStack))
12202           return StmtError();
12203     }
12204   }
12205 
12206   if (checkSimdlenSafelenSpecified(*this, Clauses))
12207     return StmtError();
12208 
12209   setFunctionHasBranchProtectedScope();
12210 
12211   DSAStack->setParentTeamsRegionLoc(StartLoc);
12212 
12213   return OMPTeamsDistributeParallelForSimdDirective::Create(
12214       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
12215 }
12216 
12217 StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForDirective(
12218     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
12219     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
12220   if (!AStmt)
12221     return StmtError();
12222 
12223   auto *CS = cast<CapturedStmt>(AStmt);
12224   // 1.2.2 OpenMP Language Terminology
12225   // Structured block - An executable statement with a single entry at the
12226   // top and a single exit at the bottom.
12227   // The point of exit cannot be a branch out of the structured block.
12228   // longjmp() and throw() must not violate the entry/exit criteria.
12229   CS->getCapturedDecl()->setNothrow();
12230 
12231   for (int ThisCaptureLevel =
12232            getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for);
12233        ThisCaptureLevel > 1; --ThisCaptureLevel) {
12234     CS = cast<CapturedStmt>(CS->getCapturedStmt());
12235     // 1.2.2 OpenMP Language Terminology
12236     // Structured block - An executable statement with a single entry at the
12237     // top and a single exit at the bottom.
12238     // The point of exit cannot be a branch out of the structured block.
12239     // longjmp() and throw() must not violate the entry/exit criteria.
12240     CS->getCapturedDecl()->setNothrow();
12241   }
12242 
12243   OMPLoopBasedDirective::HelperExprs B;
12244   // In presence of clause 'collapse' with number of loops, it will
12245   // define the nested loops number.
12246   unsigned NestedLoopCount = checkOpenMPLoop(
12247       OMPD_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
12248       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
12249       VarsWithImplicitDSA, B);
12250 
12251   if (NestedLoopCount == 0)
12252     return StmtError();
12253 
12254   assert((CurContext->isDependentContext() || B.builtAll()) &&
12255          "omp for loop exprs were not built");
12256 
12257   setFunctionHasBranchProtectedScope();
12258 
12259   DSAStack->setParentTeamsRegionLoc(StartLoc);
12260 
12261   return OMPTeamsDistributeParallelForDirective::Create(
12262       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
12263       DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion());
12264 }
12265 
12266 StmtResult Sema::ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses,
12267                                                  Stmt *AStmt,
12268                                                  SourceLocation StartLoc,
12269                                                  SourceLocation EndLoc) {
12270   if (!AStmt)
12271     return StmtError();
12272 
12273   auto *CS = cast<CapturedStmt>(AStmt);
12274   // 1.2.2 OpenMP Language Terminology
12275   // Structured block - An executable statement with a single entry at the
12276   // top and a single exit at the bottom.
12277   // The point of exit cannot be a branch out of the structured block.
12278   // longjmp() and throw() must not violate the entry/exit criteria.
12279   CS->getCapturedDecl()->setNothrow();
12280 
12281   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_teams);
12282        ThisCaptureLevel > 1; --ThisCaptureLevel) {
12283     CS = cast<CapturedStmt>(CS->getCapturedStmt());
12284     // 1.2.2 OpenMP Language Terminology
12285     // Structured block - An executable statement with a single entry at the
12286     // top and a single exit at the bottom.
12287     // The point of exit cannot be a branch out of the structured block.
12288     // longjmp() and throw() must not violate the entry/exit criteria.
12289     CS->getCapturedDecl()->setNothrow();
12290   }
12291   setFunctionHasBranchProtectedScope();
12292 
12293   return OMPTargetTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses,
12294                                          AStmt);
12295 }
12296 
12297 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeDirective(
12298     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
12299     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
12300   if (!AStmt)
12301     return StmtError();
12302 
12303   auto *CS = cast<CapturedStmt>(AStmt);
12304   // 1.2.2 OpenMP Language Terminology
12305   // Structured block - An executable statement with a single entry at the
12306   // top and a single exit at the bottom.
12307   // The point of exit cannot be a branch out of the structured block.
12308   // longjmp() and throw() must not violate the entry/exit criteria.
12309   CS->getCapturedDecl()->setNothrow();
12310   for (int ThisCaptureLevel =
12311            getOpenMPCaptureLevels(OMPD_target_teams_distribute);
12312        ThisCaptureLevel > 1; --ThisCaptureLevel) {
12313     CS = cast<CapturedStmt>(CS->getCapturedStmt());
12314     // 1.2.2 OpenMP Language Terminology
12315     // Structured block - An executable statement with a single entry at the
12316     // top and a single exit at the bottom.
12317     // The point of exit cannot be a branch out of the structured block.
12318     // longjmp() and throw() must not violate the entry/exit criteria.
12319     CS->getCapturedDecl()->setNothrow();
12320   }
12321 
12322   OMPLoopBasedDirective::HelperExprs B;
12323   // In presence of clause 'collapse' with number of loops, it will
12324   // define the nested loops number.
12325   unsigned NestedLoopCount = checkOpenMPLoop(
12326       OMPD_target_teams_distribute, getCollapseNumberExpr(Clauses),
12327       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
12328       VarsWithImplicitDSA, B);
12329   if (NestedLoopCount == 0)
12330     return StmtError();
12331 
12332   assert((CurContext->isDependentContext() || B.builtAll()) &&
12333          "omp target teams distribute loop exprs were not built");
12334 
12335   setFunctionHasBranchProtectedScope();
12336   return OMPTargetTeamsDistributeDirective::Create(
12337       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
12338 }
12339 
12340 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForDirective(
12341     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
12342     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
12343   if (!AStmt)
12344     return StmtError();
12345 
12346   auto *CS = cast<CapturedStmt>(AStmt);
12347   // 1.2.2 OpenMP Language Terminology
12348   // Structured block - An executable statement with a single entry at the
12349   // top and a single exit at the bottom.
12350   // The point of exit cannot be a branch out of the structured block.
12351   // longjmp() and throw() must not violate the entry/exit criteria.
12352   CS->getCapturedDecl()->setNothrow();
12353   for (int ThisCaptureLevel =
12354            getOpenMPCaptureLevels(OMPD_target_teams_distribute_parallel_for);
12355        ThisCaptureLevel > 1; --ThisCaptureLevel) {
12356     CS = cast<CapturedStmt>(CS->getCapturedStmt());
12357     // 1.2.2 OpenMP Language Terminology
12358     // Structured block - An executable statement with a single entry at the
12359     // top and a single exit at the bottom.
12360     // The point of exit cannot be a branch out of the structured block.
12361     // longjmp() and throw() must not violate the entry/exit criteria.
12362     CS->getCapturedDecl()->setNothrow();
12363   }
12364 
12365   OMPLoopBasedDirective::HelperExprs B;
12366   // In presence of clause 'collapse' with number of loops, it will
12367   // define the nested loops number.
12368   unsigned NestedLoopCount = checkOpenMPLoop(
12369       OMPD_target_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
12370       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
12371       VarsWithImplicitDSA, B);
12372   if (NestedLoopCount == 0)
12373     return StmtError();
12374 
12375   assert((CurContext->isDependentContext() || B.builtAll()) &&
12376          "omp target teams distribute parallel for loop exprs were not built");
12377 
12378   if (!CurContext->isDependentContext()) {
12379     // Finalize the clauses that need pre-built expressions for CodeGen.
12380     for (OMPClause *C : Clauses) {
12381       if (auto *LC = dyn_cast<OMPLinearClause>(C))
12382         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
12383                                      B.NumIterations, *this, CurScope,
12384                                      DSAStack))
12385           return StmtError();
12386     }
12387   }
12388 
12389   setFunctionHasBranchProtectedScope();
12390   return OMPTargetTeamsDistributeParallelForDirective::Create(
12391       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
12392       DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion());
12393 }
12394 
12395 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
12396     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
12397     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
12398   if (!AStmt)
12399     return StmtError();
12400 
12401   auto *CS = cast<CapturedStmt>(AStmt);
12402   // 1.2.2 OpenMP Language Terminology
12403   // Structured block - An executable statement with a single entry at the
12404   // top and a single exit at the bottom.
12405   // The point of exit cannot be a branch out of the structured block.
12406   // longjmp() and throw() must not violate the entry/exit criteria.
12407   CS->getCapturedDecl()->setNothrow();
12408   for (int ThisCaptureLevel = getOpenMPCaptureLevels(
12409            OMPD_target_teams_distribute_parallel_for_simd);
12410        ThisCaptureLevel > 1; --ThisCaptureLevel) {
12411     CS = cast<CapturedStmt>(CS->getCapturedStmt());
12412     // 1.2.2 OpenMP Language Terminology
12413     // Structured block - An executable statement with a single entry at the
12414     // top and a single exit at the bottom.
12415     // The point of exit cannot be a branch out of the structured block.
12416     // longjmp() and throw() must not violate the entry/exit criteria.
12417     CS->getCapturedDecl()->setNothrow();
12418   }
12419 
12420   OMPLoopBasedDirective::HelperExprs B;
12421   // In presence of clause 'collapse' with number of loops, it will
12422   // define the nested loops number.
12423   unsigned NestedLoopCount =
12424       checkOpenMPLoop(OMPD_target_teams_distribute_parallel_for_simd,
12425                       getCollapseNumberExpr(Clauses),
12426                       nullptr /*ordered not a clause on distribute*/, CS, *this,
12427                       *DSAStack, VarsWithImplicitDSA, B);
12428   if (NestedLoopCount == 0)
12429     return StmtError();
12430 
12431   assert((CurContext->isDependentContext() || B.builtAll()) &&
12432          "omp target teams distribute parallel for simd loop exprs were not "
12433          "built");
12434 
12435   if (!CurContext->isDependentContext()) {
12436     // Finalize the clauses that need pre-built expressions for CodeGen.
12437     for (OMPClause *C : Clauses) {
12438       if (auto *LC = dyn_cast<OMPLinearClause>(C))
12439         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
12440                                      B.NumIterations, *this, CurScope,
12441                                      DSAStack))
12442           return StmtError();
12443     }
12444   }
12445 
12446   if (checkSimdlenSafelenSpecified(*this, Clauses))
12447     return StmtError();
12448 
12449   setFunctionHasBranchProtectedScope();
12450   return OMPTargetTeamsDistributeParallelForSimdDirective::Create(
12451       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
12452 }
12453 
12454 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeSimdDirective(
12455     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
12456     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
12457   if (!AStmt)
12458     return StmtError();
12459 
12460   auto *CS = cast<CapturedStmt>(AStmt);
12461   // 1.2.2 OpenMP Language Terminology
12462   // Structured block - An executable statement with a single entry at the
12463   // top and a single exit at the bottom.
12464   // The point of exit cannot be a branch out of the structured block.
12465   // longjmp() and throw() must not violate the entry/exit criteria.
12466   CS->getCapturedDecl()->setNothrow();
12467   for (int ThisCaptureLevel =
12468            getOpenMPCaptureLevels(OMPD_target_teams_distribute_simd);
12469        ThisCaptureLevel > 1; --ThisCaptureLevel) {
12470     CS = cast<CapturedStmt>(CS->getCapturedStmt());
12471     // 1.2.2 OpenMP Language Terminology
12472     // Structured block - An executable statement with a single entry at the
12473     // top and a single exit at the bottom.
12474     // The point of exit cannot be a branch out of the structured block.
12475     // longjmp() and throw() must not violate the entry/exit criteria.
12476     CS->getCapturedDecl()->setNothrow();
12477   }
12478 
12479   OMPLoopBasedDirective::HelperExprs B;
12480   // In presence of clause 'collapse' with number of loops, it will
12481   // define the nested loops number.
12482   unsigned NestedLoopCount = checkOpenMPLoop(
12483       OMPD_target_teams_distribute_simd, getCollapseNumberExpr(Clauses),
12484       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
12485       VarsWithImplicitDSA, B);
12486   if (NestedLoopCount == 0)
12487     return StmtError();
12488 
12489   assert((CurContext->isDependentContext() || B.builtAll()) &&
12490          "omp target teams distribute simd loop exprs were not built");
12491 
12492   if (!CurContext->isDependentContext()) {
12493     // Finalize the clauses that need pre-built expressions for CodeGen.
12494     for (OMPClause *C : Clauses) {
12495       if (auto *LC = dyn_cast<OMPLinearClause>(C))
12496         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
12497                                      B.NumIterations, *this, CurScope,
12498                                      DSAStack))
12499           return StmtError();
12500     }
12501   }
12502 
12503   if (checkSimdlenSafelenSpecified(*this, Clauses))
12504     return StmtError();
12505 
12506   setFunctionHasBranchProtectedScope();
12507   return OMPTargetTeamsDistributeSimdDirective::Create(
12508       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
12509 }
12510 
12511 StmtResult Sema::ActOnOpenMPTileDirective(ArrayRef<OMPClause *> Clauses,
12512                                           Stmt *AStmt, SourceLocation StartLoc,
12513                                           SourceLocation EndLoc) {
12514   auto SizesClauses =
12515       OMPExecutableDirective::getClausesOfKind<OMPSizesClause>(Clauses);
12516   if (SizesClauses.empty()) {
12517     // A missing 'sizes' clause is already reported by the parser.
12518     return StmtError();
12519   }
12520   const OMPSizesClause *SizesClause = *SizesClauses.begin();
12521   unsigned NumLoops = SizesClause->getNumSizes();
12522 
12523   // Empty statement should only be possible if there already was an error.
12524   if (!AStmt)
12525     return StmtError();
12526 
12527   // Verify and diagnose loop nest.
12528   SmallVector<OMPLoopBasedDirective::HelperExprs, 4> LoopHelpers(NumLoops);
12529   Stmt *Body = nullptr;
12530   SmallVector<Stmt *, 4> OriginalInits;
12531   if (!OMPLoopBasedDirective::doForAllLoops(
12532           AStmt->IgnoreContainers(), /*TryImperfectlyNestedLoops=*/false,
12533           NumLoops,
12534           [this, &LoopHelpers, &Body, &OriginalInits](unsigned Cnt,
12535                                                       Stmt *CurStmt) {
12536             VarsWithInheritedDSAType TmpDSA;
12537             unsigned SingleNumLoops =
12538                 checkOpenMPLoop(OMPD_tile, nullptr, nullptr, CurStmt, *this,
12539                                 *DSAStack, TmpDSA, LoopHelpers[Cnt]);
12540             if (SingleNumLoops == 0)
12541               return true;
12542             assert(SingleNumLoops == 1 && "Expect single loop iteration space");
12543             if (auto *For = dyn_cast<ForStmt>(CurStmt)) {
12544               OriginalInits.push_back(For->getInit());
12545               Body = For->getBody();
12546             } else {
12547               assert(isa<CXXForRangeStmt>(CurStmt) &&
12548                      "Expected canonical for or range-based for loops.");
12549               auto *CXXFor = cast<CXXForRangeStmt>(CurStmt);
12550               OriginalInits.push_back(CXXFor->getBeginStmt());
12551               Body = CXXFor->getBody();
12552             }
12553             return false;
12554           }))
12555     return StmtError();
12556 
12557   // Delay tiling to when template is completely instantiated.
12558   if (CurContext->isDependentContext())
12559     return OMPTileDirective::Create(Context, StartLoc, EndLoc, Clauses,
12560                                     NumLoops, AStmt, nullptr, nullptr);
12561 
12562   // Collection of generated variable declaration.
12563   SmallVector<Decl *, 4> PreInits;
12564 
12565   // Create iteration variables for the generated loops.
12566   SmallVector<VarDecl *, 4> FloorIndVars;
12567   SmallVector<VarDecl *, 4> TileIndVars;
12568   FloorIndVars.resize(NumLoops);
12569   TileIndVars.resize(NumLoops);
12570   for (unsigned I = 0; I < NumLoops; ++I) {
12571     OMPLoopBasedDirective::HelperExprs &LoopHelper = LoopHelpers[I];
12572     if (auto *PI = cast_or_null<DeclStmt>(LoopHelper.PreInits))
12573       PreInits.append(PI->decl_begin(), PI->decl_end());
12574     assert(LoopHelper.Counters.size() == 1 &&
12575            "Expect single-dimensional loop iteration space");
12576     auto *OrigCntVar = cast<DeclRefExpr>(LoopHelper.Counters.front());
12577     std::string OrigVarName = OrigCntVar->getNameInfo().getAsString();
12578     DeclRefExpr *IterVarRef = cast<DeclRefExpr>(LoopHelper.IterationVarRef);
12579     QualType CntTy = IterVarRef->getType();
12580 
12581     // Iteration variable for the floor (i.e. outer) loop.
12582     {
12583       std::string FloorCntName =
12584           (Twine(".floor_") + llvm::utostr(I) + ".iv." + OrigVarName).str();
12585       VarDecl *FloorCntDecl =
12586           buildVarDecl(*this, {}, CntTy, FloorCntName, nullptr, OrigCntVar);
12587       FloorIndVars[I] = FloorCntDecl;
12588     }
12589 
12590     // Iteration variable for the tile (i.e. inner) loop.
12591     {
12592       std::string TileCntName =
12593           (Twine(".tile_") + llvm::utostr(I) + ".iv." + OrigVarName).str();
12594 
12595       // Reuse the iteration variable created by checkOpenMPLoop. It is also
12596       // used by the expressions to derive the original iteration variable's
12597       // value from the logical iteration number.
12598       auto *TileCntDecl = cast<VarDecl>(IterVarRef->getDecl());
12599       TileCntDecl->setDeclName(&PP.getIdentifierTable().get(TileCntName));
12600       TileIndVars[I] = TileCntDecl;
12601     }
12602     if (auto *PI = dyn_cast_or_null<DeclStmt>(OriginalInits[I]))
12603       PreInits.append(PI->decl_begin(), PI->decl_end());
12604     // Gather declarations for the data members used as counters.
12605     for (Expr *CounterRef : LoopHelper.Counters) {
12606       auto *CounterDecl = cast<DeclRefExpr>(CounterRef)->getDecl();
12607       if (isa<OMPCapturedExprDecl>(CounterDecl))
12608         PreInits.push_back(CounterDecl);
12609     }
12610   }
12611 
12612   // Once the original iteration values are set, append the innermost body.
12613   Stmt *Inner = Body;
12614 
12615   // Create tile loops from the inside to the outside.
12616   for (int I = NumLoops - 1; I >= 0; --I) {
12617     OMPLoopBasedDirective::HelperExprs &LoopHelper = LoopHelpers[I];
12618     Expr *NumIterations = LoopHelper.NumIterations;
12619     auto *OrigCntVar = cast<DeclRefExpr>(LoopHelper.Counters[0]);
12620     QualType CntTy = OrigCntVar->getType();
12621     Expr *DimTileSize = SizesClause->getSizesRefs()[I];
12622     Scope *CurScope = getCurScope();
12623 
12624     // Commonly used variables.
12625     DeclRefExpr *TileIV = buildDeclRefExpr(*this, TileIndVars[I], CntTy,
12626                                            OrigCntVar->getExprLoc());
12627     DeclRefExpr *FloorIV = buildDeclRefExpr(*this, FloorIndVars[I], CntTy,
12628                                             OrigCntVar->getExprLoc());
12629 
12630     // For init-statement: auto .tile.iv = .floor.iv
12631     AddInitializerToDecl(TileIndVars[I], DefaultLvalueConversion(FloorIV).get(),
12632                          /*DirectInit=*/false);
12633     Decl *CounterDecl = TileIndVars[I];
12634     StmtResult InitStmt = new (Context)
12635         DeclStmt(DeclGroupRef::Create(Context, &CounterDecl, 1),
12636                  OrigCntVar->getBeginLoc(), OrigCntVar->getEndLoc());
12637     if (!InitStmt.isUsable())
12638       return StmtError();
12639 
12640     // For cond-expression: .tile.iv < min(.floor.iv + DimTileSize,
12641     // NumIterations)
12642     ExprResult EndOfTile = BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(),
12643                                       BO_Add, FloorIV, DimTileSize);
12644     if (!EndOfTile.isUsable())
12645       return StmtError();
12646     ExprResult IsPartialTile =
12647         BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(), BO_LT,
12648                    NumIterations, EndOfTile.get());
12649     if (!IsPartialTile.isUsable())
12650       return StmtError();
12651     ExprResult MinTileAndIterSpace = ActOnConditionalOp(
12652         LoopHelper.Cond->getBeginLoc(), LoopHelper.Cond->getEndLoc(),
12653         IsPartialTile.get(), NumIterations, EndOfTile.get());
12654     if (!MinTileAndIterSpace.isUsable())
12655       return StmtError();
12656     ExprResult CondExpr = BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(),
12657                                      BO_LT, TileIV, MinTileAndIterSpace.get());
12658     if (!CondExpr.isUsable())
12659       return StmtError();
12660 
12661     // For incr-statement: ++.tile.iv
12662     ExprResult IncrStmt =
12663         BuildUnaryOp(CurScope, LoopHelper.Inc->getExprLoc(), UO_PreInc, TileIV);
12664     if (!IncrStmt.isUsable())
12665       return StmtError();
12666 
12667     // Statements to set the original iteration variable's value from the
12668     // logical iteration number.
12669     // Generated for loop is:
12670     // Original_for_init;
12671     // for (auto .tile.iv = .floor.iv; .tile.iv < min(.floor.iv + DimTileSize,
12672     // NumIterations); ++.tile.iv) {
12673     //   Original_Body;
12674     //   Original_counter_update;
12675     // }
12676     // FIXME: If the innermost body is an loop itself, inserting these
12677     // statements stops it being recognized  as a perfectly nested loop (e.g.
12678     // for applying tiling again). If this is the case, sink the expressions
12679     // further into the inner loop.
12680     SmallVector<Stmt *, 4> BodyParts;
12681     BodyParts.append(LoopHelper.Updates.begin(), LoopHelper.Updates.end());
12682     BodyParts.push_back(Inner);
12683     Inner = CompoundStmt::Create(Context, BodyParts, Inner->getBeginLoc(),
12684                                  Inner->getEndLoc());
12685     Inner = new (Context)
12686         ForStmt(Context, InitStmt.get(), CondExpr.get(), nullptr,
12687                 IncrStmt.get(), Inner, LoopHelper.Init->getBeginLoc(),
12688                 LoopHelper.Init->getBeginLoc(), LoopHelper.Inc->getEndLoc());
12689   }
12690 
12691   // Create floor loops from the inside to the outside.
12692   for (int I = NumLoops - 1; I >= 0; --I) {
12693     auto &LoopHelper = LoopHelpers[I];
12694     Expr *NumIterations = LoopHelper.NumIterations;
12695     DeclRefExpr *OrigCntVar = cast<DeclRefExpr>(LoopHelper.Counters[0]);
12696     QualType CntTy = OrigCntVar->getType();
12697     Expr *DimTileSize = SizesClause->getSizesRefs()[I];
12698     Scope *CurScope = getCurScope();
12699 
12700     // Commonly used variables.
12701     DeclRefExpr *FloorIV = buildDeclRefExpr(*this, FloorIndVars[I], CntTy,
12702                                             OrigCntVar->getExprLoc());
12703 
12704     // For init-statement: auto .floor.iv = 0
12705     AddInitializerToDecl(
12706         FloorIndVars[I],
12707         ActOnIntegerConstant(LoopHelper.Init->getExprLoc(), 0).get(),
12708         /*DirectInit=*/false);
12709     Decl *CounterDecl = FloorIndVars[I];
12710     StmtResult InitStmt = new (Context)
12711         DeclStmt(DeclGroupRef::Create(Context, &CounterDecl, 1),
12712                  OrigCntVar->getBeginLoc(), OrigCntVar->getEndLoc());
12713     if (!InitStmt.isUsable())
12714       return StmtError();
12715 
12716     // For cond-expression: .floor.iv < NumIterations
12717     ExprResult CondExpr = BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(),
12718                                      BO_LT, FloorIV, NumIterations);
12719     if (!CondExpr.isUsable())
12720       return StmtError();
12721 
12722     // For incr-statement: .floor.iv += DimTileSize
12723     ExprResult IncrStmt = BuildBinOp(CurScope, LoopHelper.Inc->getExprLoc(),
12724                                      BO_AddAssign, FloorIV, DimTileSize);
12725     if (!IncrStmt.isUsable())
12726       return StmtError();
12727 
12728     Inner = new (Context)
12729         ForStmt(Context, InitStmt.get(), CondExpr.get(), nullptr,
12730                 IncrStmt.get(), Inner, LoopHelper.Init->getBeginLoc(),
12731                 LoopHelper.Init->getBeginLoc(), LoopHelper.Inc->getEndLoc());
12732   }
12733 
12734   return OMPTileDirective::Create(Context, StartLoc, EndLoc, Clauses, NumLoops,
12735                                   AStmt, Inner,
12736                                   buildPreInits(Context, PreInits));
12737 }
12738 
12739 OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
12740                                              SourceLocation StartLoc,
12741                                              SourceLocation LParenLoc,
12742                                              SourceLocation EndLoc) {
12743   OMPClause *Res = nullptr;
12744   switch (Kind) {
12745   case OMPC_final:
12746     Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc);
12747     break;
12748   case OMPC_num_threads:
12749     Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc);
12750     break;
12751   case OMPC_safelen:
12752     Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
12753     break;
12754   case OMPC_simdlen:
12755     Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc);
12756     break;
12757   case OMPC_allocator:
12758     Res = ActOnOpenMPAllocatorClause(Expr, StartLoc, LParenLoc, EndLoc);
12759     break;
12760   case OMPC_collapse:
12761     Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc);
12762     break;
12763   case OMPC_ordered:
12764     Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr);
12765     break;
12766   case OMPC_num_teams:
12767     Res = ActOnOpenMPNumTeamsClause(Expr, StartLoc, LParenLoc, EndLoc);
12768     break;
12769   case OMPC_thread_limit:
12770     Res = ActOnOpenMPThreadLimitClause(Expr, StartLoc, LParenLoc, EndLoc);
12771     break;
12772   case OMPC_priority:
12773     Res = ActOnOpenMPPriorityClause(Expr, StartLoc, LParenLoc, EndLoc);
12774     break;
12775   case OMPC_grainsize:
12776     Res = ActOnOpenMPGrainsizeClause(Expr, StartLoc, LParenLoc, EndLoc);
12777     break;
12778   case OMPC_num_tasks:
12779     Res = ActOnOpenMPNumTasksClause(Expr, StartLoc, LParenLoc, EndLoc);
12780     break;
12781   case OMPC_hint:
12782     Res = ActOnOpenMPHintClause(Expr, StartLoc, LParenLoc, EndLoc);
12783     break;
12784   case OMPC_depobj:
12785     Res = ActOnOpenMPDepobjClause(Expr, StartLoc, LParenLoc, EndLoc);
12786     break;
12787   case OMPC_detach:
12788     Res = ActOnOpenMPDetachClause(Expr, StartLoc, LParenLoc, EndLoc);
12789     break;
12790   case OMPC_novariants:
12791     Res = ActOnOpenMPNovariantsClause(Expr, StartLoc, LParenLoc, EndLoc);
12792     break;
12793   case OMPC_nocontext:
12794     Res = ActOnOpenMPNocontextClause(Expr, StartLoc, LParenLoc, EndLoc);
12795     break;
12796   case OMPC_device:
12797   case OMPC_if:
12798   case OMPC_default:
12799   case OMPC_proc_bind:
12800   case OMPC_schedule:
12801   case OMPC_private:
12802   case OMPC_firstprivate:
12803   case OMPC_lastprivate:
12804   case OMPC_shared:
12805   case OMPC_reduction:
12806   case OMPC_task_reduction:
12807   case OMPC_in_reduction:
12808   case OMPC_linear:
12809   case OMPC_aligned:
12810   case OMPC_copyin:
12811   case OMPC_copyprivate:
12812   case OMPC_nowait:
12813   case OMPC_untied:
12814   case OMPC_mergeable:
12815   case OMPC_threadprivate:
12816   case OMPC_sizes:
12817   case OMPC_allocate:
12818   case OMPC_flush:
12819   case OMPC_read:
12820   case OMPC_write:
12821   case OMPC_update:
12822   case OMPC_capture:
12823   case OMPC_seq_cst:
12824   case OMPC_acq_rel:
12825   case OMPC_acquire:
12826   case OMPC_release:
12827   case OMPC_relaxed:
12828   case OMPC_depend:
12829   case OMPC_threads:
12830   case OMPC_simd:
12831   case OMPC_map:
12832   case OMPC_nogroup:
12833   case OMPC_dist_schedule:
12834   case OMPC_defaultmap:
12835   case OMPC_unknown:
12836   case OMPC_uniform:
12837   case OMPC_to:
12838   case OMPC_from:
12839   case OMPC_use_device_ptr:
12840   case OMPC_use_device_addr:
12841   case OMPC_is_device_ptr:
12842   case OMPC_unified_address:
12843   case OMPC_unified_shared_memory:
12844   case OMPC_reverse_offload:
12845   case OMPC_dynamic_allocators:
12846   case OMPC_atomic_default_mem_order:
12847   case OMPC_device_type:
12848   case OMPC_match:
12849   case OMPC_nontemporal:
12850   case OMPC_order:
12851   case OMPC_destroy:
12852   case OMPC_inclusive:
12853   case OMPC_exclusive:
12854   case OMPC_uses_allocators:
12855   case OMPC_affinity:
12856   default:
12857     llvm_unreachable("Clause is not allowed.");
12858   }
12859   return Res;
12860 }
12861 
12862 // An OpenMP directive such as 'target parallel' has two captured regions:
12863 // for the 'target' and 'parallel' respectively.  This function returns
12864 // the region in which to capture expressions associated with a clause.
12865 // A return value of OMPD_unknown signifies that the expression should not
12866 // be captured.
12867 static OpenMPDirectiveKind getOpenMPCaptureRegionForClause(
12868     OpenMPDirectiveKind DKind, OpenMPClauseKind CKind, unsigned OpenMPVersion,
12869     OpenMPDirectiveKind NameModifier = OMPD_unknown) {
12870   OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
12871   switch (CKind) {
12872   case OMPC_if:
12873     switch (DKind) {
12874     case OMPD_target_parallel_for_simd:
12875       if (OpenMPVersion >= 50 &&
12876           (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)) {
12877         CaptureRegion = OMPD_parallel;
12878         break;
12879       }
12880       LLVM_FALLTHROUGH;
12881     case OMPD_target_parallel:
12882     case OMPD_target_parallel_for:
12883       // If this clause applies to the nested 'parallel' region, capture within
12884       // the 'target' region, otherwise do not capture.
12885       if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
12886         CaptureRegion = OMPD_target;
12887       break;
12888     case OMPD_target_teams_distribute_parallel_for_simd:
12889       if (OpenMPVersion >= 50 &&
12890           (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)) {
12891         CaptureRegion = OMPD_parallel;
12892         break;
12893       }
12894       LLVM_FALLTHROUGH;
12895     case OMPD_target_teams_distribute_parallel_for:
12896       // If this clause applies to the nested 'parallel' region, capture within
12897       // the 'teams' region, otherwise do not capture.
12898       if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
12899         CaptureRegion = OMPD_teams;
12900       break;
12901     case OMPD_teams_distribute_parallel_for_simd:
12902       if (OpenMPVersion >= 50 &&
12903           (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)) {
12904         CaptureRegion = OMPD_parallel;
12905         break;
12906       }
12907       LLVM_FALLTHROUGH;
12908     case OMPD_teams_distribute_parallel_for:
12909       CaptureRegion = OMPD_teams;
12910       break;
12911     case OMPD_target_update:
12912     case OMPD_target_enter_data:
12913     case OMPD_target_exit_data:
12914       CaptureRegion = OMPD_task;
12915       break;
12916     case OMPD_parallel_master_taskloop:
12917       if (NameModifier == OMPD_unknown || NameModifier == OMPD_taskloop)
12918         CaptureRegion = OMPD_parallel;
12919       break;
12920     case OMPD_parallel_master_taskloop_simd:
12921       if ((OpenMPVersion <= 45 && NameModifier == OMPD_unknown) ||
12922           NameModifier == OMPD_taskloop) {
12923         CaptureRegion = OMPD_parallel;
12924         break;
12925       }
12926       if (OpenMPVersion <= 45)
12927         break;
12928       if (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)
12929         CaptureRegion = OMPD_taskloop;
12930       break;
12931     case OMPD_parallel_for_simd:
12932       if (OpenMPVersion <= 45)
12933         break;
12934       if (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)
12935         CaptureRegion = OMPD_parallel;
12936       break;
12937     case OMPD_taskloop_simd:
12938     case OMPD_master_taskloop_simd:
12939       if (OpenMPVersion <= 45)
12940         break;
12941       if (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)
12942         CaptureRegion = OMPD_taskloop;
12943       break;
12944     case OMPD_distribute_parallel_for_simd:
12945       if (OpenMPVersion <= 45)
12946         break;
12947       if (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)
12948         CaptureRegion = OMPD_parallel;
12949       break;
12950     case OMPD_target_simd:
12951       if (OpenMPVersion >= 50 &&
12952           (NameModifier == OMPD_unknown || NameModifier == OMPD_simd))
12953         CaptureRegion = OMPD_target;
12954       break;
12955     case OMPD_teams_distribute_simd:
12956     case OMPD_target_teams_distribute_simd:
12957       if (OpenMPVersion >= 50 &&
12958           (NameModifier == OMPD_unknown || NameModifier == OMPD_simd))
12959         CaptureRegion = OMPD_teams;
12960       break;
12961     case OMPD_cancel:
12962     case OMPD_parallel:
12963     case OMPD_parallel_master:
12964     case OMPD_parallel_sections:
12965     case OMPD_parallel_for:
12966     case OMPD_target:
12967     case OMPD_target_teams:
12968     case OMPD_target_teams_distribute:
12969     case OMPD_distribute_parallel_for:
12970     case OMPD_task:
12971     case OMPD_taskloop:
12972     case OMPD_master_taskloop:
12973     case OMPD_target_data:
12974     case OMPD_simd:
12975     case OMPD_for_simd:
12976     case OMPD_distribute_simd:
12977       // Do not capture if-clause expressions.
12978       break;
12979     case OMPD_threadprivate:
12980     case OMPD_allocate:
12981     case OMPD_taskyield:
12982     case OMPD_barrier:
12983     case OMPD_taskwait:
12984     case OMPD_cancellation_point:
12985     case OMPD_flush:
12986     case OMPD_depobj:
12987     case OMPD_scan:
12988     case OMPD_declare_reduction:
12989     case OMPD_declare_mapper:
12990     case OMPD_declare_simd:
12991     case OMPD_declare_variant:
12992     case OMPD_begin_declare_variant:
12993     case OMPD_end_declare_variant:
12994     case OMPD_declare_target:
12995     case OMPD_end_declare_target:
12996     case OMPD_teams:
12997     case OMPD_tile:
12998     case OMPD_for:
12999     case OMPD_sections:
13000     case OMPD_section:
13001     case OMPD_single:
13002     case OMPD_master:
13003     case OMPD_critical:
13004     case OMPD_taskgroup:
13005     case OMPD_distribute:
13006     case OMPD_ordered:
13007     case OMPD_atomic:
13008     case OMPD_teams_distribute:
13009     case OMPD_requires:
13010       llvm_unreachable("Unexpected OpenMP directive with if-clause");
13011     case OMPD_unknown:
13012     default:
13013       llvm_unreachable("Unknown OpenMP directive");
13014     }
13015     break;
13016   case OMPC_num_threads:
13017     switch (DKind) {
13018     case OMPD_target_parallel:
13019     case OMPD_target_parallel_for:
13020     case OMPD_target_parallel_for_simd:
13021       CaptureRegion = OMPD_target;
13022       break;
13023     case OMPD_teams_distribute_parallel_for:
13024     case OMPD_teams_distribute_parallel_for_simd:
13025     case OMPD_target_teams_distribute_parallel_for:
13026     case OMPD_target_teams_distribute_parallel_for_simd:
13027       CaptureRegion = OMPD_teams;
13028       break;
13029     case OMPD_parallel:
13030     case OMPD_parallel_master:
13031     case OMPD_parallel_sections:
13032     case OMPD_parallel_for:
13033     case OMPD_parallel_for_simd:
13034     case OMPD_distribute_parallel_for:
13035     case OMPD_distribute_parallel_for_simd:
13036     case OMPD_parallel_master_taskloop:
13037     case OMPD_parallel_master_taskloop_simd:
13038       // Do not capture num_threads-clause expressions.
13039       break;
13040     case OMPD_target_data:
13041     case OMPD_target_enter_data:
13042     case OMPD_target_exit_data:
13043     case OMPD_target_update:
13044     case OMPD_target:
13045     case OMPD_target_simd:
13046     case OMPD_target_teams:
13047     case OMPD_target_teams_distribute:
13048     case OMPD_target_teams_distribute_simd:
13049     case OMPD_cancel:
13050     case OMPD_task:
13051     case OMPD_taskloop:
13052     case OMPD_taskloop_simd:
13053     case OMPD_master_taskloop:
13054     case OMPD_master_taskloop_simd:
13055     case OMPD_threadprivate:
13056     case OMPD_allocate:
13057     case OMPD_taskyield:
13058     case OMPD_barrier:
13059     case OMPD_taskwait:
13060     case OMPD_cancellation_point:
13061     case OMPD_flush:
13062     case OMPD_depobj:
13063     case OMPD_scan:
13064     case OMPD_declare_reduction:
13065     case OMPD_declare_mapper:
13066     case OMPD_declare_simd:
13067     case OMPD_declare_variant:
13068     case OMPD_begin_declare_variant:
13069     case OMPD_end_declare_variant:
13070     case OMPD_declare_target:
13071     case OMPD_end_declare_target:
13072     case OMPD_teams:
13073     case OMPD_simd:
13074     case OMPD_tile:
13075     case OMPD_for:
13076     case OMPD_for_simd:
13077     case OMPD_sections:
13078     case OMPD_section:
13079     case OMPD_single:
13080     case OMPD_master:
13081     case OMPD_critical:
13082     case OMPD_taskgroup:
13083     case OMPD_distribute:
13084     case OMPD_ordered:
13085     case OMPD_atomic:
13086     case OMPD_distribute_simd:
13087     case OMPD_teams_distribute:
13088     case OMPD_teams_distribute_simd:
13089     case OMPD_requires:
13090       llvm_unreachable("Unexpected OpenMP directive with num_threads-clause");
13091     case OMPD_unknown:
13092     default:
13093       llvm_unreachable("Unknown OpenMP directive");
13094     }
13095     break;
13096   case OMPC_num_teams:
13097     switch (DKind) {
13098     case OMPD_target_teams:
13099     case OMPD_target_teams_distribute:
13100     case OMPD_target_teams_distribute_simd:
13101     case OMPD_target_teams_distribute_parallel_for:
13102     case OMPD_target_teams_distribute_parallel_for_simd:
13103       CaptureRegion = OMPD_target;
13104       break;
13105     case OMPD_teams_distribute_parallel_for:
13106     case OMPD_teams_distribute_parallel_for_simd:
13107     case OMPD_teams:
13108     case OMPD_teams_distribute:
13109     case OMPD_teams_distribute_simd:
13110       // Do not capture num_teams-clause expressions.
13111       break;
13112     case OMPD_distribute_parallel_for:
13113     case OMPD_distribute_parallel_for_simd:
13114     case OMPD_task:
13115     case OMPD_taskloop:
13116     case OMPD_taskloop_simd:
13117     case OMPD_master_taskloop:
13118     case OMPD_master_taskloop_simd:
13119     case OMPD_parallel_master_taskloop:
13120     case OMPD_parallel_master_taskloop_simd:
13121     case OMPD_target_data:
13122     case OMPD_target_enter_data:
13123     case OMPD_target_exit_data:
13124     case OMPD_target_update:
13125     case OMPD_cancel:
13126     case OMPD_parallel:
13127     case OMPD_parallel_master:
13128     case OMPD_parallel_sections:
13129     case OMPD_parallel_for:
13130     case OMPD_parallel_for_simd:
13131     case OMPD_target:
13132     case OMPD_target_simd:
13133     case OMPD_target_parallel:
13134     case OMPD_target_parallel_for:
13135     case OMPD_target_parallel_for_simd:
13136     case OMPD_threadprivate:
13137     case OMPD_allocate:
13138     case OMPD_taskyield:
13139     case OMPD_barrier:
13140     case OMPD_taskwait:
13141     case OMPD_cancellation_point:
13142     case OMPD_flush:
13143     case OMPD_depobj:
13144     case OMPD_scan:
13145     case OMPD_declare_reduction:
13146     case OMPD_declare_mapper:
13147     case OMPD_declare_simd:
13148     case OMPD_declare_variant:
13149     case OMPD_begin_declare_variant:
13150     case OMPD_end_declare_variant:
13151     case OMPD_declare_target:
13152     case OMPD_end_declare_target:
13153     case OMPD_simd:
13154     case OMPD_tile:
13155     case OMPD_for:
13156     case OMPD_for_simd:
13157     case OMPD_sections:
13158     case OMPD_section:
13159     case OMPD_single:
13160     case OMPD_master:
13161     case OMPD_critical:
13162     case OMPD_taskgroup:
13163     case OMPD_distribute:
13164     case OMPD_ordered:
13165     case OMPD_atomic:
13166     case OMPD_distribute_simd:
13167     case OMPD_requires:
13168       llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
13169     case OMPD_unknown:
13170     default:
13171       llvm_unreachable("Unknown OpenMP directive");
13172     }
13173     break;
13174   case OMPC_thread_limit:
13175     switch (DKind) {
13176     case OMPD_target_teams:
13177     case OMPD_target_teams_distribute:
13178     case OMPD_target_teams_distribute_simd:
13179     case OMPD_target_teams_distribute_parallel_for:
13180     case OMPD_target_teams_distribute_parallel_for_simd:
13181       CaptureRegion = OMPD_target;
13182       break;
13183     case OMPD_teams_distribute_parallel_for:
13184     case OMPD_teams_distribute_parallel_for_simd:
13185     case OMPD_teams:
13186     case OMPD_teams_distribute:
13187     case OMPD_teams_distribute_simd:
13188       // Do not capture thread_limit-clause expressions.
13189       break;
13190     case OMPD_distribute_parallel_for:
13191     case OMPD_distribute_parallel_for_simd:
13192     case OMPD_task:
13193     case OMPD_taskloop:
13194     case OMPD_taskloop_simd:
13195     case OMPD_master_taskloop:
13196     case OMPD_master_taskloop_simd:
13197     case OMPD_parallel_master_taskloop:
13198     case OMPD_parallel_master_taskloop_simd:
13199     case OMPD_target_data:
13200     case OMPD_target_enter_data:
13201     case OMPD_target_exit_data:
13202     case OMPD_target_update:
13203     case OMPD_cancel:
13204     case OMPD_parallel:
13205     case OMPD_parallel_master:
13206     case OMPD_parallel_sections:
13207     case OMPD_parallel_for:
13208     case OMPD_parallel_for_simd:
13209     case OMPD_target:
13210     case OMPD_target_simd:
13211     case OMPD_target_parallel:
13212     case OMPD_target_parallel_for:
13213     case OMPD_target_parallel_for_simd:
13214     case OMPD_threadprivate:
13215     case OMPD_allocate:
13216     case OMPD_taskyield:
13217     case OMPD_barrier:
13218     case OMPD_taskwait:
13219     case OMPD_cancellation_point:
13220     case OMPD_flush:
13221     case OMPD_depobj:
13222     case OMPD_scan:
13223     case OMPD_declare_reduction:
13224     case OMPD_declare_mapper:
13225     case OMPD_declare_simd:
13226     case OMPD_declare_variant:
13227     case OMPD_begin_declare_variant:
13228     case OMPD_end_declare_variant:
13229     case OMPD_declare_target:
13230     case OMPD_end_declare_target:
13231     case OMPD_simd:
13232     case OMPD_tile:
13233     case OMPD_for:
13234     case OMPD_for_simd:
13235     case OMPD_sections:
13236     case OMPD_section:
13237     case OMPD_single:
13238     case OMPD_master:
13239     case OMPD_critical:
13240     case OMPD_taskgroup:
13241     case OMPD_distribute:
13242     case OMPD_ordered:
13243     case OMPD_atomic:
13244     case OMPD_distribute_simd:
13245     case OMPD_requires:
13246       llvm_unreachable("Unexpected OpenMP directive with thread_limit-clause");
13247     case OMPD_unknown:
13248     default:
13249       llvm_unreachable("Unknown OpenMP directive");
13250     }
13251     break;
13252   case OMPC_schedule:
13253     switch (DKind) {
13254     case OMPD_parallel_for:
13255     case OMPD_parallel_for_simd:
13256     case OMPD_distribute_parallel_for:
13257     case OMPD_distribute_parallel_for_simd:
13258     case OMPD_teams_distribute_parallel_for:
13259     case OMPD_teams_distribute_parallel_for_simd:
13260     case OMPD_target_parallel_for:
13261     case OMPD_target_parallel_for_simd:
13262     case OMPD_target_teams_distribute_parallel_for:
13263     case OMPD_target_teams_distribute_parallel_for_simd:
13264       CaptureRegion = OMPD_parallel;
13265       break;
13266     case OMPD_for:
13267     case OMPD_for_simd:
13268       // Do not capture schedule-clause expressions.
13269       break;
13270     case OMPD_task:
13271     case OMPD_taskloop:
13272     case OMPD_taskloop_simd:
13273     case OMPD_master_taskloop:
13274     case OMPD_master_taskloop_simd:
13275     case OMPD_parallel_master_taskloop:
13276     case OMPD_parallel_master_taskloop_simd:
13277     case OMPD_target_data:
13278     case OMPD_target_enter_data:
13279     case OMPD_target_exit_data:
13280     case OMPD_target_update:
13281     case OMPD_teams:
13282     case OMPD_teams_distribute:
13283     case OMPD_teams_distribute_simd:
13284     case OMPD_target_teams_distribute:
13285     case OMPD_target_teams_distribute_simd:
13286     case OMPD_target:
13287     case OMPD_target_simd:
13288     case OMPD_target_parallel:
13289     case OMPD_cancel:
13290     case OMPD_parallel:
13291     case OMPD_parallel_master:
13292     case OMPD_parallel_sections:
13293     case OMPD_threadprivate:
13294     case OMPD_allocate:
13295     case OMPD_taskyield:
13296     case OMPD_barrier:
13297     case OMPD_taskwait:
13298     case OMPD_cancellation_point:
13299     case OMPD_flush:
13300     case OMPD_depobj:
13301     case OMPD_scan:
13302     case OMPD_declare_reduction:
13303     case OMPD_declare_mapper:
13304     case OMPD_declare_simd:
13305     case OMPD_declare_variant:
13306     case OMPD_begin_declare_variant:
13307     case OMPD_end_declare_variant:
13308     case OMPD_declare_target:
13309     case OMPD_end_declare_target:
13310     case OMPD_simd:
13311     case OMPD_tile:
13312     case OMPD_sections:
13313     case OMPD_section:
13314     case OMPD_single:
13315     case OMPD_master:
13316     case OMPD_critical:
13317     case OMPD_taskgroup:
13318     case OMPD_distribute:
13319     case OMPD_ordered:
13320     case OMPD_atomic:
13321     case OMPD_distribute_simd:
13322     case OMPD_target_teams:
13323     case OMPD_requires:
13324       llvm_unreachable("Unexpected OpenMP directive with schedule clause");
13325     case OMPD_unknown:
13326     default:
13327       llvm_unreachable("Unknown OpenMP directive");
13328     }
13329     break;
13330   case OMPC_dist_schedule:
13331     switch (DKind) {
13332     case OMPD_teams_distribute_parallel_for:
13333     case OMPD_teams_distribute_parallel_for_simd:
13334     case OMPD_teams_distribute:
13335     case OMPD_teams_distribute_simd:
13336     case OMPD_target_teams_distribute_parallel_for:
13337     case OMPD_target_teams_distribute_parallel_for_simd:
13338     case OMPD_target_teams_distribute:
13339     case OMPD_target_teams_distribute_simd:
13340       CaptureRegion = OMPD_teams;
13341       break;
13342     case OMPD_distribute_parallel_for:
13343     case OMPD_distribute_parallel_for_simd:
13344     case OMPD_distribute:
13345     case OMPD_distribute_simd:
13346       // Do not capture dist_schedule-clause expressions.
13347       break;
13348     case OMPD_parallel_for:
13349     case OMPD_parallel_for_simd:
13350     case OMPD_target_parallel_for_simd:
13351     case OMPD_target_parallel_for:
13352     case OMPD_task:
13353     case OMPD_taskloop:
13354     case OMPD_taskloop_simd:
13355     case OMPD_master_taskloop:
13356     case OMPD_master_taskloop_simd:
13357     case OMPD_parallel_master_taskloop:
13358     case OMPD_parallel_master_taskloop_simd:
13359     case OMPD_target_data:
13360     case OMPD_target_enter_data:
13361     case OMPD_target_exit_data:
13362     case OMPD_target_update:
13363     case OMPD_teams:
13364     case OMPD_target:
13365     case OMPD_target_simd:
13366     case OMPD_target_parallel:
13367     case OMPD_cancel:
13368     case OMPD_parallel:
13369     case OMPD_parallel_master:
13370     case OMPD_parallel_sections:
13371     case OMPD_threadprivate:
13372     case OMPD_allocate:
13373     case OMPD_taskyield:
13374     case OMPD_barrier:
13375     case OMPD_taskwait:
13376     case OMPD_cancellation_point:
13377     case OMPD_flush:
13378     case OMPD_depobj:
13379     case OMPD_scan:
13380     case OMPD_declare_reduction:
13381     case OMPD_declare_mapper:
13382     case OMPD_declare_simd:
13383     case OMPD_declare_variant:
13384     case OMPD_begin_declare_variant:
13385     case OMPD_end_declare_variant:
13386     case OMPD_declare_target:
13387     case OMPD_end_declare_target:
13388     case OMPD_simd:
13389     case OMPD_tile:
13390     case OMPD_for:
13391     case OMPD_for_simd:
13392     case OMPD_sections:
13393     case OMPD_section:
13394     case OMPD_single:
13395     case OMPD_master:
13396     case OMPD_critical:
13397     case OMPD_taskgroup:
13398     case OMPD_ordered:
13399     case OMPD_atomic:
13400     case OMPD_target_teams:
13401     case OMPD_requires:
13402       llvm_unreachable("Unexpected OpenMP directive with dist_schedule clause");
13403     case OMPD_unknown:
13404     default:
13405       llvm_unreachable("Unknown OpenMP directive");
13406     }
13407     break;
13408   case OMPC_device:
13409     switch (DKind) {
13410     case OMPD_target_update:
13411     case OMPD_target_enter_data:
13412     case OMPD_target_exit_data:
13413     case OMPD_target:
13414     case OMPD_target_simd:
13415     case OMPD_target_teams:
13416     case OMPD_target_parallel:
13417     case OMPD_target_teams_distribute:
13418     case OMPD_target_teams_distribute_simd:
13419     case OMPD_target_parallel_for:
13420     case OMPD_target_parallel_for_simd:
13421     case OMPD_target_teams_distribute_parallel_for:
13422     case OMPD_target_teams_distribute_parallel_for_simd:
13423     case OMPD_dispatch:
13424       CaptureRegion = OMPD_task;
13425       break;
13426     case OMPD_target_data:
13427     case OMPD_interop:
13428       // Do not capture device-clause expressions.
13429       break;
13430     case OMPD_teams_distribute_parallel_for:
13431     case OMPD_teams_distribute_parallel_for_simd:
13432     case OMPD_teams:
13433     case OMPD_teams_distribute:
13434     case OMPD_teams_distribute_simd:
13435     case OMPD_distribute_parallel_for:
13436     case OMPD_distribute_parallel_for_simd:
13437     case OMPD_task:
13438     case OMPD_taskloop:
13439     case OMPD_taskloop_simd:
13440     case OMPD_master_taskloop:
13441     case OMPD_master_taskloop_simd:
13442     case OMPD_parallel_master_taskloop:
13443     case OMPD_parallel_master_taskloop_simd:
13444     case OMPD_cancel:
13445     case OMPD_parallel:
13446     case OMPD_parallel_master:
13447     case OMPD_parallel_sections:
13448     case OMPD_parallel_for:
13449     case OMPD_parallel_for_simd:
13450     case OMPD_threadprivate:
13451     case OMPD_allocate:
13452     case OMPD_taskyield:
13453     case OMPD_barrier:
13454     case OMPD_taskwait:
13455     case OMPD_cancellation_point:
13456     case OMPD_flush:
13457     case OMPD_depobj:
13458     case OMPD_scan:
13459     case OMPD_declare_reduction:
13460     case OMPD_declare_mapper:
13461     case OMPD_declare_simd:
13462     case OMPD_declare_variant:
13463     case OMPD_begin_declare_variant:
13464     case OMPD_end_declare_variant:
13465     case OMPD_declare_target:
13466     case OMPD_end_declare_target:
13467     case OMPD_simd:
13468     case OMPD_tile:
13469     case OMPD_for:
13470     case OMPD_for_simd:
13471     case OMPD_sections:
13472     case OMPD_section:
13473     case OMPD_single:
13474     case OMPD_master:
13475     case OMPD_critical:
13476     case OMPD_taskgroup:
13477     case OMPD_distribute:
13478     case OMPD_ordered:
13479     case OMPD_atomic:
13480     case OMPD_distribute_simd:
13481     case OMPD_requires:
13482       llvm_unreachable("Unexpected OpenMP directive with device-clause");
13483     case OMPD_unknown:
13484     default:
13485       llvm_unreachable("Unknown OpenMP directive");
13486     }
13487     break;
13488   case OMPC_grainsize:
13489   case OMPC_num_tasks:
13490   case OMPC_final:
13491   case OMPC_priority:
13492     switch (DKind) {
13493     case OMPD_task:
13494     case OMPD_taskloop:
13495     case OMPD_taskloop_simd:
13496     case OMPD_master_taskloop:
13497     case OMPD_master_taskloop_simd:
13498       break;
13499     case OMPD_parallel_master_taskloop:
13500     case OMPD_parallel_master_taskloop_simd:
13501       CaptureRegion = OMPD_parallel;
13502       break;
13503     case OMPD_target_update:
13504     case OMPD_target_enter_data:
13505     case OMPD_target_exit_data:
13506     case OMPD_target:
13507     case OMPD_target_simd:
13508     case OMPD_target_teams:
13509     case OMPD_target_parallel:
13510     case OMPD_target_teams_distribute:
13511     case OMPD_target_teams_distribute_simd:
13512     case OMPD_target_parallel_for:
13513     case OMPD_target_parallel_for_simd:
13514     case OMPD_target_teams_distribute_parallel_for:
13515     case OMPD_target_teams_distribute_parallel_for_simd:
13516     case OMPD_target_data:
13517     case OMPD_teams_distribute_parallel_for:
13518     case OMPD_teams_distribute_parallel_for_simd:
13519     case OMPD_teams:
13520     case OMPD_teams_distribute:
13521     case OMPD_teams_distribute_simd:
13522     case OMPD_distribute_parallel_for:
13523     case OMPD_distribute_parallel_for_simd:
13524     case OMPD_cancel:
13525     case OMPD_parallel:
13526     case OMPD_parallel_master:
13527     case OMPD_parallel_sections:
13528     case OMPD_parallel_for:
13529     case OMPD_parallel_for_simd:
13530     case OMPD_threadprivate:
13531     case OMPD_allocate:
13532     case OMPD_taskyield:
13533     case OMPD_barrier:
13534     case OMPD_taskwait:
13535     case OMPD_cancellation_point:
13536     case OMPD_flush:
13537     case OMPD_depobj:
13538     case OMPD_scan:
13539     case OMPD_declare_reduction:
13540     case OMPD_declare_mapper:
13541     case OMPD_declare_simd:
13542     case OMPD_declare_variant:
13543     case OMPD_begin_declare_variant:
13544     case OMPD_end_declare_variant:
13545     case OMPD_declare_target:
13546     case OMPD_end_declare_target:
13547     case OMPD_simd:
13548     case OMPD_tile:
13549     case OMPD_for:
13550     case OMPD_for_simd:
13551     case OMPD_sections:
13552     case OMPD_section:
13553     case OMPD_single:
13554     case OMPD_master:
13555     case OMPD_critical:
13556     case OMPD_taskgroup:
13557     case OMPD_distribute:
13558     case OMPD_ordered:
13559     case OMPD_atomic:
13560     case OMPD_distribute_simd:
13561     case OMPD_requires:
13562       llvm_unreachable("Unexpected OpenMP directive with grainsize-clause");
13563     case OMPD_unknown:
13564     default:
13565       llvm_unreachable("Unknown OpenMP directive");
13566     }
13567     break;
13568   case OMPC_novariants:
13569   case OMPC_nocontext:
13570     switch (DKind) {
13571     case OMPD_dispatch:
13572       CaptureRegion = OMPD_task;
13573       break;
13574     default:
13575       llvm_unreachable("Unexpected OpenMP directive");
13576     }
13577     break;
13578   case OMPC_firstprivate:
13579   case OMPC_lastprivate:
13580   case OMPC_reduction:
13581   case OMPC_task_reduction:
13582   case OMPC_in_reduction:
13583   case OMPC_linear:
13584   case OMPC_default:
13585   case OMPC_proc_bind:
13586   case OMPC_safelen:
13587   case OMPC_simdlen:
13588   case OMPC_sizes:
13589   case OMPC_allocator:
13590   case OMPC_collapse:
13591   case OMPC_private:
13592   case OMPC_shared:
13593   case OMPC_aligned:
13594   case OMPC_copyin:
13595   case OMPC_copyprivate:
13596   case OMPC_ordered:
13597   case OMPC_nowait:
13598   case OMPC_untied:
13599   case OMPC_mergeable:
13600   case OMPC_threadprivate:
13601   case OMPC_allocate:
13602   case OMPC_flush:
13603   case OMPC_depobj:
13604   case OMPC_read:
13605   case OMPC_write:
13606   case OMPC_update:
13607   case OMPC_capture:
13608   case OMPC_seq_cst:
13609   case OMPC_acq_rel:
13610   case OMPC_acquire:
13611   case OMPC_release:
13612   case OMPC_relaxed:
13613   case OMPC_depend:
13614   case OMPC_threads:
13615   case OMPC_simd:
13616   case OMPC_map:
13617   case OMPC_nogroup:
13618   case OMPC_hint:
13619   case OMPC_defaultmap:
13620   case OMPC_unknown:
13621   case OMPC_uniform:
13622   case OMPC_to:
13623   case OMPC_from:
13624   case OMPC_use_device_ptr:
13625   case OMPC_use_device_addr:
13626   case OMPC_is_device_ptr:
13627   case OMPC_unified_address:
13628   case OMPC_unified_shared_memory:
13629   case OMPC_reverse_offload:
13630   case OMPC_dynamic_allocators:
13631   case OMPC_atomic_default_mem_order:
13632   case OMPC_device_type:
13633   case OMPC_match:
13634   case OMPC_nontemporal:
13635   case OMPC_order:
13636   case OMPC_destroy:
13637   case OMPC_detach:
13638   case OMPC_inclusive:
13639   case OMPC_exclusive:
13640   case OMPC_uses_allocators:
13641   case OMPC_affinity:
13642   default:
13643     llvm_unreachable("Unexpected OpenMP clause.");
13644   }
13645   return CaptureRegion;
13646 }
13647 
13648 OMPClause *Sema::ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
13649                                      Expr *Condition, SourceLocation StartLoc,
13650                                      SourceLocation LParenLoc,
13651                                      SourceLocation NameModifierLoc,
13652                                      SourceLocation ColonLoc,
13653                                      SourceLocation EndLoc) {
13654   Expr *ValExpr = Condition;
13655   Stmt *HelperValStmt = nullptr;
13656   OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
13657   if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
13658       !Condition->isInstantiationDependent() &&
13659       !Condition->containsUnexpandedParameterPack()) {
13660     ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
13661     if (Val.isInvalid())
13662       return nullptr;
13663 
13664     ValExpr = Val.get();
13665 
13666     OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
13667     CaptureRegion = getOpenMPCaptureRegionForClause(
13668         DKind, OMPC_if, LangOpts.OpenMP, NameModifier);
13669     if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
13670       ValExpr = MakeFullExpr(ValExpr).get();
13671       llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
13672       ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
13673       HelperValStmt = buildPreInits(Context, Captures);
13674     }
13675   }
13676 
13677   return new (Context)
13678       OMPIfClause(NameModifier, ValExpr, HelperValStmt, CaptureRegion, StartLoc,
13679                   LParenLoc, NameModifierLoc, ColonLoc, EndLoc);
13680 }
13681 
13682 OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition,
13683                                         SourceLocation StartLoc,
13684                                         SourceLocation LParenLoc,
13685                                         SourceLocation EndLoc) {
13686   Expr *ValExpr = Condition;
13687   Stmt *HelperValStmt = nullptr;
13688   OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
13689   if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
13690       !Condition->isInstantiationDependent() &&
13691       !Condition->containsUnexpandedParameterPack()) {
13692     ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
13693     if (Val.isInvalid())
13694       return nullptr;
13695 
13696     ValExpr = MakeFullExpr(Val.get()).get();
13697 
13698     OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
13699     CaptureRegion =
13700         getOpenMPCaptureRegionForClause(DKind, OMPC_final, LangOpts.OpenMP);
13701     if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
13702       ValExpr = MakeFullExpr(ValExpr).get();
13703       llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
13704       ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
13705       HelperValStmt = buildPreInits(Context, Captures);
13706     }
13707   }
13708 
13709   return new (Context) OMPFinalClause(ValExpr, HelperValStmt, CaptureRegion,
13710                                       StartLoc, LParenLoc, EndLoc);
13711 }
13712 
13713 ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc,
13714                                                         Expr *Op) {
13715   if (!Op)
13716     return ExprError();
13717 
13718   class IntConvertDiagnoser : public ICEConvertDiagnoser {
13719   public:
13720     IntConvertDiagnoser()
13721         : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {}
13722     SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
13723                                          QualType T) override {
13724       return S.Diag(Loc, diag::err_omp_not_integral) << T;
13725     }
13726     SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
13727                                              QualType T) override {
13728       return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
13729     }
13730     SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
13731                                                QualType T,
13732                                                QualType ConvTy) override {
13733       return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
13734     }
13735     SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
13736                                            QualType ConvTy) override {
13737       return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
13738              << ConvTy->isEnumeralType() << ConvTy;
13739     }
13740     SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
13741                                             QualType T) override {
13742       return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
13743     }
13744     SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
13745                                         QualType ConvTy) override {
13746       return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
13747              << ConvTy->isEnumeralType() << ConvTy;
13748     }
13749     SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType,
13750                                              QualType) override {
13751       llvm_unreachable("conversion functions are permitted");
13752     }
13753   } ConvertDiagnoser;
13754   return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
13755 }
13756 
13757 static bool
13758 isNonNegativeIntegerValue(Expr *&ValExpr, Sema &SemaRef, OpenMPClauseKind CKind,
13759                           bool StrictlyPositive, bool BuildCapture = false,
13760                           OpenMPDirectiveKind DKind = OMPD_unknown,
13761                           OpenMPDirectiveKind *CaptureRegion = nullptr,
13762                           Stmt **HelperValStmt = nullptr) {
13763   if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() &&
13764       !ValExpr->isInstantiationDependent()) {
13765     SourceLocation Loc = ValExpr->getExprLoc();
13766     ExprResult Value =
13767         SemaRef.PerformOpenMPImplicitIntegerConversion(Loc, ValExpr);
13768     if (Value.isInvalid())
13769       return false;
13770 
13771     ValExpr = Value.get();
13772     // The expression must evaluate to a non-negative integer value.
13773     if (Optional<llvm::APSInt> Result =
13774             ValExpr->getIntegerConstantExpr(SemaRef.Context)) {
13775       if (Result->isSigned() &&
13776           !((!StrictlyPositive && Result->isNonNegative()) ||
13777             (StrictlyPositive && Result->isStrictlyPositive()))) {
13778         SemaRef.Diag(Loc, diag::err_omp_negative_expression_in_clause)
13779             << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
13780             << ValExpr->getSourceRange();
13781         return false;
13782       }
13783     }
13784     if (!BuildCapture)
13785       return true;
13786     *CaptureRegion =
13787         getOpenMPCaptureRegionForClause(DKind, CKind, SemaRef.LangOpts.OpenMP);
13788     if (*CaptureRegion != OMPD_unknown &&
13789         !SemaRef.CurContext->isDependentContext()) {
13790       ValExpr = SemaRef.MakeFullExpr(ValExpr).get();
13791       llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
13792       ValExpr = tryBuildCapture(SemaRef, ValExpr, Captures).get();
13793       *HelperValStmt = buildPreInits(SemaRef.Context, Captures);
13794     }
13795   }
13796   return true;
13797 }
13798 
13799 OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
13800                                              SourceLocation StartLoc,
13801                                              SourceLocation LParenLoc,
13802                                              SourceLocation EndLoc) {
13803   Expr *ValExpr = NumThreads;
13804   Stmt *HelperValStmt = nullptr;
13805 
13806   // OpenMP [2.5, Restrictions]
13807   //  The num_threads expression must evaluate to a positive integer value.
13808   if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_threads,
13809                                  /*StrictlyPositive=*/true))
13810     return nullptr;
13811 
13812   OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
13813   OpenMPDirectiveKind CaptureRegion =
13814       getOpenMPCaptureRegionForClause(DKind, OMPC_num_threads, LangOpts.OpenMP);
13815   if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
13816     ValExpr = MakeFullExpr(ValExpr).get();
13817     llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
13818     ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
13819     HelperValStmt = buildPreInits(Context, Captures);
13820   }
13821 
13822   return new (Context) OMPNumThreadsClause(
13823       ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
13824 }
13825 
13826 ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
13827                                                        OpenMPClauseKind CKind,
13828                                                        bool StrictlyPositive) {
13829   if (!E)
13830     return ExprError();
13831   if (E->isValueDependent() || E->isTypeDependent() ||
13832       E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
13833     return E;
13834   llvm::APSInt Result;
13835   ExprResult ICE =
13836       VerifyIntegerConstantExpression(E, &Result, /*FIXME*/ AllowFold);
13837   if (ICE.isInvalid())
13838     return ExprError();
13839   if ((StrictlyPositive && !Result.isStrictlyPositive()) ||
13840       (!StrictlyPositive && !Result.isNonNegative())) {
13841     Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
13842         << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
13843         << E->getSourceRange();
13844     return ExprError();
13845   }
13846   if (CKind == OMPC_aligned && !Result.isPowerOf2()) {
13847     Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two)
13848         << E->getSourceRange();
13849     return ExprError();
13850   }
13851   if (CKind == OMPC_collapse && DSAStack->getAssociatedLoops() == 1)
13852     DSAStack->setAssociatedLoops(Result.getExtValue());
13853   else if (CKind == OMPC_ordered)
13854     DSAStack->setAssociatedLoops(Result.getExtValue());
13855   return ICE;
13856 }
13857 
13858 OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
13859                                           SourceLocation LParenLoc,
13860                                           SourceLocation EndLoc) {
13861   // OpenMP [2.8.1, simd construct, Description]
13862   // The parameter of the safelen clause must be a constant
13863   // positive integer expression.
13864   ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen);
13865   if (Safelen.isInvalid())
13866     return nullptr;
13867   return new (Context)
13868       OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc);
13869 }
13870 
13871 OMPClause *Sema::ActOnOpenMPSimdlenClause(Expr *Len, SourceLocation StartLoc,
13872                                           SourceLocation LParenLoc,
13873                                           SourceLocation EndLoc) {
13874   // OpenMP [2.8.1, simd construct, Description]
13875   // The parameter of the simdlen clause must be a constant
13876   // positive integer expression.
13877   ExprResult Simdlen = VerifyPositiveIntegerConstantInClause(Len, OMPC_simdlen);
13878   if (Simdlen.isInvalid())
13879     return nullptr;
13880   return new (Context)
13881       OMPSimdlenClause(Simdlen.get(), StartLoc, LParenLoc, EndLoc);
13882 }
13883 
13884 /// Tries to find omp_allocator_handle_t type.
13885 static bool findOMPAllocatorHandleT(Sema &S, SourceLocation Loc,
13886                                     DSAStackTy *Stack) {
13887   QualType OMPAllocatorHandleT = Stack->getOMPAllocatorHandleT();
13888   if (!OMPAllocatorHandleT.isNull())
13889     return true;
13890   // Build the predefined allocator expressions.
13891   bool ErrorFound = false;
13892   for (int I = 0; I < OMPAllocateDeclAttr::OMPUserDefinedMemAlloc; ++I) {
13893     auto AllocatorKind = static_cast<OMPAllocateDeclAttr::AllocatorTypeTy>(I);
13894     StringRef Allocator =
13895         OMPAllocateDeclAttr::ConvertAllocatorTypeTyToStr(AllocatorKind);
13896     DeclarationName AllocatorName = &S.getASTContext().Idents.get(Allocator);
13897     auto *VD = dyn_cast_or_null<ValueDecl>(
13898         S.LookupSingleName(S.TUScope, AllocatorName, Loc, Sema::LookupAnyName));
13899     if (!VD) {
13900       ErrorFound = true;
13901       break;
13902     }
13903     QualType AllocatorType =
13904         VD->getType().getNonLValueExprType(S.getASTContext());
13905     ExprResult Res = S.BuildDeclRefExpr(VD, AllocatorType, VK_LValue, Loc);
13906     if (!Res.isUsable()) {
13907       ErrorFound = true;
13908       break;
13909     }
13910     if (OMPAllocatorHandleT.isNull())
13911       OMPAllocatorHandleT = AllocatorType;
13912     if (!S.getASTContext().hasSameType(OMPAllocatorHandleT, AllocatorType)) {
13913       ErrorFound = true;
13914       break;
13915     }
13916     Stack->setAllocator(AllocatorKind, Res.get());
13917   }
13918   if (ErrorFound) {
13919     S.Diag(Loc, diag::err_omp_implied_type_not_found)
13920         << "omp_allocator_handle_t";
13921     return false;
13922   }
13923   OMPAllocatorHandleT.addConst();
13924   Stack->setOMPAllocatorHandleT(OMPAllocatorHandleT);
13925   return true;
13926 }
13927 
13928 OMPClause *Sema::ActOnOpenMPAllocatorClause(Expr *A, SourceLocation StartLoc,
13929                                             SourceLocation LParenLoc,
13930                                             SourceLocation EndLoc) {
13931   // OpenMP [2.11.3, allocate Directive, Description]
13932   // allocator is an expression of omp_allocator_handle_t type.
13933   if (!findOMPAllocatorHandleT(*this, A->getExprLoc(), DSAStack))
13934     return nullptr;
13935 
13936   ExprResult Allocator = DefaultLvalueConversion(A);
13937   if (Allocator.isInvalid())
13938     return nullptr;
13939   Allocator = PerformImplicitConversion(Allocator.get(),
13940                                         DSAStack->getOMPAllocatorHandleT(),
13941                                         Sema::AA_Initializing,
13942                                         /*AllowExplicit=*/true);
13943   if (Allocator.isInvalid())
13944     return nullptr;
13945   return new (Context)
13946       OMPAllocatorClause(Allocator.get(), StartLoc, LParenLoc, EndLoc);
13947 }
13948 
13949 OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops,
13950                                            SourceLocation StartLoc,
13951                                            SourceLocation LParenLoc,
13952                                            SourceLocation EndLoc) {
13953   // OpenMP [2.7.1, loop construct, Description]
13954   // OpenMP [2.8.1, simd construct, Description]
13955   // OpenMP [2.9.6, distribute construct, Description]
13956   // The parameter of the collapse clause must be a constant
13957   // positive integer expression.
13958   ExprResult NumForLoopsResult =
13959       VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse);
13960   if (NumForLoopsResult.isInvalid())
13961     return nullptr;
13962   return new (Context)
13963       OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc);
13964 }
13965 
13966 OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc,
13967                                           SourceLocation EndLoc,
13968                                           SourceLocation LParenLoc,
13969                                           Expr *NumForLoops) {
13970   // OpenMP [2.7.1, loop construct, Description]
13971   // OpenMP [2.8.1, simd construct, Description]
13972   // OpenMP [2.9.6, distribute construct, Description]
13973   // The parameter of the ordered clause must be a constant
13974   // positive integer expression if any.
13975   if (NumForLoops && LParenLoc.isValid()) {
13976     ExprResult NumForLoopsResult =
13977         VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_ordered);
13978     if (NumForLoopsResult.isInvalid())
13979       return nullptr;
13980     NumForLoops = NumForLoopsResult.get();
13981   } else {
13982     NumForLoops = nullptr;
13983   }
13984   auto *Clause = OMPOrderedClause::Create(
13985       Context, NumForLoops, NumForLoops ? DSAStack->getAssociatedLoops() : 0,
13986       StartLoc, LParenLoc, EndLoc);
13987   DSAStack->setOrderedRegion(/*IsOrdered=*/true, NumForLoops, Clause);
13988   return Clause;
13989 }
13990 
13991 OMPClause *Sema::ActOnOpenMPSimpleClause(
13992     OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc,
13993     SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
13994   OMPClause *Res = nullptr;
13995   switch (Kind) {
13996   case OMPC_default:
13997     Res = ActOnOpenMPDefaultClause(static_cast<DefaultKind>(Argument),
13998                                    ArgumentLoc, StartLoc, LParenLoc, EndLoc);
13999     break;
14000   case OMPC_proc_bind:
14001     Res = ActOnOpenMPProcBindClause(static_cast<ProcBindKind>(Argument),
14002                                     ArgumentLoc, StartLoc, LParenLoc, EndLoc);
14003     break;
14004   case OMPC_atomic_default_mem_order:
14005     Res = ActOnOpenMPAtomicDefaultMemOrderClause(
14006         static_cast<OpenMPAtomicDefaultMemOrderClauseKind>(Argument),
14007         ArgumentLoc, StartLoc, LParenLoc, EndLoc);
14008     break;
14009   case OMPC_order:
14010     Res = ActOnOpenMPOrderClause(static_cast<OpenMPOrderClauseKind>(Argument),
14011                                  ArgumentLoc, StartLoc, LParenLoc, EndLoc);
14012     break;
14013   case OMPC_update:
14014     Res = ActOnOpenMPUpdateClause(static_cast<OpenMPDependClauseKind>(Argument),
14015                                   ArgumentLoc, StartLoc, LParenLoc, EndLoc);
14016     break;
14017   case OMPC_if:
14018   case OMPC_final:
14019   case OMPC_num_threads:
14020   case OMPC_safelen:
14021   case OMPC_simdlen:
14022   case OMPC_sizes:
14023   case OMPC_allocator:
14024   case OMPC_collapse:
14025   case OMPC_schedule:
14026   case OMPC_private:
14027   case OMPC_firstprivate:
14028   case OMPC_lastprivate:
14029   case OMPC_shared:
14030   case OMPC_reduction:
14031   case OMPC_task_reduction:
14032   case OMPC_in_reduction:
14033   case OMPC_linear:
14034   case OMPC_aligned:
14035   case OMPC_copyin:
14036   case OMPC_copyprivate:
14037   case OMPC_ordered:
14038   case OMPC_nowait:
14039   case OMPC_untied:
14040   case OMPC_mergeable:
14041   case OMPC_threadprivate:
14042   case OMPC_allocate:
14043   case OMPC_flush:
14044   case OMPC_depobj:
14045   case OMPC_read:
14046   case OMPC_write:
14047   case OMPC_capture:
14048   case OMPC_seq_cst:
14049   case OMPC_acq_rel:
14050   case OMPC_acquire:
14051   case OMPC_release:
14052   case OMPC_relaxed:
14053   case OMPC_depend:
14054   case OMPC_device:
14055   case OMPC_threads:
14056   case OMPC_simd:
14057   case OMPC_map:
14058   case OMPC_num_teams:
14059   case OMPC_thread_limit:
14060   case OMPC_priority:
14061   case OMPC_grainsize:
14062   case OMPC_nogroup:
14063   case OMPC_num_tasks:
14064   case OMPC_hint:
14065   case OMPC_dist_schedule:
14066   case OMPC_defaultmap:
14067   case OMPC_unknown:
14068   case OMPC_uniform:
14069   case OMPC_to:
14070   case OMPC_from:
14071   case OMPC_use_device_ptr:
14072   case OMPC_use_device_addr:
14073   case OMPC_is_device_ptr:
14074   case OMPC_unified_address:
14075   case OMPC_unified_shared_memory:
14076   case OMPC_reverse_offload:
14077   case OMPC_dynamic_allocators:
14078   case OMPC_device_type:
14079   case OMPC_match:
14080   case OMPC_nontemporal:
14081   case OMPC_destroy:
14082   case OMPC_novariants:
14083   case OMPC_nocontext:
14084   case OMPC_detach:
14085   case OMPC_inclusive:
14086   case OMPC_exclusive:
14087   case OMPC_uses_allocators:
14088   case OMPC_affinity:
14089   default:
14090     llvm_unreachable("Clause is not allowed.");
14091   }
14092   return Res;
14093 }
14094 
14095 static std::string
14096 getListOfPossibleValues(OpenMPClauseKind K, unsigned First, unsigned Last,
14097                         ArrayRef<unsigned> Exclude = llvm::None) {
14098   SmallString<256> Buffer;
14099   llvm::raw_svector_ostream Out(Buffer);
14100   unsigned Skipped = Exclude.size();
14101   auto S = Exclude.begin(), E = Exclude.end();
14102   for (unsigned I = First; I < Last; ++I) {
14103     if (std::find(S, E, I) != E) {
14104       --Skipped;
14105       continue;
14106     }
14107     Out << "'" << getOpenMPSimpleClauseTypeName(K, I) << "'";
14108     if (I + Skipped + 2 == Last)
14109       Out << " or ";
14110     else if (I + Skipped + 1 != Last)
14111       Out << ", ";
14112   }
14113   return std::string(Out.str());
14114 }
14115 
14116 OMPClause *Sema::ActOnOpenMPDefaultClause(DefaultKind Kind,
14117                                           SourceLocation KindKwLoc,
14118                                           SourceLocation StartLoc,
14119                                           SourceLocation LParenLoc,
14120                                           SourceLocation EndLoc) {
14121   if (Kind == OMP_DEFAULT_unknown) {
14122     Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
14123         << getListOfPossibleValues(OMPC_default, /*First=*/0,
14124                                    /*Last=*/unsigned(OMP_DEFAULT_unknown))
14125         << getOpenMPClauseName(OMPC_default);
14126     return nullptr;
14127   }
14128 
14129   switch (Kind) {
14130   case OMP_DEFAULT_none:
14131     DSAStack->setDefaultDSANone(KindKwLoc);
14132     break;
14133   case OMP_DEFAULT_shared:
14134     DSAStack->setDefaultDSAShared(KindKwLoc);
14135     break;
14136   case OMP_DEFAULT_firstprivate:
14137     DSAStack->setDefaultDSAFirstPrivate(KindKwLoc);
14138     break;
14139   default:
14140     llvm_unreachable("DSA unexpected in OpenMP default clause");
14141   }
14142 
14143   return new (Context)
14144       OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
14145 }
14146 
14147 OMPClause *Sema::ActOnOpenMPProcBindClause(ProcBindKind Kind,
14148                                            SourceLocation KindKwLoc,
14149                                            SourceLocation StartLoc,
14150                                            SourceLocation LParenLoc,
14151                                            SourceLocation EndLoc) {
14152   if (Kind == OMP_PROC_BIND_unknown) {
14153     Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
14154         << getListOfPossibleValues(OMPC_proc_bind,
14155                                    /*First=*/unsigned(OMP_PROC_BIND_master),
14156                                    /*Last=*/
14157                                    unsigned(LangOpts.OpenMP > 50
14158                                                 ? OMP_PROC_BIND_primary
14159                                                 : OMP_PROC_BIND_spread) +
14160                                        1)
14161         << getOpenMPClauseName(OMPC_proc_bind);
14162     return nullptr;
14163   }
14164   if (Kind == OMP_PROC_BIND_primary && LangOpts.OpenMP < 51)
14165     Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
14166         << getListOfPossibleValues(OMPC_proc_bind,
14167                                    /*First=*/unsigned(OMP_PROC_BIND_master),
14168                                    /*Last=*/
14169                                    unsigned(OMP_PROC_BIND_spread) + 1)
14170         << getOpenMPClauseName(OMPC_proc_bind);
14171   return new (Context)
14172       OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
14173 }
14174 
14175 OMPClause *Sema::ActOnOpenMPAtomicDefaultMemOrderClause(
14176     OpenMPAtomicDefaultMemOrderClauseKind Kind, SourceLocation KindKwLoc,
14177     SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
14178   if (Kind == OMPC_ATOMIC_DEFAULT_MEM_ORDER_unknown) {
14179     Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
14180         << getListOfPossibleValues(
14181                OMPC_atomic_default_mem_order, /*First=*/0,
14182                /*Last=*/OMPC_ATOMIC_DEFAULT_MEM_ORDER_unknown)
14183         << getOpenMPClauseName(OMPC_atomic_default_mem_order);
14184     return nullptr;
14185   }
14186   return new (Context) OMPAtomicDefaultMemOrderClause(Kind, KindKwLoc, StartLoc,
14187                                                       LParenLoc, EndLoc);
14188 }
14189 
14190 OMPClause *Sema::ActOnOpenMPOrderClause(OpenMPOrderClauseKind Kind,
14191                                         SourceLocation KindKwLoc,
14192                                         SourceLocation StartLoc,
14193                                         SourceLocation LParenLoc,
14194                                         SourceLocation EndLoc) {
14195   if (Kind == OMPC_ORDER_unknown) {
14196     static_assert(OMPC_ORDER_unknown > 0,
14197                   "OMPC_ORDER_unknown not greater than 0");
14198     Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
14199         << getListOfPossibleValues(OMPC_order, /*First=*/0,
14200                                    /*Last=*/OMPC_ORDER_unknown)
14201         << getOpenMPClauseName(OMPC_order);
14202     return nullptr;
14203   }
14204   return new (Context)
14205       OMPOrderClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
14206 }
14207 
14208 OMPClause *Sema::ActOnOpenMPUpdateClause(OpenMPDependClauseKind Kind,
14209                                          SourceLocation KindKwLoc,
14210                                          SourceLocation StartLoc,
14211                                          SourceLocation LParenLoc,
14212                                          SourceLocation EndLoc) {
14213   if (Kind == OMPC_DEPEND_unknown || Kind == OMPC_DEPEND_source ||
14214       Kind == OMPC_DEPEND_sink || Kind == OMPC_DEPEND_depobj) {
14215     unsigned Except[] = {OMPC_DEPEND_source, OMPC_DEPEND_sink,
14216                          OMPC_DEPEND_depobj};
14217     Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
14218         << getListOfPossibleValues(OMPC_depend, /*First=*/0,
14219                                    /*Last=*/OMPC_DEPEND_unknown, Except)
14220         << getOpenMPClauseName(OMPC_update);
14221     return nullptr;
14222   }
14223   return OMPUpdateClause::Create(Context, StartLoc, LParenLoc, KindKwLoc, Kind,
14224                                  EndLoc);
14225 }
14226 
14227 OMPClause *Sema::ActOnOpenMPSizesClause(ArrayRef<Expr *> SizeExprs,
14228                                         SourceLocation StartLoc,
14229                                         SourceLocation LParenLoc,
14230                                         SourceLocation EndLoc) {
14231   for (Expr *SizeExpr : SizeExprs) {
14232     ExprResult NumForLoopsResult = VerifyPositiveIntegerConstantInClause(
14233         SizeExpr, OMPC_sizes, /*StrictlyPositive=*/true);
14234     if (!NumForLoopsResult.isUsable())
14235       return nullptr;
14236   }
14237 
14238   DSAStack->setAssociatedLoops(SizeExprs.size());
14239   return OMPSizesClause::Create(Context, StartLoc, LParenLoc, EndLoc,
14240                                 SizeExprs);
14241 }
14242 
14243 OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause(
14244     OpenMPClauseKind Kind, ArrayRef<unsigned> Argument, Expr *Expr,
14245     SourceLocation StartLoc, SourceLocation LParenLoc,
14246     ArrayRef<SourceLocation> ArgumentLoc, SourceLocation DelimLoc,
14247     SourceLocation EndLoc) {
14248   OMPClause *Res = nullptr;
14249   switch (Kind) {
14250   case OMPC_schedule:
14251     enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements };
14252     assert(Argument.size() == NumberOfElements &&
14253            ArgumentLoc.size() == NumberOfElements);
14254     Res = ActOnOpenMPScheduleClause(
14255         static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier1]),
14256         static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier2]),
14257         static_cast<OpenMPScheduleClauseKind>(Argument[ScheduleKind]), Expr,
14258         StartLoc, LParenLoc, ArgumentLoc[Modifier1], ArgumentLoc[Modifier2],
14259         ArgumentLoc[ScheduleKind], DelimLoc, EndLoc);
14260     break;
14261   case OMPC_if:
14262     assert(Argument.size() == 1 && ArgumentLoc.size() == 1);
14263     Res = ActOnOpenMPIfClause(static_cast<OpenMPDirectiveKind>(Argument.back()),
14264                               Expr, StartLoc, LParenLoc, ArgumentLoc.back(),
14265                               DelimLoc, EndLoc);
14266     break;
14267   case OMPC_dist_schedule:
14268     Res = ActOnOpenMPDistScheduleClause(
14269         static_cast<OpenMPDistScheduleClauseKind>(Argument.back()), Expr,
14270         StartLoc, LParenLoc, ArgumentLoc.back(), DelimLoc, EndLoc);
14271     break;
14272   case OMPC_defaultmap:
14273     enum { Modifier, DefaultmapKind };
14274     Res = ActOnOpenMPDefaultmapClause(
14275         static_cast<OpenMPDefaultmapClauseModifier>(Argument[Modifier]),
14276         static_cast<OpenMPDefaultmapClauseKind>(Argument[DefaultmapKind]),
14277         StartLoc, LParenLoc, ArgumentLoc[Modifier], ArgumentLoc[DefaultmapKind],
14278         EndLoc);
14279     break;
14280   case OMPC_device:
14281     assert(Argument.size() == 1 && ArgumentLoc.size() == 1);
14282     Res = ActOnOpenMPDeviceClause(
14283         static_cast<OpenMPDeviceClauseModifier>(Argument.back()), Expr,
14284         StartLoc, LParenLoc, ArgumentLoc.back(), EndLoc);
14285     break;
14286   case OMPC_final:
14287   case OMPC_num_threads:
14288   case OMPC_safelen:
14289   case OMPC_simdlen:
14290   case OMPC_sizes:
14291   case OMPC_allocator:
14292   case OMPC_collapse:
14293   case OMPC_default:
14294   case OMPC_proc_bind:
14295   case OMPC_private:
14296   case OMPC_firstprivate:
14297   case OMPC_lastprivate:
14298   case OMPC_shared:
14299   case OMPC_reduction:
14300   case OMPC_task_reduction:
14301   case OMPC_in_reduction:
14302   case OMPC_linear:
14303   case OMPC_aligned:
14304   case OMPC_copyin:
14305   case OMPC_copyprivate:
14306   case OMPC_ordered:
14307   case OMPC_nowait:
14308   case OMPC_untied:
14309   case OMPC_mergeable:
14310   case OMPC_threadprivate:
14311   case OMPC_allocate:
14312   case OMPC_flush:
14313   case OMPC_depobj:
14314   case OMPC_read:
14315   case OMPC_write:
14316   case OMPC_update:
14317   case OMPC_capture:
14318   case OMPC_seq_cst:
14319   case OMPC_acq_rel:
14320   case OMPC_acquire:
14321   case OMPC_release:
14322   case OMPC_relaxed:
14323   case OMPC_depend:
14324   case OMPC_threads:
14325   case OMPC_simd:
14326   case OMPC_map:
14327   case OMPC_num_teams:
14328   case OMPC_thread_limit:
14329   case OMPC_priority:
14330   case OMPC_grainsize:
14331   case OMPC_nogroup:
14332   case OMPC_num_tasks:
14333   case OMPC_hint:
14334   case OMPC_unknown:
14335   case OMPC_uniform:
14336   case OMPC_to:
14337   case OMPC_from:
14338   case OMPC_use_device_ptr:
14339   case OMPC_use_device_addr:
14340   case OMPC_is_device_ptr:
14341   case OMPC_unified_address:
14342   case OMPC_unified_shared_memory:
14343   case OMPC_reverse_offload:
14344   case OMPC_dynamic_allocators:
14345   case OMPC_atomic_default_mem_order:
14346   case OMPC_device_type:
14347   case OMPC_match:
14348   case OMPC_nontemporal:
14349   case OMPC_order:
14350   case OMPC_destroy:
14351   case OMPC_novariants:
14352   case OMPC_nocontext:
14353   case OMPC_detach:
14354   case OMPC_inclusive:
14355   case OMPC_exclusive:
14356   case OMPC_uses_allocators:
14357   case OMPC_affinity:
14358   default:
14359     llvm_unreachable("Clause is not allowed.");
14360   }
14361   return Res;
14362 }
14363 
14364 static bool checkScheduleModifiers(Sema &S, OpenMPScheduleClauseModifier M1,
14365                                    OpenMPScheduleClauseModifier M2,
14366                                    SourceLocation M1Loc, SourceLocation M2Loc) {
14367   if (M1 == OMPC_SCHEDULE_MODIFIER_unknown && M1Loc.isValid()) {
14368     SmallVector<unsigned, 2> Excluded;
14369     if (M2 != OMPC_SCHEDULE_MODIFIER_unknown)
14370       Excluded.push_back(M2);
14371     if (M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic)
14372       Excluded.push_back(OMPC_SCHEDULE_MODIFIER_monotonic);
14373     if (M2 == OMPC_SCHEDULE_MODIFIER_monotonic)
14374       Excluded.push_back(OMPC_SCHEDULE_MODIFIER_nonmonotonic);
14375     S.Diag(M1Loc, diag::err_omp_unexpected_clause_value)
14376         << getListOfPossibleValues(OMPC_schedule,
14377                                    /*First=*/OMPC_SCHEDULE_MODIFIER_unknown + 1,
14378                                    /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
14379                                    Excluded)
14380         << getOpenMPClauseName(OMPC_schedule);
14381     return true;
14382   }
14383   return false;
14384 }
14385 
14386 OMPClause *Sema::ActOnOpenMPScheduleClause(
14387     OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
14388     OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
14389     SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
14390     SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) {
14391   if (checkScheduleModifiers(*this, M1, M2, M1Loc, M2Loc) ||
14392       checkScheduleModifiers(*this, M2, M1, M2Loc, M1Loc))
14393     return nullptr;
14394   // OpenMP, 2.7.1, Loop Construct, Restrictions
14395   // Either the monotonic modifier or the nonmonotonic modifier can be specified
14396   // but not both.
14397   if ((M1 == M2 && M1 != OMPC_SCHEDULE_MODIFIER_unknown) ||
14398       (M1 == OMPC_SCHEDULE_MODIFIER_monotonic &&
14399        M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) ||
14400       (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic &&
14401        M2 == OMPC_SCHEDULE_MODIFIER_monotonic)) {
14402     Diag(M2Loc, diag::err_omp_unexpected_schedule_modifier)
14403         << getOpenMPSimpleClauseTypeName(OMPC_schedule, M2)
14404         << getOpenMPSimpleClauseTypeName(OMPC_schedule, M1);
14405     return nullptr;
14406   }
14407   if (Kind == OMPC_SCHEDULE_unknown) {
14408     std::string Values;
14409     if (M1Loc.isInvalid() && M2Loc.isInvalid()) {
14410       unsigned Exclude[] = {OMPC_SCHEDULE_unknown};
14411       Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
14412                                        /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
14413                                        Exclude);
14414     } else {
14415       Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
14416                                        /*Last=*/OMPC_SCHEDULE_unknown);
14417     }
14418     Diag(KindLoc, diag::err_omp_unexpected_clause_value)
14419         << Values << getOpenMPClauseName(OMPC_schedule);
14420     return nullptr;
14421   }
14422   // OpenMP, 2.7.1, Loop Construct, Restrictions
14423   // The nonmonotonic modifier can only be specified with schedule(dynamic) or
14424   // schedule(guided).
14425   // OpenMP 5.0 does not have this restriction.
14426   if (LangOpts.OpenMP < 50 &&
14427       (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
14428        M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
14429       Kind != OMPC_SCHEDULE_dynamic && Kind != OMPC_SCHEDULE_guided) {
14430     Diag(M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ? M1Loc : M2Loc,
14431          diag::err_omp_schedule_nonmonotonic_static);
14432     return nullptr;
14433   }
14434   Expr *ValExpr = ChunkSize;
14435   Stmt *HelperValStmt = nullptr;
14436   if (ChunkSize) {
14437     if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
14438         !ChunkSize->isInstantiationDependent() &&
14439         !ChunkSize->containsUnexpandedParameterPack()) {
14440       SourceLocation ChunkSizeLoc = ChunkSize->getBeginLoc();
14441       ExprResult Val =
14442           PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
14443       if (Val.isInvalid())
14444         return nullptr;
14445 
14446       ValExpr = Val.get();
14447 
14448       // OpenMP [2.7.1, Restrictions]
14449       //  chunk_size must be a loop invariant integer expression with a positive
14450       //  value.
14451       if (Optional<llvm::APSInt> Result =
14452               ValExpr->getIntegerConstantExpr(Context)) {
14453         if (Result->isSigned() && !Result->isStrictlyPositive()) {
14454           Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
14455               << "schedule" << 1 << ChunkSize->getSourceRange();
14456           return nullptr;
14457         }
14458       } else if (getOpenMPCaptureRegionForClause(
14459                      DSAStack->getCurrentDirective(), OMPC_schedule,
14460                      LangOpts.OpenMP) != OMPD_unknown &&
14461                  !CurContext->isDependentContext()) {
14462         ValExpr = MakeFullExpr(ValExpr).get();
14463         llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
14464         ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
14465         HelperValStmt = buildPreInits(Context, Captures);
14466       }
14467     }
14468   }
14469 
14470   return new (Context)
14471       OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, Kind,
14472                         ValExpr, HelperValStmt, M1, M1Loc, M2, M2Loc);
14473 }
14474 
14475 OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind,
14476                                    SourceLocation StartLoc,
14477                                    SourceLocation EndLoc) {
14478   OMPClause *Res = nullptr;
14479   switch (Kind) {
14480   case OMPC_ordered:
14481     Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc);
14482     break;
14483   case OMPC_nowait:
14484     Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc);
14485     break;
14486   case OMPC_untied:
14487     Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc);
14488     break;
14489   case OMPC_mergeable:
14490     Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc);
14491     break;
14492   case OMPC_read:
14493     Res = ActOnOpenMPReadClause(StartLoc, EndLoc);
14494     break;
14495   case OMPC_write:
14496     Res = ActOnOpenMPWriteClause(StartLoc, EndLoc);
14497     break;
14498   case OMPC_update:
14499     Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc);
14500     break;
14501   case OMPC_capture:
14502     Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc);
14503     break;
14504   case OMPC_seq_cst:
14505     Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc);
14506     break;
14507   case OMPC_acq_rel:
14508     Res = ActOnOpenMPAcqRelClause(StartLoc, EndLoc);
14509     break;
14510   case OMPC_acquire:
14511     Res = ActOnOpenMPAcquireClause(StartLoc, EndLoc);
14512     break;
14513   case OMPC_release:
14514     Res = ActOnOpenMPReleaseClause(StartLoc, EndLoc);
14515     break;
14516   case OMPC_relaxed:
14517     Res = ActOnOpenMPRelaxedClause(StartLoc, EndLoc);
14518     break;
14519   case OMPC_threads:
14520     Res = ActOnOpenMPThreadsClause(StartLoc, EndLoc);
14521     break;
14522   case OMPC_simd:
14523     Res = ActOnOpenMPSIMDClause(StartLoc, EndLoc);
14524     break;
14525   case OMPC_nogroup:
14526     Res = ActOnOpenMPNogroupClause(StartLoc, EndLoc);
14527     break;
14528   case OMPC_unified_address:
14529     Res = ActOnOpenMPUnifiedAddressClause(StartLoc, EndLoc);
14530     break;
14531   case OMPC_unified_shared_memory:
14532     Res = ActOnOpenMPUnifiedSharedMemoryClause(StartLoc, EndLoc);
14533     break;
14534   case OMPC_reverse_offload:
14535     Res = ActOnOpenMPReverseOffloadClause(StartLoc, EndLoc);
14536     break;
14537   case OMPC_dynamic_allocators:
14538     Res = ActOnOpenMPDynamicAllocatorsClause(StartLoc, EndLoc);
14539     break;
14540   case OMPC_destroy:
14541     Res = ActOnOpenMPDestroyClause(/*InteropVar=*/nullptr, StartLoc,
14542                                    /*LParenLoc=*/SourceLocation(),
14543                                    /*VarLoc=*/SourceLocation(), EndLoc);
14544     break;
14545   case OMPC_if:
14546   case OMPC_final:
14547   case OMPC_num_threads:
14548   case OMPC_safelen:
14549   case OMPC_simdlen:
14550   case OMPC_sizes:
14551   case OMPC_allocator:
14552   case OMPC_collapse:
14553   case OMPC_schedule:
14554   case OMPC_private:
14555   case OMPC_firstprivate:
14556   case OMPC_lastprivate:
14557   case OMPC_shared:
14558   case OMPC_reduction:
14559   case OMPC_task_reduction:
14560   case OMPC_in_reduction:
14561   case OMPC_linear:
14562   case OMPC_aligned:
14563   case OMPC_copyin:
14564   case OMPC_copyprivate:
14565   case OMPC_default:
14566   case OMPC_proc_bind:
14567   case OMPC_threadprivate:
14568   case OMPC_allocate:
14569   case OMPC_flush:
14570   case OMPC_depobj:
14571   case OMPC_depend:
14572   case OMPC_device:
14573   case OMPC_map:
14574   case OMPC_num_teams:
14575   case OMPC_thread_limit:
14576   case OMPC_priority:
14577   case OMPC_grainsize:
14578   case OMPC_num_tasks:
14579   case OMPC_hint:
14580   case OMPC_dist_schedule:
14581   case OMPC_defaultmap:
14582   case OMPC_unknown:
14583   case OMPC_uniform:
14584   case OMPC_to:
14585   case OMPC_from:
14586   case OMPC_use_device_ptr:
14587   case OMPC_use_device_addr:
14588   case OMPC_is_device_ptr:
14589   case OMPC_atomic_default_mem_order:
14590   case OMPC_device_type:
14591   case OMPC_match:
14592   case OMPC_nontemporal:
14593   case OMPC_order:
14594   case OMPC_novariants:
14595   case OMPC_nocontext:
14596   case OMPC_detach:
14597   case OMPC_inclusive:
14598   case OMPC_exclusive:
14599   case OMPC_uses_allocators:
14600   case OMPC_affinity:
14601   default:
14602     llvm_unreachable("Clause is not allowed.");
14603   }
14604   return Res;
14605 }
14606 
14607 OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc,
14608                                          SourceLocation EndLoc) {
14609   DSAStack->setNowaitRegion();
14610   return new (Context) OMPNowaitClause(StartLoc, EndLoc);
14611 }
14612 
14613 OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc,
14614                                          SourceLocation EndLoc) {
14615   return new (Context) OMPUntiedClause(StartLoc, EndLoc);
14616 }
14617 
14618 OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc,
14619                                             SourceLocation EndLoc) {
14620   return new (Context) OMPMergeableClause(StartLoc, EndLoc);
14621 }
14622 
14623 OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc,
14624                                        SourceLocation EndLoc) {
14625   return new (Context) OMPReadClause(StartLoc, EndLoc);
14626 }
14627 
14628 OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc,
14629                                         SourceLocation EndLoc) {
14630   return new (Context) OMPWriteClause(StartLoc, EndLoc);
14631 }
14632 
14633 OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc,
14634                                          SourceLocation EndLoc) {
14635   return OMPUpdateClause::Create(Context, StartLoc, EndLoc);
14636 }
14637 
14638 OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc,
14639                                           SourceLocation EndLoc) {
14640   return new (Context) OMPCaptureClause(StartLoc, EndLoc);
14641 }
14642 
14643 OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
14644                                          SourceLocation EndLoc) {
14645   return new (Context) OMPSeqCstClause(StartLoc, EndLoc);
14646 }
14647 
14648 OMPClause *Sema::ActOnOpenMPAcqRelClause(SourceLocation StartLoc,
14649                                          SourceLocation EndLoc) {
14650   return new (Context) OMPAcqRelClause(StartLoc, EndLoc);
14651 }
14652 
14653 OMPClause *Sema::ActOnOpenMPAcquireClause(SourceLocation StartLoc,
14654                                           SourceLocation EndLoc) {
14655   return new (Context) OMPAcquireClause(StartLoc, EndLoc);
14656 }
14657 
14658 OMPClause *Sema::ActOnOpenMPReleaseClause(SourceLocation StartLoc,
14659                                           SourceLocation EndLoc) {
14660   return new (Context) OMPReleaseClause(StartLoc, EndLoc);
14661 }
14662 
14663 OMPClause *Sema::ActOnOpenMPRelaxedClause(SourceLocation StartLoc,
14664                                           SourceLocation EndLoc) {
14665   return new (Context) OMPRelaxedClause(StartLoc, EndLoc);
14666 }
14667 
14668 OMPClause *Sema::ActOnOpenMPThreadsClause(SourceLocation StartLoc,
14669                                           SourceLocation EndLoc) {
14670   return new (Context) OMPThreadsClause(StartLoc, EndLoc);
14671 }
14672 
14673 OMPClause *Sema::ActOnOpenMPSIMDClause(SourceLocation StartLoc,
14674                                        SourceLocation EndLoc) {
14675   return new (Context) OMPSIMDClause(StartLoc, EndLoc);
14676 }
14677 
14678 OMPClause *Sema::ActOnOpenMPNogroupClause(SourceLocation StartLoc,
14679                                           SourceLocation EndLoc) {
14680   return new (Context) OMPNogroupClause(StartLoc, EndLoc);
14681 }
14682 
14683 OMPClause *Sema::ActOnOpenMPUnifiedAddressClause(SourceLocation StartLoc,
14684                                                  SourceLocation EndLoc) {
14685   return new (Context) OMPUnifiedAddressClause(StartLoc, EndLoc);
14686 }
14687 
14688 OMPClause *Sema::ActOnOpenMPUnifiedSharedMemoryClause(SourceLocation StartLoc,
14689                                                       SourceLocation EndLoc) {
14690   return new (Context) OMPUnifiedSharedMemoryClause(StartLoc, EndLoc);
14691 }
14692 
14693 OMPClause *Sema::ActOnOpenMPReverseOffloadClause(SourceLocation StartLoc,
14694                                                  SourceLocation EndLoc) {
14695   return new (Context) OMPReverseOffloadClause(StartLoc, EndLoc);
14696 }
14697 
14698 OMPClause *Sema::ActOnOpenMPDynamicAllocatorsClause(SourceLocation StartLoc,
14699                                                     SourceLocation EndLoc) {
14700   return new (Context) OMPDynamicAllocatorsClause(StartLoc, EndLoc);
14701 }
14702 
14703 StmtResult Sema::ActOnOpenMPInteropDirective(ArrayRef<OMPClause *> Clauses,
14704                                              SourceLocation StartLoc,
14705                                              SourceLocation EndLoc) {
14706 
14707   // OpenMP 5.1 [2.15.1, interop Construct, Restrictions]
14708   // At least one action-clause must appear on a directive.
14709   if (!hasClauses(Clauses, OMPC_init, OMPC_use, OMPC_destroy, OMPC_nowait)) {
14710     StringRef Expected = "'init', 'use', 'destroy', or 'nowait'";
14711     Diag(StartLoc, diag::err_omp_no_clause_for_directive)
14712         << Expected << getOpenMPDirectiveName(OMPD_interop);
14713     return StmtError();
14714   }
14715 
14716   // OpenMP 5.1 [2.15.1, interop Construct, Restrictions]
14717   // A depend clause can only appear on the directive if a targetsync
14718   // interop-type is present or the interop-var was initialized with
14719   // the targetsync interop-type.
14720 
14721   // If there is any 'init' clause diagnose if there is no 'init' clause with
14722   // interop-type of 'targetsync'. Cases involving other directives cannot be
14723   // diagnosed.
14724   const OMPDependClause *DependClause = nullptr;
14725   bool HasInitClause = false;
14726   bool IsTargetSync = false;
14727   for (const OMPClause *C : Clauses) {
14728     if (IsTargetSync)
14729       break;
14730     if (const auto *InitClause = dyn_cast<OMPInitClause>(C)) {
14731       HasInitClause = true;
14732       if (InitClause->getIsTargetSync())
14733         IsTargetSync = true;
14734     } else if (const auto *DC = dyn_cast<OMPDependClause>(C)) {
14735       DependClause = DC;
14736     }
14737   }
14738   if (DependClause && HasInitClause && !IsTargetSync) {
14739     Diag(DependClause->getBeginLoc(), diag::err_omp_interop_bad_depend_clause);
14740     return StmtError();
14741   }
14742 
14743   // OpenMP 5.1 [2.15.1, interop Construct, Restrictions]
14744   // Each interop-var may be specified for at most one action-clause of each
14745   // interop construct.
14746   llvm::SmallPtrSet<const VarDecl *, 4> InteropVars;
14747   for (const OMPClause *C : Clauses) {
14748     OpenMPClauseKind ClauseKind = C->getClauseKind();
14749     const DeclRefExpr *DRE = nullptr;
14750     SourceLocation VarLoc;
14751 
14752     if (ClauseKind == OMPC_init) {
14753       const auto *IC = cast<OMPInitClause>(C);
14754       VarLoc = IC->getVarLoc();
14755       DRE = dyn_cast_or_null<DeclRefExpr>(IC->getInteropVar());
14756     } else if (ClauseKind == OMPC_use) {
14757       const auto *UC = cast<OMPUseClause>(C);
14758       VarLoc = UC->getVarLoc();
14759       DRE = dyn_cast_or_null<DeclRefExpr>(UC->getInteropVar());
14760     } else if (ClauseKind == OMPC_destroy) {
14761       const auto *DC = cast<OMPDestroyClause>(C);
14762       VarLoc = DC->getVarLoc();
14763       DRE = dyn_cast_or_null<DeclRefExpr>(DC->getInteropVar());
14764     }
14765 
14766     if (!DRE)
14767       continue;
14768 
14769     if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
14770       if (!InteropVars.insert(VD->getCanonicalDecl()).second) {
14771         Diag(VarLoc, diag::err_omp_interop_var_multiple_actions) << VD;
14772         return StmtError();
14773       }
14774     }
14775   }
14776 
14777   return OMPInteropDirective::Create(Context, StartLoc, EndLoc, Clauses);
14778 }
14779 
14780 static bool isValidInteropVariable(Sema &SemaRef, Expr *InteropVarExpr,
14781                                    SourceLocation VarLoc,
14782                                    OpenMPClauseKind Kind) {
14783   if (InteropVarExpr->isValueDependent() || InteropVarExpr->isTypeDependent() ||
14784       InteropVarExpr->isInstantiationDependent() ||
14785       InteropVarExpr->containsUnexpandedParameterPack())
14786     return true;
14787 
14788   const auto *DRE = dyn_cast<DeclRefExpr>(InteropVarExpr);
14789   if (!DRE || !isa<VarDecl>(DRE->getDecl())) {
14790     SemaRef.Diag(VarLoc, diag::err_omp_interop_variable_expected) << 0;
14791     return false;
14792   }
14793 
14794   // Interop variable should be of type omp_interop_t.
14795   bool HasError = false;
14796   QualType InteropType;
14797   LookupResult Result(SemaRef, &SemaRef.Context.Idents.get("omp_interop_t"),
14798                       VarLoc, Sema::LookupOrdinaryName);
14799   if (SemaRef.LookupName(Result, SemaRef.getCurScope())) {
14800     NamedDecl *ND = Result.getFoundDecl();
14801     if (const auto *TD = dyn_cast<TypeDecl>(ND)) {
14802       InteropType = QualType(TD->getTypeForDecl(), 0);
14803     } else {
14804       HasError = true;
14805     }
14806   } else {
14807     HasError = true;
14808   }
14809 
14810   if (HasError) {
14811     SemaRef.Diag(VarLoc, diag::err_omp_implied_type_not_found)
14812         << "omp_interop_t";
14813     return false;
14814   }
14815 
14816   QualType VarType = InteropVarExpr->getType().getUnqualifiedType();
14817   if (!SemaRef.Context.hasSameType(InteropType, VarType)) {
14818     SemaRef.Diag(VarLoc, diag::err_omp_interop_variable_wrong_type);
14819     return false;
14820   }
14821 
14822   // OpenMP 5.1 [2.15.1, interop Construct, Restrictions]
14823   // The interop-var passed to init or destroy must be non-const.
14824   if ((Kind == OMPC_init || Kind == OMPC_destroy) &&
14825       isConstNotMutableType(SemaRef, InteropVarExpr->getType())) {
14826     SemaRef.Diag(VarLoc, diag::err_omp_interop_variable_expected)
14827         << /*non-const*/ 1;
14828     return false;
14829   }
14830   return true;
14831 }
14832 
14833 OMPClause *
14834 Sema::ActOnOpenMPInitClause(Expr *InteropVar, ArrayRef<Expr *> PrefExprs,
14835                             bool IsTarget, bool IsTargetSync,
14836                             SourceLocation StartLoc, SourceLocation LParenLoc,
14837                             SourceLocation VarLoc, SourceLocation EndLoc) {
14838 
14839   if (!isValidInteropVariable(*this, InteropVar, VarLoc, OMPC_init))
14840     return nullptr;
14841 
14842   // Check prefer_type values.  These foreign-runtime-id values are either
14843   // string literals or constant integral expressions.
14844   for (const Expr *E : PrefExprs) {
14845     if (E->isValueDependent() || E->isTypeDependent() ||
14846         E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
14847       continue;
14848     if (E->isIntegerConstantExpr(Context))
14849       continue;
14850     if (isa<StringLiteral>(E))
14851       continue;
14852     Diag(E->getExprLoc(), diag::err_omp_interop_prefer_type);
14853     return nullptr;
14854   }
14855 
14856   return OMPInitClause::Create(Context, InteropVar, PrefExprs, IsTarget,
14857                                IsTargetSync, StartLoc, LParenLoc, VarLoc,
14858                                EndLoc);
14859 }
14860 
14861 OMPClause *Sema::ActOnOpenMPUseClause(Expr *InteropVar, SourceLocation StartLoc,
14862                                       SourceLocation LParenLoc,
14863                                       SourceLocation VarLoc,
14864                                       SourceLocation EndLoc) {
14865 
14866   if (!isValidInteropVariable(*this, InteropVar, VarLoc, OMPC_use))
14867     return nullptr;
14868 
14869   return new (Context)
14870       OMPUseClause(InteropVar, StartLoc, LParenLoc, VarLoc, EndLoc);
14871 }
14872 
14873 OMPClause *Sema::ActOnOpenMPDestroyClause(Expr *InteropVar,
14874                                           SourceLocation StartLoc,
14875                                           SourceLocation LParenLoc,
14876                                           SourceLocation VarLoc,
14877                                           SourceLocation EndLoc) {
14878   if (InteropVar &&
14879       !isValidInteropVariable(*this, InteropVar, VarLoc, OMPC_destroy))
14880     return nullptr;
14881 
14882   return new (Context)
14883       OMPDestroyClause(InteropVar, StartLoc, LParenLoc, VarLoc, EndLoc);
14884 }
14885 
14886 OMPClause *Sema::ActOnOpenMPNovariantsClause(Expr *Condition,
14887                                              SourceLocation StartLoc,
14888                                              SourceLocation LParenLoc,
14889                                              SourceLocation EndLoc) {
14890   Expr *ValExpr = Condition;
14891   Stmt *HelperValStmt = nullptr;
14892   OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
14893   if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
14894       !Condition->isInstantiationDependent() &&
14895       !Condition->containsUnexpandedParameterPack()) {
14896     ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
14897     if (Val.isInvalid())
14898       return nullptr;
14899 
14900     ValExpr = MakeFullExpr(Val.get()).get();
14901 
14902     OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
14903     CaptureRegion = getOpenMPCaptureRegionForClause(DKind, OMPC_novariants,
14904                                                     LangOpts.OpenMP);
14905     if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
14906       ValExpr = MakeFullExpr(ValExpr).get();
14907       llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
14908       ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
14909       HelperValStmt = buildPreInits(Context, Captures);
14910     }
14911   }
14912 
14913   return new (Context) OMPNovariantsClause(
14914       ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
14915 }
14916 
14917 OMPClause *Sema::ActOnOpenMPNocontextClause(Expr *Condition,
14918                                             SourceLocation StartLoc,
14919                                             SourceLocation LParenLoc,
14920                                             SourceLocation EndLoc) {
14921   Expr *ValExpr = Condition;
14922   Stmt *HelperValStmt = nullptr;
14923   OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
14924   if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
14925       !Condition->isInstantiationDependent() &&
14926       !Condition->containsUnexpandedParameterPack()) {
14927     ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
14928     if (Val.isInvalid())
14929       return nullptr;
14930 
14931     ValExpr = MakeFullExpr(Val.get()).get();
14932 
14933     OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
14934     CaptureRegion =
14935         getOpenMPCaptureRegionForClause(DKind, OMPC_nocontext, LangOpts.OpenMP);
14936     if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
14937       ValExpr = MakeFullExpr(ValExpr).get();
14938       llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
14939       ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
14940       HelperValStmt = buildPreInits(Context, Captures);
14941     }
14942   }
14943 
14944   return new (Context) OMPNocontextClause(ValExpr, HelperValStmt, CaptureRegion,
14945                                           StartLoc, LParenLoc, EndLoc);
14946 }
14947 
14948 OMPClause *Sema::ActOnOpenMPVarListClause(
14949     OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *DepModOrTailExpr,
14950     const OMPVarListLocTy &Locs, SourceLocation ColonLoc,
14951     CXXScopeSpec &ReductionOrMapperIdScopeSpec,
14952     DeclarationNameInfo &ReductionOrMapperId, int ExtraModifier,
14953     ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
14954     ArrayRef<SourceLocation> MapTypeModifiersLoc, bool IsMapTypeImplicit,
14955     SourceLocation ExtraModifierLoc,
14956     ArrayRef<OpenMPMotionModifierKind> MotionModifiers,
14957     ArrayRef<SourceLocation> MotionModifiersLoc) {
14958   SourceLocation StartLoc = Locs.StartLoc;
14959   SourceLocation LParenLoc = Locs.LParenLoc;
14960   SourceLocation EndLoc = Locs.EndLoc;
14961   OMPClause *Res = nullptr;
14962   switch (Kind) {
14963   case OMPC_private:
14964     Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
14965     break;
14966   case OMPC_firstprivate:
14967     Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
14968     break;
14969   case OMPC_lastprivate:
14970     assert(0 <= ExtraModifier && ExtraModifier <= OMPC_LASTPRIVATE_unknown &&
14971            "Unexpected lastprivate modifier.");
14972     Res = ActOnOpenMPLastprivateClause(
14973         VarList, static_cast<OpenMPLastprivateModifier>(ExtraModifier),
14974         ExtraModifierLoc, ColonLoc, StartLoc, LParenLoc, EndLoc);
14975     break;
14976   case OMPC_shared:
14977     Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
14978     break;
14979   case OMPC_reduction:
14980     assert(0 <= ExtraModifier && ExtraModifier <= OMPC_REDUCTION_unknown &&
14981            "Unexpected lastprivate modifier.");
14982     Res = ActOnOpenMPReductionClause(
14983         VarList, static_cast<OpenMPReductionClauseModifier>(ExtraModifier),
14984         StartLoc, LParenLoc, ExtraModifierLoc, ColonLoc, EndLoc,
14985         ReductionOrMapperIdScopeSpec, ReductionOrMapperId);
14986     break;
14987   case OMPC_task_reduction:
14988     Res = ActOnOpenMPTaskReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
14989                                          EndLoc, ReductionOrMapperIdScopeSpec,
14990                                          ReductionOrMapperId);
14991     break;
14992   case OMPC_in_reduction:
14993     Res = ActOnOpenMPInReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
14994                                        EndLoc, ReductionOrMapperIdScopeSpec,
14995                                        ReductionOrMapperId);
14996     break;
14997   case OMPC_linear:
14998     assert(0 <= ExtraModifier && ExtraModifier <= OMPC_LINEAR_unknown &&
14999            "Unexpected linear modifier.");
15000     Res = ActOnOpenMPLinearClause(
15001         VarList, DepModOrTailExpr, StartLoc, LParenLoc,
15002         static_cast<OpenMPLinearClauseKind>(ExtraModifier), ExtraModifierLoc,
15003         ColonLoc, EndLoc);
15004     break;
15005   case OMPC_aligned:
15006     Res = ActOnOpenMPAlignedClause(VarList, DepModOrTailExpr, StartLoc,
15007                                    LParenLoc, ColonLoc, EndLoc);
15008     break;
15009   case OMPC_copyin:
15010     Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
15011     break;
15012   case OMPC_copyprivate:
15013     Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
15014     break;
15015   case OMPC_flush:
15016     Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc);
15017     break;
15018   case OMPC_depend:
15019     assert(0 <= ExtraModifier && ExtraModifier <= OMPC_DEPEND_unknown &&
15020            "Unexpected depend modifier.");
15021     Res = ActOnOpenMPDependClause(
15022         DepModOrTailExpr, static_cast<OpenMPDependClauseKind>(ExtraModifier),
15023         ExtraModifierLoc, ColonLoc, VarList, StartLoc, LParenLoc, EndLoc);
15024     break;
15025   case OMPC_map:
15026     assert(0 <= ExtraModifier && ExtraModifier <= OMPC_MAP_unknown &&
15027            "Unexpected map modifier.");
15028     Res = ActOnOpenMPMapClause(
15029         MapTypeModifiers, MapTypeModifiersLoc, ReductionOrMapperIdScopeSpec,
15030         ReductionOrMapperId, static_cast<OpenMPMapClauseKind>(ExtraModifier),
15031         IsMapTypeImplicit, ExtraModifierLoc, ColonLoc, VarList, Locs);
15032     break;
15033   case OMPC_to:
15034     Res = ActOnOpenMPToClause(MotionModifiers, MotionModifiersLoc,
15035                               ReductionOrMapperIdScopeSpec, ReductionOrMapperId,
15036                               ColonLoc, VarList, Locs);
15037     break;
15038   case OMPC_from:
15039     Res = ActOnOpenMPFromClause(MotionModifiers, MotionModifiersLoc,
15040                                 ReductionOrMapperIdScopeSpec,
15041                                 ReductionOrMapperId, ColonLoc, VarList, Locs);
15042     break;
15043   case OMPC_use_device_ptr:
15044     Res = ActOnOpenMPUseDevicePtrClause(VarList, Locs);
15045     break;
15046   case OMPC_use_device_addr:
15047     Res = ActOnOpenMPUseDeviceAddrClause(VarList, Locs);
15048     break;
15049   case OMPC_is_device_ptr:
15050     Res = ActOnOpenMPIsDevicePtrClause(VarList, Locs);
15051     break;
15052   case OMPC_allocate:
15053     Res = ActOnOpenMPAllocateClause(DepModOrTailExpr, VarList, StartLoc,
15054                                     LParenLoc, ColonLoc, EndLoc);
15055     break;
15056   case OMPC_nontemporal:
15057     Res = ActOnOpenMPNontemporalClause(VarList, StartLoc, LParenLoc, EndLoc);
15058     break;
15059   case OMPC_inclusive:
15060     Res = ActOnOpenMPInclusiveClause(VarList, StartLoc, LParenLoc, EndLoc);
15061     break;
15062   case OMPC_exclusive:
15063     Res = ActOnOpenMPExclusiveClause(VarList, StartLoc, LParenLoc, EndLoc);
15064     break;
15065   case OMPC_affinity:
15066     Res = ActOnOpenMPAffinityClause(StartLoc, LParenLoc, ColonLoc, EndLoc,
15067                                     DepModOrTailExpr, VarList);
15068     break;
15069   case OMPC_if:
15070   case OMPC_depobj:
15071   case OMPC_final:
15072   case OMPC_num_threads:
15073   case OMPC_safelen:
15074   case OMPC_simdlen:
15075   case OMPC_sizes:
15076   case OMPC_allocator:
15077   case OMPC_collapse:
15078   case OMPC_default:
15079   case OMPC_proc_bind:
15080   case OMPC_schedule:
15081   case OMPC_ordered:
15082   case OMPC_nowait:
15083   case OMPC_untied:
15084   case OMPC_mergeable:
15085   case OMPC_threadprivate:
15086   case OMPC_read:
15087   case OMPC_write:
15088   case OMPC_update:
15089   case OMPC_capture:
15090   case OMPC_seq_cst:
15091   case OMPC_acq_rel:
15092   case OMPC_acquire:
15093   case OMPC_release:
15094   case OMPC_relaxed:
15095   case OMPC_device:
15096   case OMPC_threads:
15097   case OMPC_simd:
15098   case OMPC_num_teams:
15099   case OMPC_thread_limit:
15100   case OMPC_priority:
15101   case OMPC_grainsize:
15102   case OMPC_nogroup:
15103   case OMPC_num_tasks:
15104   case OMPC_hint:
15105   case OMPC_dist_schedule:
15106   case OMPC_defaultmap:
15107   case OMPC_unknown:
15108   case OMPC_uniform:
15109   case OMPC_unified_address:
15110   case OMPC_unified_shared_memory:
15111   case OMPC_reverse_offload:
15112   case OMPC_dynamic_allocators:
15113   case OMPC_atomic_default_mem_order:
15114   case OMPC_device_type:
15115   case OMPC_match:
15116   case OMPC_order:
15117   case OMPC_destroy:
15118   case OMPC_novariants:
15119   case OMPC_nocontext:
15120   case OMPC_detach:
15121   case OMPC_uses_allocators:
15122   default:
15123     llvm_unreachable("Clause is not allowed.");
15124   }
15125   return Res;
15126 }
15127 
15128 ExprResult Sema::getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
15129                                        ExprObjectKind OK, SourceLocation Loc) {
15130   ExprResult Res = BuildDeclRefExpr(
15131       Capture, Capture->getType().getNonReferenceType(), VK_LValue, Loc);
15132   if (!Res.isUsable())
15133     return ExprError();
15134   if (OK == OK_Ordinary && !getLangOpts().CPlusPlus) {
15135     Res = CreateBuiltinUnaryOp(Loc, UO_Deref, Res.get());
15136     if (!Res.isUsable())
15137       return ExprError();
15138   }
15139   if (VK != VK_LValue && Res.get()->isGLValue()) {
15140     Res = DefaultLvalueConversion(Res.get());
15141     if (!Res.isUsable())
15142       return ExprError();
15143   }
15144   return Res;
15145 }
15146 
15147 OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
15148                                           SourceLocation StartLoc,
15149                                           SourceLocation LParenLoc,
15150                                           SourceLocation EndLoc) {
15151   SmallVector<Expr *, 8> Vars;
15152   SmallVector<Expr *, 8> PrivateCopies;
15153   for (Expr *RefExpr : VarList) {
15154     assert(RefExpr && "NULL expr in OpenMP private clause.");
15155     SourceLocation ELoc;
15156     SourceRange ERange;
15157     Expr *SimpleRefExpr = RefExpr;
15158     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
15159     if (Res.second) {
15160       // It will be analyzed later.
15161       Vars.push_back(RefExpr);
15162       PrivateCopies.push_back(nullptr);
15163     }
15164     ValueDecl *D = Res.first;
15165     if (!D)
15166       continue;
15167 
15168     QualType Type = D->getType();
15169     auto *VD = dyn_cast<VarDecl>(D);
15170 
15171     // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
15172     //  A variable that appears in a private clause must not have an incomplete
15173     //  type or a reference type.
15174     if (RequireCompleteType(ELoc, Type, diag::err_omp_private_incomplete_type))
15175       continue;
15176     Type = Type.getNonReferenceType();
15177 
15178     // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
15179     // A variable that is privatized must not have a const-qualified type
15180     // unless it is of class type with a mutable member. This restriction does
15181     // not apply to the firstprivate clause.
15182     //
15183     // OpenMP 3.1 [2.9.3.3, private clause, Restrictions]
15184     // A variable that appears in a private clause must not have a
15185     // const-qualified type unless it is of class type with a mutable member.
15186     if (rejectConstNotMutableType(*this, D, Type, OMPC_private, ELoc))
15187       continue;
15188 
15189     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
15190     // in a Construct]
15191     //  Variables with the predetermined data-sharing attributes may not be
15192     //  listed in data-sharing attributes clauses, except for the cases
15193     //  listed below. For these exceptions only, listing a predetermined
15194     //  variable in a data-sharing attribute clause is allowed and overrides
15195     //  the variable's predetermined data-sharing attributes.
15196     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
15197     if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
15198       Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
15199                                           << getOpenMPClauseName(OMPC_private);
15200       reportOriginalDsa(*this, DSAStack, D, DVar);
15201       continue;
15202     }
15203 
15204     OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
15205     // Variably modified types are not supported for tasks.
15206     if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
15207         isOpenMPTaskingDirective(CurrDir)) {
15208       Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
15209           << getOpenMPClauseName(OMPC_private) << Type
15210           << getOpenMPDirectiveName(CurrDir);
15211       bool IsDecl =
15212           !VD ||
15213           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
15214       Diag(D->getLocation(),
15215            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
15216           << D;
15217       continue;
15218     }
15219 
15220     // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
15221     // A list item cannot appear in both a map clause and a data-sharing
15222     // attribute clause on the same construct
15223     //
15224     // OpenMP 5.0 [2.19.7.1, Restrictions, p.7]
15225     // A list item cannot appear in both a map clause and a data-sharing
15226     // attribute clause on the same construct unless the construct is a
15227     // combined construct.
15228     if ((LangOpts.OpenMP <= 45 && isOpenMPTargetExecutionDirective(CurrDir)) ||
15229         CurrDir == OMPD_target) {
15230       OpenMPClauseKind ConflictKind;
15231       if (DSAStack->checkMappableExprComponentListsForDecl(
15232               VD, /*CurrentRegionOnly=*/true,
15233               [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
15234                   OpenMPClauseKind WhereFoundClauseKind) -> bool {
15235                 ConflictKind = WhereFoundClauseKind;
15236                 return true;
15237               })) {
15238         Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
15239             << getOpenMPClauseName(OMPC_private)
15240             << getOpenMPClauseName(ConflictKind)
15241             << getOpenMPDirectiveName(CurrDir);
15242         reportOriginalDsa(*this, DSAStack, D, DVar);
15243         continue;
15244       }
15245     }
15246 
15247     // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
15248     //  A variable of class type (or array thereof) that appears in a private
15249     //  clause requires an accessible, unambiguous default constructor for the
15250     //  class type.
15251     // Generate helper private variable and initialize it with the default
15252     // value. The address of the original variable is replaced by the address of
15253     // the new private variable in CodeGen. This new variable is not added to
15254     // IdResolver, so the code in the OpenMP region uses original variable for
15255     // proper diagnostics.
15256     Type = Type.getUnqualifiedType();
15257     VarDecl *VDPrivate =
15258         buildVarDecl(*this, ELoc, Type, D->getName(),
15259                      D->hasAttrs() ? &D->getAttrs() : nullptr,
15260                      VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
15261     ActOnUninitializedDecl(VDPrivate);
15262     if (VDPrivate->isInvalidDecl())
15263       continue;
15264     DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
15265         *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
15266 
15267     DeclRefExpr *Ref = nullptr;
15268     if (!VD && !CurContext->isDependentContext())
15269       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
15270     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_private, Ref);
15271     Vars.push_back((VD || CurContext->isDependentContext())
15272                        ? RefExpr->IgnoreParens()
15273                        : Ref);
15274     PrivateCopies.push_back(VDPrivateRefExpr);
15275   }
15276 
15277   if (Vars.empty())
15278     return nullptr;
15279 
15280   return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
15281                                   PrivateCopies);
15282 }
15283 
15284 namespace {
15285 class DiagsUninitializedSeveretyRAII {
15286 private:
15287   DiagnosticsEngine &Diags;
15288   SourceLocation SavedLoc;
15289   bool IsIgnored = false;
15290 
15291 public:
15292   DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc,
15293                                  bool IsIgnored)
15294       : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) {
15295     if (!IsIgnored) {
15296       Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init,
15297                         /*Map*/ diag::Severity::Ignored, Loc);
15298     }
15299   }
15300   ~DiagsUninitializedSeveretyRAII() {
15301     if (!IsIgnored)
15302       Diags.popMappings(SavedLoc);
15303   }
15304 };
15305 }
15306 
15307 OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
15308                                                SourceLocation StartLoc,
15309                                                SourceLocation LParenLoc,
15310                                                SourceLocation EndLoc) {
15311   SmallVector<Expr *, 8> Vars;
15312   SmallVector<Expr *, 8> PrivateCopies;
15313   SmallVector<Expr *, 8> Inits;
15314   SmallVector<Decl *, 4> ExprCaptures;
15315   bool IsImplicitClause =
15316       StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid();
15317   SourceLocation ImplicitClauseLoc = DSAStack->getConstructLoc();
15318 
15319   for (Expr *RefExpr : VarList) {
15320     assert(RefExpr && "NULL expr in OpenMP firstprivate clause.");
15321     SourceLocation ELoc;
15322     SourceRange ERange;
15323     Expr *SimpleRefExpr = RefExpr;
15324     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
15325     if (Res.second) {
15326       // It will be analyzed later.
15327       Vars.push_back(RefExpr);
15328       PrivateCopies.push_back(nullptr);
15329       Inits.push_back(nullptr);
15330     }
15331     ValueDecl *D = Res.first;
15332     if (!D)
15333       continue;
15334 
15335     ELoc = IsImplicitClause ? ImplicitClauseLoc : ELoc;
15336     QualType Type = D->getType();
15337     auto *VD = dyn_cast<VarDecl>(D);
15338 
15339     // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
15340     //  A variable that appears in a private clause must not have an incomplete
15341     //  type or a reference type.
15342     if (RequireCompleteType(ELoc, Type,
15343                             diag::err_omp_firstprivate_incomplete_type))
15344       continue;
15345     Type = Type.getNonReferenceType();
15346 
15347     // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
15348     //  A variable of class type (or array thereof) that appears in a private
15349     //  clause requires an accessible, unambiguous copy constructor for the
15350     //  class type.
15351     QualType ElemType = Context.getBaseElementType(Type).getNonReferenceType();
15352 
15353     // If an implicit firstprivate variable found it was checked already.
15354     DSAStackTy::DSAVarData TopDVar;
15355     if (!IsImplicitClause) {
15356       DSAStackTy::DSAVarData DVar =
15357           DSAStack->getTopDSA(D, /*FromParent=*/false);
15358       TopDVar = DVar;
15359       OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
15360       bool IsConstant = ElemType.isConstant(Context);
15361       // OpenMP [2.4.13, Data-sharing Attribute Clauses]
15362       //  A list item that specifies a given variable may not appear in more
15363       // than one clause on the same directive, except that a variable may be
15364       //  specified in both firstprivate and lastprivate clauses.
15365       // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
15366       // A list item may appear in a firstprivate or lastprivate clause but not
15367       // both.
15368       if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
15369           (isOpenMPDistributeDirective(CurrDir) ||
15370            DVar.CKind != OMPC_lastprivate) &&
15371           DVar.RefExpr) {
15372         Diag(ELoc, diag::err_omp_wrong_dsa)
15373             << getOpenMPClauseName(DVar.CKind)
15374             << getOpenMPClauseName(OMPC_firstprivate);
15375         reportOriginalDsa(*this, DSAStack, D, DVar);
15376         continue;
15377       }
15378 
15379       // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
15380       // in a Construct]
15381       //  Variables with the predetermined data-sharing attributes may not be
15382       //  listed in data-sharing attributes clauses, except for the cases
15383       //  listed below. For these exceptions only, listing a predetermined
15384       //  variable in a data-sharing attribute clause is allowed and overrides
15385       //  the variable's predetermined data-sharing attributes.
15386       // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
15387       // in a Construct, C/C++, p.2]
15388       //  Variables with const-qualified type having no mutable member may be
15389       //  listed in a firstprivate clause, even if they are static data members.
15390       if (!(IsConstant || (VD && VD->isStaticDataMember())) && !DVar.RefExpr &&
15391           DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
15392         Diag(ELoc, diag::err_omp_wrong_dsa)
15393             << getOpenMPClauseName(DVar.CKind)
15394             << getOpenMPClauseName(OMPC_firstprivate);
15395         reportOriginalDsa(*this, DSAStack, D, DVar);
15396         continue;
15397       }
15398 
15399       // OpenMP [2.9.3.4, Restrictions, p.2]
15400       //  A list item that is private within a parallel region must not appear
15401       //  in a firstprivate clause on a worksharing construct if any of the
15402       //  worksharing regions arising from the worksharing construct ever bind
15403       //  to any of the parallel regions arising from the parallel construct.
15404       // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
15405       // A list item that is private within a teams region must not appear in a
15406       // firstprivate clause on a distribute construct if any of the distribute
15407       // regions arising from the distribute construct ever bind to any of the
15408       // teams regions arising from the teams construct.
15409       // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
15410       // A list item that appears in a reduction clause of a teams construct
15411       // must not appear in a firstprivate clause on a distribute construct if
15412       // any of the distribute regions arising from the distribute construct
15413       // ever bind to any of the teams regions arising from the teams construct.
15414       if ((isOpenMPWorksharingDirective(CurrDir) ||
15415            isOpenMPDistributeDirective(CurrDir)) &&
15416           !isOpenMPParallelDirective(CurrDir) &&
15417           !isOpenMPTeamsDirective(CurrDir)) {
15418         DVar = DSAStack->getImplicitDSA(D, true);
15419         if (DVar.CKind != OMPC_shared &&
15420             (isOpenMPParallelDirective(DVar.DKind) ||
15421              isOpenMPTeamsDirective(DVar.DKind) ||
15422              DVar.DKind == OMPD_unknown)) {
15423           Diag(ELoc, diag::err_omp_required_access)
15424               << getOpenMPClauseName(OMPC_firstprivate)
15425               << getOpenMPClauseName(OMPC_shared);
15426           reportOriginalDsa(*this, DSAStack, D, DVar);
15427           continue;
15428         }
15429       }
15430       // OpenMP [2.9.3.4, Restrictions, p.3]
15431       //  A list item that appears in a reduction clause of a parallel construct
15432       //  must not appear in a firstprivate clause on a worksharing or task
15433       //  construct if any of the worksharing or task regions arising from the
15434       //  worksharing or task construct ever bind to any of the parallel regions
15435       //  arising from the parallel construct.
15436       // OpenMP [2.9.3.4, Restrictions, p.4]
15437       //  A list item that appears in a reduction clause in worksharing
15438       //  construct must not appear in a firstprivate clause in a task construct
15439       //  encountered during execution of any of the worksharing regions arising
15440       //  from the worksharing construct.
15441       if (isOpenMPTaskingDirective(CurrDir)) {
15442         DVar = DSAStack->hasInnermostDSA(
15443             D,
15444             [](OpenMPClauseKind C, bool AppliedToPointee) {
15445               return C == OMPC_reduction && !AppliedToPointee;
15446             },
15447             [](OpenMPDirectiveKind K) {
15448               return isOpenMPParallelDirective(K) ||
15449                      isOpenMPWorksharingDirective(K) ||
15450                      isOpenMPTeamsDirective(K);
15451             },
15452             /*FromParent=*/true);
15453         if (DVar.CKind == OMPC_reduction &&
15454             (isOpenMPParallelDirective(DVar.DKind) ||
15455              isOpenMPWorksharingDirective(DVar.DKind) ||
15456              isOpenMPTeamsDirective(DVar.DKind))) {
15457           Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate)
15458               << getOpenMPDirectiveName(DVar.DKind);
15459           reportOriginalDsa(*this, DSAStack, D, DVar);
15460           continue;
15461         }
15462       }
15463 
15464       // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
15465       // A list item cannot appear in both a map clause and a data-sharing
15466       // attribute clause on the same construct
15467       //
15468       // OpenMP 5.0 [2.19.7.1, Restrictions, p.7]
15469       // A list item cannot appear in both a map clause and a data-sharing
15470       // attribute clause on the same construct unless the construct is a
15471       // combined construct.
15472       if ((LangOpts.OpenMP <= 45 &&
15473            isOpenMPTargetExecutionDirective(CurrDir)) ||
15474           CurrDir == OMPD_target) {
15475         OpenMPClauseKind ConflictKind;
15476         if (DSAStack->checkMappableExprComponentListsForDecl(
15477                 VD, /*CurrentRegionOnly=*/true,
15478                 [&ConflictKind](
15479                     OMPClauseMappableExprCommon::MappableExprComponentListRef,
15480                     OpenMPClauseKind WhereFoundClauseKind) {
15481                   ConflictKind = WhereFoundClauseKind;
15482                   return true;
15483                 })) {
15484           Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
15485               << getOpenMPClauseName(OMPC_firstprivate)
15486               << getOpenMPClauseName(ConflictKind)
15487               << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
15488           reportOriginalDsa(*this, DSAStack, D, DVar);
15489           continue;
15490         }
15491       }
15492     }
15493 
15494     // Variably modified types are not supported for tasks.
15495     if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
15496         isOpenMPTaskingDirective(DSAStack->getCurrentDirective())) {
15497       Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
15498           << getOpenMPClauseName(OMPC_firstprivate) << Type
15499           << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
15500       bool IsDecl =
15501           !VD ||
15502           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
15503       Diag(D->getLocation(),
15504            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
15505           << D;
15506       continue;
15507     }
15508 
15509     Type = Type.getUnqualifiedType();
15510     VarDecl *VDPrivate =
15511         buildVarDecl(*this, ELoc, Type, D->getName(),
15512                      D->hasAttrs() ? &D->getAttrs() : nullptr,
15513                      VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
15514     // Generate helper private variable and initialize it with the value of the
15515     // original variable. The address of the original variable is replaced by
15516     // the address of the new private variable in the CodeGen. This new variable
15517     // is not added to IdResolver, so the code in the OpenMP region uses
15518     // original variable for proper diagnostics and variable capturing.
15519     Expr *VDInitRefExpr = nullptr;
15520     // For arrays generate initializer for single element and replace it by the
15521     // original array element in CodeGen.
15522     if (Type->isArrayType()) {
15523       VarDecl *VDInit =
15524           buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, D->getName());
15525       VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc);
15526       Expr *Init = DefaultLvalueConversion(VDInitRefExpr).get();
15527       ElemType = ElemType.getUnqualifiedType();
15528       VarDecl *VDInitTemp = buildVarDecl(*this, RefExpr->getExprLoc(), ElemType,
15529                                          ".firstprivate.temp");
15530       InitializedEntity Entity =
15531           InitializedEntity::InitializeVariable(VDInitTemp);
15532       InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc);
15533 
15534       InitializationSequence InitSeq(*this, Entity, Kind, Init);
15535       ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init);
15536       if (Result.isInvalid())
15537         VDPrivate->setInvalidDecl();
15538       else
15539         VDPrivate->setInit(Result.getAs<Expr>());
15540       // Remove temp variable declaration.
15541       Context.Deallocate(VDInitTemp);
15542     } else {
15543       VarDecl *VDInit = buildVarDecl(*this, RefExpr->getExprLoc(), Type,
15544                                      ".firstprivate.temp");
15545       VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
15546                                        RefExpr->getExprLoc());
15547       AddInitializerToDecl(VDPrivate,
15548                            DefaultLvalueConversion(VDInitRefExpr).get(),
15549                            /*DirectInit=*/false);
15550     }
15551     if (VDPrivate->isInvalidDecl()) {
15552       if (IsImplicitClause) {
15553         Diag(RefExpr->getExprLoc(),
15554              diag::note_omp_task_predetermined_firstprivate_here);
15555       }
15556       continue;
15557     }
15558     CurContext->addDecl(VDPrivate);
15559     DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
15560         *this, VDPrivate, RefExpr->getType().getUnqualifiedType(),
15561         RefExpr->getExprLoc());
15562     DeclRefExpr *Ref = nullptr;
15563     if (!VD && !CurContext->isDependentContext()) {
15564       if (TopDVar.CKind == OMPC_lastprivate) {
15565         Ref = TopDVar.PrivateCopy;
15566       } else {
15567         Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
15568         if (!isOpenMPCapturedDecl(D))
15569           ExprCaptures.push_back(Ref->getDecl());
15570       }
15571     }
15572     if (!IsImplicitClause)
15573       DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
15574     Vars.push_back((VD || CurContext->isDependentContext())
15575                        ? RefExpr->IgnoreParens()
15576                        : Ref);
15577     PrivateCopies.push_back(VDPrivateRefExpr);
15578     Inits.push_back(VDInitRefExpr);
15579   }
15580 
15581   if (Vars.empty())
15582     return nullptr;
15583 
15584   return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
15585                                        Vars, PrivateCopies, Inits,
15586                                        buildPreInits(Context, ExprCaptures));
15587 }
15588 
15589 OMPClause *Sema::ActOnOpenMPLastprivateClause(
15590     ArrayRef<Expr *> VarList, OpenMPLastprivateModifier LPKind,
15591     SourceLocation LPKindLoc, SourceLocation ColonLoc, SourceLocation StartLoc,
15592     SourceLocation LParenLoc, SourceLocation EndLoc) {
15593   if (LPKind == OMPC_LASTPRIVATE_unknown && LPKindLoc.isValid()) {
15594     assert(ColonLoc.isValid() && "Colon location must be valid.");
15595     Diag(LPKindLoc, diag::err_omp_unexpected_clause_value)
15596         << getListOfPossibleValues(OMPC_lastprivate, /*First=*/0,
15597                                    /*Last=*/OMPC_LASTPRIVATE_unknown)
15598         << getOpenMPClauseName(OMPC_lastprivate);
15599     return nullptr;
15600   }
15601 
15602   SmallVector<Expr *, 8> Vars;
15603   SmallVector<Expr *, 8> SrcExprs;
15604   SmallVector<Expr *, 8> DstExprs;
15605   SmallVector<Expr *, 8> AssignmentOps;
15606   SmallVector<Decl *, 4> ExprCaptures;
15607   SmallVector<Expr *, 4> ExprPostUpdates;
15608   for (Expr *RefExpr : VarList) {
15609     assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
15610     SourceLocation ELoc;
15611     SourceRange ERange;
15612     Expr *SimpleRefExpr = RefExpr;
15613     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
15614     if (Res.second) {
15615       // It will be analyzed later.
15616       Vars.push_back(RefExpr);
15617       SrcExprs.push_back(nullptr);
15618       DstExprs.push_back(nullptr);
15619       AssignmentOps.push_back(nullptr);
15620     }
15621     ValueDecl *D = Res.first;
15622     if (!D)
15623       continue;
15624 
15625     QualType Type = D->getType();
15626     auto *VD = dyn_cast<VarDecl>(D);
15627 
15628     // OpenMP [2.14.3.5, Restrictions, C/C++, p.2]
15629     //  A variable that appears in a lastprivate clause must not have an
15630     //  incomplete type or a reference type.
15631     if (RequireCompleteType(ELoc, Type,
15632                             diag::err_omp_lastprivate_incomplete_type))
15633       continue;
15634     Type = Type.getNonReferenceType();
15635 
15636     // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
15637     // A variable that is privatized must not have a const-qualified type
15638     // unless it is of class type with a mutable member. This restriction does
15639     // not apply to the firstprivate clause.
15640     //
15641     // OpenMP 3.1 [2.9.3.5, lastprivate clause, Restrictions]
15642     // A variable that appears in a lastprivate clause must not have a
15643     // const-qualified type unless it is of class type with a mutable member.
15644     if (rejectConstNotMutableType(*this, D, Type, OMPC_lastprivate, ELoc))
15645       continue;
15646 
15647     // OpenMP 5.0 [2.19.4.5 lastprivate Clause, Restrictions]
15648     // A list item that appears in a lastprivate clause with the conditional
15649     // modifier must be a scalar variable.
15650     if (LPKind == OMPC_LASTPRIVATE_conditional && !Type->isScalarType()) {
15651       Diag(ELoc, diag::err_omp_lastprivate_conditional_non_scalar);
15652       bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
15653                                VarDecl::DeclarationOnly;
15654       Diag(D->getLocation(),
15655            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
15656           << D;
15657       continue;
15658     }
15659 
15660     OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
15661     // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
15662     // in a Construct]
15663     //  Variables with the predetermined data-sharing attributes may not be
15664     //  listed in data-sharing attributes clauses, except for the cases
15665     //  listed below.
15666     // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
15667     // A list item may appear in a firstprivate or lastprivate clause but not
15668     // both.
15669     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
15670     if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate &&
15671         (isOpenMPDistributeDirective(CurrDir) ||
15672          DVar.CKind != OMPC_firstprivate) &&
15673         (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
15674       Diag(ELoc, diag::err_omp_wrong_dsa)
15675           << getOpenMPClauseName(DVar.CKind)
15676           << getOpenMPClauseName(OMPC_lastprivate);
15677       reportOriginalDsa(*this, DSAStack, D, DVar);
15678       continue;
15679     }
15680 
15681     // OpenMP [2.14.3.5, Restrictions, p.2]
15682     // A list item that is private within a parallel region, or that appears in
15683     // the reduction clause of a parallel construct, must not appear in a
15684     // lastprivate clause on a worksharing construct if any of the corresponding
15685     // worksharing regions ever binds to any of the corresponding parallel
15686     // regions.
15687     DSAStackTy::DSAVarData TopDVar = DVar;
15688     if (isOpenMPWorksharingDirective(CurrDir) &&
15689         !isOpenMPParallelDirective(CurrDir) &&
15690         !isOpenMPTeamsDirective(CurrDir)) {
15691       DVar = DSAStack->getImplicitDSA(D, true);
15692       if (DVar.CKind != OMPC_shared) {
15693         Diag(ELoc, diag::err_omp_required_access)
15694             << getOpenMPClauseName(OMPC_lastprivate)
15695             << getOpenMPClauseName(OMPC_shared);
15696         reportOriginalDsa(*this, DSAStack, D, DVar);
15697         continue;
15698       }
15699     }
15700 
15701     // OpenMP [2.14.3.5, Restrictions, C++, p.1,2]
15702     //  A variable of class type (or array thereof) that appears in a
15703     //  lastprivate clause requires an accessible, unambiguous default
15704     //  constructor for the class type, unless the list item is also specified
15705     //  in a firstprivate clause.
15706     //  A variable of class type (or array thereof) that appears in a
15707     //  lastprivate clause requires an accessible, unambiguous copy assignment
15708     //  operator for the class type.
15709     Type = Context.getBaseElementType(Type).getNonReferenceType();
15710     VarDecl *SrcVD = buildVarDecl(*this, ERange.getBegin(),
15711                                   Type.getUnqualifiedType(), ".lastprivate.src",
15712                                   D->hasAttrs() ? &D->getAttrs() : nullptr);
15713     DeclRefExpr *PseudoSrcExpr =
15714         buildDeclRefExpr(*this, SrcVD, Type.getUnqualifiedType(), ELoc);
15715     VarDecl *DstVD =
15716         buildVarDecl(*this, ERange.getBegin(), Type, ".lastprivate.dst",
15717                      D->hasAttrs() ? &D->getAttrs() : nullptr);
15718     DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
15719     // For arrays generate assignment operation for single element and replace
15720     // it by the original array element in CodeGen.
15721     ExprResult AssignmentOp = BuildBinOp(/*S=*/nullptr, ELoc, BO_Assign,
15722                                          PseudoDstExpr, PseudoSrcExpr);
15723     if (AssignmentOp.isInvalid())
15724       continue;
15725     AssignmentOp =
15726         ActOnFinishFullExpr(AssignmentOp.get(), ELoc, /*DiscardedValue*/ false);
15727     if (AssignmentOp.isInvalid())
15728       continue;
15729 
15730     DeclRefExpr *Ref = nullptr;
15731     if (!VD && !CurContext->isDependentContext()) {
15732       if (TopDVar.CKind == OMPC_firstprivate) {
15733         Ref = TopDVar.PrivateCopy;
15734       } else {
15735         Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
15736         if (!isOpenMPCapturedDecl(D))
15737           ExprCaptures.push_back(Ref->getDecl());
15738       }
15739       if ((TopDVar.CKind == OMPC_firstprivate && !TopDVar.PrivateCopy) ||
15740           (!isOpenMPCapturedDecl(D) &&
15741            Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>())) {
15742         ExprResult RefRes = DefaultLvalueConversion(Ref);
15743         if (!RefRes.isUsable())
15744           continue;
15745         ExprResult PostUpdateRes =
15746             BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
15747                        RefRes.get());
15748         if (!PostUpdateRes.isUsable())
15749           continue;
15750         ExprPostUpdates.push_back(
15751             IgnoredValueConversions(PostUpdateRes.get()).get());
15752       }
15753     }
15754     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_lastprivate, Ref);
15755     Vars.push_back((VD || CurContext->isDependentContext())
15756                        ? RefExpr->IgnoreParens()
15757                        : Ref);
15758     SrcExprs.push_back(PseudoSrcExpr);
15759     DstExprs.push_back(PseudoDstExpr);
15760     AssignmentOps.push_back(AssignmentOp.get());
15761   }
15762 
15763   if (Vars.empty())
15764     return nullptr;
15765 
15766   return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
15767                                       Vars, SrcExprs, DstExprs, AssignmentOps,
15768                                       LPKind, LPKindLoc, ColonLoc,
15769                                       buildPreInits(Context, ExprCaptures),
15770                                       buildPostUpdate(*this, ExprPostUpdates));
15771 }
15772 
15773 OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
15774                                          SourceLocation StartLoc,
15775                                          SourceLocation LParenLoc,
15776                                          SourceLocation EndLoc) {
15777   SmallVector<Expr *, 8> Vars;
15778   for (Expr *RefExpr : VarList) {
15779     assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
15780     SourceLocation ELoc;
15781     SourceRange ERange;
15782     Expr *SimpleRefExpr = RefExpr;
15783     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
15784     if (Res.second) {
15785       // It will be analyzed later.
15786       Vars.push_back(RefExpr);
15787     }
15788     ValueDecl *D = Res.first;
15789     if (!D)
15790       continue;
15791 
15792     auto *VD = dyn_cast<VarDecl>(D);
15793     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
15794     // in a Construct]
15795     //  Variables with the predetermined data-sharing attributes may not be
15796     //  listed in data-sharing attributes clauses, except for the cases
15797     //  listed below. For these exceptions only, listing a predetermined
15798     //  variable in a data-sharing attribute clause is allowed and overrides
15799     //  the variable's predetermined data-sharing attributes.
15800     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
15801     if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared &&
15802         DVar.RefExpr) {
15803       Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
15804                                           << getOpenMPClauseName(OMPC_shared);
15805       reportOriginalDsa(*this, DSAStack, D, DVar);
15806       continue;
15807     }
15808 
15809     DeclRefExpr *Ref = nullptr;
15810     if (!VD && isOpenMPCapturedDecl(D) && !CurContext->isDependentContext())
15811       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
15812     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_shared, Ref);
15813     Vars.push_back((VD || !Ref || CurContext->isDependentContext())
15814                        ? RefExpr->IgnoreParens()
15815                        : Ref);
15816   }
15817 
15818   if (Vars.empty())
15819     return nullptr;
15820 
15821   return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
15822 }
15823 
15824 namespace {
15825 class DSARefChecker : public StmtVisitor<DSARefChecker, bool> {
15826   DSAStackTy *Stack;
15827 
15828 public:
15829   bool VisitDeclRefExpr(DeclRefExpr *E) {
15830     if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
15831       DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, /*FromParent=*/false);
15832       if (DVar.CKind == OMPC_shared && !DVar.RefExpr)
15833         return false;
15834       if (DVar.CKind != OMPC_unknown)
15835         return true;
15836       DSAStackTy::DSAVarData DVarPrivate = Stack->hasDSA(
15837           VD,
15838           [](OpenMPClauseKind C, bool AppliedToPointee) {
15839             return isOpenMPPrivate(C) && !AppliedToPointee;
15840           },
15841           [](OpenMPDirectiveKind) { return true; },
15842           /*FromParent=*/true);
15843       return DVarPrivate.CKind != OMPC_unknown;
15844     }
15845     return false;
15846   }
15847   bool VisitStmt(Stmt *S) {
15848     for (Stmt *Child : S->children()) {
15849       if (Child && Visit(Child))
15850         return true;
15851     }
15852     return false;
15853   }
15854   explicit DSARefChecker(DSAStackTy *S) : Stack(S) {}
15855 };
15856 } // namespace
15857 
15858 namespace {
15859 // Transform MemberExpression for specified FieldDecl of current class to
15860 // DeclRefExpr to specified OMPCapturedExprDecl.
15861 class TransformExprToCaptures : public TreeTransform<TransformExprToCaptures> {
15862   typedef TreeTransform<TransformExprToCaptures> BaseTransform;
15863   ValueDecl *Field = nullptr;
15864   DeclRefExpr *CapturedExpr = nullptr;
15865 
15866 public:
15867   TransformExprToCaptures(Sema &SemaRef, ValueDecl *FieldDecl)
15868       : BaseTransform(SemaRef), Field(FieldDecl), CapturedExpr(nullptr) {}
15869 
15870   ExprResult TransformMemberExpr(MemberExpr *E) {
15871     if (isa<CXXThisExpr>(E->getBase()->IgnoreParenImpCasts()) &&
15872         E->getMemberDecl() == Field) {
15873       CapturedExpr = buildCapture(SemaRef, Field, E, /*WithInit=*/false);
15874       return CapturedExpr;
15875     }
15876     return BaseTransform::TransformMemberExpr(E);
15877   }
15878   DeclRefExpr *getCapturedExpr() { return CapturedExpr; }
15879 };
15880 } // namespace
15881 
15882 template <typename T, typename U>
15883 static T filterLookupForUDReductionAndMapper(
15884     SmallVectorImpl<U> &Lookups, const llvm::function_ref<T(ValueDecl *)> Gen) {
15885   for (U &Set : Lookups) {
15886     for (auto *D : Set) {
15887       if (T Res = Gen(cast<ValueDecl>(D)))
15888         return Res;
15889     }
15890   }
15891   return T();
15892 }
15893 
15894 static NamedDecl *findAcceptableDecl(Sema &SemaRef, NamedDecl *D) {
15895   assert(!LookupResult::isVisible(SemaRef, D) && "not in slow case");
15896 
15897   for (auto RD : D->redecls()) {
15898     // Don't bother with extra checks if we already know this one isn't visible.
15899     if (RD == D)
15900       continue;
15901 
15902     auto ND = cast<NamedDecl>(RD);
15903     if (LookupResult::isVisible(SemaRef, ND))
15904       return ND;
15905   }
15906 
15907   return nullptr;
15908 }
15909 
15910 static void
15911 argumentDependentLookup(Sema &SemaRef, const DeclarationNameInfo &Id,
15912                         SourceLocation Loc, QualType Ty,
15913                         SmallVectorImpl<UnresolvedSet<8>> &Lookups) {
15914   // Find all of the associated namespaces and classes based on the
15915   // arguments we have.
15916   Sema::AssociatedNamespaceSet AssociatedNamespaces;
15917   Sema::AssociatedClassSet AssociatedClasses;
15918   OpaqueValueExpr OVE(Loc, Ty, VK_LValue);
15919   SemaRef.FindAssociatedClassesAndNamespaces(Loc, &OVE, AssociatedNamespaces,
15920                                              AssociatedClasses);
15921 
15922   // C++ [basic.lookup.argdep]p3:
15923   //   Let X be the lookup set produced by unqualified lookup (3.4.1)
15924   //   and let Y be the lookup set produced by argument dependent
15925   //   lookup (defined as follows). If X contains [...] then Y is
15926   //   empty. Otherwise Y is the set of declarations found in the
15927   //   namespaces associated with the argument types as described
15928   //   below. The set of declarations found by the lookup of the name
15929   //   is the union of X and Y.
15930   //
15931   // Here, we compute Y and add its members to the overloaded
15932   // candidate set.
15933   for (auto *NS : AssociatedNamespaces) {
15934     //   When considering an associated namespace, the lookup is the
15935     //   same as the lookup performed when the associated namespace is
15936     //   used as a qualifier (3.4.3.2) except that:
15937     //
15938     //     -- Any using-directives in the associated namespace are
15939     //        ignored.
15940     //
15941     //     -- Any namespace-scope friend functions declared in
15942     //        associated classes are visible within their respective
15943     //        namespaces even if they are not visible during an ordinary
15944     //        lookup (11.4).
15945     DeclContext::lookup_result R = NS->lookup(Id.getName());
15946     for (auto *D : R) {
15947       auto *Underlying = D;
15948       if (auto *USD = dyn_cast<UsingShadowDecl>(D))
15949         Underlying = USD->getTargetDecl();
15950 
15951       if (!isa<OMPDeclareReductionDecl>(Underlying) &&
15952           !isa<OMPDeclareMapperDecl>(Underlying))
15953         continue;
15954 
15955       if (!SemaRef.isVisible(D)) {
15956         D = findAcceptableDecl(SemaRef, D);
15957         if (!D)
15958           continue;
15959         if (auto *USD = dyn_cast<UsingShadowDecl>(D))
15960           Underlying = USD->getTargetDecl();
15961       }
15962       Lookups.emplace_back();
15963       Lookups.back().addDecl(Underlying);
15964     }
15965   }
15966 }
15967 
15968 static ExprResult
15969 buildDeclareReductionRef(Sema &SemaRef, SourceLocation Loc, SourceRange Range,
15970                          Scope *S, CXXScopeSpec &ReductionIdScopeSpec,
15971                          const DeclarationNameInfo &ReductionId, QualType Ty,
15972                          CXXCastPath &BasePath, Expr *UnresolvedReduction) {
15973   if (ReductionIdScopeSpec.isInvalid())
15974     return ExprError();
15975   SmallVector<UnresolvedSet<8>, 4> Lookups;
15976   if (S) {
15977     LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
15978     Lookup.suppressDiagnostics();
15979     while (S && SemaRef.LookupParsedName(Lookup, S, &ReductionIdScopeSpec)) {
15980       NamedDecl *D = Lookup.getRepresentativeDecl();
15981       do {
15982         S = S->getParent();
15983       } while (S && !S->isDeclScope(D));
15984       if (S)
15985         S = S->getParent();
15986       Lookups.emplace_back();
15987       Lookups.back().append(Lookup.begin(), Lookup.end());
15988       Lookup.clear();
15989     }
15990   } else if (auto *ULE =
15991                  cast_or_null<UnresolvedLookupExpr>(UnresolvedReduction)) {
15992     Lookups.push_back(UnresolvedSet<8>());
15993     Decl *PrevD = nullptr;
15994     for (NamedDecl *D : ULE->decls()) {
15995       if (D == PrevD)
15996         Lookups.push_back(UnresolvedSet<8>());
15997       else if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(D))
15998         Lookups.back().addDecl(DRD);
15999       PrevD = D;
16000     }
16001   }
16002   if (SemaRef.CurContext->isDependentContext() || Ty->isDependentType() ||
16003       Ty->isInstantiationDependentType() ||
16004       Ty->containsUnexpandedParameterPack() ||
16005       filterLookupForUDReductionAndMapper<bool>(Lookups, [](ValueDecl *D) {
16006         return !D->isInvalidDecl() &&
16007                (D->getType()->isDependentType() ||
16008                 D->getType()->isInstantiationDependentType() ||
16009                 D->getType()->containsUnexpandedParameterPack());
16010       })) {
16011     UnresolvedSet<8> ResSet;
16012     for (const UnresolvedSet<8> &Set : Lookups) {
16013       if (Set.empty())
16014         continue;
16015       ResSet.append(Set.begin(), Set.end());
16016       // The last item marks the end of all declarations at the specified scope.
16017       ResSet.addDecl(Set[Set.size() - 1]);
16018     }
16019     return UnresolvedLookupExpr::Create(
16020         SemaRef.Context, /*NamingClass=*/nullptr,
16021         ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), ReductionId,
16022         /*ADL=*/true, /*Overloaded=*/true, ResSet.begin(), ResSet.end());
16023   }
16024   // Lookup inside the classes.
16025   // C++ [over.match.oper]p3:
16026   //   For a unary operator @ with an operand of a type whose
16027   //   cv-unqualified version is T1, and for a binary operator @ with
16028   //   a left operand of a type whose cv-unqualified version is T1 and
16029   //   a right operand of a type whose cv-unqualified version is T2,
16030   //   three sets of candidate functions, designated member
16031   //   candidates, non-member candidates and built-in candidates, are
16032   //   constructed as follows:
16033   //     -- If T1 is a complete class type or a class currently being
16034   //        defined, the set of member candidates is the result of the
16035   //        qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
16036   //        the set of member candidates is empty.
16037   LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
16038   Lookup.suppressDiagnostics();
16039   if (const auto *TyRec = Ty->getAs<RecordType>()) {
16040     // Complete the type if it can be completed.
16041     // If the type is neither complete nor being defined, bail out now.
16042     if (SemaRef.isCompleteType(Loc, Ty) || TyRec->isBeingDefined() ||
16043         TyRec->getDecl()->getDefinition()) {
16044       Lookup.clear();
16045       SemaRef.LookupQualifiedName(Lookup, TyRec->getDecl());
16046       if (Lookup.empty()) {
16047         Lookups.emplace_back();
16048         Lookups.back().append(Lookup.begin(), Lookup.end());
16049       }
16050     }
16051   }
16052   // Perform ADL.
16053   if (SemaRef.getLangOpts().CPlusPlus)
16054     argumentDependentLookup(SemaRef, ReductionId, Loc, Ty, Lookups);
16055   if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
16056           Lookups, [&SemaRef, Ty](ValueDecl *D) -> ValueDecl * {
16057             if (!D->isInvalidDecl() &&
16058                 SemaRef.Context.hasSameType(D->getType(), Ty))
16059               return D;
16060             return nullptr;
16061           }))
16062     return SemaRef.BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(),
16063                                     VK_LValue, Loc);
16064   if (SemaRef.getLangOpts().CPlusPlus) {
16065     if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
16066             Lookups, [&SemaRef, Ty, Loc](ValueDecl *D) -> ValueDecl * {
16067               if (!D->isInvalidDecl() &&
16068                   SemaRef.IsDerivedFrom(Loc, Ty, D->getType()) &&
16069                   !Ty.isMoreQualifiedThan(D->getType()))
16070                 return D;
16071               return nullptr;
16072             })) {
16073       CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
16074                          /*DetectVirtual=*/false);
16075       if (SemaRef.IsDerivedFrom(Loc, Ty, VD->getType(), Paths)) {
16076         if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
16077                 VD->getType().getUnqualifiedType()))) {
16078           if (SemaRef.CheckBaseClassAccess(
16079                   Loc, VD->getType(), Ty, Paths.front(),
16080                   /*DiagID=*/0) != Sema::AR_inaccessible) {
16081             SemaRef.BuildBasePathArray(Paths, BasePath);
16082             return SemaRef.BuildDeclRefExpr(
16083                 VD, VD->getType().getNonReferenceType(), VK_LValue, Loc);
16084           }
16085         }
16086       }
16087     }
16088   }
16089   if (ReductionIdScopeSpec.isSet()) {
16090     SemaRef.Diag(Loc, diag::err_omp_not_resolved_reduction_identifier)
16091         << Ty << Range;
16092     return ExprError();
16093   }
16094   return ExprEmpty();
16095 }
16096 
16097 namespace {
16098 /// Data for the reduction-based clauses.
16099 struct ReductionData {
16100   /// List of original reduction items.
16101   SmallVector<Expr *, 8> Vars;
16102   /// List of private copies of the reduction items.
16103   SmallVector<Expr *, 8> Privates;
16104   /// LHS expressions for the reduction_op expressions.
16105   SmallVector<Expr *, 8> LHSs;
16106   /// RHS expressions for the reduction_op expressions.
16107   SmallVector<Expr *, 8> RHSs;
16108   /// Reduction operation expression.
16109   SmallVector<Expr *, 8> ReductionOps;
16110   /// inscan copy operation expressions.
16111   SmallVector<Expr *, 8> InscanCopyOps;
16112   /// inscan copy temp array expressions for prefix sums.
16113   SmallVector<Expr *, 8> InscanCopyArrayTemps;
16114   /// inscan copy temp array element expressions for prefix sums.
16115   SmallVector<Expr *, 8> InscanCopyArrayElems;
16116   /// Taskgroup descriptors for the corresponding reduction items in
16117   /// in_reduction clauses.
16118   SmallVector<Expr *, 8> TaskgroupDescriptors;
16119   /// List of captures for clause.
16120   SmallVector<Decl *, 4> ExprCaptures;
16121   /// List of postupdate expressions.
16122   SmallVector<Expr *, 4> ExprPostUpdates;
16123   /// Reduction modifier.
16124   unsigned RedModifier = 0;
16125   ReductionData() = delete;
16126   /// Reserves required memory for the reduction data.
16127   ReductionData(unsigned Size, unsigned Modifier = 0) : RedModifier(Modifier) {
16128     Vars.reserve(Size);
16129     Privates.reserve(Size);
16130     LHSs.reserve(Size);
16131     RHSs.reserve(Size);
16132     ReductionOps.reserve(Size);
16133     if (RedModifier == OMPC_REDUCTION_inscan) {
16134       InscanCopyOps.reserve(Size);
16135       InscanCopyArrayTemps.reserve(Size);
16136       InscanCopyArrayElems.reserve(Size);
16137     }
16138     TaskgroupDescriptors.reserve(Size);
16139     ExprCaptures.reserve(Size);
16140     ExprPostUpdates.reserve(Size);
16141   }
16142   /// Stores reduction item and reduction operation only (required for dependent
16143   /// reduction item).
16144   void push(Expr *Item, Expr *ReductionOp) {
16145     Vars.emplace_back(Item);
16146     Privates.emplace_back(nullptr);
16147     LHSs.emplace_back(nullptr);
16148     RHSs.emplace_back(nullptr);
16149     ReductionOps.emplace_back(ReductionOp);
16150     TaskgroupDescriptors.emplace_back(nullptr);
16151     if (RedModifier == OMPC_REDUCTION_inscan) {
16152       InscanCopyOps.push_back(nullptr);
16153       InscanCopyArrayTemps.push_back(nullptr);
16154       InscanCopyArrayElems.push_back(nullptr);
16155     }
16156   }
16157   /// Stores reduction data.
16158   void push(Expr *Item, Expr *Private, Expr *LHS, Expr *RHS, Expr *ReductionOp,
16159             Expr *TaskgroupDescriptor, Expr *CopyOp, Expr *CopyArrayTemp,
16160             Expr *CopyArrayElem) {
16161     Vars.emplace_back(Item);
16162     Privates.emplace_back(Private);
16163     LHSs.emplace_back(LHS);
16164     RHSs.emplace_back(RHS);
16165     ReductionOps.emplace_back(ReductionOp);
16166     TaskgroupDescriptors.emplace_back(TaskgroupDescriptor);
16167     if (RedModifier == OMPC_REDUCTION_inscan) {
16168       InscanCopyOps.push_back(CopyOp);
16169       InscanCopyArrayTemps.push_back(CopyArrayTemp);
16170       InscanCopyArrayElems.push_back(CopyArrayElem);
16171     } else {
16172       assert(CopyOp == nullptr && CopyArrayTemp == nullptr &&
16173              CopyArrayElem == nullptr &&
16174              "Copy operation must be used for inscan reductions only.");
16175     }
16176   }
16177 };
16178 } // namespace
16179 
16180 static bool checkOMPArraySectionConstantForReduction(
16181     ASTContext &Context, const OMPArraySectionExpr *OASE, bool &SingleElement,
16182     SmallVectorImpl<llvm::APSInt> &ArraySizes) {
16183   const Expr *Length = OASE->getLength();
16184   if (Length == nullptr) {
16185     // For array sections of the form [1:] or [:], we would need to analyze
16186     // the lower bound...
16187     if (OASE->getColonLocFirst().isValid())
16188       return false;
16189 
16190     // This is an array subscript which has implicit length 1!
16191     SingleElement = true;
16192     ArraySizes.push_back(llvm::APSInt::get(1));
16193   } else {
16194     Expr::EvalResult Result;
16195     if (!Length->EvaluateAsInt(Result, Context))
16196       return false;
16197 
16198     llvm::APSInt ConstantLengthValue = Result.Val.getInt();
16199     SingleElement = (ConstantLengthValue.getSExtValue() == 1);
16200     ArraySizes.push_back(ConstantLengthValue);
16201   }
16202 
16203   // Get the base of this array section and walk up from there.
16204   const Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
16205 
16206   // We require length = 1 for all array sections except the right-most to
16207   // guarantee that the memory region is contiguous and has no holes in it.
16208   while (const auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base)) {
16209     Length = TempOASE->getLength();
16210     if (Length == nullptr) {
16211       // For array sections of the form [1:] or [:], we would need to analyze
16212       // the lower bound...
16213       if (OASE->getColonLocFirst().isValid())
16214         return false;
16215 
16216       // This is an array subscript which has implicit length 1!
16217       ArraySizes.push_back(llvm::APSInt::get(1));
16218     } else {
16219       Expr::EvalResult Result;
16220       if (!Length->EvaluateAsInt(Result, Context))
16221         return false;
16222 
16223       llvm::APSInt ConstantLengthValue = Result.Val.getInt();
16224       if (ConstantLengthValue.getSExtValue() != 1)
16225         return false;
16226 
16227       ArraySizes.push_back(ConstantLengthValue);
16228     }
16229     Base = TempOASE->getBase()->IgnoreParenImpCasts();
16230   }
16231 
16232   // If we have a single element, we don't need to add the implicit lengths.
16233   if (!SingleElement) {
16234     while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) {
16235       // Has implicit length 1!
16236       ArraySizes.push_back(llvm::APSInt::get(1));
16237       Base = TempASE->getBase()->IgnoreParenImpCasts();
16238     }
16239   }
16240 
16241   // This array section can be privatized as a single value or as a constant
16242   // sized array.
16243   return true;
16244 }
16245 
16246 static bool actOnOMPReductionKindClause(
16247     Sema &S, DSAStackTy *Stack, OpenMPClauseKind ClauseKind,
16248     ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
16249     SourceLocation ColonLoc, SourceLocation EndLoc,
16250     CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
16251     ArrayRef<Expr *> UnresolvedReductions, ReductionData &RD) {
16252   DeclarationName DN = ReductionId.getName();
16253   OverloadedOperatorKind OOK = DN.getCXXOverloadedOperator();
16254   BinaryOperatorKind BOK = BO_Comma;
16255 
16256   ASTContext &Context = S.Context;
16257   // OpenMP [2.14.3.6, reduction clause]
16258   // C
16259   // reduction-identifier is either an identifier or one of the following
16260   // operators: +, -, *,  &, |, ^, && and ||
16261   // C++
16262   // reduction-identifier is either an id-expression or one of the following
16263   // operators: +, -, *, &, |, ^, && and ||
16264   switch (OOK) {
16265   case OO_Plus:
16266   case OO_Minus:
16267     BOK = BO_Add;
16268     break;
16269   case OO_Star:
16270     BOK = BO_Mul;
16271     break;
16272   case OO_Amp:
16273     BOK = BO_And;
16274     break;
16275   case OO_Pipe:
16276     BOK = BO_Or;
16277     break;
16278   case OO_Caret:
16279     BOK = BO_Xor;
16280     break;
16281   case OO_AmpAmp:
16282     BOK = BO_LAnd;
16283     break;
16284   case OO_PipePipe:
16285     BOK = BO_LOr;
16286     break;
16287   case OO_New:
16288   case OO_Delete:
16289   case OO_Array_New:
16290   case OO_Array_Delete:
16291   case OO_Slash:
16292   case OO_Percent:
16293   case OO_Tilde:
16294   case OO_Exclaim:
16295   case OO_Equal:
16296   case OO_Less:
16297   case OO_Greater:
16298   case OO_LessEqual:
16299   case OO_GreaterEqual:
16300   case OO_PlusEqual:
16301   case OO_MinusEqual:
16302   case OO_StarEqual:
16303   case OO_SlashEqual:
16304   case OO_PercentEqual:
16305   case OO_CaretEqual:
16306   case OO_AmpEqual:
16307   case OO_PipeEqual:
16308   case OO_LessLess:
16309   case OO_GreaterGreater:
16310   case OO_LessLessEqual:
16311   case OO_GreaterGreaterEqual:
16312   case OO_EqualEqual:
16313   case OO_ExclaimEqual:
16314   case OO_Spaceship:
16315   case OO_PlusPlus:
16316   case OO_MinusMinus:
16317   case OO_Comma:
16318   case OO_ArrowStar:
16319   case OO_Arrow:
16320   case OO_Call:
16321   case OO_Subscript:
16322   case OO_Conditional:
16323   case OO_Coawait:
16324   case NUM_OVERLOADED_OPERATORS:
16325     llvm_unreachable("Unexpected reduction identifier");
16326   case OO_None:
16327     if (IdentifierInfo *II = DN.getAsIdentifierInfo()) {
16328       if (II->isStr("max"))
16329         BOK = BO_GT;
16330       else if (II->isStr("min"))
16331         BOK = BO_LT;
16332     }
16333     break;
16334   }
16335   SourceRange ReductionIdRange;
16336   if (ReductionIdScopeSpec.isValid())
16337     ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc());
16338   else
16339     ReductionIdRange.setBegin(ReductionId.getBeginLoc());
16340   ReductionIdRange.setEnd(ReductionId.getEndLoc());
16341 
16342   auto IR = UnresolvedReductions.begin(), ER = UnresolvedReductions.end();
16343   bool FirstIter = true;
16344   for (Expr *RefExpr : VarList) {
16345     assert(RefExpr && "nullptr expr in OpenMP reduction clause.");
16346     // OpenMP [2.1, C/C++]
16347     //  A list item is a variable or array section, subject to the restrictions
16348     //  specified in Section 2.4 on page 42 and in each of the sections
16349     // describing clauses and directives for which a list appears.
16350     // OpenMP  [2.14.3.3, Restrictions, p.1]
16351     //  A variable that is part of another variable (as an array or
16352     //  structure element) cannot appear in a private clause.
16353     if (!FirstIter && IR != ER)
16354       ++IR;
16355     FirstIter = false;
16356     SourceLocation ELoc;
16357     SourceRange ERange;
16358     Expr *SimpleRefExpr = RefExpr;
16359     auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange,
16360                               /*AllowArraySection=*/true);
16361     if (Res.second) {
16362       // Try to find 'declare reduction' corresponding construct before using
16363       // builtin/overloaded operators.
16364       QualType Type = Context.DependentTy;
16365       CXXCastPath BasePath;
16366       ExprResult DeclareReductionRef = buildDeclareReductionRef(
16367           S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
16368           ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
16369       Expr *ReductionOp = nullptr;
16370       if (S.CurContext->isDependentContext() &&
16371           (DeclareReductionRef.isUnset() ||
16372            isa<UnresolvedLookupExpr>(DeclareReductionRef.get())))
16373         ReductionOp = DeclareReductionRef.get();
16374       // It will be analyzed later.
16375       RD.push(RefExpr, ReductionOp);
16376     }
16377     ValueDecl *D = Res.first;
16378     if (!D)
16379       continue;
16380 
16381     Expr *TaskgroupDescriptor = nullptr;
16382     QualType Type;
16383     auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr->IgnoreParens());
16384     auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr->IgnoreParens());
16385     if (ASE) {
16386       Type = ASE->getType().getNonReferenceType();
16387     } else if (OASE) {
16388       QualType BaseType =
16389           OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
16390       if (const auto *ATy = BaseType->getAsArrayTypeUnsafe())
16391         Type = ATy->getElementType();
16392       else
16393         Type = BaseType->getPointeeType();
16394       Type = Type.getNonReferenceType();
16395     } else {
16396       Type = Context.getBaseElementType(D->getType().getNonReferenceType());
16397     }
16398     auto *VD = dyn_cast<VarDecl>(D);
16399 
16400     // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
16401     //  A variable that appears in a private clause must not have an incomplete
16402     //  type or a reference type.
16403     if (S.RequireCompleteType(ELoc, D->getType(),
16404                               diag::err_omp_reduction_incomplete_type))
16405       continue;
16406     // OpenMP [2.14.3.6, reduction clause, Restrictions]
16407     // A list item that appears in a reduction clause must not be
16408     // const-qualified.
16409     if (rejectConstNotMutableType(S, D, Type, ClauseKind, ELoc,
16410                                   /*AcceptIfMutable*/ false, ASE || OASE))
16411       continue;
16412 
16413     OpenMPDirectiveKind CurrDir = Stack->getCurrentDirective();
16414     // OpenMP [2.9.3.6, Restrictions, C/C++, p.4]
16415     //  If a list-item is a reference type then it must bind to the same object
16416     //  for all threads of the team.
16417     if (!ASE && !OASE) {
16418       if (VD) {
16419         VarDecl *VDDef = VD->getDefinition();
16420         if (VD->getType()->isReferenceType() && VDDef && VDDef->hasInit()) {
16421           DSARefChecker Check(Stack);
16422           if (Check.Visit(VDDef->getInit())) {
16423             S.Diag(ELoc, diag::err_omp_reduction_ref_type_arg)
16424                 << getOpenMPClauseName(ClauseKind) << ERange;
16425             S.Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef;
16426             continue;
16427           }
16428         }
16429       }
16430 
16431       // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
16432       // in a Construct]
16433       //  Variables with the predetermined data-sharing attributes may not be
16434       //  listed in data-sharing attributes clauses, except for the cases
16435       //  listed below. For these exceptions only, listing a predetermined
16436       //  variable in a data-sharing attribute clause is allowed and overrides
16437       //  the variable's predetermined data-sharing attributes.
16438       // OpenMP [2.14.3.6, Restrictions, p.3]
16439       //  Any number of reduction clauses can be specified on the directive,
16440       //  but a list item can appear only once in the reduction clauses for that
16441       //  directive.
16442       DSAStackTy::DSAVarData DVar = Stack->getTopDSA(D, /*FromParent=*/false);
16443       if (DVar.CKind == OMPC_reduction) {
16444         S.Diag(ELoc, diag::err_omp_once_referenced)
16445             << getOpenMPClauseName(ClauseKind);
16446         if (DVar.RefExpr)
16447           S.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced);
16448         continue;
16449       }
16450       if (DVar.CKind != OMPC_unknown) {
16451         S.Diag(ELoc, diag::err_omp_wrong_dsa)
16452             << getOpenMPClauseName(DVar.CKind)
16453             << getOpenMPClauseName(OMPC_reduction);
16454         reportOriginalDsa(S, Stack, D, DVar);
16455         continue;
16456       }
16457 
16458       // OpenMP [2.14.3.6, Restrictions, p.1]
16459       //  A list item that appears in a reduction clause of a worksharing
16460       //  construct must be shared in the parallel regions to which any of the
16461       //  worksharing regions arising from the worksharing construct bind.
16462       if (isOpenMPWorksharingDirective(CurrDir) &&
16463           !isOpenMPParallelDirective(CurrDir) &&
16464           !isOpenMPTeamsDirective(CurrDir)) {
16465         DVar = Stack->getImplicitDSA(D, true);
16466         if (DVar.CKind != OMPC_shared) {
16467           S.Diag(ELoc, diag::err_omp_required_access)
16468               << getOpenMPClauseName(OMPC_reduction)
16469               << getOpenMPClauseName(OMPC_shared);
16470           reportOriginalDsa(S, Stack, D, DVar);
16471           continue;
16472         }
16473       }
16474     } else {
16475       // Threadprivates cannot be shared between threads, so dignose if the base
16476       // is a threadprivate variable.
16477       DSAStackTy::DSAVarData DVar = Stack->getTopDSA(D, /*FromParent=*/false);
16478       if (DVar.CKind == OMPC_threadprivate) {
16479         S.Diag(ELoc, diag::err_omp_wrong_dsa)
16480             << getOpenMPClauseName(DVar.CKind)
16481             << getOpenMPClauseName(OMPC_reduction);
16482         reportOriginalDsa(S, Stack, D, DVar);
16483         continue;
16484       }
16485     }
16486 
16487     // Try to find 'declare reduction' corresponding construct before using
16488     // builtin/overloaded operators.
16489     CXXCastPath BasePath;
16490     ExprResult DeclareReductionRef = buildDeclareReductionRef(
16491         S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
16492         ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
16493     if (DeclareReductionRef.isInvalid())
16494       continue;
16495     if (S.CurContext->isDependentContext() &&
16496         (DeclareReductionRef.isUnset() ||
16497          isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) {
16498       RD.push(RefExpr, DeclareReductionRef.get());
16499       continue;
16500     }
16501     if (BOK == BO_Comma && DeclareReductionRef.isUnset()) {
16502       // Not allowed reduction identifier is found.
16503       S.Diag(ReductionId.getBeginLoc(),
16504              diag::err_omp_unknown_reduction_identifier)
16505           << Type << ReductionIdRange;
16506       continue;
16507     }
16508 
16509     // OpenMP [2.14.3.6, reduction clause, Restrictions]
16510     // The type of a list item that appears in a reduction clause must be valid
16511     // for the reduction-identifier. For a max or min reduction in C, the type
16512     // of the list item must be an allowed arithmetic data type: char, int,
16513     // float, double, or _Bool, possibly modified with long, short, signed, or
16514     // unsigned. For a max or min reduction in C++, the type of the list item
16515     // must be an allowed arithmetic data type: char, wchar_t, int, float,
16516     // double, or bool, possibly modified with long, short, signed, or unsigned.
16517     if (DeclareReductionRef.isUnset()) {
16518       if ((BOK == BO_GT || BOK == BO_LT) &&
16519           !(Type->isScalarType() ||
16520             (S.getLangOpts().CPlusPlus && Type->isArithmeticType()))) {
16521         S.Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg)
16522             << getOpenMPClauseName(ClauseKind) << S.getLangOpts().CPlusPlus;
16523         if (!ASE && !OASE) {
16524           bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
16525                                    VarDecl::DeclarationOnly;
16526           S.Diag(D->getLocation(),
16527                  IsDecl ? diag::note_previous_decl : diag::note_defined_here)
16528               << D;
16529         }
16530         continue;
16531       }
16532       if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) &&
16533           !S.getLangOpts().CPlusPlus && Type->isFloatingType()) {
16534         S.Diag(ELoc, diag::err_omp_clause_floating_type_arg)
16535             << getOpenMPClauseName(ClauseKind);
16536         if (!ASE && !OASE) {
16537           bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
16538                                    VarDecl::DeclarationOnly;
16539           S.Diag(D->getLocation(),
16540                  IsDecl ? diag::note_previous_decl : diag::note_defined_here)
16541               << D;
16542         }
16543         continue;
16544       }
16545     }
16546 
16547     Type = Type.getNonLValueExprType(Context).getUnqualifiedType();
16548     VarDecl *LHSVD = buildVarDecl(S, ELoc, Type, ".reduction.lhs",
16549                                   D->hasAttrs() ? &D->getAttrs() : nullptr);
16550     VarDecl *RHSVD = buildVarDecl(S, ELoc, Type, D->getName(),
16551                                   D->hasAttrs() ? &D->getAttrs() : nullptr);
16552     QualType PrivateTy = Type;
16553 
16554     // Try if we can determine constant lengths for all array sections and avoid
16555     // the VLA.
16556     bool ConstantLengthOASE = false;
16557     if (OASE) {
16558       bool SingleElement;
16559       llvm::SmallVector<llvm::APSInt, 4> ArraySizes;
16560       ConstantLengthOASE = checkOMPArraySectionConstantForReduction(
16561           Context, OASE, SingleElement, ArraySizes);
16562 
16563       // If we don't have a single element, we must emit a constant array type.
16564       if (ConstantLengthOASE && !SingleElement) {
16565         for (llvm::APSInt &Size : ArraySizes)
16566           PrivateTy = Context.getConstantArrayType(PrivateTy, Size, nullptr,
16567                                                    ArrayType::Normal,
16568                                                    /*IndexTypeQuals=*/0);
16569       }
16570     }
16571 
16572     if ((OASE && !ConstantLengthOASE) ||
16573         (!OASE && !ASE &&
16574          D->getType().getNonReferenceType()->isVariablyModifiedType())) {
16575       if (!Context.getTargetInfo().isVLASupported()) {
16576         if (isOpenMPTargetExecutionDirective(Stack->getCurrentDirective())) {
16577           S.Diag(ELoc, diag::err_omp_reduction_vla_unsupported) << !!OASE;
16578           S.Diag(ELoc, diag::note_vla_unsupported);
16579           continue;
16580         } else {
16581           S.targetDiag(ELoc, diag::err_omp_reduction_vla_unsupported) << !!OASE;
16582           S.targetDiag(ELoc, diag::note_vla_unsupported);
16583         }
16584       }
16585       // For arrays/array sections only:
16586       // Create pseudo array type for private copy. The size for this array will
16587       // be generated during codegen.
16588       // For array subscripts or single variables Private Ty is the same as Type
16589       // (type of the variable or single array element).
16590       PrivateTy = Context.getVariableArrayType(
16591           Type,
16592           new (Context) OpaqueValueExpr(ELoc, Context.getSizeType(), VK_RValue),
16593           ArrayType::Normal, /*IndexTypeQuals=*/0, SourceRange());
16594     } else if (!ASE && !OASE &&
16595                Context.getAsArrayType(D->getType().getNonReferenceType())) {
16596       PrivateTy = D->getType().getNonReferenceType();
16597     }
16598     // Private copy.
16599     VarDecl *PrivateVD =
16600         buildVarDecl(S, ELoc, PrivateTy, D->getName(),
16601                      D->hasAttrs() ? &D->getAttrs() : nullptr,
16602                      VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
16603     // Add initializer for private variable.
16604     Expr *Init = nullptr;
16605     DeclRefExpr *LHSDRE = buildDeclRefExpr(S, LHSVD, Type, ELoc);
16606     DeclRefExpr *RHSDRE = buildDeclRefExpr(S, RHSVD, Type, ELoc);
16607     if (DeclareReductionRef.isUsable()) {
16608       auto *DRDRef = DeclareReductionRef.getAs<DeclRefExpr>();
16609       auto *DRD = cast<OMPDeclareReductionDecl>(DRDRef->getDecl());
16610       if (DRD->getInitializer()) {
16611         S.ActOnUninitializedDecl(PrivateVD);
16612         Init = DRDRef;
16613         RHSVD->setInit(DRDRef);
16614         RHSVD->setInitStyle(VarDecl::CallInit);
16615       }
16616     } else {
16617       switch (BOK) {
16618       case BO_Add:
16619       case BO_Xor:
16620       case BO_Or:
16621       case BO_LOr:
16622         // '+', '-', '^', '|', '||' reduction ops - initializer is '0'.
16623         if (Type->isScalarType() || Type->isAnyComplexType())
16624           Init = S.ActOnIntegerConstant(ELoc, /*Val=*/0).get();
16625         break;
16626       case BO_Mul:
16627       case BO_LAnd:
16628         if (Type->isScalarType() || Type->isAnyComplexType()) {
16629           // '*' and '&&' reduction ops - initializer is '1'.
16630           Init = S.ActOnIntegerConstant(ELoc, /*Val=*/1).get();
16631         }
16632         break;
16633       case BO_And: {
16634         // '&' reduction op - initializer is '~0'.
16635         QualType OrigType = Type;
16636         if (auto *ComplexTy = OrigType->getAs<ComplexType>())
16637           Type = ComplexTy->getElementType();
16638         if (Type->isRealFloatingType()) {
16639           llvm::APFloat InitValue = llvm::APFloat::getAllOnesValue(
16640               Context.getFloatTypeSemantics(Type),
16641               Context.getTypeSize(Type));
16642           Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
16643                                          Type, ELoc);
16644         } else if (Type->isScalarType()) {
16645           uint64_t Size = Context.getTypeSize(Type);
16646           QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0);
16647           llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size);
16648           Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
16649         }
16650         if (Init && OrigType->isAnyComplexType()) {
16651           // Init = 0xFFFF + 0xFFFFi;
16652           auto *Im = new (Context) ImaginaryLiteral(Init, OrigType);
16653           Init = S.CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get();
16654         }
16655         Type = OrigType;
16656         break;
16657       }
16658       case BO_LT:
16659       case BO_GT: {
16660         // 'min' reduction op - initializer is 'Largest representable number in
16661         // the reduction list item type'.
16662         // 'max' reduction op - initializer is 'Least representable number in
16663         // the reduction list item type'.
16664         if (Type->isIntegerType() || Type->isPointerType()) {
16665           bool IsSigned = Type->hasSignedIntegerRepresentation();
16666           uint64_t Size = Context.getTypeSize(Type);
16667           QualType IntTy =
16668               Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned);
16669           llvm::APInt InitValue =
16670               (BOK != BO_LT) ? IsSigned ? llvm::APInt::getSignedMinValue(Size)
16671                                         : llvm::APInt::getMinValue(Size)
16672                              : IsSigned ? llvm::APInt::getSignedMaxValue(Size)
16673                                         : llvm::APInt::getMaxValue(Size);
16674           Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
16675           if (Type->isPointerType()) {
16676             // Cast to pointer type.
16677             ExprResult CastExpr = S.BuildCStyleCastExpr(
16678                 ELoc, Context.getTrivialTypeSourceInfo(Type, ELoc), ELoc, Init);
16679             if (CastExpr.isInvalid())
16680               continue;
16681             Init = CastExpr.get();
16682           }
16683         } else if (Type->isRealFloatingType()) {
16684           llvm::APFloat InitValue = llvm::APFloat::getLargest(
16685               Context.getFloatTypeSemantics(Type), BOK != BO_LT);
16686           Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
16687                                          Type, ELoc);
16688         }
16689         break;
16690       }
16691       case BO_PtrMemD:
16692       case BO_PtrMemI:
16693       case BO_MulAssign:
16694       case BO_Div:
16695       case BO_Rem:
16696       case BO_Sub:
16697       case BO_Shl:
16698       case BO_Shr:
16699       case BO_LE:
16700       case BO_GE:
16701       case BO_EQ:
16702       case BO_NE:
16703       case BO_Cmp:
16704       case BO_AndAssign:
16705       case BO_XorAssign:
16706       case BO_OrAssign:
16707       case BO_Assign:
16708       case BO_AddAssign:
16709       case BO_SubAssign:
16710       case BO_DivAssign:
16711       case BO_RemAssign:
16712       case BO_ShlAssign:
16713       case BO_ShrAssign:
16714       case BO_Comma:
16715         llvm_unreachable("Unexpected reduction operation");
16716       }
16717     }
16718     if (Init && DeclareReductionRef.isUnset()) {
16719       S.AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false);
16720       // Store initializer for single element in private copy. Will be used
16721       // during codegen.
16722       PrivateVD->setInit(RHSVD->getInit());
16723       PrivateVD->setInitStyle(RHSVD->getInitStyle());
16724     } else if (!Init) {
16725       S.ActOnUninitializedDecl(RHSVD);
16726       // Store initializer for single element in private copy. Will be used
16727       // during codegen.
16728       PrivateVD->setInit(RHSVD->getInit());
16729       PrivateVD->setInitStyle(RHSVD->getInitStyle());
16730     }
16731     if (RHSVD->isInvalidDecl())
16732       continue;
16733     if (!RHSVD->hasInit() && DeclareReductionRef.isUnset()) {
16734       S.Diag(ELoc, diag::err_omp_reduction_id_not_compatible)
16735           << Type << ReductionIdRange;
16736       bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
16737                                VarDecl::DeclarationOnly;
16738       S.Diag(D->getLocation(),
16739              IsDecl ? diag::note_previous_decl : diag::note_defined_here)
16740           << D;
16741       continue;
16742     }
16743     DeclRefExpr *PrivateDRE = buildDeclRefExpr(S, PrivateVD, PrivateTy, ELoc);
16744     ExprResult ReductionOp;
16745     if (DeclareReductionRef.isUsable()) {
16746       QualType RedTy = DeclareReductionRef.get()->getType();
16747       QualType PtrRedTy = Context.getPointerType(RedTy);
16748       ExprResult LHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, LHSDRE);
16749       ExprResult RHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RHSDRE);
16750       if (!BasePath.empty()) {
16751         LHS = S.DefaultLvalueConversion(LHS.get());
16752         RHS = S.DefaultLvalueConversion(RHS.get());
16753         LHS = ImplicitCastExpr::Create(
16754             Context, PtrRedTy, CK_UncheckedDerivedToBase, LHS.get(), &BasePath,
16755             LHS.get()->getValueKind(), FPOptionsOverride());
16756         RHS = ImplicitCastExpr::Create(
16757             Context, PtrRedTy, CK_UncheckedDerivedToBase, RHS.get(), &BasePath,
16758             RHS.get()->getValueKind(), FPOptionsOverride());
16759       }
16760       FunctionProtoType::ExtProtoInfo EPI;
16761       QualType Params[] = {PtrRedTy, PtrRedTy};
16762       QualType FnTy = Context.getFunctionType(Context.VoidTy, Params, EPI);
16763       auto *OVE = new (Context) OpaqueValueExpr(
16764           ELoc, Context.getPointerType(FnTy), VK_RValue, OK_Ordinary,
16765           S.DefaultLvalueConversion(DeclareReductionRef.get()).get());
16766       Expr *Args[] = {LHS.get(), RHS.get()};
16767       ReductionOp =
16768           CallExpr::Create(Context, OVE, Args, Context.VoidTy, VK_RValue, ELoc,
16769                            S.CurFPFeatureOverrides());
16770     } else {
16771       ReductionOp = S.BuildBinOp(
16772           Stack->getCurScope(), ReductionId.getBeginLoc(), BOK, LHSDRE, RHSDRE);
16773       if (ReductionOp.isUsable()) {
16774         if (BOK != BO_LT && BOK != BO_GT) {
16775           ReductionOp =
16776               S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(),
16777                            BO_Assign, LHSDRE, ReductionOp.get());
16778         } else {
16779           auto *ConditionalOp = new (Context)
16780               ConditionalOperator(ReductionOp.get(), ELoc, LHSDRE, ELoc, RHSDRE,
16781                                   Type, VK_LValue, OK_Ordinary);
16782           ReductionOp =
16783               S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(),
16784                            BO_Assign, LHSDRE, ConditionalOp);
16785         }
16786         if (ReductionOp.isUsable())
16787           ReductionOp = S.ActOnFinishFullExpr(ReductionOp.get(),
16788                                               /*DiscardedValue*/ false);
16789       }
16790       if (!ReductionOp.isUsable())
16791         continue;
16792     }
16793 
16794     // Add copy operations for inscan reductions.
16795     // LHS = RHS;
16796     ExprResult CopyOpRes, TempArrayRes, TempArrayElem;
16797     if (ClauseKind == OMPC_reduction &&
16798         RD.RedModifier == OMPC_REDUCTION_inscan) {
16799       ExprResult RHS = S.DefaultLvalueConversion(RHSDRE);
16800       CopyOpRes = S.BuildBinOp(Stack->getCurScope(), ELoc, BO_Assign, LHSDRE,
16801                                RHS.get());
16802       if (!CopyOpRes.isUsable())
16803         continue;
16804       CopyOpRes =
16805           S.ActOnFinishFullExpr(CopyOpRes.get(), /*DiscardedValue=*/true);
16806       if (!CopyOpRes.isUsable())
16807         continue;
16808       // For simd directive and simd-based directives in simd mode no need to
16809       // construct temp array, need just a single temp element.
16810       if (Stack->getCurrentDirective() == OMPD_simd ||
16811           (S.getLangOpts().OpenMPSimd &&
16812            isOpenMPSimdDirective(Stack->getCurrentDirective()))) {
16813         VarDecl *TempArrayVD =
16814             buildVarDecl(S, ELoc, PrivateTy, D->getName(),
16815                          D->hasAttrs() ? &D->getAttrs() : nullptr);
16816         // Add a constructor to the temp decl.
16817         S.ActOnUninitializedDecl(TempArrayVD);
16818         TempArrayRes = buildDeclRefExpr(S, TempArrayVD, PrivateTy, ELoc);
16819       } else {
16820         // Build temp array for prefix sum.
16821         auto *Dim = new (S.Context)
16822             OpaqueValueExpr(ELoc, S.Context.getSizeType(), VK_RValue);
16823         QualType ArrayTy =
16824             S.Context.getVariableArrayType(PrivateTy, Dim, ArrayType::Normal,
16825                                            /*IndexTypeQuals=*/0, {ELoc, ELoc});
16826         VarDecl *TempArrayVD =
16827             buildVarDecl(S, ELoc, ArrayTy, D->getName(),
16828                          D->hasAttrs() ? &D->getAttrs() : nullptr);
16829         // Add a constructor to the temp decl.
16830         S.ActOnUninitializedDecl(TempArrayVD);
16831         TempArrayRes = buildDeclRefExpr(S, TempArrayVD, ArrayTy, ELoc);
16832         TempArrayElem =
16833             S.DefaultFunctionArrayLvalueConversion(TempArrayRes.get());
16834         auto *Idx = new (S.Context)
16835             OpaqueValueExpr(ELoc, S.Context.getSizeType(), VK_RValue);
16836         TempArrayElem = S.CreateBuiltinArraySubscriptExpr(TempArrayElem.get(),
16837                                                           ELoc, Idx, ELoc);
16838       }
16839     }
16840 
16841     // OpenMP [2.15.4.6, Restrictions, p.2]
16842     // A list item that appears in an in_reduction clause of a task construct
16843     // must appear in a task_reduction clause of a construct associated with a
16844     // taskgroup region that includes the participating task in its taskgroup
16845     // set. The construct associated with the innermost region that meets this
16846     // condition must specify the same reduction-identifier as the in_reduction
16847     // clause.
16848     if (ClauseKind == OMPC_in_reduction) {
16849       SourceRange ParentSR;
16850       BinaryOperatorKind ParentBOK;
16851       const Expr *ParentReductionOp = nullptr;
16852       Expr *ParentBOKTD = nullptr, *ParentReductionOpTD = nullptr;
16853       DSAStackTy::DSAVarData ParentBOKDSA =
16854           Stack->getTopMostTaskgroupReductionData(D, ParentSR, ParentBOK,
16855                                                   ParentBOKTD);
16856       DSAStackTy::DSAVarData ParentReductionOpDSA =
16857           Stack->getTopMostTaskgroupReductionData(
16858               D, ParentSR, ParentReductionOp, ParentReductionOpTD);
16859       bool IsParentBOK = ParentBOKDSA.DKind != OMPD_unknown;
16860       bool IsParentReductionOp = ParentReductionOpDSA.DKind != OMPD_unknown;
16861       if ((DeclareReductionRef.isUnset() && IsParentReductionOp) ||
16862           (DeclareReductionRef.isUsable() && IsParentBOK) ||
16863           (IsParentBOK && BOK != ParentBOK) || IsParentReductionOp) {
16864         bool EmitError = true;
16865         if (IsParentReductionOp && DeclareReductionRef.isUsable()) {
16866           llvm::FoldingSetNodeID RedId, ParentRedId;
16867           ParentReductionOp->Profile(ParentRedId, Context, /*Canonical=*/true);
16868           DeclareReductionRef.get()->Profile(RedId, Context,
16869                                              /*Canonical=*/true);
16870           EmitError = RedId != ParentRedId;
16871         }
16872         if (EmitError) {
16873           S.Diag(ReductionId.getBeginLoc(),
16874                  diag::err_omp_reduction_identifier_mismatch)
16875               << ReductionIdRange << RefExpr->getSourceRange();
16876           S.Diag(ParentSR.getBegin(),
16877                  diag::note_omp_previous_reduction_identifier)
16878               << ParentSR
16879               << (IsParentBOK ? ParentBOKDSA.RefExpr
16880                               : ParentReductionOpDSA.RefExpr)
16881                      ->getSourceRange();
16882           continue;
16883         }
16884       }
16885       TaskgroupDescriptor = IsParentBOK ? ParentBOKTD : ParentReductionOpTD;
16886     }
16887 
16888     DeclRefExpr *Ref = nullptr;
16889     Expr *VarsExpr = RefExpr->IgnoreParens();
16890     if (!VD && !S.CurContext->isDependentContext()) {
16891       if (ASE || OASE) {
16892         TransformExprToCaptures RebuildToCapture(S, D);
16893         VarsExpr =
16894             RebuildToCapture.TransformExpr(RefExpr->IgnoreParens()).get();
16895         Ref = RebuildToCapture.getCapturedExpr();
16896       } else {
16897         VarsExpr = Ref = buildCapture(S, D, SimpleRefExpr, /*WithInit=*/false);
16898       }
16899       if (!S.isOpenMPCapturedDecl(D)) {
16900         RD.ExprCaptures.emplace_back(Ref->getDecl());
16901         if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
16902           ExprResult RefRes = S.DefaultLvalueConversion(Ref);
16903           if (!RefRes.isUsable())
16904             continue;
16905           ExprResult PostUpdateRes =
16906               S.BuildBinOp(Stack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
16907                            RefRes.get());
16908           if (!PostUpdateRes.isUsable())
16909             continue;
16910           if (isOpenMPTaskingDirective(Stack->getCurrentDirective()) ||
16911               Stack->getCurrentDirective() == OMPD_taskgroup) {
16912             S.Diag(RefExpr->getExprLoc(),
16913                    diag::err_omp_reduction_non_addressable_expression)
16914                 << RefExpr->getSourceRange();
16915             continue;
16916           }
16917           RD.ExprPostUpdates.emplace_back(
16918               S.IgnoredValueConversions(PostUpdateRes.get()).get());
16919         }
16920       }
16921     }
16922     // All reduction items are still marked as reduction (to do not increase
16923     // code base size).
16924     unsigned Modifier = RD.RedModifier;
16925     // Consider task_reductions as reductions with task modifier. Required for
16926     // correct analysis of in_reduction clauses.
16927     if (CurrDir == OMPD_taskgroup && ClauseKind == OMPC_task_reduction)
16928       Modifier = OMPC_REDUCTION_task;
16929     Stack->addDSA(D, RefExpr->IgnoreParens(), OMPC_reduction, Ref, Modifier,
16930                   ASE || OASE);
16931     if (Modifier == OMPC_REDUCTION_task &&
16932         (CurrDir == OMPD_taskgroup ||
16933          ((isOpenMPParallelDirective(CurrDir) ||
16934            isOpenMPWorksharingDirective(CurrDir)) &&
16935           !isOpenMPSimdDirective(CurrDir)))) {
16936       if (DeclareReductionRef.isUsable())
16937         Stack->addTaskgroupReductionData(D, ReductionIdRange,
16938                                          DeclareReductionRef.get());
16939       else
16940         Stack->addTaskgroupReductionData(D, ReductionIdRange, BOK);
16941     }
16942     RD.push(VarsExpr, PrivateDRE, LHSDRE, RHSDRE, ReductionOp.get(),
16943             TaskgroupDescriptor, CopyOpRes.get(), TempArrayRes.get(),
16944             TempArrayElem.get());
16945   }
16946   return RD.Vars.empty();
16947 }
16948 
16949 OMPClause *Sema::ActOnOpenMPReductionClause(
16950     ArrayRef<Expr *> VarList, OpenMPReductionClauseModifier Modifier,
16951     SourceLocation StartLoc, SourceLocation LParenLoc,
16952     SourceLocation ModifierLoc, SourceLocation ColonLoc, SourceLocation EndLoc,
16953     CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
16954     ArrayRef<Expr *> UnresolvedReductions) {
16955   if (ModifierLoc.isValid() && Modifier == OMPC_REDUCTION_unknown) {
16956     Diag(LParenLoc, diag::err_omp_unexpected_clause_value)
16957         << getListOfPossibleValues(OMPC_reduction, /*First=*/0,
16958                                    /*Last=*/OMPC_REDUCTION_unknown)
16959         << getOpenMPClauseName(OMPC_reduction);
16960     return nullptr;
16961   }
16962   // OpenMP 5.0, 2.19.5.4 reduction Clause, Restrictions
16963   // A reduction clause with the inscan reduction-modifier may only appear on a
16964   // worksharing-loop construct, a worksharing-loop SIMD construct, a simd
16965   // construct, a parallel worksharing-loop construct or a parallel
16966   // worksharing-loop SIMD construct.
16967   if (Modifier == OMPC_REDUCTION_inscan &&
16968       (DSAStack->getCurrentDirective() != OMPD_for &&
16969        DSAStack->getCurrentDirective() != OMPD_for_simd &&
16970        DSAStack->getCurrentDirective() != OMPD_simd &&
16971        DSAStack->getCurrentDirective() != OMPD_parallel_for &&
16972        DSAStack->getCurrentDirective() != OMPD_parallel_for_simd)) {
16973     Diag(ModifierLoc, diag::err_omp_wrong_inscan_reduction);
16974     return nullptr;
16975   }
16976 
16977   ReductionData RD(VarList.size(), Modifier);
16978   if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_reduction, VarList,
16979                                   StartLoc, LParenLoc, ColonLoc, EndLoc,
16980                                   ReductionIdScopeSpec, ReductionId,
16981                                   UnresolvedReductions, RD))
16982     return nullptr;
16983 
16984   return OMPReductionClause::Create(
16985       Context, StartLoc, LParenLoc, ModifierLoc, ColonLoc, EndLoc, Modifier,
16986       RD.Vars, ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
16987       RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, RD.InscanCopyOps,
16988       RD.InscanCopyArrayTemps, RD.InscanCopyArrayElems,
16989       buildPreInits(Context, RD.ExprCaptures),
16990       buildPostUpdate(*this, RD.ExprPostUpdates));
16991 }
16992 
16993 OMPClause *Sema::ActOnOpenMPTaskReductionClause(
16994     ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
16995     SourceLocation ColonLoc, SourceLocation EndLoc,
16996     CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
16997     ArrayRef<Expr *> UnresolvedReductions) {
16998   ReductionData RD(VarList.size());
16999   if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_task_reduction, VarList,
17000                                   StartLoc, LParenLoc, ColonLoc, EndLoc,
17001                                   ReductionIdScopeSpec, ReductionId,
17002                                   UnresolvedReductions, RD))
17003     return nullptr;
17004 
17005   return OMPTaskReductionClause::Create(
17006       Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
17007       ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
17008       RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
17009       buildPreInits(Context, RD.ExprCaptures),
17010       buildPostUpdate(*this, RD.ExprPostUpdates));
17011 }
17012 
17013 OMPClause *Sema::ActOnOpenMPInReductionClause(
17014     ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
17015     SourceLocation ColonLoc, SourceLocation EndLoc,
17016     CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
17017     ArrayRef<Expr *> UnresolvedReductions) {
17018   ReductionData RD(VarList.size());
17019   if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_in_reduction, VarList,
17020                                   StartLoc, LParenLoc, ColonLoc, EndLoc,
17021                                   ReductionIdScopeSpec, ReductionId,
17022                                   UnresolvedReductions, RD))
17023     return nullptr;
17024 
17025   return OMPInReductionClause::Create(
17026       Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
17027       ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
17028       RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, RD.TaskgroupDescriptors,
17029       buildPreInits(Context, RD.ExprCaptures),
17030       buildPostUpdate(*this, RD.ExprPostUpdates));
17031 }
17032 
17033 bool Sema::CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
17034                                      SourceLocation LinLoc) {
17035   if ((!LangOpts.CPlusPlus && LinKind != OMPC_LINEAR_val) ||
17036       LinKind == OMPC_LINEAR_unknown) {
17037     Diag(LinLoc, diag::err_omp_wrong_linear_modifier) << LangOpts.CPlusPlus;
17038     return true;
17039   }
17040   return false;
17041 }
17042 
17043 bool Sema::CheckOpenMPLinearDecl(const ValueDecl *D, SourceLocation ELoc,
17044                                  OpenMPLinearClauseKind LinKind, QualType Type,
17045                                  bool IsDeclareSimd) {
17046   const auto *VD = dyn_cast_or_null<VarDecl>(D);
17047   // A variable must not have an incomplete type or a reference type.
17048   if (RequireCompleteType(ELoc, Type, diag::err_omp_linear_incomplete_type))
17049     return true;
17050   if ((LinKind == OMPC_LINEAR_uval || LinKind == OMPC_LINEAR_ref) &&
17051       !Type->isReferenceType()) {
17052     Diag(ELoc, diag::err_omp_wrong_linear_modifier_non_reference)
17053         << Type << getOpenMPSimpleClauseTypeName(OMPC_linear, LinKind);
17054     return true;
17055   }
17056   Type = Type.getNonReferenceType();
17057 
17058   // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
17059   // A variable that is privatized must not have a const-qualified type
17060   // unless it is of class type with a mutable member. This restriction does
17061   // not apply to the firstprivate clause, nor to the linear clause on
17062   // declarative directives (like declare simd).
17063   if (!IsDeclareSimd &&
17064       rejectConstNotMutableType(*this, D, Type, OMPC_linear, ELoc))
17065     return true;
17066 
17067   // A list item must be of integral or pointer type.
17068   Type = Type.getUnqualifiedType().getCanonicalType();
17069   const auto *Ty = Type.getTypePtrOrNull();
17070   if (!Ty || (LinKind != OMPC_LINEAR_ref && !Ty->isDependentType() &&
17071               !Ty->isIntegralType(Context) && !Ty->isPointerType())) {
17072     Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << Type;
17073     if (D) {
17074       bool IsDecl =
17075           !VD ||
17076           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
17077       Diag(D->getLocation(),
17078            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
17079           << D;
17080     }
17081     return true;
17082   }
17083   return false;
17084 }
17085 
17086 OMPClause *Sema::ActOnOpenMPLinearClause(
17087     ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc,
17088     SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind,
17089     SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
17090   SmallVector<Expr *, 8> Vars;
17091   SmallVector<Expr *, 8> Privates;
17092   SmallVector<Expr *, 8> Inits;
17093   SmallVector<Decl *, 4> ExprCaptures;
17094   SmallVector<Expr *, 4> ExprPostUpdates;
17095   if (CheckOpenMPLinearModifier(LinKind, LinLoc))
17096     LinKind = OMPC_LINEAR_val;
17097   for (Expr *RefExpr : VarList) {
17098     assert(RefExpr && "NULL expr in OpenMP linear clause.");
17099     SourceLocation ELoc;
17100     SourceRange ERange;
17101     Expr *SimpleRefExpr = RefExpr;
17102     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
17103     if (Res.second) {
17104       // It will be analyzed later.
17105       Vars.push_back(RefExpr);
17106       Privates.push_back(nullptr);
17107       Inits.push_back(nullptr);
17108     }
17109     ValueDecl *D = Res.first;
17110     if (!D)
17111       continue;
17112 
17113     QualType Type = D->getType();
17114     auto *VD = dyn_cast<VarDecl>(D);
17115 
17116     // OpenMP [2.14.3.7, linear clause]
17117     //  A list-item cannot appear in more than one linear clause.
17118     //  A list-item that appears in a linear clause cannot appear in any
17119     //  other data-sharing attribute clause.
17120     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
17121     if (DVar.RefExpr) {
17122       Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
17123                                           << getOpenMPClauseName(OMPC_linear);
17124       reportOriginalDsa(*this, DSAStack, D, DVar);
17125       continue;
17126     }
17127 
17128     if (CheckOpenMPLinearDecl(D, ELoc, LinKind, Type))
17129       continue;
17130     Type = Type.getNonReferenceType().getUnqualifiedType().getCanonicalType();
17131 
17132     // Build private copy of original var.
17133     VarDecl *Private =
17134         buildVarDecl(*this, ELoc, Type, D->getName(),
17135                      D->hasAttrs() ? &D->getAttrs() : nullptr,
17136                      VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
17137     DeclRefExpr *PrivateRef = buildDeclRefExpr(*this, Private, Type, ELoc);
17138     // Build var to save initial value.
17139     VarDecl *Init = buildVarDecl(*this, ELoc, Type, ".linear.start");
17140     Expr *InitExpr;
17141     DeclRefExpr *Ref = nullptr;
17142     if (!VD && !CurContext->isDependentContext()) {
17143       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
17144       if (!isOpenMPCapturedDecl(D)) {
17145         ExprCaptures.push_back(Ref->getDecl());
17146         if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
17147           ExprResult RefRes = DefaultLvalueConversion(Ref);
17148           if (!RefRes.isUsable())
17149             continue;
17150           ExprResult PostUpdateRes =
17151               BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
17152                          SimpleRefExpr, RefRes.get());
17153           if (!PostUpdateRes.isUsable())
17154             continue;
17155           ExprPostUpdates.push_back(
17156               IgnoredValueConversions(PostUpdateRes.get()).get());
17157         }
17158       }
17159     }
17160     if (LinKind == OMPC_LINEAR_uval)
17161       InitExpr = VD ? VD->getInit() : SimpleRefExpr;
17162     else
17163       InitExpr = VD ? SimpleRefExpr : Ref;
17164     AddInitializerToDecl(Init, DefaultLvalueConversion(InitExpr).get(),
17165                          /*DirectInit=*/false);
17166     DeclRefExpr *InitRef = buildDeclRefExpr(*this, Init, Type, ELoc);
17167 
17168     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_linear, Ref);
17169     Vars.push_back((VD || CurContext->isDependentContext())
17170                        ? RefExpr->IgnoreParens()
17171                        : Ref);
17172     Privates.push_back(PrivateRef);
17173     Inits.push_back(InitRef);
17174   }
17175 
17176   if (Vars.empty())
17177     return nullptr;
17178 
17179   Expr *StepExpr = Step;
17180   Expr *CalcStepExpr = nullptr;
17181   if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
17182       !Step->isInstantiationDependent() &&
17183       !Step->containsUnexpandedParameterPack()) {
17184     SourceLocation StepLoc = Step->getBeginLoc();
17185     ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step);
17186     if (Val.isInvalid())
17187       return nullptr;
17188     StepExpr = Val.get();
17189 
17190     // Build var to save the step value.
17191     VarDecl *SaveVar =
17192         buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step");
17193     ExprResult SaveRef =
17194         buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc);
17195     ExprResult CalcStep =
17196         BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr);
17197     CalcStep = ActOnFinishFullExpr(CalcStep.get(), /*DiscardedValue*/ false);
17198 
17199     // Warn about zero linear step (it would be probably better specified as
17200     // making corresponding variables 'const').
17201     if (Optional<llvm::APSInt> Result =
17202             StepExpr->getIntegerConstantExpr(Context)) {
17203       if (!Result->isNegative() && !Result->isStrictlyPositive())
17204         Diag(StepLoc, diag::warn_omp_linear_step_zero)
17205             << Vars[0] << (Vars.size() > 1);
17206     } else if (CalcStep.isUsable()) {
17207       // Calculate the step beforehand instead of doing this on each iteration.
17208       // (This is not used if the number of iterations may be kfold-ed).
17209       CalcStepExpr = CalcStep.get();
17210     }
17211   }
17212 
17213   return OMPLinearClause::Create(Context, StartLoc, LParenLoc, LinKind, LinLoc,
17214                                  ColonLoc, EndLoc, Vars, Privates, Inits,
17215                                  StepExpr, CalcStepExpr,
17216                                  buildPreInits(Context, ExprCaptures),
17217                                  buildPostUpdate(*this, ExprPostUpdates));
17218 }
17219 
17220 static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
17221                                      Expr *NumIterations, Sema &SemaRef,
17222                                      Scope *S, DSAStackTy *Stack) {
17223   // Walk the vars and build update/final expressions for the CodeGen.
17224   SmallVector<Expr *, 8> Updates;
17225   SmallVector<Expr *, 8> Finals;
17226   SmallVector<Expr *, 8> UsedExprs;
17227   Expr *Step = Clause.getStep();
17228   Expr *CalcStep = Clause.getCalcStep();
17229   // OpenMP [2.14.3.7, linear clause]
17230   // If linear-step is not specified it is assumed to be 1.
17231   if (!Step)
17232     Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
17233   else if (CalcStep)
17234     Step = cast<BinaryOperator>(CalcStep)->getLHS();
17235   bool HasErrors = false;
17236   auto CurInit = Clause.inits().begin();
17237   auto CurPrivate = Clause.privates().begin();
17238   OpenMPLinearClauseKind LinKind = Clause.getModifier();
17239   for (Expr *RefExpr : Clause.varlists()) {
17240     SourceLocation ELoc;
17241     SourceRange ERange;
17242     Expr *SimpleRefExpr = RefExpr;
17243     auto Res = getPrivateItem(SemaRef, SimpleRefExpr, ELoc, ERange);
17244     ValueDecl *D = Res.first;
17245     if (Res.second || !D) {
17246       Updates.push_back(nullptr);
17247       Finals.push_back(nullptr);
17248       HasErrors = true;
17249       continue;
17250     }
17251     auto &&Info = Stack->isLoopControlVariable(D);
17252     // OpenMP [2.15.11, distribute simd Construct]
17253     // A list item may not appear in a linear clause, unless it is the loop
17254     // iteration variable.
17255     if (isOpenMPDistributeDirective(Stack->getCurrentDirective()) &&
17256         isOpenMPSimdDirective(Stack->getCurrentDirective()) && !Info.first) {
17257       SemaRef.Diag(ELoc,
17258                    diag::err_omp_linear_distribute_var_non_loop_iteration);
17259       Updates.push_back(nullptr);
17260       Finals.push_back(nullptr);
17261       HasErrors = true;
17262       continue;
17263     }
17264     Expr *InitExpr = *CurInit;
17265 
17266     // Build privatized reference to the current linear var.
17267     auto *DE = cast<DeclRefExpr>(SimpleRefExpr);
17268     Expr *CapturedRef;
17269     if (LinKind == OMPC_LINEAR_uval)
17270       CapturedRef = cast<VarDecl>(DE->getDecl())->getInit();
17271     else
17272       CapturedRef =
17273           buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()),
17274                            DE->getType().getUnqualifiedType(), DE->getExprLoc(),
17275                            /*RefersToCapture=*/true);
17276 
17277     // Build update: Var = InitExpr + IV * Step
17278     ExprResult Update;
17279     if (!Info.first)
17280       Update = buildCounterUpdate(
17281           SemaRef, S, RefExpr->getExprLoc(), *CurPrivate, InitExpr, IV, Step,
17282           /*Subtract=*/false, /*IsNonRectangularLB=*/false);
17283     else
17284       Update = *CurPrivate;
17285     Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getBeginLoc(),
17286                                          /*DiscardedValue*/ false);
17287 
17288     // Build final: Var = InitExpr + NumIterations * Step
17289     ExprResult Final;
17290     if (!Info.first)
17291       Final =
17292           buildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), CapturedRef,
17293                              InitExpr, NumIterations, Step, /*Subtract=*/false,
17294                              /*IsNonRectangularLB=*/false);
17295     else
17296       Final = *CurPrivate;
17297     Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getBeginLoc(),
17298                                         /*DiscardedValue*/ false);
17299 
17300     if (!Update.isUsable() || !Final.isUsable()) {
17301       Updates.push_back(nullptr);
17302       Finals.push_back(nullptr);
17303       UsedExprs.push_back(nullptr);
17304       HasErrors = true;
17305     } else {
17306       Updates.push_back(Update.get());
17307       Finals.push_back(Final.get());
17308       if (!Info.first)
17309         UsedExprs.push_back(SimpleRefExpr);
17310     }
17311     ++CurInit;
17312     ++CurPrivate;
17313   }
17314   if (Expr *S = Clause.getStep())
17315     UsedExprs.push_back(S);
17316   // Fill the remaining part with the nullptr.
17317   UsedExprs.append(Clause.varlist_size() + 1 - UsedExprs.size(), nullptr);
17318   Clause.setUpdates(Updates);
17319   Clause.setFinals(Finals);
17320   Clause.setUsedExprs(UsedExprs);
17321   return HasErrors;
17322 }
17323 
17324 OMPClause *Sema::ActOnOpenMPAlignedClause(
17325     ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc,
17326     SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
17327   SmallVector<Expr *, 8> Vars;
17328   for (Expr *RefExpr : VarList) {
17329     assert(RefExpr && "NULL expr in OpenMP linear clause.");
17330     SourceLocation ELoc;
17331     SourceRange ERange;
17332     Expr *SimpleRefExpr = RefExpr;
17333     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
17334     if (Res.second) {
17335       // It will be analyzed later.
17336       Vars.push_back(RefExpr);
17337     }
17338     ValueDecl *D = Res.first;
17339     if (!D)
17340       continue;
17341 
17342     QualType QType = D->getType();
17343     auto *VD = dyn_cast<VarDecl>(D);
17344 
17345     // OpenMP  [2.8.1, simd construct, Restrictions]
17346     // The type of list items appearing in the aligned clause must be
17347     // array, pointer, reference to array, or reference to pointer.
17348     QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType();
17349     const Type *Ty = QType.getTypePtrOrNull();
17350     if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
17351       Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr)
17352           << QType << getLangOpts().CPlusPlus << ERange;
17353       bool IsDecl =
17354           !VD ||
17355           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
17356       Diag(D->getLocation(),
17357            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
17358           << D;
17359       continue;
17360     }
17361 
17362     // OpenMP  [2.8.1, simd construct, Restrictions]
17363     // A list-item cannot appear in more than one aligned clause.
17364     if (const Expr *PrevRef = DSAStack->addUniqueAligned(D, SimpleRefExpr)) {
17365       Diag(ELoc, diag::err_omp_used_in_clause_twice)
17366           << 0 << getOpenMPClauseName(OMPC_aligned) << ERange;
17367       Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
17368           << getOpenMPClauseName(OMPC_aligned);
17369       continue;
17370     }
17371 
17372     DeclRefExpr *Ref = nullptr;
17373     if (!VD && isOpenMPCapturedDecl(D))
17374       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
17375     Vars.push_back(DefaultFunctionArrayConversion(
17376                        (VD || !Ref) ? RefExpr->IgnoreParens() : Ref)
17377                        .get());
17378   }
17379 
17380   // OpenMP [2.8.1, simd construct, Description]
17381   // The parameter of the aligned clause, alignment, must be a constant
17382   // positive integer expression.
17383   // If no optional parameter is specified, implementation-defined default
17384   // alignments for SIMD instructions on the target platforms are assumed.
17385   if (Alignment != nullptr) {
17386     ExprResult AlignResult =
17387         VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned);
17388     if (AlignResult.isInvalid())
17389       return nullptr;
17390     Alignment = AlignResult.get();
17391   }
17392   if (Vars.empty())
17393     return nullptr;
17394 
17395   return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
17396                                   EndLoc, Vars, Alignment);
17397 }
17398 
17399 OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
17400                                          SourceLocation StartLoc,
17401                                          SourceLocation LParenLoc,
17402                                          SourceLocation EndLoc) {
17403   SmallVector<Expr *, 8> Vars;
17404   SmallVector<Expr *, 8> SrcExprs;
17405   SmallVector<Expr *, 8> DstExprs;
17406   SmallVector<Expr *, 8> AssignmentOps;
17407   for (Expr *RefExpr : VarList) {
17408     assert(RefExpr && "NULL expr in OpenMP copyin clause.");
17409     if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
17410       // It will be analyzed later.
17411       Vars.push_back(RefExpr);
17412       SrcExprs.push_back(nullptr);
17413       DstExprs.push_back(nullptr);
17414       AssignmentOps.push_back(nullptr);
17415       continue;
17416     }
17417 
17418     SourceLocation ELoc = RefExpr->getExprLoc();
17419     // OpenMP [2.1, C/C++]
17420     //  A list item is a variable name.
17421     // OpenMP  [2.14.4.1, Restrictions, p.1]
17422     //  A list item that appears in a copyin clause must be threadprivate.
17423     auto *DE = dyn_cast<DeclRefExpr>(RefExpr);
17424     if (!DE || !isa<VarDecl>(DE->getDecl())) {
17425       Diag(ELoc, diag::err_omp_expected_var_name_member_expr)
17426           << 0 << RefExpr->getSourceRange();
17427       continue;
17428     }
17429 
17430     Decl *D = DE->getDecl();
17431     auto *VD = cast<VarDecl>(D);
17432 
17433     QualType Type = VD->getType();
17434     if (Type->isDependentType() || Type->isInstantiationDependentType()) {
17435       // It will be analyzed later.
17436       Vars.push_back(DE);
17437       SrcExprs.push_back(nullptr);
17438       DstExprs.push_back(nullptr);
17439       AssignmentOps.push_back(nullptr);
17440       continue;
17441     }
17442 
17443     // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
17444     //  A list item that appears in a copyin clause must be threadprivate.
17445     if (!DSAStack->isThreadPrivate(VD)) {
17446       Diag(ELoc, diag::err_omp_required_access)
17447           << getOpenMPClauseName(OMPC_copyin)
17448           << getOpenMPDirectiveName(OMPD_threadprivate);
17449       continue;
17450     }
17451 
17452     // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
17453     //  A variable of class type (or array thereof) that appears in a
17454     //  copyin clause requires an accessible, unambiguous copy assignment
17455     //  operator for the class type.
17456     QualType ElemType = Context.getBaseElementType(Type).getNonReferenceType();
17457     VarDecl *SrcVD =
17458         buildVarDecl(*this, DE->getBeginLoc(), ElemType.getUnqualifiedType(),
17459                      ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr);
17460     DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr(
17461         *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc());
17462     VarDecl *DstVD =
17463         buildVarDecl(*this, DE->getBeginLoc(), ElemType, ".copyin.dst",
17464                      VD->hasAttrs() ? &VD->getAttrs() : nullptr);
17465     DeclRefExpr *PseudoDstExpr =
17466         buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc());
17467     // For arrays generate assignment operation for single element and replace
17468     // it by the original array element in CodeGen.
17469     ExprResult AssignmentOp =
17470         BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign, PseudoDstExpr,
17471                    PseudoSrcExpr);
17472     if (AssignmentOp.isInvalid())
17473       continue;
17474     AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
17475                                        /*DiscardedValue*/ false);
17476     if (AssignmentOp.isInvalid())
17477       continue;
17478 
17479     DSAStack->addDSA(VD, DE, OMPC_copyin);
17480     Vars.push_back(DE);
17481     SrcExprs.push_back(PseudoSrcExpr);
17482     DstExprs.push_back(PseudoDstExpr);
17483     AssignmentOps.push_back(AssignmentOp.get());
17484   }
17485 
17486   if (Vars.empty())
17487     return nullptr;
17488 
17489   return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
17490                                  SrcExprs, DstExprs, AssignmentOps);
17491 }
17492 
17493 OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
17494                                               SourceLocation StartLoc,
17495                                               SourceLocation LParenLoc,
17496                                               SourceLocation EndLoc) {
17497   SmallVector<Expr *, 8> Vars;
17498   SmallVector<Expr *, 8> SrcExprs;
17499   SmallVector<Expr *, 8> DstExprs;
17500   SmallVector<Expr *, 8> AssignmentOps;
17501   for (Expr *RefExpr : VarList) {
17502     assert(RefExpr && "NULL expr in OpenMP linear clause.");
17503     SourceLocation ELoc;
17504     SourceRange ERange;
17505     Expr *SimpleRefExpr = RefExpr;
17506     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
17507     if (Res.second) {
17508       // It will be analyzed later.
17509       Vars.push_back(RefExpr);
17510       SrcExprs.push_back(nullptr);
17511       DstExprs.push_back(nullptr);
17512       AssignmentOps.push_back(nullptr);
17513     }
17514     ValueDecl *D = Res.first;
17515     if (!D)
17516       continue;
17517 
17518     QualType Type = D->getType();
17519     auto *VD = dyn_cast<VarDecl>(D);
17520 
17521     // OpenMP [2.14.4.2, Restrictions, p.2]
17522     //  A list item that appears in a copyprivate clause may not appear in a
17523     //  private or firstprivate clause on the single construct.
17524     if (!VD || !DSAStack->isThreadPrivate(VD)) {
17525       DSAStackTy::DSAVarData DVar =
17526           DSAStack->getTopDSA(D, /*FromParent=*/false);
17527       if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate &&
17528           DVar.RefExpr) {
17529         Diag(ELoc, diag::err_omp_wrong_dsa)
17530             << getOpenMPClauseName(DVar.CKind)
17531             << getOpenMPClauseName(OMPC_copyprivate);
17532         reportOriginalDsa(*this, DSAStack, D, DVar);
17533         continue;
17534       }
17535 
17536       // OpenMP [2.11.4.2, Restrictions, p.1]
17537       //  All list items that appear in a copyprivate clause must be either
17538       //  threadprivate or private in the enclosing context.
17539       if (DVar.CKind == OMPC_unknown) {
17540         DVar = DSAStack->getImplicitDSA(D, false);
17541         if (DVar.CKind == OMPC_shared) {
17542           Diag(ELoc, diag::err_omp_required_access)
17543               << getOpenMPClauseName(OMPC_copyprivate)
17544               << "threadprivate or private in the enclosing context";
17545           reportOriginalDsa(*this, DSAStack, D, DVar);
17546           continue;
17547         }
17548       }
17549     }
17550 
17551     // Variably modified types are not supported.
17552     if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) {
17553       Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
17554           << getOpenMPClauseName(OMPC_copyprivate) << Type
17555           << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
17556       bool IsDecl =
17557           !VD ||
17558           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
17559       Diag(D->getLocation(),
17560            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
17561           << D;
17562       continue;
17563     }
17564 
17565     // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
17566     //  A variable of class type (or array thereof) that appears in a
17567     //  copyin clause requires an accessible, unambiguous copy assignment
17568     //  operator for the class type.
17569     Type = Context.getBaseElementType(Type.getNonReferenceType())
17570                .getUnqualifiedType();
17571     VarDecl *SrcVD =
17572         buildVarDecl(*this, RefExpr->getBeginLoc(), Type, ".copyprivate.src",
17573                      D->hasAttrs() ? &D->getAttrs() : nullptr);
17574     DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr(*this, SrcVD, Type, ELoc);
17575     VarDecl *DstVD =
17576         buildVarDecl(*this, RefExpr->getBeginLoc(), Type, ".copyprivate.dst",
17577                      D->hasAttrs() ? &D->getAttrs() : nullptr);
17578     DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
17579     ExprResult AssignmentOp = BuildBinOp(
17580         DSAStack->getCurScope(), ELoc, BO_Assign, PseudoDstExpr, PseudoSrcExpr);
17581     if (AssignmentOp.isInvalid())
17582       continue;
17583     AssignmentOp =
17584         ActOnFinishFullExpr(AssignmentOp.get(), ELoc, /*DiscardedValue*/ false);
17585     if (AssignmentOp.isInvalid())
17586       continue;
17587 
17588     // No need to mark vars as copyprivate, they are already threadprivate or
17589     // implicitly private.
17590     assert(VD || isOpenMPCapturedDecl(D));
17591     Vars.push_back(
17592         VD ? RefExpr->IgnoreParens()
17593            : buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false));
17594     SrcExprs.push_back(PseudoSrcExpr);
17595     DstExprs.push_back(PseudoDstExpr);
17596     AssignmentOps.push_back(AssignmentOp.get());
17597   }
17598 
17599   if (Vars.empty())
17600     return nullptr;
17601 
17602   return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
17603                                       Vars, SrcExprs, DstExprs, AssignmentOps);
17604 }
17605 
17606 OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
17607                                         SourceLocation StartLoc,
17608                                         SourceLocation LParenLoc,
17609                                         SourceLocation EndLoc) {
17610   if (VarList.empty())
17611     return nullptr;
17612 
17613   return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList);
17614 }
17615 
17616 /// Tries to find omp_depend_t. type.
17617 static bool findOMPDependT(Sema &S, SourceLocation Loc, DSAStackTy *Stack,
17618                            bool Diagnose = true) {
17619   QualType OMPDependT = Stack->getOMPDependT();
17620   if (!OMPDependT.isNull())
17621     return true;
17622   IdentifierInfo *II = &S.PP.getIdentifierTable().get("omp_depend_t");
17623   ParsedType PT = S.getTypeName(*II, Loc, S.getCurScope());
17624   if (!PT.getAsOpaquePtr() || PT.get().isNull()) {
17625     if (Diagnose)
17626       S.Diag(Loc, diag::err_omp_implied_type_not_found) << "omp_depend_t";
17627     return false;
17628   }
17629   Stack->setOMPDependT(PT.get());
17630   return true;
17631 }
17632 
17633 OMPClause *Sema::ActOnOpenMPDepobjClause(Expr *Depobj, SourceLocation StartLoc,
17634                                          SourceLocation LParenLoc,
17635                                          SourceLocation EndLoc) {
17636   if (!Depobj)
17637     return nullptr;
17638 
17639   bool OMPDependTFound = findOMPDependT(*this, StartLoc, DSAStack);
17640 
17641   // OpenMP 5.0, 2.17.10.1 depobj Construct
17642   // depobj is an lvalue expression of type omp_depend_t.
17643   if (!Depobj->isTypeDependent() && !Depobj->isValueDependent() &&
17644       !Depobj->isInstantiationDependent() &&
17645       !Depobj->containsUnexpandedParameterPack() &&
17646       (OMPDependTFound &&
17647        !Context.typesAreCompatible(DSAStack->getOMPDependT(), Depobj->getType(),
17648                                    /*CompareUnqualified=*/true))) {
17649     Diag(Depobj->getExprLoc(), diag::err_omp_expected_omp_depend_t_lvalue)
17650         << 0 << Depobj->getType() << Depobj->getSourceRange();
17651   }
17652 
17653   if (!Depobj->isLValue()) {
17654     Diag(Depobj->getExprLoc(), diag::err_omp_expected_omp_depend_t_lvalue)
17655         << 1 << Depobj->getSourceRange();
17656   }
17657 
17658   return OMPDepobjClause::Create(Context, StartLoc, LParenLoc, EndLoc, Depobj);
17659 }
17660 
17661 OMPClause *
17662 Sema::ActOnOpenMPDependClause(Expr *DepModifier, OpenMPDependClauseKind DepKind,
17663                               SourceLocation DepLoc, SourceLocation ColonLoc,
17664                               ArrayRef<Expr *> VarList, SourceLocation StartLoc,
17665                               SourceLocation LParenLoc, SourceLocation EndLoc) {
17666   if (DSAStack->getCurrentDirective() == OMPD_ordered &&
17667       DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink) {
17668     Diag(DepLoc, diag::err_omp_unexpected_clause_value)
17669         << "'source' or 'sink'" << getOpenMPClauseName(OMPC_depend);
17670     return nullptr;
17671   }
17672   if ((DSAStack->getCurrentDirective() != OMPD_ordered ||
17673        DSAStack->getCurrentDirective() == OMPD_depobj) &&
17674       (DepKind == OMPC_DEPEND_unknown || DepKind == OMPC_DEPEND_source ||
17675        DepKind == OMPC_DEPEND_sink ||
17676        ((LangOpts.OpenMP < 50 ||
17677          DSAStack->getCurrentDirective() == OMPD_depobj) &&
17678         DepKind == OMPC_DEPEND_depobj))) {
17679     SmallVector<unsigned, 3> Except;
17680     Except.push_back(OMPC_DEPEND_source);
17681     Except.push_back(OMPC_DEPEND_sink);
17682     if (LangOpts.OpenMP < 50 || DSAStack->getCurrentDirective() == OMPD_depobj)
17683       Except.push_back(OMPC_DEPEND_depobj);
17684     std::string Expected = (LangOpts.OpenMP >= 50 && !DepModifier)
17685                                ? "depend modifier(iterator) or "
17686                                : "";
17687     Diag(DepLoc, diag::err_omp_unexpected_clause_value)
17688         << Expected + getListOfPossibleValues(OMPC_depend, /*First=*/0,
17689                                               /*Last=*/OMPC_DEPEND_unknown,
17690                                               Except)
17691         << getOpenMPClauseName(OMPC_depend);
17692     return nullptr;
17693   }
17694   if (DepModifier &&
17695       (DepKind == OMPC_DEPEND_source || DepKind == OMPC_DEPEND_sink)) {
17696     Diag(DepModifier->getExprLoc(),
17697          diag::err_omp_depend_sink_source_with_modifier);
17698     return nullptr;
17699   }
17700   if (DepModifier &&
17701       !DepModifier->getType()->isSpecificBuiltinType(BuiltinType::OMPIterator))
17702     Diag(DepModifier->getExprLoc(), diag::err_omp_depend_modifier_not_iterator);
17703 
17704   SmallVector<Expr *, 8> Vars;
17705   DSAStackTy::OperatorOffsetTy OpsOffs;
17706   llvm::APSInt DepCounter(/*BitWidth=*/32);
17707   llvm::APSInt TotalDepCount(/*BitWidth=*/32);
17708   if (DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) {
17709     if (const Expr *OrderedCountExpr =
17710             DSAStack->getParentOrderedRegionParam().first) {
17711       TotalDepCount = OrderedCountExpr->EvaluateKnownConstInt(Context);
17712       TotalDepCount.setIsUnsigned(/*Val=*/true);
17713     }
17714   }
17715   for (Expr *RefExpr : VarList) {
17716     assert(RefExpr && "NULL expr in OpenMP shared clause.");
17717     if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
17718       // It will be analyzed later.
17719       Vars.push_back(RefExpr);
17720       continue;
17721     }
17722 
17723     SourceLocation ELoc = RefExpr->getExprLoc();
17724     Expr *SimpleExpr = RefExpr->IgnoreParenCasts();
17725     if (DepKind == OMPC_DEPEND_sink) {
17726       if (DSAStack->getParentOrderedRegionParam().first &&
17727           DepCounter >= TotalDepCount) {
17728         Diag(ELoc, diag::err_omp_depend_sink_unexpected_expr);
17729         continue;
17730       }
17731       ++DepCounter;
17732       // OpenMP  [2.13.9, Summary]
17733       // depend(dependence-type : vec), where dependence-type is:
17734       // 'sink' and where vec is the iteration vector, which has the form:
17735       //  x1 [+- d1], x2 [+- d2 ], . . . , xn [+- dn]
17736       // where n is the value specified by the ordered clause in the loop
17737       // directive, xi denotes the loop iteration variable of the i-th nested
17738       // loop associated with the loop directive, and di is a constant
17739       // non-negative integer.
17740       if (CurContext->isDependentContext()) {
17741         // It will be analyzed later.
17742         Vars.push_back(RefExpr);
17743         continue;
17744       }
17745       SimpleExpr = SimpleExpr->IgnoreImplicit();
17746       OverloadedOperatorKind OOK = OO_None;
17747       SourceLocation OOLoc;
17748       Expr *LHS = SimpleExpr;
17749       Expr *RHS = nullptr;
17750       if (auto *BO = dyn_cast<BinaryOperator>(SimpleExpr)) {
17751         OOK = BinaryOperator::getOverloadedOperator(BO->getOpcode());
17752         OOLoc = BO->getOperatorLoc();
17753         LHS = BO->getLHS()->IgnoreParenImpCasts();
17754         RHS = BO->getRHS()->IgnoreParenImpCasts();
17755       } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(SimpleExpr)) {
17756         OOK = OCE->getOperator();
17757         OOLoc = OCE->getOperatorLoc();
17758         LHS = OCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
17759         RHS = OCE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
17760       } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SimpleExpr)) {
17761         OOK = MCE->getMethodDecl()
17762                   ->getNameInfo()
17763                   .getName()
17764                   .getCXXOverloadedOperator();
17765         OOLoc = MCE->getCallee()->getExprLoc();
17766         LHS = MCE->getImplicitObjectArgument()->IgnoreParenImpCasts();
17767         RHS = MCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
17768       }
17769       SourceLocation ELoc;
17770       SourceRange ERange;
17771       auto Res = getPrivateItem(*this, LHS, ELoc, ERange);
17772       if (Res.second) {
17773         // It will be analyzed later.
17774         Vars.push_back(RefExpr);
17775       }
17776       ValueDecl *D = Res.first;
17777       if (!D)
17778         continue;
17779 
17780       if (OOK != OO_Plus && OOK != OO_Minus && (RHS || OOK != OO_None)) {
17781         Diag(OOLoc, diag::err_omp_depend_sink_expected_plus_minus);
17782         continue;
17783       }
17784       if (RHS) {
17785         ExprResult RHSRes = VerifyPositiveIntegerConstantInClause(
17786             RHS, OMPC_depend, /*StrictlyPositive=*/false);
17787         if (RHSRes.isInvalid())
17788           continue;
17789       }
17790       if (!CurContext->isDependentContext() &&
17791           DSAStack->getParentOrderedRegionParam().first &&
17792           DepCounter != DSAStack->isParentLoopControlVariable(D).first) {
17793         const ValueDecl *VD =
17794             DSAStack->getParentLoopControlVariable(DepCounter.getZExtValue());
17795         if (VD)
17796           Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration)
17797               << 1 << VD;
17798         else
17799           Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration) << 0;
17800         continue;
17801       }
17802       OpsOffs.emplace_back(RHS, OOK);
17803     } else {
17804       bool OMPDependTFound = LangOpts.OpenMP >= 50;
17805       if (OMPDependTFound)
17806         OMPDependTFound = findOMPDependT(*this, StartLoc, DSAStack,
17807                                          DepKind == OMPC_DEPEND_depobj);
17808       if (DepKind == OMPC_DEPEND_depobj) {
17809         // OpenMP 5.0, 2.17.11 depend Clause, Restrictions, C/C++
17810         // List items used in depend clauses with the depobj dependence type
17811         // must be expressions of the omp_depend_t type.
17812         if (!RefExpr->isValueDependent() && !RefExpr->isTypeDependent() &&
17813             !RefExpr->isInstantiationDependent() &&
17814             !RefExpr->containsUnexpandedParameterPack() &&
17815             (OMPDependTFound &&
17816              !Context.hasSameUnqualifiedType(DSAStack->getOMPDependT(),
17817                                              RefExpr->getType()))) {
17818           Diag(ELoc, diag::err_omp_expected_omp_depend_t_lvalue)
17819               << 0 << RefExpr->getType() << RefExpr->getSourceRange();
17820           continue;
17821         }
17822         if (!RefExpr->isLValue()) {
17823           Diag(ELoc, diag::err_omp_expected_omp_depend_t_lvalue)
17824               << 1 << RefExpr->getType() << RefExpr->getSourceRange();
17825           continue;
17826         }
17827       } else {
17828         // OpenMP 5.0 [2.17.11, Restrictions]
17829         // List items used in depend clauses cannot be zero-length array
17830         // sections.
17831         QualType ExprTy = RefExpr->getType().getNonReferenceType();
17832         const auto *OASE = dyn_cast<OMPArraySectionExpr>(SimpleExpr);
17833         if (OASE) {
17834           QualType BaseType =
17835               OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
17836           if (const auto *ATy = BaseType->getAsArrayTypeUnsafe())
17837             ExprTy = ATy->getElementType();
17838           else
17839             ExprTy = BaseType->getPointeeType();
17840           ExprTy = ExprTy.getNonReferenceType();
17841           const Expr *Length = OASE->getLength();
17842           Expr::EvalResult Result;
17843           if (Length && !Length->isValueDependent() &&
17844               Length->EvaluateAsInt(Result, Context) &&
17845               Result.Val.getInt().isNullValue()) {
17846             Diag(ELoc,
17847                  diag::err_omp_depend_zero_length_array_section_not_allowed)
17848                 << SimpleExpr->getSourceRange();
17849             continue;
17850           }
17851         }
17852 
17853         // OpenMP 5.0, 2.17.11 depend Clause, Restrictions, C/C++
17854         // List items used in depend clauses with the in, out, inout or
17855         // mutexinoutset dependence types cannot be expressions of the
17856         // omp_depend_t type.
17857         if (!RefExpr->isValueDependent() && !RefExpr->isTypeDependent() &&
17858             !RefExpr->isInstantiationDependent() &&
17859             !RefExpr->containsUnexpandedParameterPack() &&
17860             (OMPDependTFound &&
17861              DSAStack->getOMPDependT().getTypePtr() == ExprTy.getTypePtr())) {
17862           Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
17863               << (LangOpts.OpenMP >= 50 ? 1 : 0) << 1
17864               << RefExpr->getSourceRange();
17865           continue;
17866         }
17867 
17868         auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr);
17869         if (!RefExpr->IgnoreParenImpCasts()->isLValue() ||
17870             (ASE && !ASE->getBase()->isTypeDependent() &&
17871              !ASE->getBase()
17872                   ->getType()
17873                   .getNonReferenceType()
17874                   ->isPointerType() &&
17875              !ASE->getBase()->getType().getNonReferenceType()->isArrayType())) {
17876           Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
17877               << (LangOpts.OpenMP >= 50 ? 1 : 0)
17878               << (LangOpts.OpenMP >= 50 ? 1 : 0) << RefExpr->getSourceRange();
17879           continue;
17880         }
17881 
17882         ExprResult Res;
17883         {
17884           Sema::TentativeAnalysisScope Trap(*this);
17885           Res = CreateBuiltinUnaryOp(ELoc, UO_AddrOf,
17886                                      RefExpr->IgnoreParenImpCasts());
17887         }
17888         if (!Res.isUsable() && !isa<OMPArraySectionExpr>(SimpleExpr) &&
17889             !isa<OMPArrayShapingExpr>(SimpleExpr)) {
17890           Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
17891               << (LangOpts.OpenMP >= 50 ? 1 : 0)
17892               << (LangOpts.OpenMP >= 50 ? 1 : 0) << RefExpr->getSourceRange();
17893           continue;
17894         }
17895       }
17896     }
17897     Vars.push_back(RefExpr->IgnoreParenImpCasts());
17898   }
17899 
17900   if (!CurContext->isDependentContext() && DepKind == OMPC_DEPEND_sink &&
17901       TotalDepCount > VarList.size() &&
17902       DSAStack->getParentOrderedRegionParam().first &&
17903       DSAStack->getParentLoopControlVariable(VarList.size() + 1)) {
17904     Diag(EndLoc, diag::err_omp_depend_sink_expected_loop_iteration)
17905         << 1 << DSAStack->getParentLoopControlVariable(VarList.size() + 1);
17906   }
17907   if (DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink &&
17908       Vars.empty())
17909     return nullptr;
17910 
17911   auto *C = OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc,
17912                                     DepModifier, DepKind, DepLoc, ColonLoc,
17913                                     Vars, TotalDepCount.getZExtValue());
17914   if ((DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) &&
17915       DSAStack->isParentOrderedRegion())
17916     DSAStack->addDoacrossDependClause(C, OpsOffs);
17917   return C;
17918 }
17919 
17920 OMPClause *Sema::ActOnOpenMPDeviceClause(OpenMPDeviceClauseModifier Modifier,
17921                                          Expr *Device, SourceLocation StartLoc,
17922                                          SourceLocation LParenLoc,
17923                                          SourceLocation ModifierLoc,
17924                                          SourceLocation EndLoc) {
17925   assert((ModifierLoc.isInvalid() || LangOpts.OpenMP >= 50) &&
17926          "Unexpected device modifier in OpenMP < 50.");
17927 
17928   bool ErrorFound = false;
17929   if (ModifierLoc.isValid() && Modifier == OMPC_DEVICE_unknown) {
17930     std::string Values =
17931         getListOfPossibleValues(OMPC_device, /*First=*/0, OMPC_DEVICE_unknown);
17932     Diag(ModifierLoc, diag::err_omp_unexpected_clause_value)
17933         << Values << getOpenMPClauseName(OMPC_device);
17934     ErrorFound = true;
17935   }
17936 
17937   Expr *ValExpr = Device;
17938   Stmt *HelperValStmt = nullptr;
17939 
17940   // OpenMP [2.9.1, Restrictions]
17941   // The device expression must evaluate to a non-negative integer value.
17942   ErrorFound = !isNonNegativeIntegerValue(ValExpr, *this, OMPC_device,
17943                                           /*StrictlyPositive=*/false) ||
17944                ErrorFound;
17945   if (ErrorFound)
17946     return nullptr;
17947 
17948   OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
17949   OpenMPDirectiveKind CaptureRegion =
17950       getOpenMPCaptureRegionForClause(DKind, OMPC_device, LangOpts.OpenMP);
17951   if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
17952     ValExpr = MakeFullExpr(ValExpr).get();
17953     llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
17954     ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
17955     HelperValStmt = buildPreInits(Context, Captures);
17956   }
17957 
17958   return new (Context)
17959       OMPDeviceClause(Modifier, ValExpr, HelperValStmt, CaptureRegion, StartLoc,
17960                       LParenLoc, ModifierLoc, EndLoc);
17961 }
17962 
17963 static bool checkTypeMappable(SourceLocation SL, SourceRange SR, Sema &SemaRef,
17964                               DSAStackTy *Stack, QualType QTy,
17965                               bool FullCheck = true) {
17966   NamedDecl *ND;
17967   if (QTy->isIncompleteType(&ND)) {
17968     SemaRef.Diag(SL, diag::err_incomplete_type) << QTy << SR;
17969     return false;
17970   }
17971   if (FullCheck && !SemaRef.CurContext->isDependentContext() &&
17972       !QTy.isTriviallyCopyableType(SemaRef.Context))
17973     SemaRef.Diag(SL, diag::warn_omp_non_trivial_type_mapped) << QTy << SR;
17974   return true;
17975 }
17976 
17977 /// Return true if it can be proven that the provided array expression
17978 /// (array section or array subscript) does NOT specify the whole size of the
17979 /// array whose base type is \a BaseQTy.
17980 static bool checkArrayExpressionDoesNotReferToWholeSize(Sema &SemaRef,
17981                                                         const Expr *E,
17982                                                         QualType BaseQTy) {
17983   const auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
17984 
17985   // If this is an array subscript, it refers to the whole size if the size of
17986   // the dimension is constant and equals 1. Also, an array section assumes the
17987   // format of an array subscript if no colon is used.
17988   if (isa<ArraySubscriptExpr>(E) ||
17989       (OASE && OASE->getColonLocFirst().isInvalid())) {
17990     if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
17991       return ATy->getSize().getSExtValue() != 1;
17992     // Size can't be evaluated statically.
17993     return false;
17994   }
17995 
17996   assert(OASE && "Expecting array section if not an array subscript.");
17997   const Expr *LowerBound = OASE->getLowerBound();
17998   const Expr *Length = OASE->getLength();
17999 
18000   // If there is a lower bound that does not evaluates to zero, we are not
18001   // covering the whole dimension.
18002   if (LowerBound) {
18003     Expr::EvalResult Result;
18004     if (!LowerBound->EvaluateAsInt(Result, SemaRef.getASTContext()))
18005       return false; // Can't get the integer value as a constant.
18006 
18007     llvm::APSInt ConstLowerBound = Result.Val.getInt();
18008     if (ConstLowerBound.getSExtValue())
18009       return true;
18010   }
18011 
18012   // If we don't have a length we covering the whole dimension.
18013   if (!Length)
18014     return false;
18015 
18016   // If the base is a pointer, we don't have a way to get the size of the
18017   // pointee.
18018   if (BaseQTy->isPointerType())
18019     return false;
18020 
18021   // We can only check if the length is the same as the size of the dimension
18022   // if we have a constant array.
18023   const auto *CATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr());
18024   if (!CATy)
18025     return false;
18026 
18027   Expr::EvalResult Result;
18028   if (!Length->EvaluateAsInt(Result, SemaRef.getASTContext()))
18029     return false; // Can't get the integer value as a constant.
18030 
18031   llvm::APSInt ConstLength = Result.Val.getInt();
18032   return CATy->getSize().getSExtValue() != ConstLength.getSExtValue();
18033 }
18034 
18035 // Return true if it can be proven that the provided array expression (array
18036 // section or array subscript) does NOT specify a single element of the array
18037 // whose base type is \a BaseQTy.
18038 static bool checkArrayExpressionDoesNotReferToUnitySize(Sema &SemaRef,
18039                                                         const Expr *E,
18040                                                         QualType BaseQTy) {
18041   const auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
18042 
18043   // An array subscript always refer to a single element. Also, an array section
18044   // assumes the format of an array subscript if no colon is used.
18045   if (isa<ArraySubscriptExpr>(E) ||
18046       (OASE && OASE->getColonLocFirst().isInvalid()))
18047     return false;
18048 
18049   assert(OASE && "Expecting array section if not an array subscript.");
18050   const Expr *Length = OASE->getLength();
18051 
18052   // If we don't have a length we have to check if the array has unitary size
18053   // for this dimension. Also, we should always expect a length if the base type
18054   // is pointer.
18055   if (!Length) {
18056     if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
18057       return ATy->getSize().getSExtValue() != 1;
18058     // We cannot assume anything.
18059     return false;
18060   }
18061 
18062   // Check if the length evaluates to 1.
18063   Expr::EvalResult Result;
18064   if (!Length->EvaluateAsInt(Result, SemaRef.getASTContext()))
18065     return false; // Can't get the integer value as a constant.
18066 
18067   llvm::APSInt ConstLength = Result.Val.getInt();
18068   return ConstLength.getSExtValue() != 1;
18069 }
18070 
18071 // The base of elements of list in a map clause have to be either:
18072 //  - a reference to variable or field.
18073 //  - a member expression.
18074 //  - an array expression.
18075 //
18076 // E.g. if we have the expression 'r.S.Arr[:12]', we want to retrieve the
18077 // reference to 'r'.
18078 //
18079 // If we have:
18080 //
18081 // struct SS {
18082 //   Bla S;
18083 //   foo() {
18084 //     #pragma omp target map (S.Arr[:12]);
18085 //   }
18086 // }
18087 //
18088 // We want to retrieve the member expression 'this->S';
18089 
18090 // OpenMP 5.0 [2.19.7.1, map Clause, Restrictions, p.2]
18091 //  If a list item is an array section, it must specify contiguous storage.
18092 //
18093 // For this restriction it is sufficient that we make sure only references
18094 // to variables or fields and array expressions, and that no array sections
18095 // exist except in the rightmost expression (unless they cover the whole
18096 // dimension of the array). E.g. these would be invalid:
18097 //
18098 //   r.ArrS[3:5].Arr[6:7]
18099 //
18100 //   r.ArrS[3:5].x
18101 //
18102 // but these would be valid:
18103 //   r.ArrS[3].Arr[6:7]
18104 //
18105 //   r.ArrS[3].x
18106 namespace {
18107 class MapBaseChecker final : public StmtVisitor<MapBaseChecker, bool> {
18108   Sema &SemaRef;
18109   OpenMPClauseKind CKind = OMPC_unknown;
18110   OpenMPDirectiveKind DKind = OMPD_unknown;
18111   OMPClauseMappableExprCommon::MappableExprComponentList &Components;
18112   bool IsNonContiguous = false;
18113   bool NoDiagnose = false;
18114   const Expr *RelevantExpr = nullptr;
18115   bool AllowUnitySizeArraySection = true;
18116   bool AllowWholeSizeArraySection = true;
18117   bool AllowAnotherPtr = true;
18118   SourceLocation ELoc;
18119   SourceRange ERange;
18120 
18121   void emitErrorMsg() {
18122     // If nothing else worked, this is not a valid map clause expression.
18123     if (SemaRef.getLangOpts().OpenMP < 50) {
18124       SemaRef.Diag(ELoc,
18125                    diag::err_omp_expected_named_var_member_or_array_expression)
18126           << ERange;
18127     } else {
18128       SemaRef.Diag(ELoc, diag::err_omp_non_lvalue_in_map_or_motion_clauses)
18129           << getOpenMPClauseName(CKind) << ERange;
18130     }
18131   }
18132 
18133 public:
18134   bool VisitDeclRefExpr(DeclRefExpr *DRE) {
18135     if (!isa<VarDecl>(DRE->getDecl())) {
18136       emitErrorMsg();
18137       return false;
18138     }
18139     assert(!RelevantExpr && "RelevantExpr is expected to be nullptr");
18140     RelevantExpr = DRE;
18141     // Record the component.
18142     Components.emplace_back(DRE, DRE->getDecl(), IsNonContiguous);
18143     return true;
18144   }
18145 
18146   bool VisitMemberExpr(MemberExpr *ME) {
18147     Expr *E = ME;
18148     Expr *BaseE = ME->getBase()->IgnoreParenCasts();
18149 
18150     if (isa<CXXThisExpr>(BaseE)) {
18151       assert(!RelevantExpr && "RelevantExpr is expected to be nullptr");
18152       // We found a base expression: this->Val.
18153       RelevantExpr = ME;
18154     } else {
18155       E = BaseE;
18156     }
18157 
18158     if (!isa<FieldDecl>(ME->getMemberDecl())) {
18159       if (!NoDiagnose) {
18160         SemaRef.Diag(ELoc, diag::err_omp_expected_access_to_data_field)
18161           << ME->getSourceRange();
18162         return false;
18163       }
18164       if (RelevantExpr)
18165         return false;
18166       return Visit(E);
18167     }
18168 
18169     auto *FD = cast<FieldDecl>(ME->getMemberDecl());
18170 
18171     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
18172     //  A bit-field cannot appear in a map clause.
18173     //
18174     if (FD->isBitField()) {
18175       if (!NoDiagnose) {
18176         SemaRef.Diag(ELoc, diag::err_omp_bit_fields_forbidden_in_clause)
18177           << ME->getSourceRange() << getOpenMPClauseName(CKind);
18178         return false;
18179       }
18180       if (RelevantExpr)
18181         return false;
18182       return Visit(E);
18183     }
18184 
18185     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
18186     //  If the type of a list item is a reference to a type T then the type
18187     //  will be considered to be T for all purposes of this clause.
18188     QualType CurType = BaseE->getType().getNonReferenceType();
18189 
18190     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.2]
18191     //  A list item cannot be a variable that is a member of a structure with
18192     //  a union type.
18193     //
18194     if (CurType->isUnionType()) {
18195       if (!NoDiagnose) {
18196         SemaRef.Diag(ELoc, diag::err_omp_union_type_not_allowed)
18197           << ME->getSourceRange();
18198         return false;
18199       }
18200       return RelevantExpr || Visit(E);
18201     }
18202 
18203     // If we got a member expression, we should not expect any array section
18204     // before that:
18205     //
18206     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.7]
18207     //  If a list item is an element of a structure, only the rightmost symbol
18208     //  of the variable reference can be an array section.
18209     //
18210     AllowUnitySizeArraySection = false;
18211     AllowWholeSizeArraySection = false;
18212 
18213     // Record the component.
18214     Components.emplace_back(ME, FD, IsNonContiguous);
18215     return RelevantExpr || Visit(E);
18216   }
18217 
18218   bool VisitArraySubscriptExpr(ArraySubscriptExpr *AE) {
18219     Expr *E = AE->getBase()->IgnoreParenImpCasts();
18220 
18221     if (!E->getType()->isAnyPointerType() && !E->getType()->isArrayType()) {
18222       if (!NoDiagnose) {
18223         SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
18224           << 0 << AE->getSourceRange();
18225         return false;
18226       }
18227       return RelevantExpr || Visit(E);
18228     }
18229 
18230     // If we got an array subscript that express the whole dimension we
18231     // can have any array expressions before. If it only expressing part of
18232     // the dimension, we can only have unitary-size array expressions.
18233     if (checkArrayExpressionDoesNotReferToWholeSize(SemaRef, AE,
18234                                                     E->getType()))
18235       AllowWholeSizeArraySection = false;
18236 
18237     if (const auto *TE = dyn_cast<CXXThisExpr>(E->IgnoreParenCasts())) {
18238       Expr::EvalResult Result;
18239       if (!AE->getIdx()->isValueDependent() &&
18240           AE->getIdx()->EvaluateAsInt(Result, SemaRef.getASTContext()) &&
18241           !Result.Val.getInt().isNullValue()) {
18242         SemaRef.Diag(AE->getIdx()->getExprLoc(),
18243                      diag::err_omp_invalid_map_this_expr);
18244         SemaRef.Diag(AE->getIdx()->getExprLoc(),
18245                      diag::note_omp_invalid_subscript_on_this_ptr_map);
18246       }
18247       assert(!RelevantExpr && "RelevantExpr is expected to be nullptr");
18248       RelevantExpr = TE;
18249     }
18250 
18251     // Record the component - we don't have any declaration associated.
18252     Components.emplace_back(AE, nullptr, IsNonContiguous);
18253 
18254     return RelevantExpr || Visit(E);
18255   }
18256 
18257   bool VisitOMPArraySectionExpr(OMPArraySectionExpr *OASE) {
18258     assert(!NoDiagnose && "Array sections cannot be implicitly mapped.");
18259     Expr *E = OASE->getBase()->IgnoreParenImpCasts();
18260     QualType CurType =
18261       OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
18262 
18263     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
18264     //  If the type of a list item is a reference to a type T then the type
18265     //  will be considered to be T for all purposes of this clause.
18266     if (CurType->isReferenceType())
18267       CurType = CurType->getPointeeType();
18268 
18269     bool IsPointer = CurType->isAnyPointerType();
18270 
18271     if (!IsPointer && !CurType->isArrayType()) {
18272       SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
18273         << 0 << OASE->getSourceRange();
18274       return false;
18275     }
18276 
18277     bool NotWhole =
18278       checkArrayExpressionDoesNotReferToWholeSize(SemaRef, OASE, CurType);
18279     bool NotUnity =
18280       checkArrayExpressionDoesNotReferToUnitySize(SemaRef, OASE, CurType);
18281 
18282     if (AllowWholeSizeArraySection) {
18283       // Any array section is currently allowed. Allowing a whole size array
18284       // section implies allowing a unity array section as well.
18285       //
18286       // If this array section refers to the whole dimension we can still
18287       // accept other array sections before this one, except if the base is a
18288       // pointer. Otherwise, only unitary sections are accepted.
18289       if (NotWhole || IsPointer)
18290         AllowWholeSizeArraySection = false;
18291     } else if (DKind == OMPD_target_update &&
18292                SemaRef.getLangOpts().OpenMP >= 50) {
18293       if (IsPointer && !AllowAnotherPtr)
18294         SemaRef.Diag(ELoc, diag::err_omp_section_length_undefined)
18295             << /*array of unknown bound */ 1;
18296       else
18297         IsNonContiguous = true;
18298     } else if (AllowUnitySizeArraySection && NotUnity) {
18299       // A unity or whole array section is not allowed and that is not
18300       // compatible with the properties of the current array section.
18301       SemaRef.Diag(
18302         ELoc, diag::err_array_section_does_not_specify_contiguous_storage)
18303         << OASE->getSourceRange();
18304       return false;
18305     }
18306 
18307     if (IsPointer)
18308       AllowAnotherPtr = false;
18309 
18310     if (const auto *TE = dyn_cast<CXXThisExpr>(E)) {
18311       Expr::EvalResult ResultR;
18312       Expr::EvalResult ResultL;
18313       if (!OASE->getLength()->isValueDependent() &&
18314           OASE->getLength()->EvaluateAsInt(ResultR, SemaRef.getASTContext()) &&
18315           !ResultR.Val.getInt().isOneValue()) {
18316         SemaRef.Diag(OASE->getLength()->getExprLoc(),
18317                      diag::err_omp_invalid_map_this_expr);
18318         SemaRef.Diag(OASE->getLength()->getExprLoc(),
18319                      diag::note_omp_invalid_length_on_this_ptr_mapping);
18320       }
18321       if (OASE->getLowerBound() && !OASE->getLowerBound()->isValueDependent() &&
18322           OASE->getLowerBound()->EvaluateAsInt(ResultL,
18323                                                SemaRef.getASTContext()) &&
18324           !ResultL.Val.getInt().isNullValue()) {
18325         SemaRef.Diag(OASE->getLowerBound()->getExprLoc(),
18326                      diag::err_omp_invalid_map_this_expr);
18327         SemaRef.Diag(OASE->getLowerBound()->getExprLoc(),
18328                      diag::note_omp_invalid_lower_bound_on_this_ptr_mapping);
18329       }
18330       assert(!RelevantExpr && "RelevantExpr is expected to be nullptr");
18331       RelevantExpr = TE;
18332     }
18333 
18334     // Record the component - we don't have any declaration associated.
18335     Components.emplace_back(OASE, nullptr, /*IsNonContiguous=*/false);
18336     return RelevantExpr || Visit(E);
18337   }
18338   bool VisitOMPArrayShapingExpr(OMPArrayShapingExpr *E) {
18339     Expr *Base = E->getBase();
18340 
18341     // Record the component - we don't have any declaration associated.
18342     Components.emplace_back(E, nullptr, IsNonContiguous);
18343 
18344     return Visit(Base->IgnoreParenImpCasts());
18345   }
18346 
18347   bool VisitUnaryOperator(UnaryOperator *UO) {
18348     if (SemaRef.getLangOpts().OpenMP < 50 || !UO->isLValue() ||
18349         UO->getOpcode() != UO_Deref) {
18350       emitErrorMsg();
18351       return false;
18352     }
18353     if (!RelevantExpr) {
18354       // Record the component if haven't found base decl.
18355       Components.emplace_back(UO, nullptr, /*IsNonContiguous=*/false);
18356     }
18357     return RelevantExpr || Visit(UO->getSubExpr()->IgnoreParenImpCasts());
18358   }
18359   bool VisitBinaryOperator(BinaryOperator *BO) {
18360     if (SemaRef.getLangOpts().OpenMP < 50 || !BO->getType()->isPointerType()) {
18361       emitErrorMsg();
18362       return false;
18363     }
18364 
18365     // Pointer arithmetic is the only thing we expect to happen here so after we
18366     // make sure the binary operator is a pointer type, the we only thing need
18367     // to to is to visit the subtree that has the same type as root (so that we
18368     // know the other subtree is just an offset)
18369     Expr *LE = BO->getLHS()->IgnoreParenImpCasts();
18370     Expr *RE = BO->getRHS()->IgnoreParenImpCasts();
18371     Components.emplace_back(BO, nullptr, false);
18372     assert((LE->getType().getTypePtr() == BO->getType().getTypePtr() ||
18373             RE->getType().getTypePtr() == BO->getType().getTypePtr()) &&
18374            "Either LHS or RHS have base decl inside");
18375     if (BO->getType().getTypePtr() == LE->getType().getTypePtr())
18376       return RelevantExpr || Visit(LE);
18377     return RelevantExpr || Visit(RE);
18378   }
18379   bool VisitCXXThisExpr(CXXThisExpr *CTE) {
18380     assert(!RelevantExpr && "RelevantExpr is expected to be nullptr");
18381     RelevantExpr = CTE;
18382     Components.emplace_back(CTE, nullptr, IsNonContiguous);
18383     return true;
18384   }
18385   bool VisitCXXOperatorCallExpr(CXXOperatorCallExpr *COCE) {
18386     assert(!RelevantExpr && "RelevantExpr is expected to be nullptr");
18387     Components.emplace_back(COCE, nullptr, IsNonContiguous);
18388     return true;
18389   }
18390   bool VisitOpaqueValueExpr(OpaqueValueExpr *E) {
18391     Expr *Source = E->getSourceExpr();
18392     if (!Source) {
18393       emitErrorMsg();
18394       return false;
18395     }
18396     return Visit(Source);
18397   }
18398   bool VisitStmt(Stmt *) {
18399     emitErrorMsg();
18400     return false;
18401   }
18402   const Expr *getFoundBase() const {
18403     return RelevantExpr;
18404   }
18405   explicit MapBaseChecker(
18406       Sema &SemaRef, OpenMPClauseKind CKind, OpenMPDirectiveKind DKind,
18407       OMPClauseMappableExprCommon::MappableExprComponentList &Components,
18408       bool NoDiagnose, SourceLocation &ELoc, SourceRange &ERange)
18409       : SemaRef(SemaRef), CKind(CKind), DKind(DKind), Components(Components),
18410         NoDiagnose(NoDiagnose), ELoc(ELoc), ERange(ERange) {}
18411 };
18412 } // namespace
18413 
18414 /// Return the expression of the base of the mappable expression or null if it
18415 /// cannot be determined and do all the necessary checks to see if the expression
18416 /// is valid as a standalone mappable expression. In the process, record all the
18417 /// components of the expression.
18418 static const Expr *checkMapClauseExpressionBase(
18419     Sema &SemaRef, Expr *E,
18420     OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
18421     OpenMPClauseKind CKind, OpenMPDirectiveKind DKind, bool NoDiagnose) {
18422   SourceLocation ELoc = E->getExprLoc();
18423   SourceRange ERange = E->getSourceRange();
18424   MapBaseChecker Checker(SemaRef, CKind, DKind, CurComponents, NoDiagnose, ELoc,
18425                          ERange);
18426   if (Checker.Visit(E->IgnoreParens())) {
18427     // Check if the highest dimension array section has length specified
18428     if (SemaRef.getLangOpts().OpenMP >= 50 && !CurComponents.empty() &&
18429         (CKind == OMPC_to || CKind == OMPC_from)) {
18430       auto CI = CurComponents.rbegin();
18431       auto CE = CurComponents.rend();
18432       for (; CI != CE; ++CI) {
18433         const auto *OASE =
18434             dyn_cast<OMPArraySectionExpr>(CI->getAssociatedExpression());
18435         if (!OASE)
18436           continue;
18437         if (OASE && OASE->getLength())
18438           break;
18439         SemaRef.Diag(ELoc, diag::err_array_section_does_not_specify_length)
18440             << ERange;
18441       }
18442     }
18443     return Checker.getFoundBase();
18444   }
18445   return nullptr;
18446 }
18447 
18448 // Return true if expression E associated with value VD has conflicts with other
18449 // map information.
18450 static bool checkMapConflicts(
18451     Sema &SemaRef, DSAStackTy *DSAS, const ValueDecl *VD, const Expr *E,
18452     bool CurrentRegionOnly,
18453     OMPClauseMappableExprCommon::MappableExprComponentListRef CurComponents,
18454     OpenMPClauseKind CKind) {
18455   assert(VD && E);
18456   SourceLocation ELoc = E->getExprLoc();
18457   SourceRange ERange = E->getSourceRange();
18458 
18459   // In order to easily check the conflicts we need to match each component of
18460   // the expression under test with the components of the expressions that are
18461   // already in the stack.
18462 
18463   assert(!CurComponents.empty() && "Map clause expression with no components!");
18464   assert(CurComponents.back().getAssociatedDeclaration() == VD &&
18465          "Map clause expression with unexpected base!");
18466 
18467   // Variables to help detecting enclosing problems in data environment nests.
18468   bool IsEnclosedByDataEnvironmentExpr = false;
18469   const Expr *EnclosingExpr = nullptr;
18470 
18471   bool FoundError = DSAS->checkMappableExprComponentListsForDecl(
18472       VD, CurrentRegionOnly,
18473       [&IsEnclosedByDataEnvironmentExpr, &SemaRef, VD, CurrentRegionOnly, ELoc,
18474        ERange, CKind, &EnclosingExpr,
18475        CurComponents](OMPClauseMappableExprCommon::MappableExprComponentListRef
18476                           StackComponents,
18477                       OpenMPClauseKind Kind) {
18478         if (CKind == Kind && SemaRef.LangOpts.OpenMP >= 50)
18479           return false;
18480         assert(!StackComponents.empty() &&
18481                "Map clause expression with no components!");
18482         assert(StackComponents.back().getAssociatedDeclaration() == VD &&
18483                "Map clause expression with unexpected base!");
18484         (void)VD;
18485 
18486         // The whole expression in the stack.
18487         const Expr *RE = StackComponents.front().getAssociatedExpression();
18488 
18489         // Expressions must start from the same base. Here we detect at which
18490         // point both expressions diverge from each other and see if we can
18491         // detect if the memory referred to both expressions is contiguous and
18492         // do not overlap.
18493         auto CI = CurComponents.rbegin();
18494         auto CE = CurComponents.rend();
18495         auto SI = StackComponents.rbegin();
18496         auto SE = StackComponents.rend();
18497         for (; CI != CE && SI != SE; ++CI, ++SI) {
18498 
18499           // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.3]
18500           //  At most one list item can be an array item derived from a given
18501           //  variable in map clauses of the same construct.
18502           if (CurrentRegionOnly &&
18503               (isa<ArraySubscriptExpr>(CI->getAssociatedExpression()) ||
18504                isa<OMPArraySectionExpr>(CI->getAssociatedExpression()) ||
18505                isa<OMPArrayShapingExpr>(CI->getAssociatedExpression())) &&
18506               (isa<ArraySubscriptExpr>(SI->getAssociatedExpression()) ||
18507                isa<OMPArraySectionExpr>(SI->getAssociatedExpression()) ||
18508                isa<OMPArrayShapingExpr>(SI->getAssociatedExpression()))) {
18509             SemaRef.Diag(CI->getAssociatedExpression()->getExprLoc(),
18510                          diag::err_omp_multiple_array_items_in_map_clause)
18511                 << CI->getAssociatedExpression()->getSourceRange();
18512             SemaRef.Diag(SI->getAssociatedExpression()->getExprLoc(),
18513                          diag::note_used_here)
18514                 << SI->getAssociatedExpression()->getSourceRange();
18515             return true;
18516           }
18517 
18518           // Do both expressions have the same kind?
18519           if (CI->getAssociatedExpression()->getStmtClass() !=
18520               SI->getAssociatedExpression()->getStmtClass())
18521             break;
18522 
18523           // Are we dealing with different variables/fields?
18524           if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration())
18525             break;
18526         }
18527         // Check if the extra components of the expressions in the enclosing
18528         // data environment are redundant for the current base declaration.
18529         // If they are, the maps completely overlap, which is legal.
18530         for (; SI != SE; ++SI) {
18531           QualType Type;
18532           if (const auto *ASE =
18533                   dyn_cast<ArraySubscriptExpr>(SI->getAssociatedExpression())) {
18534             Type = ASE->getBase()->IgnoreParenImpCasts()->getType();
18535           } else if (const auto *OASE = dyn_cast<OMPArraySectionExpr>(
18536                          SI->getAssociatedExpression())) {
18537             const Expr *E = OASE->getBase()->IgnoreParenImpCasts();
18538             Type =
18539                 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
18540           } else if (const auto *OASE = dyn_cast<OMPArrayShapingExpr>(
18541                          SI->getAssociatedExpression())) {
18542             Type = OASE->getBase()->getType()->getPointeeType();
18543           }
18544           if (Type.isNull() || Type->isAnyPointerType() ||
18545               checkArrayExpressionDoesNotReferToWholeSize(
18546                   SemaRef, SI->getAssociatedExpression(), Type))
18547             break;
18548         }
18549 
18550         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
18551         //  List items of map clauses in the same construct must not share
18552         //  original storage.
18553         //
18554         // If the expressions are exactly the same or one is a subset of the
18555         // other, it means they are sharing storage.
18556         if (CI == CE && SI == SE) {
18557           if (CurrentRegionOnly) {
18558             if (CKind == OMPC_map) {
18559               SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
18560             } else {
18561               assert(CKind == OMPC_to || CKind == OMPC_from);
18562               SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
18563                   << ERange;
18564             }
18565             SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
18566                 << RE->getSourceRange();
18567             return true;
18568           }
18569           // If we find the same expression in the enclosing data environment,
18570           // that is legal.
18571           IsEnclosedByDataEnvironmentExpr = true;
18572           return false;
18573         }
18574 
18575         QualType DerivedType =
18576             std::prev(CI)->getAssociatedDeclaration()->getType();
18577         SourceLocation DerivedLoc =
18578             std::prev(CI)->getAssociatedExpression()->getExprLoc();
18579 
18580         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
18581         //  If the type of a list item is a reference to a type T then the type
18582         //  will be considered to be T for all purposes of this clause.
18583         DerivedType = DerivedType.getNonReferenceType();
18584 
18585         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.1]
18586         //  A variable for which the type is pointer and an array section
18587         //  derived from that variable must not appear as list items of map
18588         //  clauses of the same construct.
18589         //
18590         // Also, cover one of the cases in:
18591         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
18592         //  If any part of the original storage of a list item has corresponding
18593         //  storage in the device data environment, all of the original storage
18594         //  must have corresponding storage in the device data environment.
18595         //
18596         if (DerivedType->isAnyPointerType()) {
18597           if (CI == CE || SI == SE) {
18598             SemaRef.Diag(
18599                 DerivedLoc,
18600                 diag::err_omp_pointer_mapped_along_with_derived_section)
18601                 << DerivedLoc;
18602             SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
18603                 << RE->getSourceRange();
18604             return true;
18605           }
18606           if (CI->getAssociatedExpression()->getStmtClass() !=
18607                          SI->getAssociatedExpression()->getStmtClass() ||
18608                      CI->getAssociatedDeclaration()->getCanonicalDecl() ==
18609                          SI->getAssociatedDeclaration()->getCanonicalDecl()) {
18610             assert(CI != CE && SI != SE);
18611             SemaRef.Diag(DerivedLoc, diag::err_omp_same_pointer_dereferenced)
18612                 << DerivedLoc;
18613             SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
18614                 << RE->getSourceRange();
18615             return true;
18616           }
18617         }
18618 
18619         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
18620         //  List items of map clauses in the same construct must not share
18621         //  original storage.
18622         //
18623         // An expression is a subset of the other.
18624         if (CurrentRegionOnly && (CI == CE || SI == SE)) {
18625           if (CKind == OMPC_map) {
18626             if (CI != CE || SI != SE) {
18627               // Allow constructs like this: map(s, s.ptr[0:1]), where s.ptr is
18628               // a pointer.
18629               auto Begin =
18630                   CI != CE ? CurComponents.begin() : StackComponents.begin();
18631               auto End = CI != CE ? CurComponents.end() : StackComponents.end();
18632               auto It = Begin;
18633               while (It != End && !It->getAssociatedDeclaration())
18634                 std::advance(It, 1);
18635               assert(It != End &&
18636                      "Expected at least one component with the declaration.");
18637               if (It != Begin && It->getAssociatedDeclaration()
18638                                      ->getType()
18639                                      .getCanonicalType()
18640                                      ->isAnyPointerType()) {
18641                 IsEnclosedByDataEnvironmentExpr = false;
18642                 EnclosingExpr = nullptr;
18643                 return false;
18644               }
18645             }
18646             SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
18647           } else {
18648             assert(CKind == OMPC_to || CKind == OMPC_from);
18649             SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
18650                 << ERange;
18651           }
18652           SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
18653               << RE->getSourceRange();
18654           return true;
18655         }
18656 
18657         // The current expression uses the same base as other expression in the
18658         // data environment but does not contain it completely.
18659         if (!CurrentRegionOnly && SI != SE)
18660           EnclosingExpr = RE;
18661 
18662         // The current expression is a subset of the expression in the data
18663         // environment.
18664         IsEnclosedByDataEnvironmentExpr |=
18665             (!CurrentRegionOnly && CI != CE && SI == SE);
18666 
18667         return false;
18668       });
18669 
18670   if (CurrentRegionOnly)
18671     return FoundError;
18672 
18673   // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
18674   //  If any part of the original storage of a list item has corresponding
18675   //  storage in the device data environment, all of the original storage must
18676   //  have corresponding storage in the device data environment.
18677   // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.6]
18678   //  If a list item is an element of a structure, and a different element of
18679   //  the structure has a corresponding list item in the device data environment
18680   //  prior to a task encountering the construct associated with the map clause,
18681   //  then the list item must also have a corresponding list item in the device
18682   //  data environment prior to the task encountering the construct.
18683   //
18684   if (EnclosingExpr && !IsEnclosedByDataEnvironmentExpr) {
18685     SemaRef.Diag(ELoc,
18686                  diag::err_omp_original_storage_is_shared_and_does_not_contain)
18687         << ERange;
18688     SemaRef.Diag(EnclosingExpr->getExprLoc(), diag::note_used_here)
18689         << EnclosingExpr->getSourceRange();
18690     return true;
18691   }
18692 
18693   return FoundError;
18694 }
18695 
18696 // Look up the user-defined mapper given the mapper name and mapped type, and
18697 // build a reference to it.
18698 static ExprResult buildUserDefinedMapperRef(Sema &SemaRef, Scope *S,
18699                                             CXXScopeSpec &MapperIdScopeSpec,
18700                                             const DeclarationNameInfo &MapperId,
18701                                             QualType Type,
18702                                             Expr *UnresolvedMapper) {
18703   if (MapperIdScopeSpec.isInvalid())
18704     return ExprError();
18705   // Get the actual type for the array type.
18706   if (Type->isArrayType()) {
18707     assert(Type->getAsArrayTypeUnsafe() && "Expect to get a valid array type");
18708     Type = Type->getAsArrayTypeUnsafe()->getElementType().getCanonicalType();
18709   }
18710   // Find all user-defined mappers with the given MapperId.
18711   SmallVector<UnresolvedSet<8>, 4> Lookups;
18712   LookupResult Lookup(SemaRef, MapperId, Sema::LookupOMPMapperName);
18713   Lookup.suppressDiagnostics();
18714   if (S) {
18715     while (S && SemaRef.LookupParsedName(Lookup, S, &MapperIdScopeSpec)) {
18716       NamedDecl *D = Lookup.getRepresentativeDecl();
18717       while (S && !S->isDeclScope(D))
18718         S = S->getParent();
18719       if (S)
18720         S = S->getParent();
18721       Lookups.emplace_back();
18722       Lookups.back().append(Lookup.begin(), Lookup.end());
18723       Lookup.clear();
18724     }
18725   } else if (auto *ULE = cast_or_null<UnresolvedLookupExpr>(UnresolvedMapper)) {
18726     // Extract the user-defined mappers with the given MapperId.
18727     Lookups.push_back(UnresolvedSet<8>());
18728     for (NamedDecl *D : ULE->decls()) {
18729       auto *DMD = cast<OMPDeclareMapperDecl>(D);
18730       assert(DMD && "Expect valid OMPDeclareMapperDecl during instantiation.");
18731       Lookups.back().addDecl(DMD);
18732     }
18733   }
18734   // Defer the lookup for dependent types. The results will be passed through
18735   // UnresolvedMapper on instantiation.
18736   if (SemaRef.CurContext->isDependentContext() || Type->isDependentType() ||
18737       Type->isInstantiationDependentType() ||
18738       Type->containsUnexpandedParameterPack() ||
18739       filterLookupForUDReductionAndMapper<bool>(Lookups, [](ValueDecl *D) {
18740         return !D->isInvalidDecl() &&
18741                (D->getType()->isDependentType() ||
18742                 D->getType()->isInstantiationDependentType() ||
18743                 D->getType()->containsUnexpandedParameterPack());
18744       })) {
18745     UnresolvedSet<8> URS;
18746     for (const UnresolvedSet<8> &Set : Lookups) {
18747       if (Set.empty())
18748         continue;
18749       URS.append(Set.begin(), Set.end());
18750     }
18751     return UnresolvedLookupExpr::Create(
18752         SemaRef.Context, /*NamingClass=*/nullptr,
18753         MapperIdScopeSpec.getWithLocInContext(SemaRef.Context), MapperId,
18754         /*ADL=*/false, /*Overloaded=*/true, URS.begin(), URS.end());
18755   }
18756   SourceLocation Loc = MapperId.getLoc();
18757   // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
18758   //  The type must be of struct, union or class type in C and C++
18759   if (!Type->isStructureOrClassType() && !Type->isUnionType() &&
18760       (MapperIdScopeSpec.isSet() || MapperId.getAsString() != "default")) {
18761     SemaRef.Diag(Loc, diag::err_omp_mapper_wrong_type);
18762     return ExprError();
18763   }
18764   // Perform argument dependent lookup.
18765   if (SemaRef.getLangOpts().CPlusPlus && !MapperIdScopeSpec.isSet())
18766     argumentDependentLookup(SemaRef, MapperId, Loc, Type, Lookups);
18767   // Return the first user-defined mapper with the desired type.
18768   if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
18769           Lookups, [&SemaRef, Type](ValueDecl *D) -> ValueDecl * {
18770             if (!D->isInvalidDecl() &&
18771                 SemaRef.Context.hasSameType(D->getType(), Type))
18772               return D;
18773             return nullptr;
18774           }))
18775     return SemaRef.BuildDeclRefExpr(VD, Type, VK_LValue, Loc);
18776   // Find the first user-defined mapper with a type derived from the desired
18777   // type.
18778   if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
18779           Lookups, [&SemaRef, Type, Loc](ValueDecl *D) -> ValueDecl * {
18780             if (!D->isInvalidDecl() &&
18781                 SemaRef.IsDerivedFrom(Loc, Type, D->getType()) &&
18782                 !Type.isMoreQualifiedThan(D->getType()))
18783               return D;
18784             return nullptr;
18785           })) {
18786     CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
18787                        /*DetectVirtual=*/false);
18788     if (SemaRef.IsDerivedFrom(Loc, Type, VD->getType(), Paths)) {
18789       if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
18790               VD->getType().getUnqualifiedType()))) {
18791         if (SemaRef.CheckBaseClassAccess(
18792                 Loc, VD->getType(), Type, Paths.front(),
18793                 /*DiagID=*/0) != Sema::AR_inaccessible) {
18794           return SemaRef.BuildDeclRefExpr(VD, Type, VK_LValue, Loc);
18795         }
18796       }
18797     }
18798   }
18799   // Report error if a mapper is specified, but cannot be found.
18800   if (MapperIdScopeSpec.isSet() || MapperId.getAsString() != "default") {
18801     SemaRef.Diag(Loc, diag::err_omp_invalid_mapper)
18802         << Type << MapperId.getName();
18803     return ExprError();
18804   }
18805   return ExprEmpty();
18806 }
18807 
18808 namespace {
18809 // Utility struct that gathers all the related lists associated with a mappable
18810 // expression.
18811 struct MappableVarListInfo {
18812   // The list of expressions.
18813   ArrayRef<Expr *> VarList;
18814   // The list of processed expressions.
18815   SmallVector<Expr *, 16> ProcessedVarList;
18816   // The mappble components for each expression.
18817   OMPClauseMappableExprCommon::MappableExprComponentLists VarComponents;
18818   // The base declaration of the variable.
18819   SmallVector<ValueDecl *, 16> VarBaseDeclarations;
18820   // The reference to the user-defined mapper associated with every expression.
18821   SmallVector<Expr *, 16> UDMapperList;
18822 
18823   MappableVarListInfo(ArrayRef<Expr *> VarList) : VarList(VarList) {
18824     // We have a list of components and base declarations for each entry in the
18825     // variable list.
18826     VarComponents.reserve(VarList.size());
18827     VarBaseDeclarations.reserve(VarList.size());
18828   }
18829 };
18830 }
18831 
18832 // Check the validity of the provided variable list for the provided clause kind
18833 // \a CKind. In the check process the valid expressions, mappable expression
18834 // components, variables, and user-defined mappers are extracted and used to
18835 // fill \a ProcessedVarList, \a VarComponents, \a VarBaseDeclarations, and \a
18836 // UDMapperList in MVLI. \a MapType, \a IsMapTypeImplicit, \a MapperIdScopeSpec,
18837 // and \a MapperId are expected to be valid if the clause kind is 'map'.
18838 static void checkMappableExpressionList(
18839     Sema &SemaRef, DSAStackTy *DSAS, OpenMPClauseKind CKind,
18840     MappableVarListInfo &MVLI, SourceLocation StartLoc,
18841     CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo MapperId,
18842     ArrayRef<Expr *> UnresolvedMappers,
18843     OpenMPMapClauseKind MapType = OMPC_MAP_unknown,
18844     bool IsMapTypeImplicit = false) {
18845   // We only expect mappable expressions in 'to', 'from', and 'map' clauses.
18846   assert((CKind == OMPC_map || CKind == OMPC_to || CKind == OMPC_from) &&
18847          "Unexpected clause kind with mappable expressions!");
18848 
18849   // If the identifier of user-defined mapper is not specified, it is "default".
18850   // We do not change the actual name in this clause to distinguish whether a
18851   // mapper is specified explicitly, i.e., it is not explicitly specified when
18852   // MapperId.getName() is empty.
18853   if (!MapperId.getName() || MapperId.getName().isEmpty()) {
18854     auto &DeclNames = SemaRef.getASTContext().DeclarationNames;
18855     MapperId.setName(DeclNames.getIdentifier(
18856         &SemaRef.getASTContext().Idents.get("default")));
18857     MapperId.setLoc(StartLoc);
18858   }
18859 
18860   // Iterators to find the current unresolved mapper expression.
18861   auto UMIt = UnresolvedMappers.begin(), UMEnd = UnresolvedMappers.end();
18862   bool UpdateUMIt = false;
18863   Expr *UnresolvedMapper = nullptr;
18864 
18865   // Keep track of the mappable components and base declarations in this clause.
18866   // Each entry in the list is going to have a list of components associated. We
18867   // record each set of the components so that we can build the clause later on.
18868   // In the end we should have the same amount of declarations and component
18869   // lists.
18870 
18871   for (Expr *RE : MVLI.VarList) {
18872     assert(RE && "Null expr in omp to/from/map clause");
18873     SourceLocation ELoc = RE->getExprLoc();
18874 
18875     // Find the current unresolved mapper expression.
18876     if (UpdateUMIt && UMIt != UMEnd) {
18877       UMIt++;
18878       assert(
18879           UMIt != UMEnd &&
18880           "Expect the size of UnresolvedMappers to match with that of VarList");
18881     }
18882     UpdateUMIt = true;
18883     if (UMIt != UMEnd)
18884       UnresolvedMapper = *UMIt;
18885 
18886     const Expr *VE = RE->IgnoreParenLValueCasts();
18887 
18888     if (VE->isValueDependent() || VE->isTypeDependent() ||
18889         VE->isInstantiationDependent() ||
18890         VE->containsUnexpandedParameterPack()) {
18891       // Try to find the associated user-defined mapper.
18892       ExprResult ER = buildUserDefinedMapperRef(
18893           SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
18894           VE->getType().getCanonicalType(), UnresolvedMapper);
18895       if (ER.isInvalid())
18896         continue;
18897       MVLI.UDMapperList.push_back(ER.get());
18898       // We can only analyze this information once the missing information is
18899       // resolved.
18900       MVLI.ProcessedVarList.push_back(RE);
18901       continue;
18902     }
18903 
18904     Expr *SimpleExpr = RE->IgnoreParenCasts();
18905 
18906     if (!RE->isLValue()) {
18907       if (SemaRef.getLangOpts().OpenMP < 50) {
18908         SemaRef.Diag(
18909             ELoc, diag::err_omp_expected_named_var_member_or_array_expression)
18910             << RE->getSourceRange();
18911       } else {
18912         SemaRef.Diag(ELoc, diag::err_omp_non_lvalue_in_map_or_motion_clauses)
18913             << getOpenMPClauseName(CKind) << RE->getSourceRange();
18914       }
18915       continue;
18916     }
18917 
18918     OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
18919     ValueDecl *CurDeclaration = nullptr;
18920 
18921     // Obtain the array or member expression bases if required. Also, fill the
18922     // components array with all the components identified in the process.
18923     const Expr *BE = checkMapClauseExpressionBase(
18924         SemaRef, SimpleExpr, CurComponents, CKind, DSAS->getCurrentDirective(),
18925         /*NoDiagnose=*/false);
18926     if (!BE)
18927       continue;
18928 
18929     assert(!CurComponents.empty() &&
18930            "Invalid mappable expression information.");
18931 
18932     if (const auto *TE = dyn_cast<CXXThisExpr>(BE)) {
18933       // Add store "this" pointer to class in DSAStackTy for future checking
18934       DSAS->addMappedClassesQualTypes(TE->getType());
18935       // Try to find the associated user-defined mapper.
18936       ExprResult ER = buildUserDefinedMapperRef(
18937           SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
18938           VE->getType().getCanonicalType(), UnresolvedMapper);
18939       if (ER.isInvalid())
18940         continue;
18941       MVLI.UDMapperList.push_back(ER.get());
18942       // Skip restriction checking for variable or field declarations
18943       MVLI.ProcessedVarList.push_back(RE);
18944       MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
18945       MVLI.VarComponents.back().append(CurComponents.begin(),
18946                                        CurComponents.end());
18947       MVLI.VarBaseDeclarations.push_back(nullptr);
18948       continue;
18949     }
18950 
18951     // For the following checks, we rely on the base declaration which is
18952     // expected to be associated with the last component. The declaration is
18953     // expected to be a variable or a field (if 'this' is being mapped).
18954     CurDeclaration = CurComponents.back().getAssociatedDeclaration();
18955     assert(CurDeclaration && "Null decl on map clause.");
18956     assert(
18957         CurDeclaration->isCanonicalDecl() &&
18958         "Expecting components to have associated only canonical declarations.");
18959 
18960     auto *VD = dyn_cast<VarDecl>(CurDeclaration);
18961     const auto *FD = dyn_cast<FieldDecl>(CurDeclaration);
18962 
18963     assert((VD || FD) && "Only variables or fields are expected here!");
18964     (void)FD;
18965 
18966     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.10]
18967     // threadprivate variables cannot appear in a map clause.
18968     // OpenMP 4.5 [2.10.5, target update Construct]
18969     // threadprivate variables cannot appear in a from clause.
18970     if (VD && DSAS->isThreadPrivate(VD)) {
18971       DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false);
18972       SemaRef.Diag(ELoc, diag::err_omp_threadprivate_in_clause)
18973           << getOpenMPClauseName(CKind);
18974       reportOriginalDsa(SemaRef, DSAS, VD, DVar);
18975       continue;
18976     }
18977 
18978     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
18979     //  A list item cannot appear in both a map clause and a data-sharing
18980     //  attribute clause on the same construct.
18981 
18982     // Check conflicts with other map clause expressions. We check the conflicts
18983     // with the current construct separately from the enclosing data
18984     // environment, because the restrictions are different. We only have to
18985     // check conflicts across regions for the map clauses.
18986     if (checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
18987                           /*CurrentRegionOnly=*/true, CurComponents, CKind))
18988       break;
18989     if (CKind == OMPC_map &&
18990         (SemaRef.getLangOpts().OpenMP <= 45 || StartLoc.isValid()) &&
18991         checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
18992                           /*CurrentRegionOnly=*/false, CurComponents, CKind))
18993       break;
18994 
18995     // OpenMP 4.5 [2.10.5, target update Construct]
18996     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
18997     //  If the type of a list item is a reference to a type T then the type will
18998     //  be considered to be T for all purposes of this clause.
18999     auto I = llvm::find_if(
19000         CurComponents,
19001         [](const OMPClauseMappableExprCommon::MappableComponent &MC) {
19002           return MC.getAssociatedDeclaration();
19003         });
19004     assert(I != CurComponents.end() && "Null decl on map clause.");
19005     (void)I;
19006     QualType Type;
19007     auto *ASE = dyn_cast<ArraySubscriptExpr>(VE->IgnoreParens());
19008     auto *OASE = dyn_cast<OMPArraySectionExpr>(VE->IgnoreParens());
19009     auto *OAShE = dyn_cast<OMPArrayShapingExpr>(VE->IgnoreParens());
19010     if (ASE) {
19011       Type = ASE->getType().getNonReferenceType();
19012     } else if (OASE) {
19013       QualType BaseType =
19014           OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
19015       if (const auto *ATy = BaseType->getAsArrayTypeUnsafe())
19016         Type = ATy->getElementType();
19017       else
19018         Type = BaseType->getPointeeType();
19019       Type = Type.getNonReferenceType();
19020     } else if (OAShE) {
19021       Type = OAShE->getBase()->getType()->getPointeeType();
19022     } else {
19023       Type = VE->getType();
19024     }
19025 
19026     // OpenMP 4.5 [2.10.5, target update Construct, Restrictions, p.4]
19027     // A list item in a to or from clause must have a mappable type.
19028     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
19029     //  A list item must have a mappable type.
19030     if (!checkTypeMappable(VE->getExprLoc(), VE->getSourceRange(), SemaRef,
19031                            DSAS, Type))
19032       continue;
19033 
19034     if (CKind == OMPC_map) {
19035       // target enter data
19036       // OpenMP [2.10.2, Restrictions, p. 99]
19037       // A map-type must be specified in all map clauses and must be either
19038       // to or alloc.
19039       OpenMPDirectiveKind DKind = DSAS->getCurrentDirective();
19040       if (DKind == OMPD_target_enter_data &&
19041           !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_alloc)) {
19042         SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
19043             << (IsMapTypeImplicit ? 1 : 0)
19044             << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
19045             << getOpenMPDirectiveName(DKind);
19046         continue;
19047       }
19048 
19049       // target exit_data
19050       // OpenMP [2.10.3, Restrictions, p. 102]
19051       // A map-type must be specified in all map clauses and must be either
19052       // from, release, or delete.
19053       if (DKind == OMPD_target_exit_data &&
19054           !(MapType == OMPC_MAP_from || MapType == OMPC_MAP_release ||
19055             MapType == OMPC_MAP_delete)) {
19056         SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
19057             << (IsMapTypeImplicit ? 1 : 0)
19058             << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
19059             << getOpenMPDirectiveName(DKind);
19060         continue;
19061       }
19062 
19063       // target, target data
19064       // OpenMP 5.0 [2.12.2, Restrictions, p. 163]
19065       // OpenMP 5.0 [2.12.5, Restrictions, p. 174]
19066       // A map-type in a map clause must be to, from, tofrom or alloc
19067       if ((DKind == OMPD_target_data ||
19068            isOpenMPTargetExecutionDirective(DKind)) &&
19069           !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_from ||
19070             MapType == OMPC_MAP_tofrom || MapType == OMPC_MAP_alloc)) {
19071         SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
19072             << (IsMapTypeImplicit ? 1 : 0)
19073             << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
19074             << getOpenMPDirectiveName(DKind);
19075         continue;
19076       }
19077 
19078       // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
19079       // A list item cannot appear in both a map clause and a data-sharing
19080       // attribute clause on the same construct
19081       //
19082       // OpenMP 5.0 [2.19.7.1, Restrictions, p.7]
19083       // A list item cannot appear in both a map clause and a data-sharing
19084       // attribute clause on the same construct unless the construct is a
19085       // combined construct.
19086       if (VD && ((SemaRef.LangOpts.OpenMP <= 45 &&
19087                   isOpenMPTargetExecutionDirective(DKind)) ||
19088                  DKind == OMPD_target)) {
19089         DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false);
19090         if (isOpenMPPrivate(DVar.CKind)) {
19091           SemaRef.Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
19092               << getOpenMPClauseName(DVar.CKind)
19093               << getOpenMPClauseName(OMPC_map)
19094               << getOpenMPDirectiveName(DSAS->getCurrentDirective());
19095           reportOriginalDsa(SemaRef, DSAS, CurDeclaration, DVar);
19096           continue;
19097         }
19098       }
19099     }
19100 
19101     // Try to find the associated user-defined mapper.
19102     ExprResult ER = buildUserDefinedMapperRef(
19103         SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
19104         Type.getCanonicalType(), UnresolvedMapper);
19105     if (ER.isInvalid())
19106       continue;
19107     MVLI.UDMapperList.push_back(ER.get());
19108 
19109     // Save the current expression.
19110     MVLI.ProcessedVarList.push_back(RE);
19111 
19112     // Store the components in the stack so that they can be used to check
19113     // against other clauses later on.
19114     DSAS->addMappableExpressionComponents(CurDeclaration, CurComponents,
19115                                           /*WhereFoundClauseKind=*/OMPC_map);
19116 
19117     // Save the components and declaration to create the clause. For purposes of
19118     // the clause creation, any component list that has has base 'this' uses
19119     // null as base declaration.
19120     MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
19121     MVLI.VarComponents.back().append(CurComponents.begin(),
19122                                      CurComponents.end());
19123     MVLI.VarBaseDeclarations.push_back(isa<MemberExpr>(BE) ? nullptr
19124                                                            : CurDeclaration);
19125   }
19126 }
19127 
19128 OMPClause *Sema::ActOnOpenMPMapClause(
19129     ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
19130     ArrayRef<SourceLocation> MapTypeModifiersLoc,
19131     CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo &MapperId,
19132     OpenMPMapClauseKind MapType, bool IsMapTypeImplicit, SourceLocation MapLoc,
19133     SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
19134     const OMPVarListLocTy &Locs, ArrayRef<Expr *> UnresolvedMappers) {
19135   OpenMPMapModifierKind Modifiers[] = {
19136       OMPC_MAP_MODIFIER_unknown, OMPC_MAP_MODIFIER_unknown,
19137       OMPC_MAP_MODIFIER_unknown, OMPC_MAP_MODIFIER_unknown};
19138   SourceLocation ModifiersLoc[NumberOfOMPMapClauseModifiers];
19139 
19140   // Process map-type-modifiers, flag errors for duplicate modifiers.
19141   unsigned Count = 0;
19142   for (unsigned I = 0, E = MapTypeModifiers.size(); I < E; ++I) {
19143     if (MapTypeModifiers[I] != OMPC_MAP_MODIFIER_unknown &&
19144         llvm::find(Modifiers, MapTypeModifiers[I]) != std::end(Modifiers)) {
19145       Diag(MapTypeModifiersLoc[I], diag::err_omp_duplicate_map_type_modifier);
19146       continue;
19147     }
19148     assert(Count < NumberOfOMPMapClauseModifiers &&
19149            "Modifiers exceed the allowed number of map type modifiers");
19150     Modifiers[Count] = MapTypeModifiers[I];
19151     ModifiersLoc[Count] = MapTypeModifiersLoc[I];
19152     ++Count;
19153   }
19154 
19155   MappableVarListInfo MVLI(VarList);
19156   checkMappableExpressionList(*this, DSAStack, OMPC_map, MVLI, Locs.StartLoc,
19157                               MapperIdScopeSpec, MapperId, UnresolvedMappers,
19158                               MapType, IsMapTypeImplicit);
19159 
19160   // We need to produce a map clause even if we don't have variables so that
19161   // other diagnostics related with non-existing map clauses are accurate.
19162   return OMPMapClause::Create(Context, Locs, MVLI.ProcessedVarList,
19163                               MVLI.VarBaseDeclarations, MVLI.VarComponents,
19164                               MVLI.UDMapperList, Modifiers, ModifiersLoc,
19165                               MapperIdScopeSpec.getWithLocInContext(Context),
19166                               MapperId, MapType, IsMapTypeImplicit, MapLoc);
19167 }
19168 
19169 QualType Sema::ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
19170                                                TypeResult ParsedType) {
19171   assert(ParsedType.isUsable());
19172 
19173   QualType ReductionType = GetTypeFromParser(ParsedType.get());
19174   if (ReductionType.isNull())
19175     return QualType();
19176 
19177   // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions, C\C++
19178   // A type name in a declare reduction directive cannot be a function type, an
19179   // array type, a reference type, or a type qualified with const, volatile or
19180   // restrict.
19181   if (ReductionType.hasQualifiers()) {
19182     Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 0;
19183     return QualType();
19184   }
19185 
19186   if (ReductionType->isFunctionType()) {
19187     Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 1;
19188     return QualType();
19189   }
19190   if (ReductionType->isReferenceType()) {
19191     Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 2;
19192     return QualType();
19193   }
19194   if (ReductionType->isArrayType()) {
19195     Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 3;
19196     return QualType();
19197   }
19198   return ReductionType;
19199 }
19200 
19201 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveStart(
19202     Scope *S, DeclContext *DC, DeclarationName Name,
19203     ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
19204     AccessSpecifier AS, Decl *PrevDeclInScope) {
19205   SmallVector<Decl *, 8> Decls;
19206   Decls.reserve(ReductionTypes.size());
19207 
19208   LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPReductionName,
19209                       forRedeclarationInCurContext());
19210   // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
19211   // A reduction-identifier may not be re-declared in the current scope for the
19212   // same type or for a type that is compatible according to the base language
19213   // rules.
19214   llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
19215   OMPDeclareReductionDecl *PrevDRD = nullptr;
19216   bool InCompoundScope = true;
19217   if (S != nullptr) {
19218     // Find previous declaration with the same name not referenced in other
19219     // declarations.
19220     FunctionScopeInfo *ParentFn = getEnclosingFunction();
19221     InCompoundScope =
19222         (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
19223     LookupName(Lookup, S);
19224     FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
19225                          /*AllowInlineNamespace=*/false);
19226     llvm::DenseMap<OMPDeclareReductionDecl *, bool> UsedAsPrevious;
19227     LookupResult::Filter Filter = Lookup.makeFilter();
19228     while (Filter.hasNext()) {
19229       auto *PrevDecl = cast<OMPDeclareReductionDecl>(Filter.next());
19230       if (InCompoundScope) {
19231         auto I = UsedAsPrevious.find(PrevDecl);
19232         if (I == UsedAsPrevious.end())
19233           UsedAsPrevious[PrevDecl] = false;
19234         if (OMPDeclareReductionDecl *D = PrevDecl->getPrevDeclInScope())
19235           UsedAsPrevious[D] = true;
19236       }
19237       PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
19238           PrevDecl->getLocation();
19239     }
19240     Filter.done();
19241     if (InCompoundScope) {
19242       for (const auto &PrevData : UsedAsPrevious) {
19243         if (!PrevData.second) {
19244           PrevDRD = PrevData.first;
19245           break;
19246         }
19247       }
19248     }
19249   } else if (PrevDeclInScope != nullptr) {
19250     auto *PrevDRDInScope = PrevDRD =
19251         cast<OMPDeclareReductionDecl>(PrevDeclInScope);
19252     do {
19253       PreviousRedeclTypes[PrevDRDInScope->getType().getCanonicalType()] =
19254           PrevDRDInScope->getLocation();
19255       PrevDRDInScope = PrevDRDInScope->getPrevDeclInScope();
19256     } while (PrevDRDInScope != nullptr);
19257   }
19258   for (const auto &TyData : ReductionTypes) {
19259     const auto I = PreviousRedeclTypes.find(TyData.first.getCanonicalType());
19260     bool Invalid = false;
19261     if (I != PreviousRedeclTypes.end()) {
19262       Diag(TyData.second, diag::err_omp_declare_reduction_redefinition)
19263           << TyData.first;
19264       Diag(I->second, diag::note_previous_definition);
19265       Invalid = true;
19266     }
19267     PreviousRedeclTypes[TyData.first.getCanonicalType()] = TyData.second;
19268     auto *DRD = OMPDeclareReductionDecl::Create(Context, DC, TyData.second,
19269                                                 Name, TyData.first, PrevDRD);
19270     DC->addDecl(DRD);
19271     DRD->setAccess(AS);
19272     Decls.push_back(DRD);
19273     if (Invalid)
19274       DRD->setInvalidDecl();
19275     else
19276       PrevDRD = DRD;
19277   }
19278 
19279   return DeclGroupPtrTy::make(
19280       DeclGroupRef::Create(Context, Decls.begin(), Decls.size()));
19281 }
19282 
19283 void Sema::ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D) {
19284   auto *DRD = cast<OMPDeclareReductionDecl>(D);
19285 
19286   // Enter new function scope.
19287   PushFunctionScope();
19288   setFunctionHasBranchProtectedScope();
19289   getCurFunction()->setHasOMPDeclareReductionCombiner();
19290 
19291   if (S != nullptr)
19292     PushDeclContext(S, DRD);
19293   else
19294     CurContext = DRD;
19295 
19296   PushExpressionEvaluationContext(
19297       ExpressionEvaluationContext::PotentiallyEvaluated);
19298 
19299   QualType ReductionType = DRD->getType();
19300   // Create 'T* omp_parm;T omp_in;'. All references to 'omp_in' will
19301   // be replaced by '*omp_parm' during codegen. This required because 'omp_in'
19302   // uses semantics of argument handles by value, but it should be passed by
19303   // reference. C lang does not support references, so pass all parameters as
19304   // pointers.
19305   // Create 'T omp_in;' variable.
19306   VarDecl *OmpInParm =
19307       buildVarDecl(*this, D->getLocation(), ReductionType, "omp_in");
19308   // Create 'T* omp_parm;T omp_out;'. All references to 'omp_out' will
19309   // be replaced by '*omp_parm' during codegen. This required because 'omp_out'
19310   // uses semantics of argument handles by value, but it should be passed by
19311   // reference. C lang does not support references, so pass all parameters as
19312   // pointers.
19313   // Create 'T omp_out;' variable.
19314   VarDecl *OmpOutParm =
19315       buildVarDecl(*this, D->getLocation(), ReductionType, "omp_out");
19316   if (S != nullptr) {
19317     PushOnScopeChains(OmpInParm, S);
19318     PushOnScopeChains(OmpOutParm, S);
19319   } else {
19320     DRD->addDecl(OmpInParm);
19321     DRD->addDecl(OmpOutParm);
19322   }
19323   Expr *InE =
19324       ::buildDeclRefExpr(*this, OmpInParm, ReductionType, D->getLocation());
19325   Expr *OutE =
19326       ::buildDeclRefExpr(*this, OmpOutParm, ReductionType, D->getLocation());
19327   DRD->setCombinerData(InE, OutE);
19328 }
19329 
19330 void Sema::ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner) {
19331   auto *DRD = cast<OMPDeclareReductionDecl>(D);
19332   DiscardCleanupsInEvaluationContext();
19333   PopExpressionEvaluationContext();
19334 
19335   PopDeclContext();
19336   PopFunctionScopeInfo();
19337 
19338   if (Combiner != nullptr)
19339     DRD->setCombiner(Combiner);
19340   else
19341     DRD->setInvalidDecl();
19342 }
19343 
19344 VarDecl *Sema::ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D) {
19345   auto *DRD = cast<OMPDeclareReductionDecl>(D);
19346 
19347   // Enter new function scope.
19348   PushFunctionScope();
19349   setFunctionHasBranchProtectedScope();
19350 
19351   if (S != nullptr)
19352     PushDeclContext(S, DRD);
19353   else
19354     CurContext = DRD;
19355 
19356   PushExpressionEvaluationContext(
19357       ExpressionEvaluationContext::PotentiallyEvaluated);
19358 
19359   QualType ReductionType = DRD->getType();
19360   // Create 'T* omp_parm;T omp_priv;'. All references to 'omp_priv' will
19361   // be replaced by '*omp_parm' during codegen. This required because 'omp_priv'
19362   // uses semantics of argument handles by value, but it should be passed by
19363   // reference. C lang does not support references, so pass all parameters as
19364   // pointers.
19365   // Create 'T omp_priv;' variable.
19366   VarDecl *OmpPrivParm =
19367       buildVarDecl(*this, D->getLocation(), ReductionType, "omp_priv");
19368   // Create 'T* omp_parm;T omp_orig;'. All references to 'omp_orig' will
19369   // be replaced by '*omp_parm' during codegen. This required because 'omp_orig'
19370   // uses semantics of argument handles by value, but it should be passed by
19371   // reference. C lang does not support references, so pass all parameters as
19372   // pointers.
19373   // Create 'T omp_orig;' variable.
19374   VarDecl *OmpOrigParm =
19375       buildVarDecl(*this, D->getLocation(), ReductionType, "omp_orig");
19376   if (S != nullptr) {
19377     PushOnScopeChains(OmpPrivParm, S);
19378     PushOnScopeChains(OmpOrigParm, S);
19379   } else {
19380     DRD->addDecl(OmpPrivParm);
19381     DRD->addDecl(OmpOrigParm);
19382   }
19383   Expr *OrigE =
19384       ::buildDeclRefExpr(*this, OmpOrigParm, ReductionType, D->getLocation());
19385   Expr *PrivE =
19386       ::buildDeclRefExpr(*this, OmpPrivParm, ReductionType, D->getLocation());
19387   DRD->setInitializerData(OrigE, PrivE);
19388   return OmpPrivParm;
19389 }
19390 
19391 void Sema::ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer,
19392                                                      VarDecl *OmpPrivParm) {
19393   auto *DRD = cast<OMPDeclareReductionDecl>(D);
19394   DiscardCleanupsInEvaluationContext();
19395   PopExpressionEvaluationContext();
19396 
19397   PopDeclContext();
19398   PopFunctionScopeInfo();
19399 
19400   if (Initializer != nullptr) {
19401     DRD->setInitializer(Initializer, OMPDeclareReductionDecl::CallInit);
19402   } else if (OmpPrivParm->hasInit()) {
19403     DRD->setInitializer(OmpPrivParm->getInit(),
19404                         OmpPrivParm->isDirectInit()
19405                             ? OMPDeclareReductionDecl::DirectInit
19406                             : OMPDeclareReductionDecl::CopyInit);
19407   } else {
19408     DRD->setInvalidDecl();
19409   }
19410 }
19411 
19412 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveEnd(
19413     Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid) {
19414   for (Decl *D : DeclReductions.get()) {
19415     if (IsValid) {
19416       if (S)
19417         PushOnScopeChains(cast<OMPDeclareReductionDecl>(D), S,
19418                           /*AddToContext=*/false);
19419     } else {
19420       D->setInvalidDecl();
19421     }
19422   }
19423   return DeclReductions;
19424 }
19425 
19426 TypeResult Sema::ActOnOpenMPDeclareMapperVarDecl(Scope *S, Declarator &D) {
19427   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
19428   QualType T = TInfo->getType();
19429   if (D.isInvalidType())
19430     return true;
19431 
19432   if (getLangOpts().CPlusPlus) {
19433     // Check that there are no default arguments (C++ only).
19434     CheckExtraCXXDefaultArguments(D);
19435   }
19436 
19437   return CreateParsedType(T, TInfo);
19438 }
19439 
19440 QualType Sema::ActOnOpenMPDeclareMapperType(SourceLocation TyLoc,
19441                                             TypeResult ParsedType) {
19442   assert(ParsedType.isUsable() && "Expect usable parsed mapper type");
19443 
19444   QualType MapperType = GetTypeFromParser(ParsedType.get());
19445   assert(!MapperType.isNull() && "Expect valid mapper type");
19446 
19447   // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
19448   //  The type must be of struct, union or class type in C and C++
19449   if (!MapperType->isStructureOrClassType() && !MapperType->isUnionType()) {
19450     Diag(TyLoc, diag::err_omp_mapper_wrong_type);
19451     return QualType();
19452   }
19453   return MapperType;
19454 }
19455 
19456 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareMapperDirective(
19457     Scope *S, DeclContext *DC, DeclarationName Name, QualType MapperType,
19458     SourceLocation StartLoc, DeclarationName VN, AccessSpecifier AS,
19459     Expr *MapperVarRef, ArrayRef<OMPClause *> Clauses, Decl *PrevDeclInScope) {
19460   LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPMapperName,
19461                       forRedeclarationInCurContext());
19462   // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
19463   //  A mapper-identifier may not be redeclared in the current scope for the
19464   //  same type or for a type that is compatible according to the base language
19465   //  rules.
19466   llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
19467   OMPDeclareMapperDecl *PrevDMD = nullptr;
19468   bool InCompoundScope = true;
19469   if (S != nullptr) {
19470     // Find previous declaration with the same name not referenced in other
19471     // declarations.
19472     FunctionScopeInfo *ParentFn = getEnclosingFunction();
19473     InCompoundScope =
19474         (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
19475     LookupName(Lookup, S);
19476     FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
19477                          /*AllowInlineNamespace=*/false);
19478     llvm::DenseMap<OMPDeclareMapperDecl *, bool> UsedAsPrevious;
19479     LookupResult::Filter Filter = Lookup.makeFilter();
19480     while (Filter.hasNext()) {
19481       auto *PrevDecl = cast<OMPDeclareMapperDecl>(Filter.next());
19482       if (InCompoundScope) {
19483         auto I = UsedAsPrevious.find(PrevDecl);
19484         if (I == UsedAsPrevious.end())
19485           UsedAsPrevious[PrevDecl] = false;
19486         if (OMPDeclareMapperDecl *D = PrevDecl->getPrevDeclInScope())
19487           UsedAsPrevious[D] = true;
19488       }
19489       PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
19490           PrevDecl->getLocation();
19491     }
19492     Filter.done();
19493     if (InCompoundScope) {
19494       for (const auto &PrevData : UsedAsPrevious) {
19495         if (!PrevData.second) {
19496           PrevDMD = PrevData.first;
19497           break;
19498         }
19499       }
19500     }
19501   } else if (PrevDeclInScope) {
19502     auto *PrevDMDInScope = PrevDMD =
19503         cast<OMPDeclareMapperDecl>(PrevDeclInScope);
19504     do {
19505       PreviousRedeclTypes[PrevDMDInScope->getType().getCanonicalType()] =
19506           PrevDMDInScope->getLocation();
19507       PrevDMDInScope = PrevDMDInScope->getPrevDeclInScope();
19508     } while (PrevDMDInScope != nullptr);
19509   }
19510   const auto I = PreviousRedeclTypes.find(MapperType.getCanonicalType());
19511   bool Invalid = false;
19512   if (I != PreviousRedeclTypes.end()) {
19513     Diag(StartLoc, diag::err_omp_declare_mapper_redefinition)
19514         << MapperType << Name;
19515     Diag(I->second, diag::note_previous_definition);
19516     Invalid = true;
19517   }
19518   // Build expressions for implicit maps of data members with 'default'
19519   // mappers.
19520   SmallVector<OMPClause *, 4> ClausesWithImplicit(Clauses.begin(),
19521                                                   Clauses.end());
19522   if (LangOpts.OpenMP >= 50)
19523     processImplicitMapsWithDefaultMappers(*this, DSAStack, ClausesWithImplicit);
19524   auto *DMD =
19525       OMPDeclareMapperDecl::Create(Context, DC, StartLoc, Name, MapperType, VN,
19526                                    ClausesWithImplicit, PrevDMD);
19527   if (S)
19528     PushOnScopeChains(DMD, S);
19529   else
19530     DC->addDecl(DMD);
19531   DMD->setAccess(AS);
19532   if (Invalid)
19533     DMD->setInvalidDecl();
19534 
19535   auto *VD = cast<DeclRefExpr>(MapperVarRef)->getDecl();
19536   VD->setDeclContext(DMD);
19537   VD->setLexicalDeclContext(DMD);
19538   DMD->addDecl(VD);
19539   DMD->setMapperVarRef(MapperVarRef);
19540 
19541   return DeclGroupPtrTy::make(DeclGroupRef(DMD));
19542 }
19543 
19544 ExprResult
19545 Sema::ActOnOpenMPDeclareMapperDirectiveVarDecl(Scope *S, QualType MapperType,
19546                                                SourceLocation StartLoc,
19547                                                DeclarationName VN) {
19548   TypeSourceInfo *TInfo =
19549       Context.getTrivialTypeSourceInfo(MapperType, StartLoc);
19550   auto *VD = VarDecl::Create(Context, Context.getTranslationUnitDecl(),
19551                              StartLoc, StartLoc, VN.getAsIdentifierInfo(),
19552                              MapperType, TInfo, SC_None);
19553   if (S)
19554     PushOnScopeChains(VD, S, /*AddToContext=*/false);
19555   Expr *E = buildDeclRefExpr(*this, VD, MapperType, StartLoc);
19556   DSAStack->addDeclareMapperVarRef(E);
19557   return E;
19558 }
19559 
19560 bool Sema::isOpenMPDeclareMapperVarDeclAllowed(const VarDecl *VD) const {
19561   assert(LangOpts.OpenMP && "Expected OpenMP mode.");
19562   const Expr *Ref = DSAStack->getDeclareMapperVarRef();
19563   if (const auto *DRE = cast_or_null<DeclRefExpr>(Ref))
19564     return VD->getCanonicalDecl() == DRE->getDecl()->getCanonicalDecl();
19565   return true;
19566 }
19567 
19568 const ValueDecl *Sema::getOpenMPDeclareMapperVarName() const {
19569   assert(LangOpts.OpenMP && "Expected OpenMP mode.");
19570   return cast<DeclRefExpr>(DSAStack->getDeclareMapperVarRef())->getDecl();
19571 }
19572 
19573 OMPClause *Sema::ActOnOpenMPNumTeamsClause(Expr *NumTeams,
19574                                            SourceLocation StartLoc,
19575                                            SourceLocation LParenLoc,
19576                                            SourceLocation EndLoc) {
19577   Expr *ValExpr = NumTeams;
19578   Stmt *HelperValStmt = nullptr;
19579 
19580   // OpenMP [teams Constrcut, Restrictions]
19581   // The num_teams expression must evaluate to a positive integer value.
19582   if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_teams,
19583                                  /*StrictlyPositive=*/true))
19584     return nullptr;
19585 
19586   OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
19587   OpenMPDirectiveKind CaptureRegion =
19588       getOpenMPCaptureRegionForClause(DKind, OMPC_num_teams, LangOpts.OpenMP);
19589   if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
19590     ValExpr = MakeFullExpr(ValExpr).get();
19591     llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
19592     ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
19593     HelperValStmt = buildPreInits(Context, Captures);
19594   }
19595 
19596   return new (Context) OMPNumTeamsClause(ValExpr, HelperValStmt, CaptureRegion,
19597                                          StartLoc, LParenLoc, EndLoc);
19598 }
19599 
19600 OMPClause *Sema::ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
19601                                               SourceLocation StartLoc,
19602                                               SourceLocation LParenLoc,
19603                                               SourceLocation EndLoc) {
19604   Expr *ValExpr = ThreadLimit;
19605   Stmt *HelperValStmt = nullptr;
19606 
19607   // OpenMP [teams Constrcut, Restrictions]
19608   // The thread_limit expression must evaluate to a positive integer value.
19609   if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_thread_limit,
19610                                  /*StrictlyPositive=*/true))
19611     return nullptr;
19612 
19613   OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
19614   OpenMPDirectiveKind CaptureRegion = getOpenMPCaptureRegionForClause(
19615       DKind, OMPC_thread_limit, LangOpts.OpenMP);
19616   if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
19617     ValExpr = MakeFullExpr(ValExpr).get();
19618     llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
19619     ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
19620     HelperValStmt = buildPreInits(Context, Captures);
19621   }
19622 
19623   return new (Context) OMPThreadLimitClause(
19624       ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
19625 }
19626 
19627 OMPClause *Sema::ActOnOpenMPPriorityClause(Expr *Priority,
19628                                            SourceLocation StartLoc,
19629                                            SourceLocation LParenLoc,
19630                                            SourceLocation EndLoc) {
19631   Expr *ValExpr = Priority;
19632   Stmt *HelperValStmt = nullptr;
19633   OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
19634 
19635   // OpenMP [2.9.1, task Constrcut]
19636   // The priority-value is a non-negative numerical scalar expression.
19637   if (!isNonNegativeIntegerValue(
19638           ValExpr, *this, OMPC_priority,
19639           /*StrictlyPositive=*/false, /*BuildCapture=*/true,
19640           DSAStack->getCurrentDirective(), &CaptureRegion, &HelperValStmt))
19641     return nullptr;
19642 
19643   return new (Context) OMPPriorityClause(ValExpr, HelperValStmt, CaptureRegion,
19644                                          StartLoc, LParenLoc, EndLoc);
19645 }
19646 
19647 OMPClause *Sema::ActOnOpenMPGrainsizeClause(Expr *Grainsize,
19648                                             SourceLocation StartLoc,
19649                                             SourceLocation LParenLoc,
19650                                             SourceLocation EndLoc) {
19651   Expr *ValExpr = Grainsize;
19652   Stmt *HelperValStmt = nullptr;
19653   OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
19654 
19655   // OpenMP [2.9.2, taskloop Constrcut]
19656   // The parameter of the grainsize clause must be a positive integer
19657   // expression.
19658   if (!isNonNegativeIntegerValue(
19659           ValExpr, *this, OMPC_grainsize,
19660           /*StrictlyPositive=*/true, /*BuildCapture=*/true,
19661           DSAStack->getCurrentDirective(), &CaptureRegion, &HelperValStmt))
19662     return nullptr;
19663 
19664   return new (Context) OMPGrainsizeClause(ValExpr, HelperValStmt, CaptureRegion,
19665                                           StartLoc, LParenLoc, EndLoc);
19666 }
19667 
19668 OMPClause *Sema::ActOnOpenMPNumTasksClause(Expr *NumTasks,
19669                                            SourceLocation StartLoc,
19670                                            SourceLocation LParenLoc,
19671                                            SourceLocation EndLoc) {
19672   Expr *ValExpr = NumTasks;
19673   Stmt *HelperValStmt = nullptr;
19674   OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
19675 
19676   // OpenMP [2.9.2, taskloop Constrcut]
19677   // The parameter of the num_tasks clause must be a positive integer
19678   // expression.
19679   if (!isNonNegativeIntegerValue(
19680           ValExpr, *this, OMPC_num_tasks,
19681           /*StrictlyPositive=*/true, /*BuildCapture=*/true,
19682           DSAStack->getCurrentDirective(), &CaptureRegion, &HelperValStmt))
19683     return nullptr;
19684 
19685   return new (Context) OMPNumTasksClause(ValExpr, HelperValStmt, CaptureRegion,
19686                                          StartLoc, LParenLoc, EndLoc);
19687 }
19688 
19689 OMPClause *Sema::ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
19690                                        SourceLocation LParenLoc,
19691                                        SourceLocation EndLoc) {
19692   // OpenMP [2.13.2, critical construct, Description]
19693   // ... where hint-expression is an integer constant expression that evaluates
19694   // to a valid lock hint.
19695   ExprResult HintExpr = VerifyPositiveIntegerConstantInClause(Hint, OMPC_hint);
19696   if (HintExpr.isInvalid())
19697     return nullptr;
19698   return new (Context)
19699       OMPHintClause(HintExpr.get(), StartLoc, LParenLoc, EndLoc);
19700 }
19701 
19702 /// Tries to find omp_event_handle_t type.
19703 static bool findOMPEventHandleT(Sema &S, SourceLocation Loc,
19704                                 DSAStackTy *Stack) {
19705   QualType OMPEventHandleT = Stack->getOMPEventHandleT();
19706   if (!OMPEventHandleT.isNull())
19707     return true;
19708   IdentifierInfo *II = &S.PP.getIdentifierTable().get("omp_event_handle_t");
19709   ParsedType PT = S.getTypeName(*II, Loc, S.getCurScope());
19710   if (!PT.getAsOpaquePtr() || PT.get().isNull()) {
19711     S.Diag(Loc, diag::err_omp_implied_type_not_found) << "omp_event_handle_t";
19712     return false;
19713   }
19714   Stack->setOMPEventHandleT(PT.get());
19715   return true;
19716 }
19717 
19718 OMPClause *Sema::ActOnOpenMPDetachClause(Expr *Evt, SourceLocation StartLoc,
19719                                          SourceLocation LParenLoc,
19720                                          SourceLocation EndLoc) {
19721   if (!Evt->isValueDependent() && !Evt->isTypeDependent() &&
19722       !Evt->isInstantiationDependent() &&
19723       !Evt->containsUnexpandedParameterPack()) {
19724     if (!findOMPEventHandleT(*this, Evt->getExprLoc(), DSAStack))
19725       return nullptr;
19726     // OpenMP 5.0, 2.10.1 task Construct.
19727     // event-handle is a variable of the omp_event_handle_t type.
19728     auto *Ref = dyn_cast<DeclRefExpr>(Evt->IgnoreParenImpCasts());
19729     if (!Ref) {
19730       Diag(Evt->getExprLoc(), diag::err_omp_var_expected)
19731           << "omp_event_handle_t" << 0 << Evt->getSourceRange();
19732       return nullptr;
19733     }
19734     auto *VD = dyn_cast_or_null<VarDecl>(Ref->getDecl());
19735     if (!VD) {
19736       Diag(Evt->getExprLoc(), diag::err_omp_var_expected)
19737           << "omp_event_handle_t" << 0 << Evt->getSourceRange();
19738       return nullptr;
19739     }
19740     if (!Context.hasSameUnqualifiedType(DSAStack->getOMPEventHandleT(),
19741                                         VD->getType()) ||
19742         VD->getType().isConstant(Context)) {
19743       Diag(Evt->getExprLoc(), diag::err_omp_var_expected)
19744           << "omp_event_handle_t" << 1 << VD->getType()
19745           << Evt->getSourceRange();
19746       return nullptr;
19747     }
19748     // OpenMP 5.0, 2.10.1 task Construct
19749     // [detach clause]... The event-handle will be considered as if it was
19750     // specified on a firstprivate clause.
19751     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, /*FromParent=*/false);
19752     if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
19753         DVar.RefExpr) {
19754       Diag(Evt->getExprLoc(), diag::err_omp_wrong_dsa)
19755           << getOpenMPClauseName(DVar.CKind)
19756           << getOpenMPClauseName(OMPC_firstprivate);
19757       reportOriginalDsa(*this, DSAStack, VD, DVar);
19758       return nullptr;
19759     }
19760   }
19761 
19762   return new (Context) OMPDetachClause(Evt, StartLoc, LParenLoc, EndLoc);
19763 }
19764 
19765 OMPClause *Sema::ActOnOpenMPDistScheduleClause(
19766     OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
19767     SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc,
19768     SourceLocation EndLoc) {
19769   if (Kind == OMPC_DIST_SCHEDULE_unknown) {
19770     std::string Values;
19771     Values += "'";
19772     Values += getOpenMPSimpleClauseTypeName(OMPC_dist_schedule, 0);
19773     Values += "'";
19774     Diag(KindLoc, diag::err_omp_unexpected_clause_value)
19775         << Values << getOpenMPClauseName(OMPC_dist_schedule);
19776     return nullptr;
19777   }
19778   Expr *ValExpr = ChunkSize;
19779   Stmt *HelperValStmt = nullptr;
19780   if (ChunkSize) {
19781     if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
19782         !ChunkSize->isInstantiationDependent() &&
19783         !ChunkSize->containsUnexpandedParameterPack()) {
19784       SourceLocation ChunkSizeLoc = ChunkSize->getBeginLoc();
19785       ExprResult Val =
19786           PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
19787       if (Val.isInvalid())
19788         return nullptr;
19789 
19790       ValExpr = Val.get();
19791 
19792       // OpenMP [2.7.1, Restrictions]
19793       //  chunk_size must be a loop invariant integer expression with a positive
19794       //  value.
19795       if (Optional<llvm::APSInt> Result =
19796               ValExpr->getIntegerConstantExpr(Context)) {
19797         if (Result->isSigned() && !Result->isStrictlyPositive()) {
19798           Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
19799               << "dist_schedule" << ChunkSize->getSourceRange();
19800           return nullptr;
19801         }
19802       } else if (getOpenMPCaptureRegionForClause(
19803                      DSAStack->getCurrentDirective(), OMPC_dist_schedule,
19804                      LangOpts.OpenMP) != OMPD_unknown &&
19805                  !CurContext->isDependentContext()) {
19806         ValExpr = MakeFullExpr(ValExpr).get();
19807         llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
19808         ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
19809         HelperValStmt = buildPreInits(Context, Captures);
19810       }
19811     }
19812   }
19813 
19814   return new (Context)
19815       OMPDistScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc,
19816                             Kind, ValExpr, HelperValStmt);
19817 }
19818 
19819 OMPClause *Sema::ActOnOpenMPDefaultmapClause(
19820     OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
19821     SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
19822     SourceLocation KindLoc, SourceLocation EndLoc) {
19823   if (getLangOpts().OpenMP < 50) {
19824     if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom ||
19825         Kind != OMPC_DEFAULTMAP_scalar) {
19826       std::string Value;
19827       SourceLocation Loc;
19828       Value += "'";
19829       if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom) {
19830         Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
19831                                                OMPC_DEFAULTMAP_MODIFIER_tofrom);
19832         Loc = MLoc;
19833       } else {
19834         Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
19835                                                OMPC_DEFAULTMAP_scalar);
19836         Loc = KindLoc;
19837       }
19838       Value += "'";
19839       Diag(Loc, diag::err_omp_unexpected_clause_value)
19840           << Value << getOpenMPClauseName(OMPC_defaultmap);
19841       return nullptr;
19842     }
19843   } else {
19844     bool isDefaultmapModifier = (M != OMPC_DEFAULTMAP_MODIFIER_unknown);
19845     bool isDefaultmapKind = (Kind != OMPC_DEFAULTMAP_unknown) ||
19846                             (LangOpts.OpenMP >= 50 && KindLoc.isInvalid());
19847     if (!isDefaultmapKind || !isDefaultmapModifier) {
19848       StringRef KindValue = "'scalar', 'aggregate', 'pointer'";
19849       if (LangOpts.OpenMP == 50) {
19850         StringRef ModifierValue = "'alloc', 'from', 'to', 'tofrom', "
19851                                   "'firstprivate', 'none', 'default'";
19852         if (!isDefaultmapKind && isDefaultmapModifier) {
19853           Diag(KindLoc, diag::err_omp_unexpected_clause_value)
19854               << KindValue << getOpenMPClauseName(OMPC_defaultmap);
19855         } else if (isDefaultmapKind && !isDefaultmapModifier) {
19856           Diag(MLoc, diag::err_omp_unexpected_clause_value)
19857               << ModifierValue << getOpenMPClauseName(OMPC_defaultmap);
19858         } else {
19859           Diag(MLoc, diag::err_omp_unexpected_clause_value)
19860               << ModifierValue << getOpenMPClauseName(OMPC_defaultmap);
19861           Diag(KindLoc, diag::err_omp_unexpected_clause_value)
19862               << KindValue << getOpenMPClauseName(OMPC_defaultmap);
19863         }
19864       } else {
19865         StringRef ModifierValue =
19866             "'alloc', 'from', 'to', 'tofrom', "
19867             "'firstprivate', 'none', 'default', 'present'";
19868         if (!isDefaultmapKind && isDefaultmapModifier) {
19869           Diag(KindLoc, diag::err_omp_unexpected_clause_value)
19870               << KindValue << getOpenMPClauseName(OMPC_defaultmap);
19871         } else if (isDefaultmapKind && !isDefaultmapModifier) {
19872           Diag(MLoc, diag::err_omp_unexpected_clause_value)
19873               << ModifierValue << getOpenMPClauseName(OMPC_defaultmap);
19874         } else {
19875           Diag(MLoc, diag::err_omp_unexpected_clause_value)
19876               << ModifierValue << getOpenMPClauseName(OMPC_defaultmap);
19877           Diag(KindLoc, diag::err_omp_unexpected_clause_value)
19878               << KindValue << getOpenMPClauseName(OMPC_defaultmap);
19879         }
19880       }
19881       return nullptr;
19882     }
19883 
19884     // OpenMP [5.0, 2.12.5, Restrictions, p. 174]
19885     //  At most one defaultmap clause for each category can appear on the
19886     //  directive.
19887     if (DSAStack->checkDefaultmapCategory(Kind)) {
19888       Diag(StartLoc, diag::err_omp_one_defaultmap_each_category);
19889       return nullptr;
19890     }
19891   }
19892   if (Kind == OMPC_DEFAULTMAP_unknown) {
19893     // Variable category is not specified - mark all categories.
19894     DSAStack->setDefaultDMAAttr(M, OMPC_DEFAULTMAP_aggregate, StartLoc);
19895     DSAStack->setDefaultDMAAttr(M, OMPC_DEFAULTMAP_scalar, StartLoc);
19896     DSAStack->setDefaultDMAAttr(M, OMPC_DEFAULTMAP_pointer, StartLoc);
19897   } else {
19898     DSAStack->setDefaultDMAAttr(M, Kind, StartLoc);
19899   }
19900 
19901   return new (Context)
19902       OMPDefaultmapClause(StartLoc, LParenLoc, MLoc, KindLoc, EndLoc, Kind, M);
19903 }
19904 
19905 bool Sema::ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc) {
19906   DeclContext *CurLexicalContext = getCurLexicalContext();
19907   if (!CurLexicalContext->isFileContext() &&
19908       !CurLexicalContext->isExternCContext() &&
19909       !CurLexicalContext->isExternCXXContext() &&
19910       !isa<CXXRecordDecl>(CurLexicalContext) &&
19911       !isa<ClassTemplateDecl>(CurLexicalContext) &&
19912       !isa<ClassTemplatePartialSpecializationDecl>(CurLexicalContext) &&
19913       !isa<ClassTemplateSpecializationDecl>(CurLexicalContext)) {
19914     Diag(Loc, diag::err_omp_region_not_file_context);
19915     return false;
19916   }
19917   DeclareTargetNesting.push_back(Loc);
19918   return true;
19919 }
19920 
19921 void Sema::ActOnFinishOpenMPDeclareTargetDirective() {
19922   assert(!DeclareTargetNesting.empty() &&
19923          "Unexpected ActOnFinishOpenMPDeclareTargetDirective");
19924   DeclareTargetNesting.pop_back();
19925 }
19926 
19927 NamedDecl *
19928 Sema::lookupOpenMPDeclareTargetName(Scope *CurScope, CXXScopeSpec &ScopeSpec,
19929                                     const DeclarationNameInfo &Id,
19930                                     NamedDeclSetType &SameDirectiveDecls) {
19931   LookupResult Lookup(*this, Id, LookupOrdinaryName);
19932   LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
19933 
19934   if (Lookup.isAmbiguous())
19935     return nullptr;
19936   Lookup.suppressDiagnostics();
19937 
19938   if (!Lookup.isSingleResult()) {
19939     VarOrFuncDeclFilterCCC CCC(*this);
19940     if (TypoCorrection Corrected =
19941             CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr, CCC,
19942                         CTK_ErrorRecovery)) {
19943       diagnoseTypo(Corrected, PDiag(diag::err_undeclared_var_use_suggest)
19944                                   << Id.getName());
19945       checkDeclIsAllowedInOpenMPTarget(nullptr, Corrected.getCorrectionDecl());
19946       return nullptr;
19947     }
19948 
19949     Diag(Id.getLoc(), diag::err_undeclared_var_use) << Id.getName();
19950     return nullptr;
19951   }
19952 
19953   NamedDecl *ND = Lookup.getAsSingle<NamedDecl>();
19954   if (!isa<VarDecl>(ND) && !isa<FunctionDecl>(ND) &&
19955       !isa<FunctionTemplateDecl>(ND)) {
19956     Diag(Id.getLoc(), diag::err_omp_invalid_target_decl) << Id.getName();
19957     return nullptr;
19958   }
19959   if (!SameDirectiveDecls.insert(cast<NamedDecl>(ND->getCanonicalDecl())))
19960     Diag(Id.getLoc(), diag::err_omp_declare_target_multiple) << Id.getName();
19961   return ND;
19962 }
19963 
19964 void Sema::ActOnOpenMPDeclareTargetName(
19965     NamedDecl *ND, SourceLocation Loc, OMPDeclareTargetDeclAttr::MapTypeTy MT,
19966     OMPDeclareTargetDeclAttr::DevTypeTy DT) {
19967   assert((isa<VarDecl>(ND) || isa<FunctionDecl>(ND) ||
19968           isa<FunctionTemplateDecl>(ND)) &&
19969          "Expected variable, function or function template.");
19970 
19971   // Diagnose marking after use as it may lead to incorrect diagnosis and
19972   // codegen.
19973   if (LangOpts.OpenMP >= 50 &&
19974       (ND->isUsed(/*CheckUsedAttr=*/false) || ND->isReferenced()))
19975     Diag(Loc, diag::warn_omp_declare_target_after_first_use);
19976 
19977   auto *VD = cast<ValueDecl>(ND);
19978   Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
19979       OMPDeclareTargetDeclAttr::getDeviceType(VD);
19980   Optional<SourceLocation> AttrLoc = OMPDeclareTargetDeclAttr::getLocation(VD);
19981   if (DevTy.hasValue() && *DevTy != DT &&
19982       (DeclareTargetNesting.empty() ||
19983        *AttrLoc != DeclareTargetNesting.back())) {
19984     Diag(Loc, diag::err_omp_device_type_mismatch)
19985         << OMPDeclareTargetDeclAttr::ConvertDevTypeTyToStr(DT)
19986         << OMPDeclareTargetDeclAttr::ConvertDevTypeTyToStr(*DevTy);
19987     return;
19988   }
19989   Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
19990       OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
19991   if (!Res || (!DeclareTargetNesting.empty() &&
19992                *AttrLoc == DeclareTargetNesting.back())) {
19993     auto *A = OMPDeclareTargetDeclAttr::CreateImplicit(
19994         Context, MT, DT, DeclareTargetNesting.size() + 1,
19995         SourceRange(Loc, Loc));
19996     ND->addAttr(A);
19997     if (ASTMutationListener *ML = Context.getASTMutationListener())
19998       ML->DeclarationMarkedOpenMPDeclareTarget(ND, A);
19999     checkDeclIsAllowedInOpenMPTarget(nullptr, ND, Loc);
20000   } else if (*Res != MT) {
20001     Diag(Loc, diag::err_omp_declare_target_to_and_link) << ND;
20002   }
20003 }
20004 
20005 static void checkDeclInTargetContext(SourceLocation SL, SourceRange SR,
20006                                      Sema &SemaRef, Decl *D) {
20007   if (!D || !isa<VarDecl>(D))
20008     return;
20009   auto *VD = cast<VarDecl>(D);
20010   Optional<OMPDeclareTargetDeclAttr::MapTypeTy> MapTy =
20011       OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
20012   if (SemaRef.LangOpts.OpenMP >= 50 &&
20013       (SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true) ||
20014        SemaRef.getCurBlock() || SemaRef.getCurCapturedRegion()) &&
20015       VD->hasGlobalStorage()) {
20016     llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> MapTy =
20017         OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
20018     if (!MapTy || *MapTy != OMPDeclareTargetDeclAttr::MT_To) {
20019       // OpenMP 5.0, 2.12.7 declare target Directive, Restrictions
20020       // If a lambda declaration and definition appears between a
20021       // declare target directive and the matching end declare target
20022       // directive, all variables that are captured by the lambda
20023       // expression must also appear in a to clause.
20024       SemaRef.Diag(VD->getLocation(),
20025                    diag::err_omp_lambda_capture_in_declare_target_not_to);
20026       SemaRef.Diag(SL, diag::note_var_explicitly_captured_here)
20027           << VD << 0 << SR;
20028       return;
20029     }
20030   }
20031   if (MapTy.hasValue())
20032     return;
20033   SemaRef.Diag(VD->getLocation(), diag::warn_omp_not_in_target_context);
20034   SemaRef.Diag(SL, diag::note_used_here) << SR;
20035 }
20036 
20037 static bool checkValueDeclInTarget(SourceLocation SL, SourceRange SR,
20038                                    Sema &SemaRef, DSAStackTy *Stack,
20039                                    ValueDecl *VD) {
20040   return OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD) ||
20041          checkTypeMappable(SL, SR, SemaRef, Stack, VD->getType(),
20042                            /*FullCheck=*/false);
20043 }
20044 
20045 void Sema::checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D,
20046                                             SourceLocation IdLoc) {
20047   if (!D || D->isInvalidDecl())
20048     return;
20049   SourceRange SR = E ? E->getSourceRange() : D->getSourceRange();
20050   SourceLocation SL = E ? E->getBeginLoc() : D->getLocation();
20051   if (auto *VD = dyn_cast<VarDecl>(D)) {
20052     // Only global variables can be marked as declare target.
20053     if (!VD->isFileVarDecl() && !VD->isStaticLocal() &&
20054         !VD->isStaticDataMember())
20055       return;
20056     // 2.10.6: threadprivate variable cannot appear in a declare target
20057     // directive.
20058     if (DSAStack->isThreadPrivate(VD)) {
20059       Diag(SL, diag::err_omp_threadprivate_in_target);
20060       reportOriginalDsa(*this, DSAStack, VD, DSAStack->getTopDSA(VD, false));
20061       return;
20062     }
20063   }
20064   if (const auto *FTD = dyn_cast<FunctionTemplateDecl>(D))
20065     D = FTD->getTemplatedDecl();
20066   if (auto *FD = dyn_cast<FunctionDecl>(D)) {
20067     llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
20068         OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(FD);
20069     if (IdLoc.isValid() && Res && *Res == OMPDeclareTargetDeclAttr::MT_Link) {
20070       Diag(IdLoc, diag::err_omp_function_in_link_clause);
20071       Diag(FD->getLocation(), diag::note_defined_here) << FD;
20072       return;
20073     }
20074   }
20075   if (auto *VD = dyn_cast<ValueDecl>(D)) {
20076     // Problem if any with var declared with incomplete type will be reported
20077     // as normal, so no need to check it here.
20078     if ((E || !VD->getType()->isIncompleteType()) &&
20079         !checkValueDeclInTarget(SL, SR, *this, DSAStack, VD))
20080       return;
20081     if (!E && !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) {
20082       // Checking declaration inside declare target region.
20083       if (isa<VarDecl>(D) || isa<FunctionDecl>(D) ||
20084           isa<FunctionTemplateDecl>(D)) {
20085         auto *A = OMPDeclareTargetDeclAttr::CreateImplicit(
20086             Context, OMPDeclareTargetDeclAttr::MT_To,
20087             OMPDeclareTargetDeclAttr::DT_Any, DeclareTargetNesting.size(),
20088             SourceRange(DeclareTargetNesting.back(),
20089                         DeclareTargetNesting.back()));
20090         D->addAttr(A);
20091         if (ASTMutationListener *ML = Context.getASTMutationListener())
20092           ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
20093       }
20094       return;
20095     }
20096   }
20097   if (!E)
20098     return;
20099   checkDeclInTargetContext(E->getExprLoc(), E->getSourceRange(), *this, D);
20100 }
20101 
20102 OMPClause *Sema::ActOnOpenMPToClause(
20103     ArrayRef<OpenMPMotionModifierKind> MotionModifiers,
20104     ArrayRef<SourceLocation> MotionModifiersLoc,
20105     CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo &MapperId,
20106     SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
20107     const OMPVarListLocTy &Locs, ArrayRef<Expr *> UnresolvedMappers) {
20108   OpenMPMotionModifierKind Modifiers[] = {OMPC_MOTION_MODIFIER_unknown,
20109                                           OMPC_MOTION_MODIFIER_unknown};
20110   SourceLocation ModifiersLoc[NumberOfOMPMotionModifiers];
20111 
20112   // Process motion-modifiers, flag errors for duplicate modifiers.
20113   unsigned Count = 0;
20114   for (unsigned I = 0, E = MotionModifiers.size(); I < E; ++I) {
20115     if (MotionModifiers[I] != OMPC_MOTION_MODIFIER_unknown &&
20116         llvm::find(Modifiers, MotionModifiers[I]) != std::end(Modifiers)) {
20117       Diag(MotionModifiersLoc[I], diag::err_omp_duplicate_motion_modifier);
20118       continue;
20119     }
20120     assert(Count < NumberOfOMPMotionModifiers &&
20121            "Modifiers exceed the allowed number of motion modifiers");
20122     Modifiers[Count] = MotionModifiers[I];
20123     ModifiersLoc[Count] = MotionModifiersLoc[I];
20124     ++Count;
20125   }
20126 
20127   MappableVarListInfo MVLI(VarList);
20128   checkMappableExpressionList(*this, DSAStack, OMPC_to, MVLI, Locs.StartLoc,
20129                               MapperIdScopeSpec, MapperId, UnresolvedMappers);
20130   if (MVLI.ProcessedVarList.empty())
20131     return nullptr;
20132 
20133   return OMPToClause::Create(
20134       Context, Locs, MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
20135       MVLI.VarComponents, MVLI.UDMapperList, Modifiers, ModifiersLoc,
20136       MapperIdScopeSpec.getWithLocInContext(Context), MapperId);
20137 }
20138 
20139 OMPClause *Sema::ActOnOpenMPFromClause(
20140     ArrayRef<OpenMPMotionModifierKind> MotionModifiers,
20141     ArrayRef<SourceLocation> MotionModifiersLoc,
20142     CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo &MapperId,
20143     SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
20144     const OMPVarListLocTy &Locs, ArrayRef<Expr *> UnresolvedMappers) {
20145   OpenMPMotionModifierKind Modifiers[] = {OMPC_MOTION_MODIFIER_unknown,
20146                                           OMPC_MOTION_MODIFIER_unknown};
20147   SourceLocation ModifiersLoc[NumberOfOMPMotionModifiers];
20148 
20149   // Process motion-modifiers, flag errors for duplicate modifiers.
20150   unsigned Count = 0;
20151   for (unsigned I = 0, E = MotionModifiers.size(); I < E; ++I) {
20152     if (MotionModifiers[I] != OMPC_MOTION_MODIFIER_unknown &&
20153         llvm::find(Modifiers, MotionModifiers[I]) != std::end(Modifiers)) {
20154       Diag(MotionModifiersLoc[I], diag::err_omp_duplicate_motion_modifier);
20155       continue;
20156     }
20157     assert(Count < NumberOfOMPMotionModifiers &&
20158            "Modifiers exceed the allowed number of motion modifiers");
20159     Modifiers[Count] = MotionModifiers[I];
20160     ModifiersLoc[Count] = MotionModifiersLoc[I];
20161     ++Count;
20162   }
20163 
20164   MappableVarListInfo MVLI(VarList);
20165   checkMappableExpressionList(*this, DSAStack, OMPC_from, MVLI, Locs.StartLoc,
20166                               MapperIdScopeSpec, MapperId, UnresolvedMappers);
20167   if (MVLI.ProcessedVarList.empty())
20168     return nullptr;
20169 
20170   return OMPFromClause::Create(
20171       Context, Locs, MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
20172       MVLI.VarComponents, MVLI.UDMapperList, Modifiers, ModifiersLoc,
20173       MapperIdScopeSpec.getWithLocInContext(Context), MapperId);
20174 }
20175 
20176 OMPClause *Sema::ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
20177                                                const OMPVarListLocTy &Locs) {
20178   MappableVarListInfo MVLI(VarList);
20179   SmallVector<Expr *, 8> PrivateCopies;
20180   SmallVector<Expr *, 8> Inits;
20181 
20182   for (Expr *RefExpr : VarList) {
20183     assert(RefExpr && "NULL expr in OpenMP use_device_ptr clause.");
20184     SourceLocation ELoc;
20185     SourceRange ERange;
20186     Expr *SimpleRefExpr = RefExpr;
20187     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
20188     if (Res.second) {
20189       // It will be analyzed later.
20190       MVLI.ProcessedVarList.push_back(RefExpr);
20191       PrivateCopies.push_back(nullptr);
20192       Inits.push_back(nullptr);
20193     }
20194     ValueDecl *D = Res.first;
20195     if (!D)
20196       continue;
20197 
20198     QualType Type = D->getType();
20199     Type = Type.getNonReferenceType().getUnqualifiedType();
20200 
20201     auto *VD = dyn_cast<VarDecl>(D);
20202 
20203     // Item should be a pointer or reference to pointer.
20204     if (!Type->isPointerType()) {
20205       Diag(ELoc, diag::err_omp_usedeviceptr_not_a_pointer)
20206           << 0 << RefExpr->getSourceRange();
20207       continue;
20208     }
20209 
20210     // Build the private variable and the expression that refers to it.
20211     auto VDPrivate =
20212         buildVarDecl(*this, ELoc, Type, D->getName(),
20213                      D->hasAttrs() ? &D->getAttrs() : nullptr,
20214                      VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
20215     if (VDPrivate->isInvalidDecl())
20216       continue;
20217 
20218     CurContext->addDecl(VDPrivate);
20219     DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
20220         *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
20221 
20222     // Add temporary variable to initialize the private copy of the pointer.
20223     VarDecl *VDInit =
20224         buildVarDecl(*this, RefExpr->getExprLoc(), Type, ".devptr.temp");
20225     DeclRefExpr *VDInitRefExpr = buildDeclRefExpr(
20226         *this, VDInit, RefExpr->getType(), RefExpr->getExprLoc());
20227     AddInitializerToDecl(VDPrivate,
20228                          DefaultLvalueConversion(VDInitRefExpr).get(),
20229                          /*DirectInit=*/false);
20230 
20231     // If required, build a capture to implement the privatization initialized
20232     // with the current list item value.
20233     DeclRefExpr *Ref = nullptr;
20234     if (!VD)
20235       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
20236     MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref);
20237     PrivateCopies.push_back(VDPrivateRefExpr);
20238     Inits.push_back(VDInitRefExpr);
20239 
20240     // We need to add a data sharing attribute for this variable to make sure it
20241     // is correctly captured. A variable that shows up in a use_device_ptr has
20242     // similar properties of a first private variable.
20243     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
20244 
20245     // Create a mappable component for the list item. List items in this clause
20246     // only need a component.
20247     MVLI.VarBaseDeclarations.push_back(D);
20248     MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
20249     MVLI.VarComponents.back().emplace_back(SimpleRefExpr, D,
20250                                            /*IsNonContiguous=*/false);
20251   }
20252 
20253   if (MVLI.ProcessedVarList.empty())
20254     return nullptr;
20255 
20256   return OMPUseDevicePtrClause::Create(
20257       Context, Locs, MVLI.ProcessedVarList, PrivateCopies, Inits,
20258       MVLI.VarBaseDeclarations, MVLI.VarComponents);
20259 }
20260 
20261 OMPClause *Sema::ActOnOpenMPUseDeviceAddrClause(ArrayRef<Expr *> VarList,
20262                                                 const OMPVarListLocTy &Locs) {
20263   MappableVarListInfo MVLI(VarList);
20264 
20265   for (Expr *RefExpr : VarList) {
20266     assert(RefExpr && "NULL expr in OpenMP use_device_addr clause.");
20267     SourceLocation ELoc;
20268     SourceRange ERange;
20269     Expr *SimpleRefExpr = RefExpr;
20270     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
20271                               /*AllowArraySection=*/true);
20272     if (Res.second) {
20273       // It will be analyzed later.
20274       MVLI.ProcessedVarList.push_back(RefExpr);
20275     }
20276     ValueDecl *D = Res.first;
20277     if (!D)
20278       continue;
20279     auto *VD = dyn_cast<VarDecl>(D);
20280 
20281     // If required, build a capture to implement the privatization initialized
20282     // with the current list item value.
20283     DeclRefExpr *Ref = nullptr;
20284     if (!VD)
20285       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
20286     MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref);
20287 
20288     // We need to add a data sharing attribute for this variable to make sure it
20289     // is correctly captured. A variable that shows up in a use_device_addr has
20290     // similar properties of a first private variable.
20291     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
20292 
20293     // Create a mappable component for the list item. List items in this clause
20294     // only need a component.
20295     MVLI.VarBaseDeclarations.push_back(D);
20296     MVLI.VarComponents.emplace_back();
20297     Expr *Component = SimpleRefExpr;
20298     if (VD && (isa<OMPArraySectionExpr>(RefExpr->IgnoreParenImpCasts()) ||
20299                isa<ArraySubscriptExpr>(RefExpr->IgnoreParenImpCasts())))
20300       Component = DefaultFunctionArrayLvalueConversion(SimpleRefExpr).get();
20301     MVLI.VarComponents.back().emplace_back(Component, D,
20302                                            /*IsNonContiguous=*/false);
20303   }
20304 
20305   if (MVLI.ProcessedVarList.empty())
20306     return nullptr;
20307 
20308   return OMPUseDeviceAddrClause::Create(Context, Locs, MVLI.ProcessedVarList,
20309                                         MVLI.VarBaseDeclarations,
20310                                         MVLI.VarComponents);
20311 }
20312 
20313 OMPClause *Sema::ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
20314                                               const OMPVarListLocTy &Locs) {
20315   MappableVarListInfo MVLI(VarList);
20316   for (Expr *RefExpr : VarList) {
20317     assert(RefExpr && "NULL expr in OpenMP is_device_ptr clause.");
20318     SourceLocation ELoc;
20319     SourceRange ERange;
20320     Expr *SimpleRefExpr = RefExpr;
20321     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
20322     if (Res.second) {
20323       // It will be analyzed later.
20324       MVLI.ProcessedVarList.push_back(RefExpr);
20325     }
20326     ValueDecl *D = Res.first;
20327     if (!D)
20328       continue;
20329 
20330     QualType Type = D->getType();
20331     // item should be a pointer or array or reference to pointer or array
20332     if (!Type.getNonReferenceType()->isPointerType() &&
20333         !Type.getNonReferenceType()->isArrayType()) {
20334       Diag(ELoc, diag::err_omp_argument_type_isdeviceptr)
20335           << 0 << RefExpr->getSourceRange();
20336       continue;
20337     }
20338 
20339     // Check if the declaration in the clause does not show up in any data
20340     // sharing attribute.
20341     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
20342     if (isOpenMPPrivate(DVar.CKind)) {
20343       Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
20344           << getOpenMPClauseName(DVar.CKind)
20345           << getOpenMPClauseName(OMPC_is_device_ptr)
20346           << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
20347       reportOriginalDsa(*this, DSAStack, D, DVar);
20348       continue;
20349     }
20350 
20351     const Expr *ConflictExpr;
20352     if (DSAStack->checkMappableExprComponentListsForDecl(
20353             D, /*CurrentRegionOnly=*/true,
20354             [&ConflictExpr](
20355                 OMPClauseMappableExprCommon::MappableExprComponentListRef R,
20356                 OpenMPClauseKind) -> bool {
20357               ConflictExpr = R.front().getAssociatedExpression();
20358               return true;
20359             })) {
20360       Diag(ELoc, diag::err_omp_map_shared_storage) << RefExpr->getSourceRange();
20361       Diag(ConflictExpr->getExprLoc(), diag::note_used_here)
20362           << ConflictExpr->getSourceRange();
20363       continue;
20364     }
20365 
20366     // Store the components in the stack so that they can be used to check
20367     // against other clauses later on.
20368     OMPClauseMappableExprCommon::MappableComponent MC(
20369         SimpleRefExpr, D, /*IsNonContiguous=*/false);
20370     DSAStack->addMappableExpressionComponents(
20371         D, MC, /*WhereFoundClauseKind=*/OMPC_is_device_ptr);
20372 
20373     // Record the expression we've just processed.
20374     MVLI.ProcessedVarList.push_back(SimpleRefExpr);
20375 
20376     // Create a mappable component for the list item. List items in this clause
20377     // only need a component. We use a null declaration to signal fields in
20378     // 'this'.
20379     assert((isa<DeclRefExpr>(SimpleRefExpr) ||
20380             isa<CXXThisExpr>(cast<MemberExpr>(SimpleRefExpr)->getBase())) &&
20381            "Unexpected device pointer expression!");
20382     MVLI.VarBaseDeclarations.push_back(
20383         isa<DeclRefExpr>(SimpleRefExpr) ? D : nullptr);
20384     MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
20385     MVLI.VarComponents.back().push_back(MC);
20386   }
20387 
20388   if (MVLI.ProcessedVarList.empty())
20389     return nullptr;
20390 
20391   return OMPIsDevicePtrClause::Create(Context, Locs, MVLI.ProcessedVarList,
20392                                       MVLI.VarBaseDeclarations,
20393                                       MVLI.VarComponents);
20394 }
20395 
20396 OMPClause *Sema::ActOnOpenMPAllocateClause(
20397     Expr *Allocator, ArrayRef<Expr *> VarList, SourceLocation StartLoc,
20398     SourceLocation ColonLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
20399   if (Allocator) {
20400     // OpenMP [2.11.4 allocate Clause, Description]
20401     // allocator is an expression of omp_allocator_handle_t type.
20402     if (!findOMPAllocatorHandleT(*this, Allocator->getExprLoc(), DSAStack))
20403       return nullptr;
20404 
20405     ExprResult AllocatorRes = DefaultLvalueConversion(Allocator);
20406     if (AllocatorRes.isInvalid())
20407       return nullptr;
20408     AllocatorRes = PerformImplicitConversion(AllocatorRes.get(),
20409                                              DSAStack->getOMPAllocatorHandleT(),
20410                                              Sema::AA_Initializing,
20411                                              /*AllowExplicit=*/true);
20412     if (AllocatorRes.isInvalid())
20413       return nullptr;
20414     Allocator = AllocatorRes.get();
20415   } else {
20416     // OpenMP 5.0, 2.11.4 allocate Clause, Restrictions.
20417     // allocate clauses that appear on a target construct or on constructs in a
20418     // target region must specify an allocator expression unless a requires
20419     // directive with the dynamic_allocators clause is present in the same
20420     // compilation unit.
20421     if (LangOpts.OpenMPIsDevice &&
20422         !DSAStack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>())
20423       targetDiag(StartLoc, diag::err_expected_allocator_expression);
20424   }
20425   // Analyze and build list of variables.
20426   SmallVector<Expr *, 8> Vars;
20427   for (Expr *RefExpr : VarList) {
20428     assert(RefExpr && "NULL expr in OpenMP private clause.");
20429     SourceLocation ELoc;
20430     SourceRange ERange;
20431     Expr *SimpleRefExpr = RefExpr;
20432     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
20433     if (Res.second) {
20434       // It will be analyzed later.
20435       Vars.push_back(RefExpr);
20436     }
20437     ValueDecl *D = Res.first;
20438     if (!D)
20439       continue;
20440 
20441     auto *VD = dyn_cast<VarDecl>(D);
20442     DeclRefExpr *Ref = nullptr;
20443     if (!VD && !CurContext->isDependentContext())
20444       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
20445     Vars.push_back((VD || CurContext->isDependentContext())
20446                        ? RefExpr->IgnoreParens()
20447                        : Ref);
20448   }
20449 
20450   if (Vars.empty())
20451     return nullptr;
20452 
20453   if (Allocator)
20454     DSAStack->addInnerAllocatorExpr(Allocator);
20455   return OMPAllocateClause::Create(Context, StartLoc, LParenLoc, Allocator,
20456                                    ColonLoc, EndLoc, Vars);
20457 }
20458 
20459 OMPClause *Sema::ActOnOpenMPNontemporalClause(ArrayRef<Expr *> VarList,
20460                                               SourceLocation StartLoc,
20461                                               SourceLocation LParenLoc,
20462                                               SourceLocation EndLoc) {
20463   SmallVector<Expr *, 8> Vars;
20464   for (Expr *RefExpr : VarList) {
20465     assert(RefExpr && "NULL expr in OpenMP nontemporal clause.");
20466     SourceLocation ELoc;
20467     SourceRange ERange;
20468     Expr *SimpleRefExpr = RefExpr;
20469     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
20470     if (Res.second)
20471       // It will be analyzed later.
20472       Vars.push_back(RefExpr);
20473     ValueDecl *D = Res.first;
20474     if (!D)
20475       continue;
20476 
20477     // OpenMP 5.0, 2.9.3.1 simd Construct, Restrictions.
20478     // A list-item cannot appear in more than one nontemporal clause.
20479     if (const Expr *PrevRef =
20480             DSAStack->addUniqueNontemporal(D, SimpleRefExpr)) {
20481       Diag(ELoc, diag::err_omp_used_in_clause_twice)
20482           << 0 << getOpenMPClauseName(OMPC_nontemporal) << ERange;
20483       Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
20484           << getOpenMPClauseName(OMPC_nontemporal);
20485       continue;
20486     }
20487 
20488     Vars.push_back(RefExpr);
20489   }
20490 
20491   if (Vars.empty())
20492     return nullptr;
20493 
20494   return OMPNontemporalClause::Create(Context, StartLoc, LParenLoc, EndLoc,
20495                                       Vars);
20496 }
20497 
20498 OMPClause *Sema::ActOnOpenMPInclusiveClause(ArrayRef<Expr *> VarList,
20499                                             SourceLocation StartLoc,
20500                                             SourceLocation LParenLoc,
20501                                             SourceLocation EndLoc) {
20502   SmallVector<Expr *, 8> Vars;
20503   for (Expr *RefExpr : VarList) {
20504     assert(RefExpr && "NULL expr in OpenMP nontemporal clause.");
20505     SourceLocation ELoc;
20506     SourceRange ERange;
20507     Expr *SimpleRefExpr = RefExpr;
20508     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
20509                               /*AllowArraySection=*/true);
20510     if (Res.second)
20511       // It will be analyzed later.
20512       Vars.push_back(RefExpr);
20513     ValueDecl *D = Res.first;
20514     if (!D)
20515       continue;
20516 
20517     const DSAStackTy::DSAVarData DVar =
20518         DSAStack->getTopDSA(D, /*FromParent=*/true);
20519     // OpenMP 5.0, 2.9.6, scan Directive, Restrictions.
20520     // A list item that appears in the inclusive or exclusive clause must appear
20521     // in a reduction clause with the inscan modifier on the enclosing
20522     // worksharing-loop, worksharing-loop SIMD, or simd construct.
20523     if (DVar.CKind != OMPC_reduction ||
20524         DVar.Modifier != OMPC_REDUCTION_inscan)
20525       Diag(ELoc, diag::err_omp_inclusive_exclusive_not_reduction)
20526           << RefExpr->getSourceRange();
20527 
20528     if (DSAStack->getParentDirective() != OMPD_unknown)
20529       DSAStack->markDeclAsUsedInScanDirective(D);
20530     Vars.push_back(RefExpr);
20531   }
20532 
20533   if (Vars.empty())
20534     return nullptr;
20535 
20536   return OMPInclusiveClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
20537 }
20538 
20539 OMPClause *Sema::ActOnOpenMPExclusiveClause(ArrayRef<Expr *> VarList,
20540                                             SourceLocation StartLoc,
20541                                             SourceLocation LParenLoc,
20542                                             SourceLocation EndLoc) {
20543   SmallVector<Expr *, 8> Vars;
20544   for (Expr *RefExpr : VarList) {
20545     assert(RefExpr && "NULL expr in OpenMP nontemporal clause.");
20546     SourceLocation ELoc;
20547     SourceRange ERange;
20548     Expr *SimpleRefExpr = RefExpr;
20549     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
20550                               /*AllowArraySection=*/true);
20551     if (Res.second)
20552       // It will be analyzed later.
20553       Vars.push_back(RefExpr);
20554     ValueDecl *D = Res.first;
20555     if (!D)
20556       continue;
20557 
20558     OpenMPDirectiveKind ParentDirective = DSAStack->getParentDirective();
20559     DSAStackTy::DSAVarData DVar;
20560     if (ParentDirective != OMPD_unknown)
20561       DVar = DSAStack->getTopDSA(D, /*FromParent=*/true);
20562     // OpenMP 5.0, 2.9.6, scan Directive, Restrictions.
20563     // A list item that appears in the inclusive or exclusive clause must appear
20564     // in a reduction clause with the inscan modifier on the enclosing
20565     // worksharing-loop, worksharing-loop SIMD, or simd construct.
20566     if (ParentDirective == OMPD_unknown || DVar.CKind != OMPC_reduction ||
20567         DVar.Modifier != OMPC_REDUCTION_inscan) {
20568       Diag(ELoc, diag::err_omp_inclusive_exclusive_not_reduction)
20569           << RefExpr->getSourceRange();
20570     } else {
20571       DSAStack->markDeclAsUsedInScanDirective(D);
20572     }
20573     Vars.push_back(RefExpr);
20574   }
20575 
20576   if (Vars.empty())
20577     return nullptr;
20578 
20579   return OMPExclusiveClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
20580 }
20581 
20582 /// Tries to find omp_alloctrait_t type.
20583 static bool findOMPAlloctraitT(Sema &S, SourceLocation Loc, DSAStackTy *Stack) {
20584   QualType OMPAlloctraitT = Stack->getOMPAlloctraitT();
20585   if (!OMPAlloctraitT.isNull())
20586     return true;
20587   IdentifierInfo &II = S.PP.getIdentifierTable().get("omp_alloctrait_t");
20588   ParsedType PT = S.getTypeName(II, Loc, S.getCurScope());
20589   if (!PT.getAsOpaquePtr() || PT.get().isNull()) {
20590     S.Diag(Loc, diag::err_omp_implied_type_not_found) << "omp_alloctrait_t";
20591     return false;
20592   }
20593   Stack->setOMPAlloctraitT(PT.get());
20594   return true;
20595 }
20596 
20597 OMPClause *Sema::ActOnOpenMPUsesAllocatorClause(
20598     SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc,
20599     ArrayRef<UsesAllocatorsData> Data) {
20600   // OpenMP [2.12.5, target Construct]
20601   // allocator is an identifier of omp_allocator_handle_t type.
20602   if (!findOMPAllocatorHandleT(*this, StartLoc, DSAStack))
20603     return nullptr;
20604   // OpenMP [2.12.5, target Construct]
20605   // allocator-traits-array is an identifier of const omp_alloctrait_t * type.
20606   if (llvm::any_of(
20607           Data,
20608           [](const UsesAllocatorsData &D) { return D.AllocatorTraits; }) &&
20609       !findOMPAlloctraitT(*this, StartLoc, DSAStack))
20610     return nullptr;
20611   llvm::SmallPtrSet<CanonicalDeclPtr<Decl>, 4> PredefinedAllocators;
20612   for (int I = 0; I < OMPAllocateDeclAttr::OMPUserDefinedMemAlloc; ++I) {
20613     auto AllocatorKind = static_cast<OMPAllocateDeclAttr::AllocatorTypeTy>(I);
20614     StringRef Allocator =
20615         OMPAllocateDeclAttr::ConvertAllocatorTypeTyToStr(AllocatorKind);
20616     DeclarationName AllocatorName = &Context.Idents.get(Allocator);
20617     PredefinedAllocators.insert(LookupSingleName(
20618         TUScope, AllocatorName, StartLoc, Sema::LookupAnyName));
20619   }
20620 
20621   SmallVector<OMPUsesAllocatorsClause::Data, 4> NewData;
20622   for (const UsesAllocatorsData &D : Data) {
20623     Expr *AllocatorExpr = nullptr;
20624     // Check allocator expression.
20625     if (D.Allocator->isTypeDependent()) {
20626       AllocatorExpr = D.Allocator;
20627     } else {
20628       // Traits were specified - need to assign new allocator to the specified
20629       // allocator, so it must be an lvalue.
20630       AllocatorExpr = D.Allocator->IgnoreParenImpCasts();
20631       auto *DRE = dyn_cast<DeclRefExpr>(AllocatorExpr);
20632       bool IsPredefinedAllocator = false;
20633       if (DRE)
20634         IsPredefinedAllocator = PredefinedAllocators.count(DRE->getDecl());
20635       if (!DRE ||
20636           !(Context.hasSameUnqualifiedType(
20637                 AllocatorExpr->getType(), DSAStack->getOMPAllocatorHandleT()) ||
20638             Context.typesAreCompatible(AllocatorExpr->getType(),
20639                                        DSAStack->getOMPAllocatorHandleT(),
20640                                        /*CompareUnqualified=*/true)) ||
20641           (!IsPredefinedAllocator &&
20642            (AllocatorExpr->getType().isConstant(Context) ||
20643             !AllocatorExpr->isLValue()))) {
20644         Diag(D.Allocator->getExprLoc(), diag::err_omp_var_expected)
20645             << "omp_allocator_handle_t" << (DRE ? 1 : 0)
20646             << AllocatorExpr->getType() << D.Allocator->getSourceRange();
20647         continue;
20648       }
20649       // OpenMP [2.12.5, target Construct]
20650       // Predefined allocators appearing in a uses_allocators clause cannot have
20651       // traits specified.
20652       if (IsPredefinedAllocator && D.AllocatorTraits) {
20653         Diag(D.AllocatorTraits->getExprLoc(),
20654              diag::err_omp_predefined_allocator_with_traits)
20655             << D.AllocatorTraits->getSourceRange();
20656         Diag(D.Allocator->getExprLoc(), diag::note_omp_predefined_allocator)
20657             << cast<NamedDecl>(DRE->getDecl())->getName()
20658             << D.Allocator->getSourceRange();
20659         continue;
20660       }
20661       // OpenMP [2.12.5, target Construct]
20662       // Non-predefined allocators appearing in a uses_allocators clause must
20663       // have traits specified.
20664       if (!IsPredefinedAllocator && !D.AllocatorTraits) {
20665         Diag(D.Allocator->getExprLoc(),
20666              diag::err_omp_nonpredefined_allocator_without_traits);
20667         continue;
20668       }
20669       // No allocator traits - just convert it to rvalue.
20670       if (!D.AllocatorTraits)
20671         AllocatorExpr = DefaultLvalueConversion(AllocatorExpr).get();
20672       DSAStack->addUsesAllocatorsDecl(
20673           DRE->getDecl(),
20674           IsPredefinedAllocator
20675               ? DSAStackTy::UsesAllocatorsDeclKind::PredefinedAllocator
20676               : DSAStackTy::UsesAllocatorsDeclKind::UserDefinedAllocator);
20677     }
20678     Expr *AllocatorTraitsExpr = nullptr;
20679     if (D.AllocatorTraits) {
20680       if (D.AllocatorTraits->isTypeDependent()) {
20681         AllocatorTraitsExpr = D.AllocatorTraits;
20682       } else {
20683         // OpenMP [2.12.5, target Construct]
20684         // Arrays that contain allocator traits that appear in a uses_allocators
20685         // clause must be constant arrays, have constant values and be defined
20686         // in the same scope as the construct in which the clause appears.
20687         AllocatorTraitsExpr = D.AllocatorTraits->IgnoreParenImpCasts();
20688         // Check that traits expr is a constant array.
20689         QualType TraitTy;
20690         if (const ArrayType *Ty =
20691                 AllocatorTraitsExpr->getType()->getAsArrayTypeUnsafe())
20692           if (const auto *ConstArrayTy = dyn_cast<ConstantArrayType>(Ty))
20693             TraitTy = ConstArrayTy->getElementType();
20694         if (TraitTy.isNull() ||
20695             !(Context.hasSameUnqualifiedType(TraitTy,
20696                                              DSAStack->getOMPAlloctraitT()) ||
20697               Context.typesAreCompatible(TraitTy, DSAStack->getOMPAlloctraitT(),
20698                                          /*CompareUnqualified=*/true))) {
20699           Diag(D.AllocatorTraits->getExprLoc(),
20700                diag::err_omp_expected_array_alloctraits)
20701               << AllocatorTraitsExpr->getType();
20702           continue;
20703         }
20704         // Do not map by default allocator traits if it is a standalone
20705         // variable.
20706         if (auto *DRE = dyn_cast<DeclRefExpr>(AllocatorTraitsExpr))
20707           DSAStack->addUsesAllocatorsDecl(
20708               DRE->getDecl(),
20709               DSAStackTy::UsesAllocatorsDeclKind::AllocatorTrait);
20710       }
20711     }
20712     OMPUsesAllocatorsClause::Data &NewD = NewData.emplace_back();
20713     NewD.Allocator = AllocatorExpr;
20714     NewD.AllocatorTraits = AllocatorTraitsExpr;
20715     NewD.LParenLoc = D.LParenLoc;
20716     NewD.RParenLoc = D.RParenLoc;
20717   }
20718   return OMPUsesAllocatorsClause::Create(Context, StartLoc, LParenLoc, EndLoc,
20719                                          NewData);
20720 }
20721 
20722 OMPClause *Sema::ActOnOpenMPAffinityClause(
20723     SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc,
20724     SourceLocation EndLoc, Expr *Modifier, ArrayRef<Expr *> Locators) {
20725   SmallVector<Expr *, 8> Vars;
20726   for (Expr *RefExpr : Locators) {
20727     assert(RefExpr && "NULL expr in OpenMP shared clause.");
20728     if (isa<DependentScopeDeclRefExpr>(RefExpr) || RefExpr->isTypeDependent()) {
20729       // It will be analyzed later.
20730       Vars.push_back(RefExpr);
20731       continue;
20732     }
20733 
20734     SourceLocation ELoc = RefExpr->getExprLoc();
20735     Expr *SimpleExpr = RefExpr->IgnoreParenImpCasts();
20736 
20737     if (!SimpleExpr->isLValue()) {
20738       Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
20739           << 1 << 0 << RefExpr->getSourceRange();
20740       continue;
20741     }
20742 
20743     ExprResult Res;
20744     {
20745       Sema::TentativeAnalysisScope Trap(*this);
20746       Res = CreateBuiltinUnaryOp(ELoc, UO_AddrOf, SimpleExpr);
20747     }
20748     if (!Res.isUsable() && !isa<OMPArraySectionExpr>(SimpleExpr) &&
20749         !isa<OMPArrayShapingExpr>(SimpleExpr)) {
20750       Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
20751           << 1 << 0 << RefExpr->getSourceRange();
20752       continue;
20753     }
20754     Vars.push_back(SimpleExpr);
20755   }
20756 
20757   return OMPAffinityClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
20758                                    EndLoc, Modifier, Vars);
20759 }
20760