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 (isInOpenMPTargetExecutionDirective()) {
2191       DSAStackTy::DSAVarData DVarTop =
2192           DSAStack->getTopDSA(D, DSAStack->isClauseParsingMode());
2193       if (DVarTop.CKind != OMPC_unknown && DVarTop.RefExpr)
2194         return VD;
2195       // If the declaration is enclosed in a 'declare target' directive,
2196       // then it should not be captured.
2197       //
2198       if (OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
2199         return nullptr;
2200       CapturedRegionScopeInfo *CSI = nullptr;
2201       for (FunctionScopeInfo *FSI : llvm::drop_begin(
2202                llvm::reverse(FunctionScopes),
2203                CheckScopeInfo ? (FunctionScopes.size() - (StopAt + 1)) : 0)) {
2204         if (!isa<CapturingScopeInfo>(FSI))
2205           return nullptr;
2206         if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(FSI))
2207           if (RSI->CapRegionKind == CR_OpenMP) {
2208             CSI = RSI;
2209             break;
2210           }
2211       }
2212       assert(CSI && "Failed to find CapturedRegionScopeInfo");
2213       SmallVector<OpenMPDirectiveKind, 4> Regions;
2214       getOpenMPCaptureRegions(Regions,
2215                               DSAStack->getDirective(CSI->OpenMPLevel));
2216       if (Regions[CSI->OpenMPCaptureLevel] != OMPD_task)
2217         return VD;
2218     }
2219     if (isInOpenMPDeclareTargetContext()) {
2220       // Try to mark variable as declare target if it is used in capturing
2221       // regions.
2222       if (LangOpts.OpenMP <= 45 &&
2223           !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
2224         checkDeclIsAllowedInOpenMPTarget(nullptr, VD);
2225       return nullptr;
2226     }
2227   }
2228 
2229   if (CheckScopeInfo) {
2230     bool OpenMPFound = false;
2231     for (unsigned I = StopAt + 1; I > 0; --I) {
2232       FunctionScopeInfo *FSI = FunctionScopes[I - 1];
2233       if(!isa<CapturingScopeInfo>(FSI))
2234         return nullptr;
2235       if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(FSI))
2236         if (RSI->CapRegionKind == CR_OpenMP) {
2237           OpenMPFound = true;
2238           break;
2239         }
2240     }
2241     if (!OpenMPFound)
2242       return nullptr;
2243   }
2244 
2245   if (DSAStack->getCurrentDirective() != OMPD_unknown &&
2246       (!DSAStack->isClauseParsingMode() ||
2247        DSAStack->getParentDirective() != OMPD_unknown)) {
2248     auto &&Info = DSAStack->isLoopControlVariable(D);
2249     if (Info.first ||
2250         (VD && VD->hasLocalStorage() &&
2251          isImplicitOrExplicitTaskingRegion(DSAStack->getCurrentDirective())) ||
2252         (VD && DSAStack->isForceVarCapturing()))
2253       return VD ? VD : Info.second;
2254     DSAStackTy::DSAVarData DVarTop =
2255         DSAStack->getTopDSA(D, DSAStack->isClauseParsingMode());
2256     if (DVarTop.CKind != OMPC_unknown && isOpenMPPrivate(DVarTop.CKind) &&
2257         (!VD || VD->hasLocalStorage() || !DVarTop.AppliedToPointee))
2258       return VD ? VD : cast<VarDecl>(DVarTop.PrivateCopy->getDecl());
2259     // Threadprivate variables must not be captured.
2260     if (isOpenMPThreadPrivate(DVarTop.CKind))
2261       return nullptr;
2262     // The variable is not private or it is the variable in the directive with
2263     // default(none) clause and not used in any clause.
2264     DSAStackTy::DSAVarData DVarPrivate = DSAStack->hasDSA(
2265         D,
2266         [](OpenMPClauseKind C, bool AppliedToPointee) {
2267           return isOpenMPPrivate(C) && !AppliedToPointee;
2268         },
2269         [](OpenMPDirectiveKind) { return true; },
2270         DSAStack->isClauseParsingMode());
2271     // Global shared must not be captured.
2272     if (VD && !VD->hasLocalStorage() && DVarPrivate.CKind == OMPC_unknown &&
2273         ((DSAStack->getDefaultDSA() != DSA_none &&
2274           DSAStack->getDefaultDSA() != DSA_firstprivate) ||
2275          DVarTop.CKind == OMPC_shared))
2276       return nullptr;
2277     if (DVarPrivate.CKind != OMPC_unknown ||
2278         (VD && (DSAStack->getDefaultDSA() == DSA_none ||
2279                 DSAStack->getDefaultDSA() == DSA_firstprivate)))
2280       return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
2281   }
2282   return nullptr;
2283 }
2284 
2285 void Sema::adjustOpenMPTargetScopeIndex(unsigned &FunctionScopesIndex,
2286                                         unsigned Level) const {
2287   FunctionScopesIndex -= getOpenMPCaptureLevels(DSAStack->getDirective(Level));
2288 }
2289 
2290 void Sema::startOpenMPLoop() {
2291   assert(LangOpts.OpenMP && "OpenMP must be enabled.");
2292   if (isOpenMPLoopDirective(DSAStack->getCurrentDirective()))
2293     DSAStack->loopInit();
2294 }
2295 
2296 void Sema::startOpenMPCXXRangeFor() {
2297   assert(LangOpts.OpenMP && "OpenMP must be enabled.");
2298   if (isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
2299     DSAStack->resetPossibleLoopCounter();
2300     DSAStack->loopStart();
2301   }
2302 }
2303 
2304 OpenMPClauseKind Sema::isOpenMPPrivateDecl(ValueDecl *D, unsigned Level,
2305                                            unsigned CapLevel) const {
2306   assert(LangOpts.OpenMP && "OpenMP is not allowed");
2307   if (DSAStack->hasExplicitDirective(
2308           [](OpenMPDirectiveKind K) { return isOpenMPTaskingDirective(K); },
2309           Level)) {
2310     bool IsTriviallyCopyable =
2311         D->getType().getNonReferenceType().isTriviallyCopyableType(Context) &&
2312         !D->getType()
2313              .getNonReferenceType()
2314              .getCanonicalType()
2315              ->getAsCXXRecordDecl();
2316     OpenMPDirectiveKind DKind = DSAStack->getDirective(Level);
2317     SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
2318     getOpenMPCaptureRegions(CaptureRegions, DKind);
2319     if (isOpenMPTaskingDirective(CaptureRegions[CapLevel]) &&
2320         (IsTriviallyCopyable ||
2321          !isOpenMPTaskLoopDirective(CaptureRegions[CapLevel]))) {
2322       if (DSAStack->hasExplicitDSA(
2323               D,
2324               [](OpenMPClauseKind K, bool) { return K == OMPC_firstprivate; },
2325               Level, /*NotLastprivate=*/true))
2326         return OMPC_firstprivate;
2327       DSAStackTy::DSAVarData DVar = DSAStack->getImplicitDSA(D, Level);
2328       if (DVar.CKind != OMPC_shared &&
2329           !DSAStack->isLoopControlVariable(D, Level).first && !DVar.RefExpr) {
2330         DSAStack->addImplicitTaskFirstprivate(Level, D);
2331         return OMPC_firstprivate;
2332       }
2333     }
2334   }
2335   if (isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
2336     if (DSAStack->getAssociatedLoops() > 0 &&
2337         !DSAStack->isLoopStarted()) {
2338       DSAStack->resetPossibleLoopCounter(D);
2339       DSAStack->loopStart();
2340       return OMPC_private;
2341     }
2342     if ((DSAStack->getPossiblyLoopCunter() == D->getCanonicalDecl() ||
2343          DSAStack->isLoopControlVariable(D).first) &&
2344         !DSAStack->hasExplicitDSA(
2345             D, [](OpenMPClauseKind K, bool) { return K != OMPC_private; },
2346             Level) &&
2347         !isOpenMPSimdDirective(DSAStack->getCurrentDirective()))
2348       return OMPC_private;
2349   }
2350   if (const auto *VD = dyn_cast<VarDecl>(D)) {
2351     if (DSAStack->isThreadPrivate(const_cast<VarDecl *>(VD)) &&
2352         DSAStack->isForceVarCapturing() &&
2353         !DSAStack->hasExplicitDSA(
2354             D, [](OpenMPClauseKind K, bool) { return K == OMPC_copyin; },
2355             Level))
2356       return OMPC_private;
2357   }
2358   // User-defined allocators are private since they must be defined in the
2359   // context of target region.
2360   if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, Level) &&
2361       DSAStack->isUsesAllocatorsDecl(Level, D).getValueOr(
2362           DSAStackTy::UsesAllocatorsDeclKind::AllocatorTrait) ==
2363           DSAStackTy::UsesAllocatorsDeclKind::UserDefinedAllocator)
2364     return OMPC_private;
2365   return (DSAStack->hasExplicitDSA(
2366               D, [](OpenMPClauseKind K, bool) { return K == OMPC_private; },
2367               Level) ||
2368           (DSAStack->isClauseParsingMode() &&
2369            DSAStack->getClauseParsingMode() == OMPC_private) ||
2370           // Consider taskgroup reduction descriptor variable a private
2371           // to avoid possible capture in the region.
2372           (DSAStack->hasExplicitDirective(
2373                [](OpenMPDirectiveKind K) {
2374                  return K == OMPD_taskgroup ||
2375                         ((isOpenMPParallelDirective(K) ||
2376                           isOpenMPWorksharingDirective(K)) &&
2377                          !isOpenMPSimdDirective(K));
2378                },
2379                Level) &&
2380            DSAStack->isTaskgroupReductionRef(D, Level)))
2381              ? OMPC_private
2382              : OMPC_unknown;
2383 }
2384 
2385 void Sema::setOpenMPCaptureKind(FieldDecl *FD, const ValueDecl *D,
2386                                 unsigned Level) {
2387   assert(LangOpts.OpenMP && "OpenMP is not allowed");
2388   D = getCanonicalDecl(D);
2389   OpenMPClauseKind OMPC = OMPC_unknown;
2390   for (unsigned I = DSAStack->getNestingLevel() + 1; I > Level; --I) {
2391     const unsigned NewLevel = I - 1;
2392     if (DSAStack->hasExplicitDSA(
2393             D,
2394             [&OMPC](const OpenMPClauseKind K, bool AppliedToPointee) {
2395               if (isOpenMPPrivate(K) && !AppliedToPointee) {
2396                 OMPC = K;
2397                 return true;
2398               }
2399               return false;
2400             },
2401             NewLevel))
2402       break;
2403     if (DSAStack->checkMappableExprComponentListsForDeclAtLevel(
2404             D, NewLevel,
2405             [](OMPClauseMappableExprCommon::MappableExprComponentListRef,
2406                OpenMPClauseKind) { return true; })) {
2407       OMPC = OMPC_map;
2408       break;
2409     }
2410     if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
2411                                        NewLevel)) {
2412       OMPC = OMPC_map;
2413       if (DSAStack->mustBeFirstprivateAtLevel(
2414               NewLevel, getVariableCategoryFromDecl(LangOpts, D)))
2415         OMPC = OMPC_firstprivate;
2416       break;
2417     }
2418   }
2419   if (OMPC != OMPC_unknown)
2420     FD->addAttr(OMPCaptureKindAttr::CreateImplicit(Context, unsigned(OMPC)));
2421 }
2422 
2423 bool Sema::isOpenMPTargetCapturedDecl(const ValueDecl *D, unsigned Level,
2424                                       unsigned CaptureLevel) const {
2425   assert(LangOpts.OpenMP && "OpenMP is not allowed");
2426   // Return true if the current level is no longer enclosed in a target region.
2427 
2428   SmallVector<OpenMPDirectiveKind, 4> Regions;
2429   getOpenMPCaptureRegions(Regions, DSAStack->getDirective(Level));
2430   const auto *VD = dyn_cast<VarDecl>(D);
2431   return VD && !VD->hasLocalStorage() &&
2432          DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
2433                                         Level) &&
2434          Regions[CaptureLevel] != OMPD_task;
2435 }
2436 
2437 bool Sema::isOpenMPGlobalCapturedDecl(ValueDecl *D, unsigned Level,
2438                                       unsigned CaptureLevel) const {
2439   assert(LangOpts.OpenMP && "OpenMP is not allowed");
2440   // Return true if the current level is no longer enclosed in a target region.
2441 
2442   if (const auto *VD = dyn_cast<VarDecl>(D)) {
2443     if (!VD->hasLocalStorage()) {
2444       if (isInOpenMPTargetExecutionDirective())
2445         return true;
2446       DSAStackTy::DSAVarData TopDVar =
2447           DSAStack->getTopDSA(D, /*FromParent=*/false);
2448       unsigned NumLevels =
2449           getOpenMPCaptureLevels(DSAStack->getDirective(Level));
2450       if (Level == 0)
2451         return (NumLevels == CaptureLevel + 1) && TopDVar.CKind != OMPC_shared;
2452       do {
2453         --Level;
2454         DSAStackTy::DSAVarData DVar = DSAStack->getImplicitDSA(D, Level);
2455         if (DVar.CKind != OMPC_shared)
2456           return true;
2457       } while (Level > 0);
2458     }
2459   }
2460   return true;
2461 }
2462 
2463 void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; }
2464 
2465 void Sema::ActOnOpenMPBeginDeclareVariant(SourceLocation Loc,
2466                                           OMPTraitInfo &TI) {
2467   OMPDeclareVariantScopes.push_back(OMPDeclareVariantScope(TI));
2468 }
2469 
2470 void Sema::ActOnOpenMPEndDeclareVariant() {
2471   assert(isInOpenMPDeclareVariantScope() &&
2472          "Not in OpenMP declare variant scope!");
2473 
2474   OMPDeclareVariantScopes.pop_back();
2475 }
2476 
2477 void Sema::finalizeOpenMPDelayedAnalysis(const FunctionDecl *Caller,
2478                                          const FunctionDecl *Callee,
2479                                          SourceLocation Loc) {
2480   assert(LangOpts.OpenMP && "Expected OpenMP compilation mode.");
2481   Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
2482       OMPDeclareTargetDeclAttr::getDeviceType(Caller->getMostRecentDecl());
2483   // Ignore host functions during device analyzis.
2484   if (LangOpts.OpenMPIsDevice &&
2485       (!DevTy || *DevTy == OMPDeclareTargetDeclAttr::DT_Host))
2486     return;
2487   // Ignore nohost functions during host analyzis.
2488   if (!LangOpts.OpenMPIsDevice && DevTy &&
2489       *DevTy == OMPDeclareTargetDeclAttr::DT_NoHost)
2490     return;
2491   const FunctionDecl *FD = Callee->getMostRecentDecl();
2492   DevTy = OMPDeclareTargetDeclAttr::getDeviceType(FD);
2493   if (LangOpts.OpenMPIsDevice && DevTy &&
2494       *DevTy == OMPDeclareTargetDeclAttr::DT_Host) {
2495     // Diagnose host function called during device codegen.
2496     StringRef HostDevTy =
2497         getOpenMPSimpleClauseTypeName(OMPC_device_type, OMPC_DEVICE_TYPE_host);
2498     Diag(Loc, diag::err_omp_wrong_device_function_call) << HostDevTy << 0;
2499     Diag(*OMPDeclareTargetDeclAttr::getLocation(FD),
2500          diag::note_omp_marked_device_type_here)
2501         << HostDevTy;
2502     return;
2503   }
2504       if (!LangOpts.OpenMPIsDevice && DevTy &&
2505           *DevTy == OMPDeclareTargetDeclAttr::DT_NoHost) {
2506         // Diagnose nohost function called during host codegen.
2507         StringRef NoHostDevTy = getOpenMPSimpleClauseTypeName(
2508             OMPC_device_type, OMPC_DEVICE_TYPE_nohost);
2509         Diag(Loc, diag::err_omp_wrong_device_function_call) << NoHostDevTy << 1;
2510         Diag(*OMPDeclareTargetDeclAttr::getLocation(FD),
2511              diag::note_omp_marked_device_type_here)
2512             << NoHostDevTy;
2513       }
2514 }
2515 
2516 void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind,
2517                                const DeclarationNameInfo &DirName,
2518                                Scope *CurScope, SourceLocation Loc) {
2519   DSAStack->push(DKind, DirName, CurScope, Loc);
2520   PushExpressionEvaluationContext(
2521       ExpressionEvaluationContext::PotentiallyEvaluated);
2522 }
2523 
2524 void Sema::StartOpenMPClause(OpenMPClauseKind K) {
2525   DSAStack->setClauseParsingMode(K);
2526 }
2527 
2528 void Sema::EndOpenMPClause() {
2529   DSAStack->setClauseParsingMode(/*K=*/OMPC_unknown);
2530   CleanupVarDeclMarking();
2531 }
2532 
2533 static std::pair<ValueDecl *, bool>
2534 getPrivateItem(Sema &S, Expr *&RefExpr, SourceLocation &ELoc,
2535                SourceRange &ERange, bool AllowArraySection = false);
2536 
2537 /// Check consistency of the reduction clauses.
2538 static void checkReductionClauses(Sema &S, DSAStackTy *Stack,
2539                                   ArrayRef<OMPClause *> Clauses) {
2540   bool InscanFound = false;
2541   SourceLocation InscanLoc;
2542   // OpenMP 5.0, 2.19.5.4 reduction Clause, Restrictions.
2543   // A reduction clause without the inscan reduction-modifier may not appear on
2544   // a construct on which a reduction clause with the inscan reduction-modifier
2545   // appears.
2546   for (OMPClause *C : Clauses) {
2547     if (C->getClauseKind() != OMPC_reduction)
2548       continue;
2549     auto *RC = cast<OMPReductionClause>(C);
2550     if (RC->getModifier() == OMPC_REDUCTION_inscan) {
2551       InscanFound = true;
2552       InscanLoc = RC->getModifierLoc();
2553       continue;
2554     }
2555     if (RC->getModifier() == OMPC_REDUCTION_task) {
2556       // OpenMP 5.0, 2.19.5.4 reduction Clause.
2557       // A reduction clause with the task reduction-modifier may only appear on
2558       // a parallel construct, a worksharing construct or a combined or
2559       // composite construct for which any of the aforementioned constructs is a
2560       // constituent construct and simd or loop are not constituent constructs.
2561       OpenMPDirectiveKind CurDir = Stack->getCurrentDirective();
2562       if (!(isOpenMPParallelDirective(CurDir) ||
2563             isOpenMPWorksharingDirective(CurDir)) ||
2564           isOpenMPSimdDirective(CurDir))
2565         S.Diag(RC->getModifierLoc(),
2566                diag::err_omp_reduction_task_not_parallel_or_worksharing);
2567       continue;
2568     }
2569   }
2570   if (InscanFound) {
2571     for (OMPClause *C : Clauses) {
2572       if (C->getClauseKind() != OMPC_reduction)
2573         continue;
2574       auto *RC = cast<OMPReductionClause>(C);
2575       if (RC->getModifier() != OMPC_REDUCTION_inscan) {
2576         S.Diag(RC->getModifier() == OMPC_REDUCTION_unknown
2577                    ? RC->getBeginLoc()
2578                    : RC->getModifierLoc(),
2579                diag::err_omp_inscan_reduction_expected);
2580         S.Diag(InscanLoc, diag::note_omp_previous_inscan_reduction);
2581         continue;
2582       }
2583       for (Expr *Ref : RC->varlists()) {
2584         assert(Ref && "NULL expr in OpenMP nontemporal clause.");
2585         SourceLocation ELoc;
2586         SourceRange ERange;
2587         Expr *SimpleRefExpr = Ref;
2588         auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange,
2589                                   /*AllowArraySection=*/true);
2590         ValueDecl *D = Res.first;
2591         if (!D)
2592           continue;
2593         if (!Stack->isUsedInScanDirective(getCanonicalDecl(D))) {
2594           S.Diag(Ref->getExprLoc(),
2595                  diag::err_omp_reduction_not_inclusive_exclusive)
2596               << Ref->getSourceRange();
2597         }
2598       }
2599     }
2600   }
2601 }
2602 
2603 static void checkAllocateClauses(Sema &S, DSAStackTy *Stack,
2604                                  ArrayRef<OMPClause *> Clauses);
2605 static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr,
2606                                  bool WithInit);
2607 
2608 static void reportOriginalDsa(Sema &SemaRef, const DSAStackTy *Stack,
2609                               const ValueDecl *D,
2610                               const DSAStackTy::DSAVarData &DVar,
2611                               bool IsLoopIterVar = false);
2612 
2613 void Sema::EndOpenMPDSABlock(Stmt *CurDirective) {
2614   // OpenMP [2.14.3.5, Restrictions, C/C++, p.1]
2615   //  A variable of class type (or array thereof) that appears in a lastprivate
2616   //  clause requires an accessible, unambiguous default constructor for the
2617   //  class type, unless the list item is also specified in a firstprivate
2618   //  clause.
2619   if (const auto *D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) {
2620     for (OMPClause *C : D->clauses()) {
2621       if (auto *Clause = dyn_cast<OMPLastprivateClause>(C)) {
2622         SmallVector<Expr *, 8> PrivateCopies;
2623         for (Expr *DE : Clause->varlists()) {
2624           if (DE->isValueDependent() || DE->isTypeDependent()) {
2625             PrivateCopies.push_back(nullptr);
2626             continue;
2627           }
2628           auto *DRE = cast<DeclRefExpr>(DE->IgnoreParens());
2629           auto *VD = cast<VarDecl>(DRE->getDecl());
2630           QualType Type = VD->getType().getNonReferenceType();
2631           const DSAStackTy::DSAVarData DVar =
2632               DSAStack->getTopDSA(VD, /*FromParent=*/false);
2633           if (DVar.CKind == OMPC_lastprivate) {
2634             // Generate helper private variable and initialize it with the
2635             // default value. The address of the original variable is replaced
2636             // by the address of the new private variable in CodeGen. This new
2637             // variable is not added to IdResolver, so the code in the OpenMP
2638             // region uses original variable for proper diagnostics.
2639             VarDecl *VDPrivate = buildVarDecl(
2640                 *this, DE->getExprLoc(), Type.getUnqualifiedType(),
2641                 VD->getName(), VD->hasAttrs() ? &VD->getAttrs() : nullptr, DRE);
2642             ActOnUninitializedDecl(VDPrivate);
2643             if (VDPrivate->isInvalidDecl()) {
2644               PrivateCopies.push_back(nullptr);
2645               continue;
2646             }
2647             PrivateCopies.push_back(buildDeclRefExpr(
2648                 *this, VDPrivate, DE->getType(), DE->getExprLoc()));
2649           } else {
2650             // The variable is also a firstprivate, so initialization sequence
2651             // for private copy is generated already.
2652             PrivateCopies.push_back(nullptr);
2653           }
2654         }
2655         Clause->setPrivateCopies(PrivateCopies);
2656         continue;
2657       }
2658       // Finalize nontemporal clause by handling private copies, if any.
2659       if (auto *Clause = dyn_cast<OMPNontemporalClause>(C)) {
2660         SmallVector<Expr *, 8> PrivateRefs;
2661         for (Expr *RefExpr : Clause->varlists()) {
2662           assert(RefExpr && "NULL expr in OpenMP nontemporal clause.");
2663           SourceLocation ELoc;
2664           SourceRange ERange;
2665           Expr *SimpleRefExpr = RefExpr;
2666           auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
2667           if (Res.second)
2668             // It will be analyzed later.
2669             PrivateRefs.push_back(RefExpr);
2670           ValueDecl *D = Res.first;
2671           if (!D)
2672             continue;
2673 
2674           const DSAStackTy::DSAVarData DVar =
2675               DSAStack->getTopDSA(D, /*FromParent=*/false);
2676           PrivateRefs.push_back(DVar.PrivateCopy ? DVar.PrivateCopy
2677                                                  : SimpleRefExpr);
2678         }
2679         Clause->setPrivateRefs(PrivateRefs);
2680         continue;
2681       }
2682       if (auto *Clause = dyn_cast<OMPUsesAllocatorsClause>(C)) {
2683         for (unsigned I = 0, E = Clause->getNumberOfAllocators(); I < E; ++I) {
2684           OMPUsesAllocatorsClause::Data D = Clause->getAllocatorData(I);
2685           auto *DRE = dyn_cast<DeclRefExpr>(D.Allocator->IgnoreParenImpCasts());
2686           if (!DRE)
2687             continue;
2688           ValueDecl *VD = DRE->getDecl();
2689           if (!VD || !isa<VarDecl>(VD))
2690             continue;
2691           DSAStackTy::DSAVarData DVar =
2692               DSAStack->getTopDSA(VD, /*FromParent=*/false);
2693           // OpenMP [2.12.5, target Construct]
2694           // Memory allocators that appear in a uses_allocators clause cannot
2695           // appear in other data-sharing attribute clauses or data-mapping
2696           // attribute clauses in the same construct.
2697           Expr *MapExpr = nullptr;
2698           if (DVar.RefExpr ||
2699               DSAStack->checkMappableExprComponentListsForDecl(
2700                   VD, /*CurrentRegionOnly=*/true,
2701                   [VD, &MapExpr](
2702                       OMPClauseMappableExprCommon::MappableExprComponentListRef
2703                           MapExprComponents,
2704                       OpenMPClauseKind C) {
2705                     auto MI = MapExprComponents.rbegin();
2706                     auto ME = MapExprComponents.rend();
2707                     if (MI != ME &&
2708                         MI->getAssociatedDeclaration()->getCanonicalDecl() ==
2709                             VD->getCanonicalDecl()) {
2710                       MapExpr = MI->getAssociatedExpression();
2711                       return true;
2712                     }
2713                     return false;
2714                   })) {
2715             Diag(D.Allocator->getExprLoc(),
2716                  diag::err_omp_allocator_used_in_clauses)
2717                 << D.Allocator->getSourceRange();
2718             if (DVar.RefExpr)
2719               reportOriginalDsa(*this, DSAStack, VD, DVar);
2720             else
2721               Diag(MapExpr->getExprLoc(), diag::note_used_here)
2722                   << MapExpr->getSourceRange();
2723           }
2724         }
2725         continue;
2726       }
2727     }
2728     // Check allocate clauses.
2729     if (!CurContext->isDependentContext())
2730       checkAllocateClauses(*this, DSAStack, D->clauses());
2731     checkReductionClauses(*this, DSAStack, D->clauses());
2732   }
2733 
2734   DSAStack->pop();
2735   DiscardCleanupsInEvaluationContext();
2736   PopExpressionEvaluationContext();
2737 }
2738 
2739 static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
2740                                      Expr *NumIterations, Sema &SemaRef,
2741                                      Scope *S, DSAStackTy *Stack);
2742 
2743 namespace {
2744 
2745 class VarDeclFilterCCC final : public CorrectionCandidateCallback {
2746 private:
2747   Sema &SemaRef;
2748 
2749 public:
2750   explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {}
2751   bool ValidateCandidate(const TypoCorrection &Candidate) override {
2752     NamedDecl *ND = Candidate.getCorrectionDecl();
2753     if (const auto *VD = dyn_cast_or_null<VarDecl>(ND)) {
2754       return VD->hasGlobalStorage() &&
2755              SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
2756                                    SemaRef.getCurScope());
2757     }
2758     return false;
2759   }
2760 
2761   std::unique_ptr<CorrectionCandidateCallback> clone() override {
2762     return std::make_unique<VarDeclFilterCCC>(*this);
2763   }
2764 
2765 };
2766 
2767 class VarOrFuncDeclFilterCCC final : public CorrectionCandidateCallback {
2768 private:
2769   Sema &SemaRef;
2770 
2771 public:
2772   explicit VarOrFuncDeclFilterCCC(Sema &S) : SemaRef(S) {}
2773   bool ValidateCandidate(const TypoCorrection &Candidate) override {
2774     NamedDecl *ND = Candidate.getCorrectionDecl();
2775     if (ND && ((isa<VarDecl>(ND) && ND->getKind() == Decl::Var) ||
2776                isa<FunctionDecl>(ND))) {
2777       return SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
2778                                    SemaRef.getCurScope());
2779     }
2780     return false;
2781   }
2782 
2783   std::unique_ptr<CorrectionCandidateCallback> clone() override {
2784     return std::make_unique<VarOrFuncDeclFilterCCC>(*this);
2785   }
2786 };
2787 
2788 } // namespace
2789 
2790 ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope,
2791                                          CXXScopeSpec &ScopeSpec,
2792                                          const DeclarationNameInfo &Id,
2793                                          OpenMPDirectiveKind Kind) {
2794   LookupResult Lookup(*this, Id, LookupOrdinaryName);
2795   LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
2796 
2797   if (Lookup.isAmbiguous())
2798     return ExprError();
2799 
2800   VarDecl *VD;
2801   if (!Lookup.isSingleResult()) {
2802     VarDeclFilterCCC CCC(*this);
2803     if (TypoCorrection Corrected =
2804             CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr, CCC,
2805                         CTK_ErrorRecovery)) {
2806       diagnoseTypo(Corrected,
2807                    PDiag(Lookup.empty()
2808                              ? diag::err_undeclared_var_use_suggest
2809                              : diag::err_omp_expected_var_arg_suggest)
2810                        << Id.getName());
2811       VD = Corrected.getCorrectionDeclAs<VarDecl>();
2812     } else {
2813       Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use
2814                                        : diag::err_omp_expected_var_arg)
2815           << Id.getName();
2816       return ExprError();
2817     }
2818   } else if (!(VD = Lookup.getAsSingle<VarDecl>())) {
2819     Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName();
2820     Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at);
2821     return ExprError();
2822   }
2823   Lookup.suppressDiagnostics();
2824 
2825   // OpenMP [2.9.2, Syntax, C/C++]
2826   //   Variables must be file-scope, namespace-scope, or static block-scope.
2827   if (Kind == OMPD_threadprivate && !VD->hasGlobalStorage()) {
2828     Diag(Id.getLoc(), diag::err_omp_global_var_arg)
2829         << getOpenMPDirectiveName(Kind) << !VD->isStaticLocal();
2830     bool IsDecl =
2831         VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2832     Diag(VD->getLocation(),
2833          IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2834         << VD;
2835     return ExprError();
2836   }
2837 
2838   VarDecl *CanonicalVD = VD->getCanonicalDecl();
2839   NamedDecl *ND = CanonicalVD;
2840   // OpenMP [2.9.2, Restrictions, C/C++, p.2]
2841   //   A threadprivate directive for file-scope variables must appear outside
2842   //   any definition or declaration.
2843   if (CanonicalVD->getDeclContext()->isTranslationUnit() &&
2844       !getCurLexicalContext()->isTranslationUnit()) {
2845     Diag(Id.getLoc(), diag::err_omp_var_scope)
2846         << getOpenMPDirectiveName(Kind) << VD;
2847     bool IsDecl =
2848         VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2849     Diag(VD->getLocation(),
2850          IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2851         << VD;
2852     return ExprError();
2853   }
2854   // OpenMP [2.9.2, Restrictions, C/C++, p.3]
2855   //   A threadprivate directive for static class member variables must appear
2856   //   in the class definition, in the same scope in which the member
2857   //   variables are declared.
2858   if (CanonicalVD->isStaticDataMember() &&
2859       !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) {
2860     Diag(Id.getLoc(), diag::err_omp_var_scope)
2861         << getOpenMPDirectiveName(Kind) << VD;
2862     bool IsDecl =
2863         VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2864     Diag(VD->getLocation(),
2865          IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2866         << VD;
2867     return ExprError();
2868   }
2869   // OpenMP [2.9.2, Restrictions, C/C++, p.4]
2870   //   A threadprivate directive for namespace-scope variables must appear
2871   //   outside any definition or declaration other than the namespace
2872   //   definition itself.
2873   if (CanonicalVD->getDeclContext()->isNamespace() &&
2874       (!getCurLexicalContext()->isFileContext() ||
2875        !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) {
2876     Diag(Id.getLoc(), diag::err_omp_var_scope)
2877         << getOpenMPDirectiveName(Kind) << VD;
2878     bool IsDecl =
2879         VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2880     Diag(VD->getLocation(),
2881          IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2882         << VD;
2883     return ExprError();
2884   }
2885   // OpenMP [2.9.2, Restrictions, C/C++, p.6]
2886   //   A threadprivate directive for static block-scope variables must appear
2887   //   in the scope of the variable and not in a nested scope.
2888   if (CanonicalVD->isLocalVarDecl() && CurScope &&
2889       !isDeclInScope(ND, getCurLexicalContext(), CurScope)) {
2890     Diag(Id.getLoc(), diag::err_omp_var_scope)
2891         << getOpenMPDirectiveName(Kind) << VD;
2892     bool IsDecl =
2893         VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2894     Diag(VD->getLocation(),
2895          IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2896         << VD;
2897     return ExprError();
2898   }
2899 
2900   // OpenMP [2.9.2, Restrictions, C/C++, p.2-6]
2901   //   A threadprivate directive must lexically precede all references to any
2902   //   of the variables in its list.
2903   if (Kind == OMPD_threadprivate && VD->isUsed() &&
2904       !DSAStack->isThreadPrivate(VD)) {
2905     Diag(Id.getLoc(), diag::err_omp_var_used)
2906         << getOpenMPDirectiveName(Kind) << VD;
2907     return ExprError();
2908   }
2909 
2910   QualType ExprType = VD->getType().getNonReferenceType();
2911   return DeclRefExpr::Create(Context, NestedNameSpecifierLoc(),
2912                              SourceLocation(), VD,
2913                              /*RefersToEnclosingVariableOrCapture=*/false,
2914                              Id.getLoc(), ExprType, VK_LValue);
2915 }
2916 
2917 Sema::DeclGroupPtrTy
2918 Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc,
2919                                         ArrayRef<Expr *> VarList) {
2920   if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) {
2921     CurContext->addDecl(D);
2922     return DeclGroupPtrTy::make(DeclGroupRef(D));
2923   }
2924   return nullptr;
2925 }
2926 
2927 namespace {
2928 class LocalVarRefChecker final
2929     : public ConstStmtVisitor<LocalVarRefChecker, bool> {
2930   Sema &SemaRef;
2931 
2932 public:
2933   bool VisitDeclRefExpr(const DeclRefExpr *E) {
2934     if (const auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
2935       if (VD->hasLocalStorage()) {
2936         SemaRef.Diag(E->getBeginLoc(),
2937                      diag::err_omp_local_var_in_threadprivate_init)
2938             << E->getSourceRange();
2939         SemaRef.Diag(VD->getLocation(), diag::note_defined_here)
2940             << VD << VD->getSourceRange();
2941         return true;
2942       }
2943     }
2944     return false;
2945   }
2946   bool VisitStmt(const Stmt *S) {
2947     for (const Stmt *Child : S->children()) {
2948       if (Child && Visit(Child))
2949         return true;
2950     }
2951     return false;
2952   }
2953   explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {}
2954 };
2955 } // namespace
2956 
2957 OMPThreadPrivateDecl *
2958 Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) {
2959   SmallVector<Expr *, 8> Vars;
2960   for (Expr *RefExpr : VarList) {
2961     auto *DE = cast<DeclRefExpr>(RefExpr);
2962     auto *VD = cast<VarDecl>(DE->getDecl());
2963     SourceLocation ILoc = DE->getExprLoc();
2964 
2965     // Mark variable as used.
2966     VD->setReferenced();
2967     VD->markUsed(Context);
2968 
2969     QualType QType = VD->getType();
2970     if (QType->isDependentType() || QType->isInstantiationDependentType()) {
2971       // It will be analyzed later.
2972       Vars.push_back(DE);
2973       continue;
2974     }
2975 
2976     // OpenMP [2.9.2, Restrictions, C/C++, p.10]
2977     //   A threadprivate variable must not have an incomplete type.
2978     if (RequireCompleteType(ILoc, VD->getType(),
2979                             diag::err_omp_threadprivate_incomplete_type)) {
2980       continue;
2981     }
2982 
2983     // OpenMP [2.9.2, Restrictions, C/C++, p.10]
2984     //   A threadprivate variable must not have a reference type.
2985     if (VD->getType()->isReferenceType()) {
2986       Diag(ILoc, diag::err_omp_ref_type_arg)
2987           << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType();
2988       bool IsDecl =
2989           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2990       Diag(VD->getLocation(),
2991            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2992           << VD;
2993       continue;
2994     }
2995 
2996     // Check if this is a TLS variable. If TLS is not being supported, produce
2997     // the corresponding diagnostic.
2998     if ((VD->getTLSKind() != VarDecl::TLS_None &&
2999          !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
3000            getLangOpts().OpenMPUseTLS &&
3001            getASTContext().getTargetInfo().isTLSSupported())) ||
3002         (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
3003          !VD->isLocalVarDecl())) {
3004       Diag(ILoc, diag::err_omp_var_thread_local)
3005           << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1);
3006       bool IsDecl =
3007           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
3008       Diag(VD->getLocation(),
3009            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
3010           << VD;
3011       continue;
3012     }
3013 
3014     // Check if initial value of threadprivate variable reference variable with
3015     // local storage (it is not supported by runtime).
3016     if (const Expr *Init = VD->getAnyInitializer()) {
3017       LocalVarRefChecker Checker(*this);
3018       if (Checker.Visit(Init))
3019         continue;
3020     }
3021 
3022     Vars.push_back(RefExpr);
3023     DSAStack->addDSA(VD, DE, OMPC_threadprivate);
3024     VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit(
3025         Context, SourceRange(Loc, Loc)));
3026     if (ASTMutationListener *ML = Context.getASTMutationListener())
3027       ML->DeclarationMarkedOpenMPThreadPrivate(VD);
3028   }
3029   OMPThreadPrivateDecl *D = nullptr;
3030   if (!Vars.empty()) {
3031     D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc,
3032                                      Vars);
3033     D->setAccess(AS_public);
3034   }
3035   return D;
3036 }
3037 
3038 static OMPAllocateDeclAttr::AllocatorTypeTy
3039 getAllocatorKind(Sema &S, DSAStackTy *Stack, Expr *Allocator) {
3040   if (!Allocator)
3041     return OMPAllocateDeclAttr::OMPNullMemAlloc;
3042   if (Allocator->isTypeDependent() || Allocator->isValueDependent() ||
3043       Allocator->isInstantiationDependent() ||
3044       Allocator->containsUnexpandedParameterPack())
3045     return OMPAllocateDeclAttr::OMPUserDefinedMemAlloc;
3046   auto AllocatorKindRes = OMPAllocateDeclAttr::OMPUserDefinedMemAlloc;
3047   const Expr *AE = Allocator->IgnoreParenImpCasts();
3048   for (int I = 0; I < OMPAllocateDeclAttr::OMPUserDefinedMemAlloc; ++I) {
3049     auto AllocatorKind = static_cast<OMPAllocateDeclAttr::AllocatorTypeTy>(I);
3050     const Expr *DefAllocator = Stack->getAllocator(AllocatorKind);
3051     llvm::FoldingSetNodeID AEId, DAEId;
3052     AE->Profile(AEId, S.getASTContext(), /*Canonical=*/true);
3053     DefAllocator->Profile(DAEId, S.getASTContext(), /*Canonical=*/true);
3054     if (AEId == DAEId) {
3055       AllocatorKindRes = AllocatorKind;
3056       break;
3057     }
3058   }
3059   return AllocatorKindRes;
3060 }
3061 
3062 static bool checkPreviousOMPAllocateAttribute(
3063     Sema &S, DSAStackTy *Stack, Expr *RefExpr, VarDecl *VD,
3064     OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind, Expr *Allocator) {
3065   if (!VD->hasAttr<OMPAllocateDeclAttr>())
3066     return false;
3067   const auto *A = VD->getAttr<OMPAllocateDeclAttr>();
3068   Expr *PrevAllocator = A->getAllocator();
3069   OMPAllocateDeclAttr::AllocatorTypeTy PrevAllocatorKind =
3070       getAllocatorKind(S, Stack, PrevAllocator);
3071   bool AllocatorsMatch = AllocatorKind == PrevAllocatorKind;
3072   if (AllocatorsMatch &&
3073       AllocatorKind == OMPAllocateDeclAttr::OMPUserDefinedMemAlloc &&
3074       Allocator && PrevAllocator) {
3075     const Expr *AE = Allocator->IgnoreParenImpCasts();
3076     const Expr *PAE = PrevAllocator->IgnoreParenImpCasts();
3077     llvm::FoldingSetNodeID AEId, PAEId;
3078     AE->Profile(AEId, S.Context, /*Canonical=*/true);
3079     PAE->Profile(PAEId, S.Context, /*Canonical=*/true);
3080     AllocatorsMatch = AEId == PAEId;
3081   }
3082   if (!AllocatorsMatch) {
3083     SmallString<256> AllocatorBuffer;
3084     llvm::raw_svector_ostream AllocatorStream(AllocatorBuffer);
3085     if (Allocator)
3086       Allocator->printPretty(AllocatorStream, nullptr, S.getPrintingPolicy());
3087     SmallString<256> PrevAllocatorBuffer;
3088     llvm::raw_svector_ostream PrevAllocatorStream(PrevAllocatorBuffer);
3089     if (PrevAllocator)
3090       PrevAllocator->printPretty(PrevAllocatorStream, nullptr,
3091                                  S.getPrintingPolicy());
3092 
3093     SourceLocation AllocatorLoc =
3094         Allocator ? Allocator->getExprLoc() : RefExpr->getExprLoc();
3095     SourceRange AllocatorRange =
3096         Allocator ? Allocator->getSourceRange() : RefExpr->getSourceRange();
3097     SourceLocation PrevAllocatorLoc =
3098         PrevAllocator ? PrevAllocator->getExprLoc() : A->getLocation();
3099     SourceRange PrevAllocatorRange =
3100         PrevAllocator ? PrevAllocator->getSourceRange() : A->getRange();
3101     S.Diag(AllocatorLoc, diag::warn_omp_used_different_allocator)
3102         << (Allocator ? 1 : 0) << AllocatorStream.str()
3103         << (PrevAllocator ? 1 : 0) << PrevAllocatorStream.str()
3104         << AllocatorRange;
3105     S.Diag(PrevAllocatorLoc, diag::note_omp_previous_allocator)
3106         << PrevAllocatorRange;
3107     return true;
3108   }
3109   return false;
3110 }
3111 
3112 static void
3113 applyOMPAllocateAttribute(Sema &S, VarDecl *VD,
3114                           OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind,
3115                           Expr *Allocator, SourceRange SR) {
3116   if (VD->hasAttr<OMPAllocateDeclAttr>())
3117     return;
3118   if (Allocator &&
3119       (Allocator->isTypeDependent() || Allocator->isValueDependent() ||
3120        Allocator->isInstantiationDependent() ||
3121        Allocator->containsUnexpandedParameterPack()))
3122     return;
3123   auto *A = OMPAllocateDeclAttr::CreateImplicit(S.Context, AllocatorKind,
3124                                                 Allocator, SR);
3125   VD->addAttr(A);
3126   if (ASTMutationListener *ML = S.Context.getASTMutationListener())
3127     ML->DeclarationMarkedOpenMPAllocate(VD, A);
3128 }
3129 
3130 Sema::DeclGroupPtrTy Sema::ActOnOpenMPAllocateDirective(
3131     SourceLocation Loc, ArrayRef<Expr *> VarList,
3132     ArrayRef<OMPClause *> Clauses, DeclContext *Owner) {
3133   assert(Clauses.size() <= 1 && "Expected at most one clause.");
3134   Expr *Allocator = nullptr;
3135   if (Clauses.empty()) {
3136     // OpenMP 5.0, 2.11.3 allocate Directive, Restrictions.
3137     // allocate directives that appear in a target region must specify an
3138     // allocator clause unless a requires directive with the dynamic_allocators
3139     // clause is present in the same compilation unit.
3140     if (LangOpts.OpenMPIsDevice &&
3141         !DSAStack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>())
3142       targetDiag(Loc, diag::err_expected_allocator_clause);
3143   } else {
3144     Allocator = cast<OMPAllocatorClause>(Clauses.back())->getAllocator();
3145   }
3146   OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind =
3147       getAllocatorKind(*this, DSAStack, Allocator);
3148   SmallVector<Expr *, 8> Vars;
3149   for (Expr *RefExpr : VarList) {
3150     auto *DE = cast<DeclRefExpr>(RefExpr);
3151     auto *VD = cast<VarDecl>(DE->getDecl());
3152 
3153     // Check if this is a TLS variable or global register.
3154     if (VD->getTLSKind() != VarDecl::TLS_None ||
3155         VD->hasAttr<OMPThreadPrivateDeclAttr>() ||
3156         (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
3157          !VD->isLocalVarDecl()))
3158       continue;
3159 
3160     // If the used several times in the allocate directive, the same allocator
3161     // must be used.
3162     if (checkPreviousOMPAllocateAttribute(*this, DSAStack, RefExpr, VD,
3163                                           AllocatorKind, Allocator))
3164       continue;
3165 
3166     // OpenMP, 2.11.3 allocate Directive, Restrictions, C / C++
3167     // If a list item has a static storage type, the allocator expression in the
3168     // allocator clause must be a constant expression that evaluates to one of
3169     // the predefined memory allocator values.
3170     if (Allocator && VD->hasGlobalStorage()) {
3171       if (AllocatorKind == OMPAllocateDeclAttr::OMPUserDefinedMemAlloc) {
3172         Diag(Allocator->getExprLoc(),
3173              diag::err_omp_expected_predefined_allocator)
3174             << Allocator->getSourceRange();
3175         bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
3176                       VarDecl::DeclarationOnly;
3177         Diag(VD->getLocation(),
3178              IsDecl ? diag::note_previous_decl : diag::note_defined_here)
3179             << VD;
3180         continue;
3181       }
3182     }
3183 
3184     Vars.push_back(RefExpr);
3185     applyOMPAllocateAttribute(*this, VD, AllocatorKind, Allocator,
3186                               DE->getSourceRange());
3187   }
3188   if (Vars.empty())
3189     return nullptr;
3190   if (!Owner)
3191     Owner = getCurLexicalContext();
3192   auto *D = OMPAllocateDecl::Create(Context, Owner, Loc, Vars, Clauses);
3193   D->setAccess(AS_public);
3194   Owner->addDecl(D);
3195   return DeclGroupPtrTy::make(DeclGroupRef(D));
3196 }
3197 
3198 Sema::DeclGroupPtrTy
3199 Sema::ActOnOpenMPRequiresDirective(SourceLocation Loc,
3200                                    ArrayRef<OMPClause *> ClauseList) {
3201   OMPRequiresDecl *D = nullptr;
3202   if (!CurContext->isFileContext()) {
3203     Diag(Loc, diag::err_omp_invalid_scope) << "requires";
3204   } else {
3205     D = CheckOMPRequiresDecl(Loc, ClauseList);
3206     if (D) {
3207       CurContext->addDecl(D);
3208       DSAStack->addRequiresDecl(D);
3209     }
3210   }
3211   return DeclGroupPtrTy::make(DeclGroupRef(D));
3212 }
3213 
3214 void Sema::ActOnOpenMPAssumesDirective(SourceLocation Loc,
3215                                        OpenMPDirectiveKind DKind,
3216                                        ArrayRef<StringRef> Assumptions,
3217                                        bool SkippedClauses) {
3218   if (!SkippedClauses && Assumptions.empty())
3219     Diag(Loc, diag::err_omp_no_clause_for_directive)
3220         << llvm::omp::getAllAssumeClauseOptions()
3221         << llvm::omp::getOpenMPDirectiveName(DKind);
3222 
3223   auto *AA = AssumptionAttr::Create(Context, llvm::join(Assumptions, ","), Loc);
3224   if (DKind == llvm::omp::Directive::OMPD_begin_assumes) {
3225     OMPAssumeScoped.push_back(AA);
3226     return;
3227   }
3228 
3229   // Global assumes without assumption clauses are ignored.
3230   if (Assumptions.empty())
3231     return;
3232 
3233   assert(DKind == llvm::omp::Directive::OMPD_assumes &&
3234          "Unexpected omp assumption directive!");
3235   OMPAssumeGlobal.push_back(AA);
3236 
3237   // The OMPAssumeGlobal scope above will take care of new declarations but
3238   // we also want to apply the assumption to existing ones, e.g., to
3239   // declarations in included headers. To this end, we traverse all existing
3240   // declaration contexts and annotate function declarations here.
3241   SmallVector<DeclContext *, 8> DeclContexts;
3242   auto *Ctx = CurContext;
3243   while (Ctx->getLexicalParent())
3244     Ctx = Ctx->getLexicalParent();
3245   DeclContexts.push_back(Ctx);
3246   while (!DeclContexts.empty()) {
3247     DeclContext *DC = DeclContexts.pop_back_val();
3248     for (auto *SubDC : DC->decls()) {
3249       if (SubDC->isInvalidDecl())
3250         continue;
3251       if (auto *CTD = dyn_cast<ClassTemplateDecl>(SubDC)) {
3252         DeclContexts.push_back(CTD->getTemplatedDecl());
3253         for (auto *S : CTD->specializations())
3254           DeclContexts.push_back(S);
3255         continue;
3256       }
3257       if (auto *DC = dyn_cast<DeclContext>(SubDC))
3258         DeclContexts.push_back(DC);
3259       if (auto *F = dyn_cast<FunctionDecl>(SubDC)) {
3260         F->addAttr(AA);
3261         continue;
3262       }
3263     }
3264   }
3265 }
3266 
3267 void Sema::ActOnOpenMPEndAssumesDirective() {
3268   assert(isInOpenMPAssumeScope() && "Not in OpenMP assumes scope!");
3269   OMPAssumeScoped.pop_back();
3270 }
3271 
3272 OMPRequiresDecl *Sema::CheckOMPRequiresDecl(SourceLocation Loc,
3273                                             ArrayRef<OMPClause *> ClauseList) {
3274   /// For target specific clauses, the requires directive cannot be
3275   /// specified after the handling of any of the target regions in the
3276   /// current compilation unit.
3277   ArrayRef<SourceLocation> TargetLocations =
3278       DSAStack->getEncounteredTargetLocs();
3279   SourceLocation AtomicLoc = DSAStack->getAtomicDirectiveLoc();
3280   if (!TargetLocations.empty() || !AtomicLoc.isInvalid()) {
3281     for (const OMPClause *CNew : ClauseList) {
3282       // Check if any of the requires clauses affect target regions.
3283       if (isa<OMPUnifiedSharedMemoryClause>(CNew) ||
3284           isa<OMPUnifiedAddressClause>(CNew) ||
3285           isa<OMPReverseOffloadClause>(CNew) ||
3286           isa<OMPDynamicAllocatorsClause>(CNew)) {
3287         Diag(Loc, diag::err_omp_directive_before_requires)
3288             << "target" << getOpenMPClauseName(CNew->getClauseKind());
3289         for (SourceLocation TargetLoc : TargetLocations) {
3290           Diag(TargetLoc, diag::note_omp_requires_encountered_directive)
3291               << "target";
3292         }
3293       } else if (!AtomicLoc.isInvalid() &&
3294                  isa<OMPAtomicDefaultMemOrderClause>(CNew)) {
3295         Diag(Loc, diag::err_omp_directive_before_requires)
3296             << "atomic" << getOpenMPClauseName(CNew->getClauseKind());
3297         Diag(AtomicLoc, diag::note_omp_requires_encountered_directive)
3298             << "atomic";
3299       }
3300     }
3301   }
3302 
3303   if (!DSAStack->hasDuplicateRequiresClause(ClauseList))
3304     return OMPRequiresDecl::Create(Context, getCurLexicalContext(), Loc,
3305                                    ClauseList);
3306   return nullptr;
3307 }
3308 
3309 static void reportOriginalDsa(Sema &SemaRef, const DSAStackTy *Stack,
3310                               const ValueDecl *D,
3311                               const DSAStackTy::DSAVarData &DVar,
3312                               bool IsLoopIterVar) {
3313   if (DVar.RefExpr) {
3314     SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
3315         << getOpenMPClauseName(DVar.CKind);
3316     return;
3317   }
3318   enum {
3319     PDSA_StaticMemberShared,
3320     PDSA_StaticLocalVarShared,
3321     PDSA_LoopIterVarPrivate,
3322     PDSA_LoopIterVarLinear,
3323     PDSA_LoopIterVarLastprivate,
3324     PDSA_ConstVarShared,
3325     PDSA_GlobalVarShared,
3326     PDSA_TaskVarFirstprivate,
3327     PDSA_LocalVarPrivate,
3328     PDSA_Implicit
3329   } Reason = PDSA_Implicit;
3330   bool ReportHint = false;
3331   auto ReportLoc = D->getLocation();
3332   auto *VD = dyn_cast<VarDecl>(D);
3333   if (IsLoopIterVar) {
3334     if (DVar.CKind == OMPC_private)
3335       Reason = PDSA_LoopIterVarPrivate;
3336     else if (DVar.CKind == OMPC_lastprivate)
3337       Reason = PDSA_LoopIterVarLastprivate;
3338     else
3339       Reason = PDSA_LoopIterVarLinear;
3340   } else if (isOpenMPTaskingDirective(DVar.DKind) &&
3341              DVar.CKind == OMPC_firstprivate) {
3342     Reason = PDSA_TaskVarFirstprivate;
3343     ReportLoc = DVar.ImplicitDSALoc;
3344   } else if (VD && VD->isStaticLocal())
3345     Reason = PDSA_StaticLocalVarShared;
3346   else if (VD && VD->isStaticDataMember())
3347     Reason = PDSA_StaticMemberShared;
3348   else if (VD && VD->isFileVarDecl())
3349     Reason = PDSA_GlobalVarShared;
3350   else if (D->getType().isConstant(SemaRef.getASTContext()))
3351     Reason = PDSA_ConstVarShared;
3352   else if (VD && VD->isLocalVarDecl() && DVar.CKind == OMPC_private) {
3353     ReportHint = true;
3354     Reason = PDSA_LocalVarPrivate;
3355   }
3356   if (Reason != PDSA_Implicit) {
3357     SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa)
3358         << Reason << ReportHint
3359         << getOpenMPDirectiveName(Stack->getCurrentDirective());
3360   } else if (DVar.ImplicitDSALoc.isValid()) {
3361     SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa)
3362         << getOpenMPClauseName(DVar.CKind);
3363   }
3364 }
3365 
3366 static OpenMPMapClauseKind
3367 getMapClauseKindFromModifier(OpenMPDefaultmapClauseModifier M,
3368                              bool IsAggregateOrDeclareTarget) {
3369   OpenMPMapClauseKind Kind = OMPC_MAP_unknown;
3370   switch (M) {
3371   case OMPC_DEFAULTMAP_MODIFIER_alloc:
3372     Kind = OMPC_MAP_alloc;
3373     break;
3374   case OMPC_DEFAULTMAP_MODIFIER_to:
3375     Kind = OMPC_MAP_to;
3376     break;
3377   case OMPC_DEFAULTMAP_MODIFIER_from:
3378     Kind = OMPC_MAP_from;
3379     break;
3380   case OMPC_DEFAULTMAP_MODIFIER_tofrom:
3381     Kind = OMPC_MAP_tofrom;
3382     break;
3383   case OMPC_DEFAULTMAP_MODIFIER_present:
3384     // OpenMP 5.1 [2.21.7.3] defaultmap clause, Description]
3385     // If implicit-behavior is present, each variable referenced in the
3386     // construct in the category specified by variable-category is treated as if
3387     // it had been listed in a map clause with the map-type of alloc and
3388     // map-type-modifier of present.
3389     Kind = OMPC_MAP_alloc;
3390     break;
3391   case OMPC_DEFAULTMAP_MODIFIER_firstprivate:
3392   case OMPC_DEFAULTMAP_MODIFIER_last:
3393     llvm_unreachable("Unexpected defaultmap implicit behavior");
3394   case OMPC_DEFAULTMAP_MODIFIER_none:
3395   case OMPC_DEFAULTMAP_MODIFIER_default:
3396   case OMPC_DEFAULTMAP_MODIFIER_unknown:
3397     // IsAggregateOrDeclareTarget could be true if:
3398     // 1. the implicit behavior for aggregate is tofrom
3399     // 2. it's a declare target link
3400     if (IsAggregateOrDeclareTarget) {
3401       Kind = OMPC_MAP_tofrom;
3402       break;
3403     }
3404     llvm_unreachable("Unexpected defaultmap implicit behavior");
3405   }
3406   assert(Kind != OMPC_MAP_unknown && "Expect map kind to be known");
3407   return Kind;
3408 }
3409 
3410 namespace {
3411 class DSAAttrChecker final : public StmtVisitor<DSAAttrChecker, void> {
3412   DSAStackTy *Stack;
3413   Sema &SemaRef;
3414   bool ErrorFound = false;
3415   bool TryCaptureCXXThisMembers = false;
3416   CapturedStmt *CS = nullptr;
3417   const static unsigned DefaultmapKindNum = OMPC_DEFAULTMAP_pointer + 1;
3418   llvm::SmallVector<Expr *, 4> ImplicitFirstprivate;
3419   llvm::SmallVector<Expr *, 4> ImplicitMap[DefaultmapKindNum][OMPC_MAP_delete];
3420   llvm::SmallVector<OpenMPMapModifierKind, NumberOfOMPMapClauseModifiers>
3421       ImplicitMapModifier[DefaultmapKindNum];
3422   Sema::VarsWithInheritedDSAType VarsWithInheritedDSA;
3423   llvm::SmallDenseSet<const ValueDecl *, 4> ImplicitDeclarations;
3424 
3425   void VisitSubCaptures(OMPExecutableDirective *S) {
3426     // Check implicitly captured variables.
3427     if (!S->hasAssociatedStmt() || !S->getAssociatedStmt())
3428       return;
3429     if (S->getDirectiveKind() == OMPD_atomic ||
3430         S->getDirectiveKind() == OMPD_critical ||
3431         S->getDirectiveKind() == OMPD_section ||
3432         S->getDirectiveKind() == OMPD_master ||
3433         S->getDirectiveKind() == OMPD_masked ||
3434         isOpenMPLoopTransformationDirective(S->getDirectiveKind())) {
3435       Visit(S->getAssociatedStmt());
3436       return;
3437     }
3438     visitSubCaptures(S->getInnermostCapturedStmt());
3439     // Try to capture inner this->member references to generate correct mappings
3440     // and diagnostics.
3441     if (TryCaptureCXXThisMembers ||
3442         (isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()) &&
3443          llvm::any_of(S->getInnermostCapturedStmt()->captures(),
3444                       [](const CapturedStmt::Capture &C) {
3445                         return C.capturesThis();
3446                       }))) {
3447       bool SavedTryCaptureCXXThisMembers = TryCaptureCXXThisMembers;
3448       TryCaptureCXXThisMembers = true;
3449       Visit(S->getInnermostCapturedStmt()->getCapturedStmt());
3450       TryCaptureCXXThisMembers = SavedTryCaptureCXXThisMembers;
3451     }
3452     // In tasks firstprivates are not captured anymore, need to analyze them
3453     // explicitly.
3454     if (isOpenMPTaskingDirective(S->getDirectiveKind()) &&
3455         !isOpenMPTaskLoopDirective(S->getDirectiveKind())) {
3456       for (OMPClause *C : S->clauses())
3457         if (auto *FC = dyn_cast<OMPFirstprivateClause>(C)) {
3458           for (Expr *Ref : FC->varlists())
3459             Visit(Ref);
3460         }
3461     }
3462   }
3463 
3464 public:
3465   void VisitDeclRefExpr(DeclRefExpr *E) {
3466     if (TryCaptureCXXThisMembers || E->isTypeDependent() ||
3467         E->isValueDependent() || E->containsUnexpandedParameterPack() ||
3468         E->isInstantiationDependent())
3469       return;
3470     if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
3471       // Check the datasharing rules for the expressions in the clauses.
3472       if (!CS) {
3473         if (auto *CED = dyn_cast<OMPCapturedExprDecl>(VD))
3474           if (!CED->hasAttr<OMPCaptureNoInitAttr>()) {
3475             Visit(CED->getInit());
3476             return;
3477           }
3478       } else if (VD->isImplicit() || isa<OMPCapturedExprDecl>(VD))
3479         // Do not analyze internal variables and do not enclose them into
3480         // implicit clauses.
3481         return;
3482       VD = VD->getCanonicalDecl();
3483       // Skip internally declared variables.
3484       if (VD->hasLocalStorage() && CS && !CS->capturesVariable(VD) &&
3485           !Stack->isImplicitTaskFirstprivate(VD))
3486         return;
3487       // Skip allocators in uses_allocators clauses.
3488       if (Stack->isUsesAllocatorsDecl(VD).hasValue())
3489         return;
3490 
3491       DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, /*FromParent=*/false);
3492       // Check if the variable has explicit DSA set and stop analysis if it so.
3493       if (DVar.RefExpr || !ImplicitDeclarations.insert(VD).second)
3494         return;
3495 
3496       // Skip internally declared static variables.
3497       llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
3498           OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
3499       if (VD->hasGlobalStorage() && CS && !CS->capturesVariable(VD) &&
3500           (Stack->hasRequiresDeclWithClause<OMPUnifiedSharedMemoryClause>() ||
3501            !Res || *Res != OMPDeclareTargetDeclAttr::MT_Link) &&
3502           !Stack->isImplicitTaskFirstprivate(VD))
3503         return;
3504 
3505       SourceLocation ELoc = E->getExprLoc();
3506       OpenMPDirectiveKind DKind = Stack->getCurrentDirective();
3507       // The default(none) clause requires that each variable that is referenced
3508       // in the construct, and does not have a predetermined data-sharing
3509       // attribute, must have its data-sharing attribute explicitly determined
3510       // by being listed in a data-sharing attribute clause.
3511       if (DVar.CKind == OMPC_unknown &&
3512           (Stack->getDefaultDSA() == DSA_none ||
3513            Stack->getDefaultDSA() == DSA_firstprivate) &&
3514           isImplicitOrExplicitTaskingRegion(DKind) &&
3515           VarsWithInheritedDSA.count(VD) == 0) {
3516         bool InheritedDSA = Stack->getDefaultDSA() == DSA_none;
3517         if (!InheritedDSA && Stack->getDefaultDSA() == DSA_firstprivate) {
3518           DSAStackTy::DSAVarData DVar =
3519               Stack->getImplicitDSA(VD, /*FromParent=*/false);
3520           InheritedDSA = DVar.CKind == OMPC_unknown;
3521         }
3522         if (InheritedDSA)
3523           VarsWithInheritedDSA[VD] = E;
3524         return;
3525       }
3526 
3527       // OpenMP 5.0 [2.19.7.2, defaultmap clause, Description]
3528       // If implicit-behavior is none, each variable referenced in the
3529       // construct that does not have a predetermined data-sharing attribute
3530       // and does not appear in a to or link clause on a declare target
3531       // directive must be listed in a data-mapping attribute clause, a
3532       // data-haring attribute clause (including a data-sharing attribute
3533       // clause on a combined construct where target. is one of the
3534       // constituent constructs), or an is_device_ptr clause.
3535       OpenMPDefaultmapClauseKind ClauseKind =
3536           getVariableCategoryFromDecl(SemaRef.getLangOpts(), VD);
3537       if (SemaRef.getLangOpts().OpenMP >= 50) {
3538         bool IsModifierNone = Stack->getDefaultmapModifier(ClauseKind) ==
3539                               OMPC_DEFAULTMAP_MODIFIER_none;
3540         if (DVar.CKind == OMPC_unknown && IsModifierNone &&
3541             VarsWithInheritedDSA.count(VD) == 0 && !Res) {
3542           // Only check for data-mapping attribute and is_device_ptr here
3543           // since we have already make sure that the declaration does not
3544           // have a data-sharing attribute above
3545           if (!Stack->checkMappableExprComponentListsForDecl(
3546                   VD, /*CurrentRegionOnly=*/true,
3547                   [VD](OMPClauseMappableExprCommon::MappableExprComponentListRef
3548                            MapExprComponents,
3549                        OpenMPClauseKind) {
3550                     auto MI = MapExprComponents.rbegin();
3551                     auto ME = MapExprComponents.rend();
3552                     return MI != ME && MI->getAssociatedDeclaration() == VD;
3553                   })) {
3554             VarsWithInheritedDSA[VD] = E;
3555             return;
3556           }
3557         }
3558       }
3559       if (SemaRef.getLangOpts().OpenMP > 50) {
3560         bool IsModifierPresent = Stack->getDefaultmapModifier(ClauseKind) ==
3561                                  OMPC_DEFAULTMAP_MODIFIER_present;
3562         if (IsModifierPresent) {
3563           if (llvm::find(ImplicitMapModifier[ClauseKind],
3564                          OMPC_MAP_MODIFIER_present) ==
3565               std::end(ImplicitMapModifier[ClauseKind])) {
3566             ImplicitMapModifier[ClauseKind].push_back(
3567                 OMPC_MAP_MODIFIER_present);
3568           }
3569         }
3570       }
3571 
3572       if (isOpenMPTargetExecutionDirective(DKind) &&
3573           !Stack->isLoopControlVariable(VD).first) {
3574         if (!Stack->checkMappableExprComponentListsForDecl(
3575                 VD, /*CurrentRegionOnly=*/true,
3576                 [this](OMPClauseMappableExprCommon::MappableExprComponentListRef
3577                            StackComponents,
3578                        OpenMPClauseKind) {
3579                   if (SemaRef.LangOpts.OpenMP >= 50)
3580                     return !StackComponents.empty();
3581                   // Variable is used if it has been marked as an array, array
3582                   // section, array shaping or the variable iself.
3583                   return StackComponents.size() == 1 ||
3584                          std::all_of(
3585                              std::next(StackComponents.rbegin()),
3586                              StackComponents.rend(),
3587                              [](const OMPClauseMappableExprCommon::
3588                                     MappableComponent &MC) {
3589                                return MC.getAssociatedDeclaration() ==
3590                                           nullptr &&
3591                                       (isa<OMPArraySectionExpr>(
3592                                            MC.getAssociatedExpression()) ||
3593                                        isa<OMPArrayShapingExpr>(
3594                                            MC.getAssociatedExpression()) ||
3595                                        isa<ArraySubscriptExpr>(
3596                                            MC.getAssociatedExpression()));
3597                              });
3598                 })) {
3599           bool IsFirstprivate = false;
3600           // By default lambdas are captured as firstprivates.
3601           if (const auto *RD =
3602                   VD->getType().getNonReferenceType()->getAsCXXRecordDecl())
3603             IsFirstprivate = RD->isLambda();
3604           IsFirstprivate =
3605               IsFirstprivate || (Stack->mustBeFirstprivate(ClauseKind) && !Res);
3606           if (IsFirstprivate) {
3607             ImplicitFirstprivate.emplace_back(E);
3608           } else {
3609             OpenMPDefaultmapClauseModifier M =
3610                 Stack->getDefaultmapModifier(ClauseKind);
3611             OpenMPMapClauseKind Kind = getMapClauseKindFromModifier(
3612                 M, ClauseKind == OMPC_DEFAULTMAP_aggregate || Res);
3613             ImplicitMap[ClauseKind][Kind].emplace_back(E);
3614           }
3615           return;
3616         }
3617       }
3618 
3619       // OpenMP [2.9.3.6, Restrictions, p.2]
3620       //  A list item that appears in a reduction clause of the innermost
3621       //  enclosing worksharing or parallel construct may not be accessed in an
3622       //  explicit task.
3623       DVar = Stack->hasInnermostDSA(
3624           VD,
3625           [](OpenMPClauseKind C, bool AppliedToPointee) {
3626             return C == OMPC_reduction && !AppliedToPointee;
3627           },
3628           [](OpenMPDirectiveKind K) {
3629             return isOpenMPParallelDirective(K) ||
3630                    isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
3631           },
3632           /*FromParent=*/true);
3633       if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
3634         ErrorFound = true;
3635         SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
3636         reportOriginalDsa(SemaRef, Stack, VD, DVar);
3637         return;
3638       }
3639 
3640       // Define implicit data-sharing attributes for task.
3641       DVar = Stack->getImplicitDSA(VD, /*FromParent=*/false);
3642       if (((isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared) ||
3643            (Stack->getDefaultDSA() == DSA_firstprivate &&
3644             DVar.CKind == OMPC_firstprivate && !DVar.RefExpr)) &&
3645           !Stack->isLoopControlVariable(VD).first) {
3646         ImplicitFirstprivate.push_back(E);
3647         return;
3648       }
3649 
3650       // Store implicitly used globals with declare target link for parent
3651       // target.
3652       if (!isOpenMPTargetExecutionDirective(DKind) && Res &&
3653           *Res == OMPDeclareTargetDeclAttr::MT_Link) {
3654         Stack->addToParentTargetRegionLinkGlobals(E);
3655         return;
3656       }
3657     }
3658   }
3659   void VisitMemberExpr(MemberExpr *E) {
3660     if (E->isTypeDependent() || E->isValueDependent() ||
3661         E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
3662       return;
3663     auto *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
3664     OpenMPDirectiveKind DKind = Stack->getCurrentDirective();
3665     if (auto *TE = dyn_cast<CXXThisExpr>(E->getBase()->IgnoreParenCasts())) {
3666       if (!FD)
3667         return;
3668       DSAStackTy::DSAVarData DVar = Stack->getTopDSA(FD, /*FromParent=*/false);
3669       // Check if the variable has explicit DSA set and stop analysis if it
3670       // so.
3671       if (DVar.RefExpr || !ImplicitDeclarations.insert(FD).second)
3672         return;
3673 
3674       if (isOpenMPTargetExecutionDirective(DKind) &&
3675           !Stack->isLoopControlVariable(FD).first &&
3676           !Stack->checkMappableExprComponentListsForDecl(
3677               FD, /*CurrentRegionOnly=*/true,
3678               [](OMPClauseMappableExprCommon::MappableExprComponentListRef
3679                      StackComponents,
3680                  OpenMPClauseKind) {
3681                 return isa<CXXThisExpr>(
3682                     cast<MemberExpr>(
3683                         StackComponents.back().getAssociatedExpression())
3684                         ->getBase()
3685                         ->IgnoreParens());
3686               })) {
3687         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
3688         //  A bit-field cannot appear in a map clause.
3689         //
3690         if (FD->isBitField())
3691           return;
3692 
3693         // Check to see if the member expression is referencing a class that
3694         // has already been explicitly mapped
3695         if (Stack->isClassPreviouslyMapped(TE->getType()))
3696           return;
3697 
3698         OpenMPDefaultmapClauseModifier Modifier =
3699             Stack->getDefaultmapModifier(OMPC_DEFAULTMAP_aggregate);
3700         OpenMPDefaultmapClauseKind ClauseKind =
3701             getVariableCategoryFromDecl(SemaRef.getLangOpts(), FD);
3702         OpenMPMapClauseKind Kind = getMapClauseKindFromModifier(
3703             Modifier, /*IsAggregateOrDeclareTarget*/ true);
3704         ImplicitMap[ClauseKind][Kind].emplace_back(E);
3705         return;
3706       }
3707 
3708       SourceLocation ELoc = E->getExprLoc();
3709       // OpenMP [2.9.3.6, Restrictions, p.2]
3710       //  A list item that appears in a reduction clause of the innermost
3711       //  enclosing worksharing or parallel construct may not be accessed in
3712       //  an  explicit task.
3713       DVar = Stack->hasInnermostDSA(
3714           FD,
3715           [](OpenMPClauseKind C, bool AppliedToPointee) {
3716             return C == OMPC_reduction && !AppliedToPointee;
3717           },
3718           [](OpenMPDirectiveKind K) {
3719             return isOpenMPParallelDirective(K) ||
3720                    isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
3721           },
3722           /*FromParent=*/true);
3723       if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
3724         ErrorFound = true;
3725         SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
3726         reportOriginalDsa(SemaRef, Stack, FD, DVar);
3727         return;
3728       }
3729 
3730       // Define implicit data-sharing attributes for task.
3731       DVar = Stack->getImplicitDSA(FD, /*FromParent=*/false);
3732       if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
3733           !Stack->isLoopControlVariable(FD).first) {
3734         // Check if there is a captured expression for the current field in the
3735         // region. Do not mark it as firstprivate unless there is no captured
3736         // expression.
3737         // TODO: try to make it firstprivate.
3738         if (DVar.CKind != OMPC_unknown)
3739           ImplicitFirstprivate.push_back(E);
3740       }
3741       return;
3742     }
3743     if (isOpenMPTargetExecutionDirective(DKind)) {
3744       OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
3745       if (!checkMapClauseExpressionBase(SemaRef, E, CurComponents, OMPC_map,
3746                                         Stack->getCurrentDirective(),
3747                                         /*NoDiagnose=*/true))
3748         return;
3749       const auto *VD = cast<ValueDecl>(
3750           CurComponents.back().getAssociatedDeclaration()->getCanonicalDecl());
3751       if (!Stack->checkMappableExprComponentListsForDecl(
3752               VD, /*CurrentRegionOnly=*/true,
3753               [&CurComponents](
3754                   OMPClauseMappableExprCommon::MappableExprComponentListRef
3755                       StackComponents,
3756                   OpenMPClauseKind) {
3757                 auto CCI = CurComponents.rbegin();
3758                 auto CCE = CurComponents.rend();
3759                 for (const auto &SC : llvm::reverse(StackComponents)) {
3760                   // Do both expressions have the same kind?
3761                   if (CCI->getAssociatedExpression()->getStmtClass() !=
3762                       SC.getAssociatedExpression()->getStmtClass())
3763                     if (!((isa<OMPArraySectionExpr>(
3764                                SC.getAssociatedExpression()) ||
3765                            isa<OMPArrayShapingExpr>(
3766                                SC.getAssociatedExpression())) &&
3767                           isa<ArraySubscriptExpr>(
3768                               CCI->getAssociatedExpression())))
3769                       return false;
3770 
3771                   const Decl *CCD = CCI->getAssociatedDeclaration();
3772                   const Decl *SCD = SC.getAssociatedDeclaration();
3773                   CCD = CCD ? CCD->getCanonicalDecl() : nullptr;
3774                   SCD = SCD ? SCD->getCanonicalDecl() : nullptr;
3775                   if (SCD != CCD)
3776                     return false;
3777                   std::advance(CCI, 1);
3778                   if (CCI == CCE)
3779                     break;
3780                 }
3781                 return true;
3782               })) {
3783         Visit(E->getBase());
3784       }
3785     } else if (!TryCaptureCXXThisMembers) {
3786       Visit(E->getBase());
3787     }
3788   }
3789   void VisitOMPExecutableDirective(OMPExecutableDirective *S) {
3790     for (OMPClause *C : S->clauses()) {
3791       // Skip analysis of arguments of implicitly defined firstprivate clause
3792       // for task|target directives.
3793       // Skip analysis of arguments of implicitly defined map clause for target
3794       // directives.
3795       if (C && !((isa<OMPFirstprivateClause>(C) || isa<OMPMapClause>(C)) &&
3796                  C->isImplicit() &&
3797                  !isOpenMPTaskingDirective(Stack->getCurrentDirective()))) {
3798         for (Stmt *CC : C->children()) {
3799           if (CC)
3800             Visit(CC);
3801         }
3802       }
3803     }
3804     // Check implicitly captured variables.
3805     VisitSubCaptures(S);
3806   }
3807 
3808   void VisitOMPTileDirective(OMPTileDirective *S) {
3809     // #pragma omp tile does not introduce data sharing.
3810     VisitStmt(S);
3811   }
3812 
3813   void VisitOMPUnrollDirective(OMPUnrollDirective *S) {
3814     // #pragma omp unroll does not introduce data sharing.
3815     VisitStmt(S);
3816   }
3817 
3818   void VisitStmt(Stmt *S) {
3819     for (Stmt *C : S->children()) {
3820       if (C) {
3821         // Check implicitly captured variables in the task-based directives to
3822         // check if they must be firstprivatized.
3823         Visit(C);
3824       }
3825     }
3826   }
3827 
3828   void visitSubCaptures(CapturedStmt *S) {
3829     for (const CapturedStmt::Capture &Cap : S->captures()) {
3830       if (!Cap.capturesVariable() && !Cap.capturesVariableByCopy())
3831         continue;
3832       VarDecl *VD = Cap.getCapturedVar();
3833       // Do not try to map the variable if it or its sub-component was mapped
3834       // already.
3835       if (isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()) &&
3836           Stack->checkMappableExprComponentListsForDecl(
3837               VD, /*CurrentRegionOnly=*/true,
3838               [](OMPClauseMappableExprCommon::MappableExprComponentListRef,
3839                  OpenMPClauseKind) { return true; }))
3840         continue;
3841       DeclRefExpr *DRE = buildDeclRefExpr(
3842           SemaRef, VD, VD->getType().getNonLValueExprType(SemaRef.Context),
3843           Cap.getLocation(), /*RefersToCapture=*/true);
3844       Visit(DRE);
3845     }
3846   }
3847   bool isErrorFound() const { return ErrorFound; }
3848   ArrayRef<Expr *> getImplicitFirstprivate() const {
3849     return ImplicitFirstprivate;
3850   }
3851   ArrayRef<Expr *> getImplicitMap(OpenMPDefaultmapClauseKind DK,
3852                                   OpenMPMapClauseKind MK) const {
3853     return ImplicitMap[DK][MK];
3854   }
3855   ArrayRef<OpenMPMapModifierKind>
3856   getImplicitMapModifier(OpenMPDefaultmapClauseKind Kind) const {
3857     return ImplicitMapModifier[Kind];
3858   }
3859   const Sema::VarsWithInheritedDSAType &getVarsWithInheritedDSA() const {
3860     return VarsWithInheritedDSA;
3861   }
3862 
3863   DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS)
3864       : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {
3865     // Process declare target link variables for the target directives.
3866     if (isOpenMPTargetExecutionDirective(S->getCurrentDirective())) {
3867       for (DeclRefExpr *E : Stack->getLinkGlobals())
3868         Visit(E);
3869     }
3870   }
3871 };
3872 } // namespace
3873 
3874 void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) {
3875   switch (DKind) {
3876   case OMPD_parallel:
3877   case OMPD_parallel_for:
3878   case OMPD_parallel_for_simd:
3879   case OMPD_parallel_sections:
3880   case OMPD_parallel_master:
3881   case OMPD_teams:
3882   case OMPD_teams_distribute:
3883   case OMPD_teams_distribute_simd: {
3884     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
3885     QualType KmpInt32PtrTy =
3886         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3887     Sema::CapturedParamNameType Params[] = {
3888         std::make_pair(".global_tid.", KmpInt32PtrTy),
3889         std::make_pair(".bound_tid.", KmpInt32PtrTy),
3890         std::make_pair(StringRef(), QualType()) // __context with shared vars
3891     };
3892     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3893                              Params);
3894     break;
3895   }
3896   case OMPD_target_teams:
3897   case OMPD_target_parallel:
3898   case OMPD_target_parallel_for:
3899   case OMPD_target_parallel_for_simd:
3900   case OMPD_target_teams_distribute:
3901   case OMPD_target_teams_distribute_simd: {
3902     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
3903     QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
3904     QualType KmpInt32PtrTy =
3905         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3906     QualType Args[] = {VoidPtrTy};
3907     FunctionProtoType::ExtProtoInfo EPI;
3908     EPI.Variadic = true;
3909     QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
3910     Sema::CapturedParamNameType Params[] = {
3911         std::make_pair(".global_tid.", KmpInt32Ty),
3912         std::make_pair(".part_id.", KmpInt32PtrTy),
3913         std::make_pair(".privates.", VoidPtrTy),
3914         std::make_pair(
3915             ".copy_fn.",
3916             Context.getPointerType(CopyFnType).withConst().withRestrict()),
3917         std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
3918         std::make_pair(StringRef(), QualType()) // __context with shared vars
3919     };
3920     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3921                              Params, /*OpenMPCaptureLevel=*/0);
3922     // Mark this captured region as inlined, because we don't use outlined
3923     // function directly.
3924     getCurCapturedRegion()->TheCapturedDecl->addAttr(
3925         AlwaysInlineAttr::CreateImplicit(
3926             Context, {}, AttributeCommonInfo::AS_Keyword,
3927             AlwaysInlineAttr::Keyword_forceinline));
3928     Sema::CapturedParamNameType ParamsTarget[] = {
3929         std::make_pair(StringRef(), QualType()) // __context with shared vars
3930     };
3931     // Start a captured region for 'target' with no implicit parameters.
3932     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3933                              ParamsTarget, /*OpenMPCaptureLevel=*/1);
3934     Sema::CapturedParamNameType ParamsTeamsOrParallel[] = {
3935         std::make_pair(".global_tid.", KmpInt32PtrTy),
3936         std::make_pair(".bound_tid.", KmpInt32PtrTy),
3937         std::make_pair(StringRef(), QualType()) // __context with shared vars
3938     };
3939     // Start a captured region for 'teams' or 'parallel'.  Both regions have
3940     // the same implicit parameters.
3941     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3942                              ParamsTeamsOrParallel, /*OpenMPCaptureLevel=*/2);
3943     break;
3944   }
3945   case OMPD_target:
3946   case OMPD_target_simd: {
3947     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
3948     QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
3949     QualType KmpInt32PtrTy =
3950         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3951     QualType Args[] = {VoidPtrTy};
3952     FunctionProtoType::ExtProtoInfo EPI;
3953     EPI.Variadic = true;
3954     QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
3955     Sema::CapturedParamNameType Params[] = {
3956         std::make_pair(".global_tid.", KmpInt32Ty),
3957         std::make_pair(".part_id.", KmpInt32PtrTy),
3958         std::make_pair(".privates.", VoidPtrTy),
3959         std::make_pair(
3960             ".copy_fn.",
3961             Context.getPointerType(CopyFnType).withConst().withRestrict()),
3962         std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
3963         std::make_pair(StringRef(), QualType()) // __context with shared vars
3964     };
3965     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3966                              Params, /*OpenMPCaptureLevel=*/0);
3967     // Mark this captured region as inlined, because we don't use outlined
3968     // function directly.
3969     getCurCapturedRegion()->TheCapturedDecl->addAttr(
3970         AlwaysInlineAttr::CreateImplicit(
3971             Context, {}, AttributeCommonInfo::AS_Keyword,
3972             AlwaysInlineAttr::Keyword_forceinline));
3973     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3974                              std::make_pair(StringRef(), QualType()),
3975                              /*OpenMPCaptureLevel=*/1);
3976     break;
3977   }
3978   case OMPD_atomic:
3979   case OMPD_critical:
3980   case OMPD_section:
3981   case OMPD_master:
3982   case OMPD_masked:
3983   case OMPD_tile:
3984   case OMPD_unroll:
3985     break;
3986   case OMPD_simd:
3987   case OMPD_for:
3988   case OMPD_for_simd:
3989   case OMPD_sections:
3990   case OMPD_single:
3991   case OMPD_taskgroup:
3992   case OMPD_distribute:
3993   case OMPD_distribute_simd:
3994   case OMPD_ordered:
3995   case OMPD_target_data:
3996   case OMPD_dispatch: {
3997     Sema::CapturedParamNameType Params[] = {
3998         std::make_pair(StringRef(), QualType()) // __context with shared vars
3999     };
4000     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
4001                              Params);
4002     break;
4003   }
4004   case OMPD_task: {
4005     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
4006     QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
4007     QualType KmpInt32PtrTy =
4008         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
4009     QualType Args[] = {VoidPtrTy};
4010     FunctionProtoType::ExtProtoInfo EPI;
4011     EPI.Variadic = true;
4012     QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
4013     Sema::CapturedParamNameType Params[] = {
4014         std::make_pair(".global_tid.", KmpInt32Ty),
4015         std::make_pair(".part_id.", KmpInt32PtrTy),
4016         std::make_pair(".privates.", VoidPtrTy),
4017         std::make_pair(
4018             ".copy_fn.",
4019             Context.getPointerType(CopyFnType).withConst().withRestrict()),
4020         std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
4021         std::make_pair(StringRef(), QualType()) // __context with shared vars
4022     };
4023     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
4024                              Params);
4025     // Mark this captured region as inlined, because we don't use outlined
4026     // function directly.
4027     getCurCapturedRegion()->TheCapturedDecl->addAttr(
4028         AlwaysInlineAttr::CreateImplicit(
4029             Context, {}, AttributeCommonInfo::AS_Keyword,
4030             AlwaysInlineAttr::Keyword_forceinline));
4031     break;
4032   }
4033   case OMPD_taskloop:
4034   case OMPD_taskloop_simd:
4035   case OMPD_master_taskloop:
4036   case OMPD_master_taskloop_simd: {
4037     QualType KmpInt32Ty =
4038         Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1)
4039             .withConst();
4040     QualType KmpUInt64Ty =
4041         Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0)
4042             .withConst();
4043     QualType KmpInt64Ty =
4044         Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1)
4045             .withConst();
4046     QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
4047     QualType KmpInt32PtrTy =
4048         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
4049     QualType Args[] = {VoidPtrTy};
4050     FunctionProtoType::ExtProtoInfo EPI;
4051     EPI.Variadic = true;
4052     QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
4053     Sema::CapturedParamNameType Params[] = {
4054         std::make_pair(".global_tid.", KmpInt32Ty),
4055         std::make_pair(".part_id.", KmpInt32PtrTy),
4056         std::make_pair(".privates.", VoidPtrTy),
4057         std::make_pair(
4058             ".copy_fn.",
4059             Context.getPointerType(CopyFnType).withConst().withRestrict()),
4060         std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
4061         std::make_pair(".lb.", KmpUInt64Ty),
4062         std::make_pair(".ub.", KmpUInt64Ty),
4063         std::make_pair(".st.", KmpInt64Ty),
4064         std::make_pair(".liter.", KmpInt32Ty),
4065         std::make_pair(".reductions.", VoidPtrTy),
4066         std::make_pair(StringRef(), QualType()) // __context with shared vars
4067     };
4068     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
4069                              Params);
4070     // Mark this captured region as inlined, because we don't use outlined
4071     // function directly.
4072     getCurCapturedRegion()->TheCapturedDecl->addAttr(
4073         AlwaysInlineAttr::CreateImplicit(
4074             Context, {}, AttributeCommonInfo::AS_Keyword,
4075             AlwaysInlineAttr::Keyword_forceinline));
4076     break;
4077   }
4078   case OMPD_parallel_master_taskloop:
4079   case OMPD_parallel_master_taskloop_simd: {
4080     QualType KmpInt32Ty =
4081         Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1)
4082             .withConst();
4083     QualType KmpUInt64Ty =
4084         Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0)
4085             .withConst();
4086     QualType KmpInt64Ty =
4087         Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1)
4088             .withConst();
4089     QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
4090     QualType KmpInt32PtrTy =
4091         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
4092     Sema::CapturedParamNameType ParamsParallel[] = {
4093         std::make_pair(".global_tid.", KmpInt32PtrTy),
4094         std::make_pair(".bound_tid.", KmpInt32PtrTy),
4095         std::make_pair(StringRef(), QualType()) // __context with shared vars
4096     };
4097     // Start a captured region for 'parallel'.
4098     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
4099                              ParamsParallel, /*OpenMPCaptureLevel=*/0);
4100     QualType Args[] = {VoidPtrTy};
4101     FunctionProtoType::ExtProtoInfo EPI;
4102     EPI.Variadic = true;
4103     QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
4104     Sema::CapturedParamNameType Params[] = {
4105         std::make_pair(".global_tid.", KmpInt32Ty),
4106         std::make_pair(".part_id.", KmpInt32PtrTy),
4107         std::make_pair(".privates.", VoidPtrTy),
4108         std::make_pair(
4109             ".copy_fn.",
4110             Context.getPointerType(CopyFnType).withConst().withRestrict()),
4111         std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
4112         std::make_pair(".lb.", KmpUInt64Ty),
4113         std::make_pair(".ub.", KmpUInt64Ty),
4114         std::make_pair(".st.", KmpInt64Ty),
4115         std::make_pair(".liter.", KmpInt32Ty),
4116         std::make_pair(".reductions.", VoidPtrTy),
4117         std::make_pair(StringRef(), QualType()) // __context with shared vars
4118     };
4119     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
4120                              Params, /*OpenMPCaptureLevel=*/1);
4121     // Mark this captured region as inlined, because we don't use outlined
4122     // function directly.
4123     getCurCapturedRegion()->TheCapturedDecl->addAttr(
4124         AlwaysInlineAttr::CreateImplicit(
4125             Context, {}, AttributeCommonInfo::AS_Keyword,
4126             AlwaysInlineAttr::Keyword_forceinline));
4127     break;
4128   }
4129   case OMPD_distribute_parallel_for_simd:
4130   case OMPD_distribute_parallel_for: {
4131     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
4132     QualType KmpInt32PtrTy =
4133         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
4134     Sema::CapturedParamNameType Params[] = {
4135         std::make_pair(".global_tid.", KmpInt32PtrTy),
4136         std::make_pair(".bound_tid.", KmpInt32PtrTy),
4137         std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
4138         std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
4139         std::make_pair(StringRef(), QualType()) // __context with shared vars
4140     };
4141     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
4142                              Params);
4143     break;
4144   }
4145   case OMPD_target_teams_distribute_parallel_for:
4146   case OMPD_target_teams_distribute_parallel_for_simd: {
4147     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
4148     QualType KmpInt32PtrTy =
4149         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
4150     QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
4151 
4152     QualType Args[] = {VoidPtrTy};
4153     FunctionProtoType::ExtProtoInfo EPI;
4154     EPI.Variadic = true;
4155     QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
4156     Sema::CapturedParamNameType Params[] = {
4157         std::make_pair(".global_tid.", KmpInt32Ty),
4158         std::make_pair(".part_id.", KmpInt32PtrTy),
4159         std::make_pair(".privates.", VoidPtrTy),
4160         std::make_pair(
4161             ".copy_fn.",
4162             Context.getPointerType(CopyFnType).withConst().withRestrict()),
4163         std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
4164         std::make_pair(StringRef(), QualType()) // __context with shared vars
4165     };
4166     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
4167                              Params, /*OpenMPCaptureLevel=*/0);
4168     // Mark this captured region as inlined, because we don't use outlined
4169     // function directly.
4170     getCurCapturedRegion()->TheCapturedDecl->addAttr(
4171         AlwaysInlineAttr::CreateImplicit(
4172             Context, {}, AttributeCommonInfo::AS_Keyword,
4173             AlwaysInlineAttr::Keyword_forceinline));
4174     Sema::CapturedParamNameType ParamsTarget[] = {
4175         std::make_pair(StringRef(), QualType()) // __context with shared vars
4176     };
4177     // Start a captured region for 'target' with no implicit parameters.
4178     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
4179                              ParamsTarget, /*OpenMPCaptureLevel=*/1);
4180 
4181     Sema::CapturedParamNameType ParamsTeams[] = {
4182         std::make_pair(".global_tid.", KmpInt32PtrTy),
4183         std::make_pair(".bound_tid.", KmpInt32PtrTy),
4184         std::make_pair(StringRef(), QualType()) // __context with shared vars
4185     };
4186     // Start a captured region for 'target' with no implicit parameters.
4187     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
4188                              ParamsTeams, /*OpenMPCaptureLevel=*/2);
4189 
4190     Sema::CapturedParamNameType ParamsParallel[] = {
4191         std::make_pair(".global_tid.", KmpInt32PtrTy),
4192         std::make_pair(".bound_tid.", KmpInt32PtrTy),
4193         std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
4194         std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
4195         std::make_pair(StringRef(), QualType()) // __context with shared vars
4196     };
4197     // Start a captured region for 'teams' or 'parallel'.  Both regions have
4198     // the same implicit parameters.
4199     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
4200                              ParamsParallel, /*OpenMPCaptureLevel=*/3);
4201     break;
4202   }
4203 
4204   case OMPD_teams_distribute_parallel_for:
4205   case OMPD_teams_distribute_parallel_for_simd: {
4206     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
4207     QualType KmpInt32PtrTy =
4208         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
4209 
4210     Sema::CapturedParamNameType ParamsTeams[] = {
4211         std::make_pair(".global_tid.", KmpInt32PtrTy),
4212         std::make_pair(".bound_tid.", KmpInt32PtrTy),
4213         std::make_pair(StringRef(), QualType()) // __context with shared vars
4214     };
4215     // Start a captured region for 'target' with no implicit parameters.
4216     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
4217                              ParamsTeams, /*OpenMPCaptureLevel=*/0);
4218 
4219     Sema::CapturedParamNameType ParamsParallel[] = {
4220         std::make_pair(".global_tid.", KmpInt32PtrTy),
4221         std::make_pair(".bound_tid.", KmpInt32PtrTy),
4222         std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
4223         std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
4224         std::make_pair(StringRef(), QualType()) // __context with shared vars
4225     };
4226     // Start a captured region for 'teams' or 'parallel'.  Both regions have
4227     // the same implicit parameters.
4228     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
4229                              ParamsParallel, /*OpenMPCaptureLevel=*/1);
4230     break;
4231   }
4232   case OMPD_target_update:
4233   case OMPD_target_enter_data:
4234   case OMPD_target_exit_data: {
4235     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
4236     QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
4237     QualType KmpInt32PtrTy =
4238         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
4239     QualType Args[] = {VoidPtrTy};
4240     FunctionProtoType::ExtProtoInfo EPI;
4241     EPI.Variadic = true;
4242     QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
4243     Sema::CapturedParamNameType Params[] = {
4244         std::make_pair(".global_tid.", KmpInt32Ty),
4245         std::make_pair(".part_id.", KmpInt32PtrTy),
4246         std::make_pair(".privates.", VoidPtrTy),
4247         std::make_pair(
4248             ".copy_fn.",
4249             Context.getPointerType(CopyFnType).withConst().withRestrict()),
4250         std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
4251         std::make_pair(StringRef(), QualType()) // __context with shared vars
4252     };
4253     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
4254                              Params);
4255     // Mark this captured region as inlined, because we don't use outlined
4256     // function directly.
4257     getCurCapturedRegion()->TheCapturedDecl->addAttr(
4258         AlwaysInlineAttr::CreateImplicit(
4259             Context, {}, AttributeCommonInfo::AS_Keyword,
4260             AlwaysInlineAttr::Keyword_forceinline));
4261     break;
4262   }
4263   case OMPD_threadprivate:
4264   case OMPD_allocate:
4265   case OMPD_taskyield:
4266   case OMPD_barrier:
4267   case OMPD_taskwait:
4268   case OMPD_cancellation_point:
4269   case OMPD_cancel:
4270   case OMPD_flush:
4271   case OMPD_depobj:
4272   case OMPD_scan:
4273   case OMPD_declare_reduction:
4274   case OMPD_declare_mapper:
4275   case OMPD_declare_simd:
4276   case OMPD_declare_target:
4277   case OMPD_end_declare_target:
4278   case OMPD_requires:
4279   case OMPD_declare_variant:
4280   case OMPD_begin_declare_variant:
4281   case OMPD_end_declare_variant:
4282     llvm_unreachable("OpenMP Directive is not allowed");
4283   case OMPD_unknown:
4284   default:
4285     llvm_unreachable("Unknown OpenMP directive");
4286   }
4287   DSAStack->setContext(CurContext);
4288 }
4289 
4290 int Sema::getNumberOfConstructScopes(unsigned Level) const {
4291   return getOpenMPCaptureLevels(DSAStack->getDirective(Level));
4292 }
4293 
4294 int Sema::getOpenMPCaptureLevels(OpenMPDirectiveKind DKind) {
4295   SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
4296   getOpenMPCaptureRegions(CaptureRegions, DKind);
4297   return CaptureRegions.size();
4298 }
4299 
4300 static OMPCapturedExprDecl *buildCaptureDecl(Sema &S, IdentifierInfo *Id,
4301                                              Expr *CaptureExpr, bool WithInit,
4302                                              bool AsExpression) {
4303   assert(CaptureExpr);
4304   ASTContext &C = S.getASTContext();
4305   Expr *Init = AsExpression ? CaptureExpr : CaptureExpr->IgnoreImpCasts();
4306   QualType Ty = Init->getType();
4307   if (CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue()) {
4308     if (S.getLangOpts().CPlusPlus) {
4309       Ty = C.getLValueReferenceType(Ty);
4310     } else {
4311       Ty = C.getPointerType(Ty);
4312       ExprResult Res =
4313           S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_AddrOf, Init);
4314       if (!Res.isUsable())
4315         return nullptr;
4316       Init = Res.get();
4317     }
4318     WithInit = true;
4319   }
4320   auto *CED = OMPCapturedExprDecl::Create(C, S.CurContext, Id, Ty,
4321                                           CaptureExpr->getBeginLoc());
4322   if (!WithInit)
4323     CED->addAttr(OMPCaptureNoInitAttr::CreateImplicit(C));
4324   S.CurContext->addHiddenDecl(CED);
4325   Sema::TentativeAnalysisScope Trap(S);
4326   S.AddInitializerToDecl(CED, Init, /*DirectInit=*/false);
4327   return CED;
4328 }
4329 
4330 static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr,
4331                                  bool WithInit) {
4332   OMPCapturedExprDecl *CD;
4333   if (VarDecl *VD = S.isOpenMPCapturedDecl(D))
4334     CD = cast<OMPCapturedExprDecl>(VD);
4335   else
4336     CD = buildCaptureDecl(S, D->getIdentifier(), CaptureExpr, WithInit,
4337                           /*AsExpression=*/false);
4338   return buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
4339                           CaptureExpr->getExprLoc());
4340 }
4341 
4342 static ExprResult buildCapture(Sema &S, Expr *CaptureExpr, DeclRefExpr *&Ref) {
4343   CaptureExpr = S.DefaultLvalueConversion(CaptureExpr).get();
4344   if (!Ref) {
4345     OMPCapturedExprDecl *CD = buildCaptureDecl(
4346         S, &S.getASTContext().Idents.get(".capture_expr."), CaptureExpr,
4347         /*WithInit=*/true, /*AsExpression=*/true);
4348     Ref = buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
4349                            CaptureExpr->getExprLoc());
4350   }
4351   ExprResult Res = Ref;
4352   if (!S.getLangOpts().CPlusPlus &&
4353       CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue() &&
4354       Ref->getType()->isPointerType()) {
4355     Res = S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_Deref, Ref);
4356     if (!Res.isUsable())
4357       return ExprError();
4358   }
4359   return S.DefaultLvalueConversion(Res.get());
4360 }
4361 
4362 namespace {
4363 // OpenMP directives parsed in this section are represented as a
4364 // CapturedStatement with an associated statement.  If a syntax error
4365 // is detected during the parsing of the associated statement, the
4366 // compiler must abort processing and close the CapturedStatement.
4367 //
4368 // Combined directives such as 'target parallel' have more than one
4369 // nested CapturedStatements.  This RAII ensures that we unwind out
4370 // of all the nested CapturedStatements when an error is found.
4371 class CaptureRegionUnwinderRAII {
4372 private:
4373   Sema &S;
4374   bool &ErrorFound;
4375   OpenMPDirectiveKind DKind = OMPD_unknown;
4376 
4377 public:
4378   CaptureRegionUnwinderRAII(Sema &S, bool &ErrorFound,
4379                             OpenMPDirectiveKind DKind)
4380       : S(S), ErrorFound(ErrorFound), DKind(DKind) {}
4381   ~CaptureRegionUnwinderRAII() {
4382     if (ErrorFound) {
4383       int ThisCaptureLevel = S.getOpenMPCaptureLevels(DKind);
4384       while (--ThisCaptureLevel >= 0)
4385         S.ActOnCapturedRegionError();
4386     }
4387   }
4388 };
4389 } // namespace
4390 
4391 void Sema::tryCaptureOpenMPLambdas(ValueDecl *V) {
4392   // Capture variables captured by reference in lambdas for target-based
4393   // directives.
4394   if (!CurContext->isDependentContext() &&
4395       (isOpenMPTargetExecutionDirective(DSAStack->getCurrentDirective()) ||
4396        isOpenMPTargetDataManagementDirective(
4397            DSAStack->getCurrentDirective()))) {
4398     QualType Type = V->getType();
4399     if (const auto *RD = Type.getCanonicalType()
4400                              .getNonReferenceType()
4401                              ->getAsCXXRecordDecl()) {
4402       bool SavedForceCaptureByReferenceInTargetExecutable =
4403           DSAStack->isForceCaptureByReferenceInTargetExecutable();
4404       DSAStack->setForceCaptureByReferenceInTargetExecutable(
4405           /*V=*/true);
4406       if (RD->isLambda()) {
4407         llvm::DenseMap<const VarDecl *, FieldDecl *> Captures;
4408         FieldDecl *ThisCapture;
4409         RD->getCaptureFields(Captures, ThisCapture);
4410         for (const LambdaCapture &LC : RD->captures()) {
4411           if (LC.getCaptureKind() == LCK_ByRef) {
4412             VarDecl *VD = LC.getCapturedVar();
4413             DeclContext *VDC = VD->getDeclContext();
4414             if (!VDC->Encloses(CurContext))
4415               continue;
4416             MarkVariableReferenced(LC.getLocation(), VD);
4417           } else if (LC.getCaptureKind() == LCK_This) {
4418             QualType ThisTy = getCurrentThisType();
4419             if (!ThisTy.isNull() &&
4420                 Context.typesAreCompatible(ThisTy, ThisCapture->getType()))
4421               CheckCXXThisCapture(LC.getLocation());
4422           }
4423         }
4424       }
4425       DSAStack->setForceCaptureByReferenceInTargetExecutable(
4426           SavedForceCaptureByReferenceInTargetExecutable);
4427     }
4428   }
4429 }
4430 
4431 static bool checkOrderedOrderSpecified(Sema &S,
4432                                        const ArrayRef<OMPClause *> Clauses) {
4433   const OMPOrderedClause *Ordered = nullptr;
4434   const OMPOrderClause *Order = nullptr;
4435 
4436   for (const OMPClause *Clause : Clauses) {
4437     if (Clause->getClauseKind() == OMPC_ordered)
4438       Ordered = cast<OMPOrderedClause>(Clause);
4439     else if (Clause->getClauseKind() == OMPC_order) {
4440       Order = cast<OMPOrderClause>(Clause);
4441       if (Order->getKind() != OMPC_ORDER_concurrent)
4442         Order = nullptr;
4443     }
4444     if (Ordered && Order)
4445       break;
4446   }
4447 
4448   if (Ordered && Order) {
4449     S.Diag(Order->getKindKwLoc(),
4450            diag::err_omp_simple_clause_incompatible_with_ordered)
4451         << getOpenMPClauseName(OMPC_order)
4452         << getOpenMPSimpleClauseTypeName(OMPC_order, OMPC_ORDER_concurrent)
4453         << SourceRange(Order->getBeginLoc(), Order->getEndLoc());
4454     S.Diag(Ordered->getBeginLoc(), diag::note_omp_ordered_param)
4455         << 0 << SourceRange(Ordered->getBeginLoc(), Ordered->getEndLoc());
4456     return true;
4457   }
4458   return false;
4459 }
4460 
4461 StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S,
4462                                       ArrayRef<OMPClause *> Clauses) {
4463   if (DSAStack->getCurrentDirective() == OMPD_atomic ||
4464       DSAStack->getCurrentDirective() == OMPD_critical ||
4465       DSAStack->getCurrentDirective() == OMPD_section ||
4466       DSAStack->getCurrentDirective() == OMPD_master ||
4467       DSAStack->getCurrentDirective() == OMPD_masked)
4468     return S;
4469 
4470   bool ErrorFound = false;
4471   CaptureRegionUnwinderRAII CaptureRegionUnwinder(
4472       *this, ErrorFound, DSAStack->getCurrentDirective());
4473   if (!S.isUsable()) {
4474     ErrorFound = true;
4475     return StmtError();
4476   }
4477 
4478   SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
4479   getOpenMPCaptureRegions(CaptureRegions, DSAStack->getCurrentDirective());
4480   OMPOrderedClause *OC = nullptr;
4481   OMPScheduleClause *SC = nullptr;
4482   SmallVector<const OMPLinearClause *, 4> LCs;
4483   SmallVector<const OMPClauseWithPreInit *, 4> PICs;
4484   // This is required for proper codegen.
4485   for (OMPClause *Clause : Clauses) {
4486     if (!LangOpts.OpenMPSimd &&
4487         isOpenMPTaskingDirective(DSAStack->getCurrentDirective()) &&
4488         Clause->getClauseKind() == OMPC_in_reduction) {
4489       // Capture taskgroup task_reduction descriptors inside the tasking regions
4490       // with the corresponding in_reduction items.
4491       auto *IRC = cast<OMPInReductionClause>(Clause);
4492       for (Expr *E : IRC->taskgroup_descriptors())
4493         if (E)
4494           MarkDeclarationsReferencedInExpr(E);
4495     }
4496     if (isOpenMPPrivate(Clause->getClauseKind()) ||
4497         Clause->getClauseKind() == OMPC_copyprivate ||
4498         (getLangOpts().OpenMPUseTLS &&
4499          getASTContext().getTargetInfo().isTLSSupported() &&
4500          Clause->getClauseKind() == OMPC_copyin)) {
4501       DSAStack->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin);
4502       // Mark all variables in private list clauses as used in inner region.
4503       for (Stmt *VarRef : Clause->children()) {
4504         if (auto *E = cast_or_null<Expr>(VarRef)) {
4505           MarkDeclarationsReferencedInExpr(E);
4506         }
4507       }
4508       DSAStack->setForceVarCapturing(/*V=*/false);
4509     } else if (isOpenMPLoopTransformationDirective(
4510                    DSAStack->getCurrentDirective())) {
4511       assert(CaptureRegions.empty() &&
4512              "No captured regions in loop transformation directives.");
4513     } else if (CaptureRegions.size() > 1 ||
4514                CaptureRegions.back() != OMPD_unknown) {
4515       if (auto *C = OMPClauseWithPreInit::get(Clause))
4516         PICs.push_back(C);
4517       if (auto *C = OMPClauseWithPostUpdate::get(Clause)) {
4518         if (Expr *E = C->getPostUpdateExpr())
4519           MarkDeclarationsReferencedInExpr(E);
4520       }
4521     }
4522     if (Clause->getClauseKind() == OMPC_schedule)
4523       SC = cast<OMPScheduleClause>(Clause);
4524     else if (Clause->getClauseKind() == OMPC_ordered)
4525       OC = cast<OMPOrderedClause>(Clause);
4526     else if (Clause->getClauseKind() == OMPC_linear)
4527       LCs.push_back(cast<OMPLinearClause>(Clause));
4528   }
4529   // Capture allocator expressions if used.
4530   for (Expr *E : DSAStack->getInnerAllocators())
4531     MarkDeclarationsReferencedInExpr(E);
4532   // OpenMP, 2.7.1 Loop Construct, Restrictions
4533   // The nonmonotonic modifier cannot be specified if an ordered clause is
4534   // specified.
4535   if (SC &&
4536       (SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
4537        SC->getSecondScheduleModifier() ==
4538            OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
4539       OC) {
4540     Diag(SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic
4541              ? SC->getFirstScheduleModifierLoc()
4542              : SC->getSecondScheduleModifierLoc(),
4543          diag::err_omp_simple_clause_incompatible_with_ordered)
4544         << getOpenMPClauseName(OMPC_schedule)
4545         << getOpenMPSimpleClauseTypeName(OMPC_schedule,
4546                                          OMPC_SCHEDULE_MODIFIER_nonmonotonic)
4547         << SourceRange(OC->getBeginLoc(), OC->getEndLoc());
4548     ErrorFound = true;
4549   }
4550   // OpenMP 5.0, 2.9.2 Worksharing-Loop Construct, Restrictions.
4551   // If an order(concurrent) clause is present, an ordered clause may not appear
4552   // on the same directive.
4553   if (checkOrderedOrderSpecified(*this, Clauses))
4554     ErrorFound = true;
4555   if (!LCs.empty() && OC && OC->getNumForLoops()) {
4556     for (const OMPLinearClause *C : LCs) {
4557       Diag(C->getBeginLoc(), diag::err_omp_linear_ordered)
4558           << SourceRange(OC->getBeginLoc(), OC->getEndLoc());
4559     }
4560     ErrorFound = true;
4561   }
4562   if (isOpenMPWorksharingDirective(DSAStack->getCurrentDirective()) &&
4563       isOpenMPSimdDirective(DSAStack->getCurrentDirective()) && OC &&
4564       OC->getNumForLoops()) {
4565     Diag(OC->getBeginLoc(), diag::err_omp_ordered_simd)
4566         << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
4567     ErrorFound = true;
4568   }
4569   if (ErrorFound) {
4570     return StmtError();
4571   }
4572   StmtResult SR = S;
4573   unsigned CompletedRegions = 0;
4574   for (OpenMPDirectiveKind ThisCaptureRegion : llvm::reverse(CaptureRegions)) {
4575     // Mark all variables in private list clauses as used in inner region.
4576     // Required for proper codegen of combined directives.
4577     // TODO: add processing for other clauses.
4578     if (ThisCaptureRegion != OMPD_unknown) {
4579       for (const clang::OMPClauseWithPreInit *C : PICs) {
4580         OpenMPDirectiveKind CaptureRegion = C->getCaptureRegion();
4581         // Find the particular capture region for the clause if the
4582         // directive is a combined one with multiple capture regions.
4583         // If the directive is not a combined one, the capture region
4584         // associated with the clause is OMPD_unknown and is generated
4585         // only once.
4586         if (CaptureRegion == ThisCaptureRegion ||
4587             CaptureRegion == OMPD_unknown) {
4588           if (auto *DS = cast_or_null<DeclStmt>(C->getPreInitStmt())) {
4589             for (Decl *D : DS->decls())
4590               MarkVariableReferenced(D->getLocation(), cast<VarDecl>(D));
4591           }
4592         }
4593       }
4594     }
4595     if (ThisCaptureRegion == OMPD_target) {
4596       // Capture allocator traits in the target region. They are used implicitly
4597       // and, thus, are not captured by default.
4598       for (OMPClause *C : Clauses) {
4599         if (const auto *UAC = dyn_cast<OMPUsesAllocatorsClause>(C)) {
4600           for (unsigned I = 0, End = UAC->getNumberOfAllocators(); I < End;
4601                ++I) {
4602             OMPUsesAllocatorsClause::Data D = UAC->getAllocatorData(I);
4603             if (Expr *E = D.AllocatorTraits)
4604               MarkDeclarationsReferencedInExpr(E);
4605           }
4606           continue;
4607         }
4608       }
4609     }
4610     if (ThisCaptureRegion == OMPD_parallel) {
4611       // Capture temp arrays for inscan reductions and locals in aligned
4612       // clauses.
4613       for (OMPClause *C : Clauses) {
4614         if (auto *RC = dyn_cast<OMPReductionClause>(C)) {
4615           if (RC->getModifier() != OMPC_REDUCTION_inscan)
4616             continue;
4617           for (Expr *E : RC->copy_array_temps())
4618             MarkDeclarationsReferencedInExpr(E);
4619         }
4620         if (auto *AC = dyn_cast<OMPAlignedClause>(C)) {
4621           for (Expr *E : AC->varlists())
4622             MarkDeclarationsReferencedInExpr(E);
4623         }
4624       }
4625     }
4626     if (++CompletedRegions == CaptureRegions.size())
4627       DSAStack->setBodyComplete();
4628     SR = ActOnCapturedRegionEnd(SR.get());
4629   }
4630   return SR;
4631 }
4632 
4633 static bool checkCancelRegion(Sema &SemaRef, OpenMPDirectiveKind CurrentRegion,
4634                               OpenMPDirectiveKind CancelRegion,
4635                               SourceLocation StartLoc) {
4636   // CancelRegion is only needed for cancel and cancellation_point.
4637   if (CurrentRegion != OMPD_cancel && CurrentRegion != OMPD_cancellation_point)
4638     return false;
4639 
4640   if (CancelRegion == OMPD_parallel || CancelRegion == OMPD_for ||
4641       CancelRegion == OMPD_sections || CancelRegion == OMPD_taskgroup)
4642     return false;
4643 
4644   SemaRef.Diag(StartLoc, diag::err_omp_wrong_cancel_region)
4645       << getOpenMPDirectiveName(CancelRegion);
4646   return true;
4647 }
4648 
4649 static bool checkNestingOfRegions(Sema &SemaRef, const DSAStackTy *Stack,
4650                                   OpenMPDirectiveKind CurrentRegion,
4651                                   const DeclarationNameInfo &CurrentName,
4652                                   OpenMPDirectiveKind CancelRegion,
4653                                   SourceLocation StartLoc) {
4654   if (Stack->getCurScope()) {
4655     OpenMPDirectiveKind ParentRegion = Stack->getParentDirective();
4656     OpenMPDirectiveKind OffendingRegion = ParentRegion;
4657     bool NestingProhibited = false;
4658     bool CloseNesting = true;
4659     bool OrphanSeen = false;
4660     enum {
4661       NoRecommend,
4662       ShouldBeInParallelRegion,
4663       ShouldBeInOrderedRegion,
4664       ShouldBeInTargetRegion,
4665       ShouldBeInTeamsRegion,
4666       ShouldBeInLoopSimdRegion,
4667     } Recommend = NoRecommend;
4668     if (isOpenMPSimdDirective(ParentRegion) &&
4669         ((SemaRef.LangOpts.OpenMP <= 45 && CurrentRegion != OMPD_ordered) ||
4670          (SemaRef.LangOpts.OpenMP >= 50 && CurrentRegion != OMPD_ordered &&
4671           CurrentRegion != OMPD_simd && CurrentRegion != OMPD_atomic &&
4672           CurrentRegion != OMPD_scan))) {
4673       // OpenMP [2.16, Nesting of Regions]
4674       // OpenMP constructs may not be nested inside a simd region.
4675       // OpenMP [2.8.1,simd Construct, Restrictions]
4676       // An ordered construct with the simd clause is the only OpenMP
4677       // construct that can appear in the simd region.
4678       // Allowing a SIMD construct nested in another SIMD construct is an
4679       // extension. The OpenMP 4.5 spec does not allow it. Issue a warning
4680       // message.
4681       // OpenMP 5.0 [2.9.3.1, simd Construct, Restrictions]
4682       // The only OpenMP constructs that can be encountered during execution of
4683       // a simd region are the atomic construct, the loop construct, the simd
4684       // construct and the ordered construct with the simd clause.
4685       SemaRef.Diag(StartLoc, (CurrentRegion != OMPD_simd)
4686                                  ? diag::err_omp_prohibited_region_simd
4687                                  : diag::warn_omp_nesting_simd)
4688           << (SemaRef.LangOpts.OpenMP >= 50 ? 1 : 0);
4689       return CurrentRegion != OMPD_simd;
4690     }
4691     if (ParentRegion == OMPD_atomic) {
4692       // OpenMP [2.16, Nesting of Regions]
4693       // OpenMP constructs may not be nested inside an atomic region.
4694       SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic);
4695       return true;
4696     }
4697     if (CurrentRegion == OMPD_section) {
4698       // OpenMP [2.7.2, sections Construct, Restrictions]
4699       // Orphaned section directives are prohibited. That is, the section
4700       // directives must appear within the sections construct and must not be
4701       // encountered elsewhere in the sections region.
4702       if (ParentRegion != OMPD_sections &&
4703           ParentRegion != OMPD_parallel_sections) {
4704         SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive)
4705             << (ParentRegion != OMPD_unknown)
4706             << getOpenMPDirectiveName(ParentRegion);
4707         return true;
4708       }
4709       return false;
4710     }
4711     // Allow some constructs (except teams and cancellation constructs) to be
4712     // orphaned (they could be used in functions, called from OpenMP regions
4713     // with the required preconditions).
4714     if (ParentRegion == OMPD_unknown &&
4715         !isOpenMPNestingTeamsDirective(CurrentRegion) &&
4716         CurrentRegion != OMPD_cancellation_point &&
4717         CurrentRegion != OMPD_cancel && CurrentRegion != OMPD_scan)
4718       return false;
4719     if (CurrentRegion == OMPD_cancellation_point ||
4720         CurrentRegion == OMPD_cancel) {
4721       // OpenMP [2.16, Nesting of Regions]
4722       // A cancellation point construct for which construct-type-clause is
4723       // taskgroup must be nested inside a task construct. A cancellation
4724       // point construct for which construct-type-clause is not taskgroup must
4725       // be closely nested inside an OpenMP construct that matches the type
4726       // specified in construct-type-clause.
4727       // A cancel construct for which construct-type-clause is taskgroup must be
4728       // nested inside a task construct. A cancel construct for which
4729       // construct-type-clause is not taskgroup must be closely nested inside an
4730       // OpenMP construct that matches the type specified in
4731       // construct-type-clause.
4732       NestingProhibited =
4733           !((CancelRegion == OMPD_parallel &&
4734              (ParentRegion == OMPD_parallel ||
4735               ParentRegion == OMPD_target_parallel)) ||
4736             (CancelRegion == OMPD_for &&
4737              (ParentRegion == OMPD_for || ParentRegion == OMPD_parallel_for ||
4738               ParentRegion == OMPD_target_parallel_for ||
4739               ParentRegion == OMPD_distribute_parallel_for ||
4740               ParentRegion == OMPD_teams_distribute_parallel_for ||
4741               ParentRegion == OMPD_target_teams_distribute_parallel_for)) ||
4742             (CancelRegion == OMPD_taskgroup &&
4743              (ParentRegion == OMPD_task ||
4744               (SemaRef.getLangOpts().OpenMP >= 50 &&
4745                (ParentRegion == OMPD_taskloop ||
4746                 ParentRegion == OMPD_master_taskloop ||
4747                 ParentRegion == OMPD_parallel_master_taskloop)))) ||
4748             (CancelRegion == OMPD_sections &&
4749              (ParentRegion == OMPD_section || ParentRegion == OMPD_sections ||
4750               ParentRegion == OMPD_parallel_sections)));
4751       OrphanSeen = ParentRegion == OMPD_unknown;
4752     } else if (CurrentRegion == OMPD_master || CurrentRegion == OMPD_masked) {
4753       // OpenMP 5.1 [2.22, Nesting of Regions]
4754       // A masked region may not be closely nested inside a worksharing, loop,
4755       // atomic, task, or taskloop region.
4756       NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
4757                           isOpenMPTaskingDirective(ParentRegion);
4758     } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) {
4759       // OpenMP [2.16, Nesting of Regions]
4760       // A critical region may not be nested (closely or otherwise) inside a
4761       // critical region with the same name. Note that this restriction is not
4762       // sufficient to prevent deadlock.
4763       SourceLocation PreviousCriticalLoc;
4764       bool DeadLock = Stack->hasDirective(
4765           [CurrentName, &PreviousCriticalLoc](OpenMPDirectiveKind K,
4766                                               const DeclarationNameInfo &DNI,
4767                                               SourceLocation Loc) {
4768             if (K == OMPD_critical && DNI.getName() == CurrentName.getName()) {
4769               PreviousCriticalLoc = Loc;
4770               return true;
4771             }
4772             return false;
4773           },
4774           false /* skip top directive */);
4775       if (DeadLock) {
4776         SemaRef.Diag(StartLoc,
4777                      diag::err_omp_prohibited_region_critical_same_name)
4778             << CurrentName.getName();
4779         if (PreviousCriticalLoc.isValid())
4780           SemaRef.Diag(PreviousCriticalLoc,
4781                        diag::note_omp_previous_critical_region);
4782         return true;
4783       }
4784     } else if (CurrentRegion == OMPD_barrier) {
4785       // OpenMP 5.1 [2.22, Nesting of Regions]
4786       // A barrier region may not be closely nested inside a worksharing, loop,
4787       // task, taskloop, critical, ordered, atomic, or masked region.
4788       NestingProhibited =
4789           isOpenMPWorksharingDirective(ParentRegion) ||
4790           isOpenMPTaskingDirective(ParentRegion) ||
4791           ParentRegion == OMPD_master || ParentRegion == OMPD_masked ||
4792           ParentRegion == OMPD_parallel_master ||
4793           ParentRegion == OMPD_critical || ParentRegion == OMPD_ordered;
4794     } else if (isOpenMPWorksharingDirective(CurrentRegion) &&
4795                !isOpenMPParallelDirective(CurrentRegion) &&
4796                !isOpenMPTeamsDirective(CurrentRegion)) {
4797       // OpenMP 5.1 [2.22, Nesting of Regions]
4798       // A loop region that binds to a parallel region or a worksharing region
4799       // may not be closely nested inside a worksharing, loop, task, taskloop,
4800       // critical, ordered, atomic, or masked region.
4801       NestingProhibited =
4802           isOpenMPWorksharingDirective(ParentRegion) ||
4803           isOpenMPTaskingDirective(ParentRegion) ||
4804           ParentRegion == OMPD_master || ParentRegion == OMPD_masked ||
4805           ParentRegion == OMPD_parallel_master ||
4806           ParentRegion == OMPD_critical || ParentRegion == OMPD_ordered;
4807       Recommend = ShouldBeInParallelRegion;
4808     } else if (CurrentRegion == OMPD_ordered) {
4809       // OpenMP [2.16, Nesting of Regions]
4810       // An ordered region may not be closely nested inside a critical,
4811       // atomic, or explicit task region.
4812       // An ordered region must be closely nested inside a loop region (or
4813       // parallel loop region) with an ordered clause.
4814       // OpenMP [2.8.1,simd Construct, Restrictions]
4815       // An ordered construct with the simd clause is the only OpenMP construct
4816       // that can appear in the simd region.
4817       NestingProhibited = ParentRegion == OMPD_critical ||
4818                           isOpenMPTaskingDirective(ParentRegion) ||
4819                           !(isOpenMPSimdDirective(ParentRegion) ||
4820                             Stack->isParentOrderedRegion());
4821       Recommend = ShouldBeInOrderedRegion;
4822     } else if (isOpenMPNestingTeamsDirective(CurrentRegion)) {
4823       // OpenMP [2.16, Nesting of Regions]
4824       // If specified, a teams construct must be contained within a target
4825       // construct.
4826       NestingProhibited =
4827           (SemaRef.LangOpts.OpenMP <= 45 && ParentRegion != OMPD_target) ||
4828           (SemaRef.LangOpts.OpenMP >= 50 && ParentRegion != OMPD_unknown &&
4829            ParentRegion != OMPD_target);
4830       OrphanSeen = ParentRegion == OMPD_unknown;
4831       Recommend = ShouldBeInTargetRegion;
4832     } else if (CurrentRegion == OMPD_scan) {
4833       // OpenMP [2.16, Nesting of Regions]
4834       // If specified, a teams construct must be contained within a target
4835       // construct.
4836       NestingProhibited =
4837           SemaRef.LangOpts.OpenMP < 50 ||
4838           (ParentRegion != OMPD_simd && ParentRegion != OMPD_for &&
4839            ParentRegion != OMPD_for_simd && ParentRegion != OMPD_parallel_for &&
4840            ParentRegion != OMPD_parallel_for_simd);
4841       OrphanSeen = ParentRegion == OMPD_unknown;
4842       Recommend = ShouldBeInLoopSimdRegion;
4843     }
4844     if (!NestingProhibited &&
4845         !isOpenMPTargetExecutionDirective(CurrentRegion) &&
4846         !isOpenMPTargetDataManagementDirective(CurrentRegion) &&
4847         (ParentRegion == OMPD_teams || ParentRegion == OMPD_target_teams)) {
4848       // OpenMP [2.16, Nesting of Regions]
4849       // distribute, parallel, parallel sections, parallel workshare, and the
4850       // parallel loop and parallel loop SIMD constructs are the only OpenMP
4851       // constructs that can be closely nested in the teams region.
4852       NestingProhibited = !isOpenMPParallelDirective(CurrentRegion) &&
4853                           !isOpenMPDistributeDirective(CurrentRegion);
4854       Recommend = ShouldBeInParallelRegion;
4855     }
4856     if (!NestingProhibited &&
4857         isOpenMPNestingDistributeDirective(CurrentRegion)) {
4858       // OpenMP 4.5 [2.17 Nesting of Regions]
4859       // The region associated with the distribute construct must be strictly
4860       // nested inside a teams region
4861       NestingProhibited =
4862           (ParentRegion != OMPD_teams && ParentRegion != OMPD_target_teams);
4863       Recommend = ShouldBeInTeamsRegion;
4864     }
4865     if (!NestingProhibited &&
4866         (isOpenMPTargetExecutionDirective(CurrentRegion) ||
4867          isOpenMPTargetDataManagementDirective(CurrentRegion))) {
4868       // OpenMP 4.5 [2.17 Nesting of Regions]
4869       // If a target, target update, target data, target enter data, or
4870       // target exit data construct is encountered during execution of a
4871       // target region, the behavior is unspecified.
4872       NestingProhibited = Stack->hasDirective(
4873           [&OffendingRegion](OpenMPDirectiveKind K, const DeclarationNameInfo &,
4874                              SourceLocation) {
4875             if (isOpenMPTargetExecutionDirective(K)) {
4876               OffendingRegion = K;
4877               return true;
4878             }
4879             return false;
4880           },
4881           false /* don't skip top directive */);
4882       CloseNesting = false;
4883     }
4884     if (NestingProhibited) {
4885       if (OrphanSeen) {
4886         SemaRef.Diag(StartLoc, diag::err_omp_orphaned_device_directive)
4887             << getOpenMPDirectiveName(CurrentRegion) << Recommend;
4888       } else {
4889         SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region)
4890             << CloseNesting << getOpenMPDirectiveName(OffendingRegion)
4891             << Recommend << getOpenMPDirectiveName(CurrentRegion);
4892       }
4893       return true;
4894     }
4895   }
4896   return false;
4897 }
4898 
4899 struct Kind2Unsigned {
4900   using argument_type = OpenMPDirectiveKind;
4901   unsigned operator()(argument_type DK) { return unsigned(DK); }
4902 };
4903 static bool checkIfClauses(Sema &S, OpenMPDirectiveKind Kind,
4904                            ArrayRef<OMPClause *> Clauses,
4905                            ArrayRef<OpenMPDirectiveKind> AllowedNameModifiers) {
4906   bool ErrorFound = false;
4907   unsigned NamedModifiersNumber = 0;
4908   llvm::IndexedMap<const OMPIfClause *, Kind2Unsigned> FoundNameModifiers;
4909   FoundNameModifiers.resize(llvm::omp::Directive_enumSize + 1);
4910   SmallVector<SourceLocation, 4> NameModifierLoc;
4911   for (const OMPClause *C : Clauses) {
4912     if (const auto *IC = dyn_cast_or_null<OMPIfClause>(C)) {
4913       // At most one if clause without a directive-name-modifier can appear on
4914       // the directive.
4915       OpenMPDirectiveKind CurNM = IC->getNameModifier();
4916       if (FoundNameModifiers[CurNM]) {
4917         S.Diag(C->getBeginLoc(), diag::err_omp_more_one_clause)
4918             << getOpenMPDirectiveName(Kind) << getOpenMPClauseName(OMPC_if)
4919             << (CurNM != OMPD_unknown) << getOpenMPDirectiveName(CurNM);
4920         ErrorFound = true;
4921       } else if (CurNM != OMPD_unknown) {
4922         NameModifierLoc.push_back(IC->getNameModifierLoc());
4923         ++NamedModifiersNumber;
4924       }
4925       FoundNameModifiers[CurNM] = IC;
4926       if (CurNM == OMPD_unknown)
4927         continue;
4928       // Check if the specified name modifier is allowed for the current
4929       // directive.
4930       // At most one if clause with the particular directive-name-modifier can
4931       // appear on the directive.
4932       bool MatchFound = false;
4933       for (auto NM : AllowedNameModifiers) {
4934         if (CurNM == NM) {
4935           MatchFound = true;
4936           break;
4937         }
4938       }
4939       if (!MatchFound) {
4940         S.Diag(IC->getNameModifierLoc(),
4941                diag::err_omp_wrong_if_directive_name_modifier)
4942             << getOpenMPDirectiveName(CurNM) << getOpenMPDirectiveName(Kind);
4943         ErrorFound = true;
4944       }
4945     }
4946   }
4947   // If any if clause on the directive includes a directive-name-modifier then
4948   // all if clauses on the directive must include a directive-name-modifier.
4949   if (FoundNameModifiers[OMPD_unknown] && NamedModifiersNumber > 0) {
4950     if (NamedModifiersNumber == AllowedNameModifiers.size()) {
4951       S.Diag(FoundNameModifiers[OMPD_unknown]->getBeginLoc(),
4952              diag::err_omp_no_more_if_clause);
4953     } else {
4954       std::string Values;
4955       std::string Sep(", ");
4956       unsigned AllowedCnt = 0;
4957       unsigned TotalAllowedNum =
4958           AllowedNameModifiers.size() - NamedModifiersNumber;
4959       for (unsigned Cnt = 0, End = AllowedNameModifiers.size(); Cnt < End;
4960            ++Cnt) {
4961         OpenMPDirectiveKind NM = AllowedNameModifiers[Cnt];
4962         if (!FoundNameModifiers[NM]) {
4963           Values += "'";
4964           Values += getOpenMPDirectiveName(NM);
4965           Values += "'";
4966           if (AllowedCnt + 2 == TotalAllowedNum)
4967             Values += " or ";
4968           else if (AllowedCnt + 1 != TotalAllowedNum)
4969             Values += Sep;
4970           ++AllowedCnt;
4971         }
4972       }
4973       S.Diag(FoundNameModifiers[OMPD_unknown]->getCondition()->getBeginLoc(),
4974              diag::err_omp_unnamed_if_clause)
4975           << (TotalAllowedNum > 1) << Values;
4976     }
4977     for (SourceLocation Loc : NameModifierLoc) {
4978       S.Diag(Loc, diag::note_omp_previous_named_if_clause);
4979     }
4980     ErrorFound = true;
4981   }
4982   return ErrorFound;
4983 }
4984 
4985 static std::pair<ValueDecl *, bool> getPrivateItem(Sema &S, Expr *&RefExpr,
4986                                                    SourceLocation &ELoc,
4987                                                    SourceRange &ERange,
4988                                                    bool AllowArraySection) {
4989   if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() ||
4990       RefExpr->containsUnexpandedParameterPack())
4991     return std::make_pair(nullptr, true);
4992 
4993   // OpenMP [3.1, C/C++]
4994   //  A list item is a variable name.
4995   // OpenMP  [2.9.3.3, Restrictions, p.1]
4996   //  A variable that is part of another variable (as an array or
4997   //  structure element) cannot appear in a private clause.
4998   RefExpr = RefExpr->IgnoreParens();
4999   enum {
5000     NoArrayExpr = -1,
5001     ArraySubscript = 0,
5002     OMPArraySection = 1
5003   } IsArrayExpr = NoArrayExpr;
5004   if (AllowArraySection) {
5005     if (auto *ASE = dyn_cast_or_null<ArraySubscriptExpr>(RefExpr)) {
5006       Expr *Base = ASE->getBase()->IgnoreParenImpCasts();
5007       while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
5008         Base = TempASE->getBase()->IgnoreParenImpCasts();
5009       RefExpr = Base;
5010       IsArrayExpr = ArraySubscript;
5011     } else if (auto *OASE = dyn_cast_or_null<OMPArraySectionExpr>(RefExpr)) {
5012       Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
5013       while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
5014         Base = TempOASE->getBase()->IgnoreParenImpCasts();
5015       while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
5016         Base = TempASE->getBase()->IgnoreParenImpCasts();
5017       RefExpr = Base;
5018       IsArrayExpr = OMPArraySection;
5019     }
5020   }
5021   ELoc = RefExpr->getExprLoc();
5022   ERange = RefExpr->getSourceRange();
5023   RefExpr = RefExpr->IgnoreParenImpCasts();
5024   auto *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
5025   auto *ME = dyn_cast_or_null<MemberExpr>(RefExpr);
5026   if ((!DE || !isa<VarDecl>(DE->getDecl())) &&
5027       (S.getCurrentThisType().isNull() || !ME ||
5028        !isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()) ||
5029        !isa<FieldDecl>(ME->getMemberDecl()))) {
5030     if (IsArrayExpr != NoArrayExpr) {
5031       S.Diag(ELoc, diag::err_omp_expected_base_var_name) << IsArrayExpr
5032                                                          << ERange;
5033     } else {
5034       S.Diag(ELoc,
5035              AllowArraySection
5036                  ? diag::err_omp_expected_var_name_member_expr_or_array_item
5037                  : diag::err_omp_expected_var_name_member_expr)
5038           << (S.getCurrentThisType().isNull() ? 0 : 1) << ERange;
5039     }
5040     return std::make_pair(nullptr, false);
5041   }
5042   return std::make_pair(
5043       getCanonicalDecl(DE ? DE->getDecl() : ME->getMemberDecl()), false);
5044 }
5045 
5046 namespace {
5047 /// Checks if the allocator is used in uses_allocators clause to be allowed in
5048 /// target regions.
5049 class AllocatorChecker final : public ConstStmtVisitor<AllocatorChecker, bool> {
5050   DSAStackTy *S = nullptr;
5051 
5052 public:
5053   bool VisitDeclRefExpr(const DeclRefExpr *E) {
5054     return S->isUsesAllocatorsDecl(E->getDecl())
5055                .getValueOr(
5056                    DSAStackTy::UsesAllocatorsDeclKind::AllocatorTrait) ==
5057            DSAStackTy::UsesAllocatorsDeclKind::AllocatorTrait;
5058   }
5059   bool VisitStmt(const Stmt *S) {
5060     for (const Stmt *Child : S->children()) {
5061       if (Child && Visit(Child))
5062         return true;
5063     }
5064     return false;
5065   }
5066   explicit AllocatorChecker(DSAStackTy *S) : S(S) {}
5067 };
5068 } // namespace
5069 
5070 static void checkAllocateClauses(Sema &S, DSAStackTy *Stack,
5071                                  ArrayRef<OMPClause *> Clauses) {
5072   assert(!S.CurContext->isDependentContext() &&
5073          "Expected non-dependent context.");
5074   auto AllocateRange =
5075       llvm::make_filter_range(Clauses, OMPAllocateClause::classof);
5076   llvm::DenseMap<CanonicalDeclPtr<Decl>, CanonicalDeclPtr<VarDecl>>
5077       DeclToCopy;
5078   auto PrivateRange = llvm::make_filter_range(Clauses, [](const OMPClause *C) {
5079     return isOpenMPPrivate(C->getClauseKind());
5080   });
5081   for (OMPClause *Cl : PrivateRange) {
5082     MutableArrayRef<Expr *>::iterator I, It, Et;
5083     if (Cl->getClauseKind() == OMPC_private) {
5084       auto *PC = cast<OMPPrivateClause>(Cl);
5085       I = PC->private_copies().begin();
5086       It = PC->varlist_begin();
5087       Et = PC->varlist_end();
5088     } else if (Cl->getClauseKind() == OMPC_firstprivate) {
5089       auto *PC = cast<OMPFirstprivateClause>(Cl);
5090       I = PC->private_copies().begin();
5091       It = PC->varlist_begin();
5092       Et = PC->varlist_end();
5093     } else if (Cl->getClauseKind() == OMPC_lastprivate) {
5094       auto *PC = cast<OMPLastprivateClause>(Cl);
5095       I = PC->private_copies().begin();
5096       It = PC->varlist_begin();
5097       Et = PC->varlist_end();
5098     } else if (Cl->getClauseKind() == OMPC_linear) {
5099       auto *PC = cast<OMPLinearClause>(Cl);
5100       I = PC->privates().begin();
5101       It = PC->varlist_begin();
5102       Et = PC->varlist_end();
5103     } else if (Cl->getClauseKind() == OMPC_reduction) {
5104       auto *PC = cast<OMPReductionClause>(Cl);
5105       I = PC->privates().begin();
5106       It = PC->varlist_begin();
5107       Et = PC->varlist_end();
5108     } else if (Cl->getClauseKind() == OMPC_task_reduction) {
5109       auto *PC = cast<OMPTaskReductionClause>(Cl);
5110       I = PC->privates().begin();
5111       It = PC->varlist_begin();
5112       Et = PC->varlist_end();
5113     } else if (Cl->getClauseKind() == OMPC_in_reduction) {
5114       auto *PC = cast<OMPInReductionClause>(Cl);
5115       I = PC->privates().begin();
5116       It = PC->varlist_begin();
5117       Et = PC->varlist_end();
5118     } else {
5119       llvm_unreachable("Expected private clause.");
5120     }
5121     for (Expr *E : llvm::make_range(It, Et)) {
5122       if (!*I) {
5123         ++I;
5124         continue;
5125       }
5126       SourceLocation ELoc;
5127       SourceRange ERange;
5128       Expr *SimpleRefExpr = E;
5129       auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange,
5130                                 /*AllowArraySection=*/true);
5131       DeclToCopy.try_emplace(Res.first,
5132                              cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()));
5133       ++I;
5134     }
5135   }
5136   for (OMPClause *C : AllocateRange) {
5137     auto *AC = cast<OMPAllocateClause>(C);
5138     if (S.getLangOpts().OpenMP >= 50 &&
5139         !Stack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>() &&
5140         isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()) &&
5141         AC->getAllocator()) {
5142       Expr *Allocator = AC->getAllocator();
5143       // OpenMP, 2.12.5 target Construct
5144       // Memory allocators that do not appear in a uses_allocators clause cannot
5145       // appear as an allocator in an allocate clause or be used in the target
5146       // region unless a requires directive with the dynamic_allocators clause
5147       // is present in the same compilation unit.
5148       AllocatorChecker Checker(Stack);
5149       if (Checker.Visit(Allocator))
5150         S.Diag(Allocator->getExprLoc(),
5151                diag::err_omp_allocator_not_in_uses_allocators)
5152             << Allocator->getSourceRange();
5153     }
5154     OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind =
5155         getAllocatorKind(S, Stack, AC->getAllocator());
5156     // OpenMP, 2.11.4 allocate Clause, Restrictions.
5157     // For task, taskloop or target directives, allocation requests to memory
5158     // allocators with the trait access set to thread result in unspecified
5159     // behavior.
5160     if (AllocatorKind == OMPAllocateDeclAttr::OMPThreadMemAlloc &&
5161         (isOpenMPTaskingDirective(Stack->getCurrentDirective()) ||
5162          isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()))) {
5163       S.Diag(AC->getAllocator()->getExprLoc(),
5164              diag::warn_omp_allocate_thread_on_task_target_directive)
5165           << getOpenMPDirectiveName(Stack->getCurrentDirective());
5166     }
5167     for (Expr *E : AC->varlists()) {
5168       SourceLocation ELoc;
5169       SourceRange ERange;
5170       Expr *SimpleRefExpr = E;
5171       auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange);
5172       ValueDecl *VD = Res.first;
5173       DSAStackTy::DSAVarData Data = Stack->getTopDSA(VD, /*FromParent=*/false);
5174       if (!isOpenMPPrivate(Data.CKind)) {
5175         S.Diag(E->getExprLoc(),
5176                diag::err_omp_expected_private_copy_for_allocate);
5177         continue;
5178       }
5179       VarDecl *PrivateVD = DeclToCopy[VD];
5180       if (checkPreviousOMPAllocateAttribute(S, Stack, E, PrivateVD,
5181                                             AllocatorKind, AC->getAllocator()))
5182         continue;
5183       applyOMPAllocateAttribute(S, PrivateVD, AllocatorKind, AC->getAllocator(),
5184                                 E->getSourceRange());
5185     }
5186   }
5187 }
5188 
5189 namespace {
5190 /// Rewrite statements and expressions for Sema \p Actions CurContext.
5191 ///
5192 /// Used to wrap already parsed statements/expressions into a new CapturedStmt
5193 /// context. DeclRefExpr used inside the new context are changed to refer to the
5194 /// captured variable instead.
5195 class CaptureVars : public TreeTransform<CaptureVars> {
5196   using BaseTransform = TreeTransform<CaptureVars>;
5197 
5198 public:
5199   CaptureVars(Sema &Actions) : BaseTransform(Actions) {}
5200 
5201   bool AlwaysRebuild() { return true; }
5202 };
5203 } // namespace
5204 
5205 static VarDecl *precomputeExpr(Sema &Actions,
5206                                SmallVectorImpl<Stmt *> &BodyStmts, Expr *E,
5207                                StringRef Name) {
5208   Expr *NewE = AssertSuccess(CaptureVars(Actions).TransformExpr(E));
5209   VarDecl *NewVar = buildVarDecl(Actions, {}, NewE->getType(), Name, nullptr,
5210                                  dyn_cast<DeclRefExpr>(E->IgnoreImplicit()));
5211   auto *NewDeclStmt = cast<DeclStmt>(AssertSuccess(
5212       Actions.ActOnDeclStmt(Actions.ConvertDeclToDeclGroup(NewVar), {}, {})));
5213   Actions.AddInitializerToDecl(NewDeclStmt->getSingleDecl(), NewE, false);
5214   BodyStmts.push_back(NewDeclStmt);
5215   return NewVar;
5216 }
5217 
5218 /// Create a closure that computes the number of iterations of a loop.
5219 ///
5220 /// \param Actions   The Sema object.
5221 /// \param LogicalTy Type for the logical iteration number.
5222 /// \param Rel       Comparison operator of the loop condition.
5223 /// \param StartExpr Value of the loop counter at the first iteration.
5224 /// \param StopExpr  Expression the loop counter is compared against in the loop
5225 /// condition. \param StepExpr      Amount of increment after each iteration.
5226 ///
5227 /// \return Closure (CapturedStmt) of the distance calculation.
5228 static CapturedStmt *buildDistanceFunc(Sema &Actions, QualType LogicalTy,
5229                                        BinaryOperator::Opcode Rel,
5230                                        Expr *StartExpr, Expr *StopExpr,
5231                                        Expr *StepExpr) {
5232   ASTContext &Ctx = Actions.getASTContext();
5233   TypeSourceInfo *LogicalTSI = Ctx.getTrivialTypeSourceInfo(LogicalTy);
5234 
5235   // Captured regions currently don't support return values, we use an
5236   // out-parameter instead. All inputs are implicit captures.
5237   // TODO: Instead of capturing each DeclRefExpr occurring in
5238   // StartExpr/StopExpr/Step, these could also be passed as a value capture.
5239   QualType ResultTy = Ctx.getLValueReferenceType(LogicalTy);
5240   Sema::CapturedParamNameType Params[] = {{"Distance", ResultTy},
5241                                           {StringRef(), QualType()}};
5242   Actions.ActOnCapturedRegionStart({}, nullptr, CR_Default, Params);
5243 
5244   Stmt *Body;
5245   {
5246     Sema::CompoundScopeRAII CompoundScope(Actions);
5247     CapturedDecl *CS = cast<CapturedDecl>(Actions.CurContext);
5248 
5249     // Get the LValue expression for the result.
5250     ImplicitParamDecl *DistParam = CS->getParam(0);
5251     DeclRefExpr *DistRef = Actions.BuildDeclRefExpr(
5252         DistParam, LogicalTy, VK_LValue, {}, nullptr, nullptr, {}, nullptr);
5253 
5254     SmallVector<Stmt *, 4> BodyStmts;
5255 
5256     // Capture all referenced variable references.
5257     // TODO: Instead of computing NewStart/NewStop/NewStep inside the
5258     // CapturedStmt, we could compute them before and capture the result, to be
5259     // used jointly with the LoopVar function.
5260     VarDecl *NewStart = precomputeExpr(Actions, BodyStmts, StartExpr, ".start");
5261     VarDecl *NewStop = precomputeExpr(Actions, BodyStmts, StopExpr, ".stop");
5262     VarDecl *NewStep = precomputeExpr(Actions, BodyStmts, StepExpr, ".step");
5263     auto BuildVarRef = [&](VarDecl *VD) {
5264       return buildDeclRefExpr(Actions, VD, VD->getType(), {});
5265     };
5266 
5267     IntegerLiteral *Zero = IntegerLiteral::Create(
5268         Ctx, llvm::APInt(Ctx.getIntWidth(LogicalTy), 0), LogicalTy, {});
5269     Expr *Dist;
5270     if (Rel == BO_NE) {
5271       // When using a != comparison, the increment can be +1 or -1. This can be
5272       // dynamic at runtime, so we need to check for the direction.
5273       Expr *IsNegStep = AssertSuccess(
5274           Actions.BuildBinOp(nullptr, {}, BO_LT, BuildVarRef(NewStep), Zero));
5275 
5276       // Positive increment.
5277       Expr *ForwardRange = AssertSuccess(Actions.BuildBinOp(
5278           nullptr, {}, BO_Sub, BuildVarRef(NewStop), BuildVarRef(NewStart)));
5279       ForwardRange = AssertSuccess(
5280           Actions.BuildCStyleCastExpr({}, LogicalTSI, {}, ForwardRange));
5281       Expr *ForwardDist = AssertSuccess(Actions.BuildBinOp(
5282           nullptr, {}, BO_Div, ForwardRange, BuildVarRef(NewStep)));
5283 
5284       // Negative increment.
5285       Expr *BackwardRange = AssertSuccess(Actions.BuildBinOp(
5286           nullptr, {}, BO_Sub, BuildVarRef(NewStart), BuildVarRef(NewStop)));
5287       BackwardRange = AssertSuccess(
5288           Actions.BuildCStyleCastExpr({}, LogicalTSI, {}, BackwardRange));
5289       Expr *NegIncAmount = AssertSuccess(
5290           Actions.BuildUnaryOp(nullptr, {}, UO_Minus, BuildVarRef(NewStep)));
5291       Expr *BackwardDist = AssertSuccess(
5292           Actions.BuildBinOp(nullptr, {}, BO_Div, BackwardRange, NegIncAmount));
5293 
5294       // Use the appropriate case.
5295       Dist = AssertSuccess(Actions.ActOnConditionalOp(
5296           {}, {}, IsNegStep, BackwardDist, ForwardDist));
5297     } else {
5298       assert((Rel == BO_LT || Rel == BO_LE || Rel == BO_GE || Rel == BO_GT) &&
5299              "Expected one of these relational operators");
5300 
5301       // We can derive the direction from any other comparison operator. It is
5302       // non well-formed OpenMP if Step increments/decrements in the other
5303       // directions. Whether at least the first iteration passes the loop
5304       // condition.
5305       Expr *HasAnyIteration = AssertSuccess(Actions.BuildBinOp(
5306           nullptr, {}, Rel, BuildVarRef(NewStart), BuildVarRef(NewStop)));
5307 
5308       // Compute the range between first and last counter value.
5309       Expr *Range;
5310       if (Rel == BO_GE || Rel == BO_GT)
5311         Range = AssertSuccess(Actions.BuildBinOp(
5312             nullptr, {}, BO_Sub, BuildVarRef(NewStart), BuildVarRef(NewStop)));
5313       else
5314         Range = AssertSuccess(Actions.BuildBinOp(
5315             nullptr, {}, BO_Sub, BuildVarRef(NewStop), BuildVarRef(NewStart)));
5316 
5317       // Ensure unsigned range space.
5318       Range =
5319           AssertSuccess(Actions.BuildCStyleCastExpr({}, LogicalTSI, {}, Range));
5320 
5321       if (Rel == BO_LE || Rel == BO_GE) {
5322         // Add one to the range if the relational operator is inclusive.
5323         Range =
5324             AssertSuccess(Actions.BuildUnaryOp(nullptr, {}, UO_PreInc, Range));
5325       }
5326 
5327       // Divide by the absolute step amount.
5328       Expr *Divisor = BuildVarRef(NewStep);
5329       if (Rel == BO_GE || Rel == BO_GT)
5330         Divisor =
5331             AssertSuccess(Actions.BuildUnaryOp(nullptr, {}, UO_Minus, Divisor));
5332       Dist = AssertSuccess(
5333           Actions.BuildBinOp(nullptr, {}, BO_Div, Range, Divisor));
5334 
5335       // If there is not at least one iteration, the range contains garbage. Fix
5336       // to zero in this case.
5337       Dist = AssertSuccess(
5338           Actions.ActOnConditionalOp({}, {}, HasAnyIteration, Dist, Zero));
5339     }
5340 
5341     // Assign the result to the out-parameter.
5342     Stmt *ResultAssign = AssertSuccess(Actions.BuildBinOp(
5343         Actions.getCurScope(), {}, BO_Assign, DistRef, Dist));
5344     BodyStmts.push_back(ResultAssign);
5345 
5346     Body = AssertSuccess(Actions.ActOnCompoundStmt({}, {}, BodyStmts, false));
5347   }
5348 
5349   return cast<CapturedStmt>(
5350       AssertSuccess(Actions.ActOnCapturedRegionEnd(Body)));
5351 }
5352 
5353 /// Create a closure that computes the loop variable from the logical iteration
5354 /// number.
5355 ///
5356 /// \param Actions   The Sema object.
5357 /// \param LoopVarTy Type for the loop variable used for result value.
5358 /// \param LogicalTy Type for the logical iteration number.
5359 /// \param StartExpr Value of the loop counter at the first iteration.
5360 /// \param Step      Amount of increment after each iteration.
5361 /// \param Deref     Whether the loop variable is a dereference of the loop
5362 /// counter variable.
5363 ///
5364 /// \return Closure (CapturedStmt) of the loop value calculation.
5365 static CapturedStmt *buildLoopVarFunc(Sema &Actions, QualType LoopVarTy,
5366                                       QualType LogicalTy,
5367                                       DeclRefExpr *StartExpr, Expr *Step,
5368                                       bool Deref) {
5369   ASTContext &Ctx = Actions.getASTContext();
5370 
5371   // Pass the result as an out-parameter. Passing as return value would require
5372   // the OpenMPIRBuilder to know additional C/C++ semantics, such as how to
5373   // invoke a copy constructor.
5374   QualType TargetParamTy = Ctx.getLValueReferenceType(LoopVarTy);
5375   Sema::CapturedParamNameType Params[] = {{"LoopVar", TargetParamTy},
5376                                           {"Logical", LogicalTy},
5377                                           {StringRef(), QualType()}};
5378   Actions.ActOnCapturedRegionStart({}, nullptr, CR_Default, Params);
5379 
5380   // Capture the initial iterator which represents the LoopVar value at the
5381   // zero's logical iteration. Since the original ForStmt/CXXForRangeStmt update
5382   // it in every iteration, capture it by value before it is modified.
5383   VarDecl *StartVar = cast<VarDecl>(StartExpr->getDecl());
5384   bool Invalid = Actions.tryCaptureVariable(StartVar, {},
5385                                             Sema::TryCapture_ExplicitByVal, {});
5386   (void)Invalid;
5387   assert(!Invalid && "Expecting capture-by-value to work.");
5388 
5389   Expr *Body;
5390   {
5391     Sema::CompoundScopeRAII CompoundScope(Actions);
5392     auto *CS = cast<CapturedDecl>(Actions.CurContext);
5393 
5394     ImplicitParamDecl *TargetParam = CS->getParam(0);
5395     DeclRefExpr *TargetRef = Actions.BuildDeclRefExpr(
5396         TargetParam, LoopVarTy, VK_LValue, {}, nullptr, nullptr, {}, nullptr);
5397     ImplicitParamDecl *IndvarParam = CS->getParam(1);
5398     DeclRefExpr *LogicalRef = Actions.BuildDeclRefExpr(
5399         IndvarParam, LogicalTy, VK_LValue, {}, nullptr, nullptr, {}, nullptr);
5400 
5401     // Capture the Start expression.
5402     CaptureVars Recap(Actions);
5403     Expr *NewStart = AssertSuccess(Recap.TransformExpr(StartExpr));
5404     Expr *NewStep = AssertSuccess(Recap.TransformExpr(Step));
5405 
5406     Expr *Skip = AssertSuccess(
5407         Actions.BuildBinOp(nullptr, {}, BO_Mul, NewStep, LogicalRef));
5408     // TODO: Explicitly cast to the iterator's difference_type instead of
5409     // relying on implicit conversion.
5410     Expr *Advanced =
5411         AssertSuccess(Actions.BuildBinOp(nullptr, {}, BO_Add, NewStart, Skip));
5412 
5413     if (Deref) {
5414       // For range-based for-loops convert the loop counter value to a concrete
5415       // loop variable value by dereferencing the iterator.
5416       Advanced =
5417           AssertSuccess(Actions.BuildUnaryOp(nullptr, {}, UO_Deref, Advanced));
5418     }
5419 
5420     // Assign the result to the output parameter.
5421     Body = AssertSuccess(Actions.BuildBinOp(Actions.getCurScope(), {},
5422                                             BO_Assign, TargetRef, Advanced));
5423   }
5424   return cast<CapturedStmt>(
5425       AssertSuccess(Actions.ActOnCapturedRegionEnd(Body)));
5426 }
5427 
5428 StmtResult Sema::ActOnOpenMPCanonicalLoop(Stmt *AStmt) {
5429   ASTContext &Ctx = getASTContext();
5430 
5431   // Extract the common elements of ForStmt and CXXForRangeStmt:
5432   // Loop variable, repeat condition, increment
5433   Expr *Cond, *Inc;
5434   VarDecl *LIVDecl, *LUVDecl;
5435   if (auto *For = dyn_cast<ForStmt>(AStmt)) {
5436     Stmt *Init = For->getInit();
5437     if (auto *LCVarDeclStmt = dyn_cast<DeclStmt>(Init)) {
5438       // For statement declares loop variable.
5439       LIVDecl = cast<VarDecl>(LCVarDeclStmt->getSingleDecl());
5440     } else if (auto *LCAssign = dyn_cast<BinaryOperator>(Init)) {
5441       // For statement reuses variable.
5442       assert(LCAssign->getOpcode() == BO_Assign &&
5443              "init part must be a loop variable assignment");
5444       auto *CounterRef = cast<DeclRefExpr>(LCAssign->getLHS());
5445       LIVDecl = cast<VarDecl>(CounterRef->getDecl());
5446     } else
5447       llvm_unreachable("Cannot determine loop variable");
5448     LUVDecl = LIVDecl;
5449 
5450     Cond = For->getCond();
5451     Inc = For->getInc();
5452   } else if (auto *RangeFor = dyn_cast<CXXForRangeStmt>(AStmt)) {
5453     DeclStmt *BeginStmt = RangeFor->getBeginStmt();
5454     LIVDecl = cast<VarDecl>(BeginStmt->getSingleDecl());
5455     LUVDecl = RangeFor->getLoopVariable();
5456 
5457     Cond = RangeFor->getCond();
5458     Inc = RangeFor->getInc();
5459   } else
5460     llvm_unreachable("unhandled kind of loop");
5461 
5462   QualType CounterTy = LIVDecl->getType();
5463   QualType LVTy = LUVDecl->getType();
5464 
5465   // Analyze the loop condition.
5466   Expr *LHS, *RHS;
5467   BinaryOperator::Opcode CondRel;
5468   Cond = Cond->IgnoreImplicit();
5469   if (auto *CondBinExpr = dyn_cast<BinaryOperator>(Cond)) {
5470     LHS = CondBinExpr->getLHS();
5471     RHS = CondBinExpr->getRHS();
5472     CondRel = CondBinExpr->getOpcode();
5473   } else if (auto *CondCXXOp = dyn_cast<CXXOperatorCallExpr>(Cond)) {
5474     assert(CondCXXOp->getNumArgs() == 2 && "Comparison should have 2 operands");
5475     LHS = CondCXXOp->getArg(0);
5476     RHS = CondCXXOp->getArg(1);
5477     switch (CondCXXOp->getOperator()) {
5478     case OO_ExclaimEqual:
5479       CondRel = BO_NE;
5480       break;
5481     case OO_Less:
5482       CondRel = BO_LT;
5483       break;
5484     case OO_LessEqual:
5485       CondRel = BO_LE;
5486       break;
5487     case OO_Greater:
5488       CondRel = BO_GT;
5489       break;
5490     case OO_GreaterEqual:
5491       CondRel = BO_GE;
5492       break;
5493     default:
5494       llvm_unreachable("unexpected iterator operator");
5495     }
5496   } else
5497     llvm_unreachable("unexpected loop condition");
5498 
5499   // Normalize such that the loop counter is on the LHS.
5500   if (!isa<DeclRefExpr>(LHS->IgnoreImplicit()) ||
5501       cast<DeclRefExpr>(LHS->IgnoreImplicit())->getDecl() != LIVDecl) {
5502     std::swap(LHS, RHS);
5503     CondRel = BinaryOperator::reverseComparisonOp(CondRel);
5504   }
5505   auto *CounterRef = cast<DeclRefExpr>(LHS->IgnoreImplicit());
5506 
5507   // Decide the bit width for the logical iteration counter. By default use the
5508   // unsigned ptrdiff_t integer size (for iterators and pointers).
5509   // TODO: For iterators, use iterator::difference_type,
5510   // std::iterator_traits<>::difference_type or decltype(it - end).
5511   QualType LogicalTy = Ctx.getUnsignedPointerDiffType();
5512   if (CounterTy->isIntegerType()) {
5513     unsigned BitWidth = Ctx.getIntWidth(CounterTy);
5514     LogicalTy = Ctx.getIntTypeForBitwidth(BitWidth, false);
5515   }
5516 
5517   // Analyze the loop increment.
5518   Expr *Step;
5519   if (auto *IncUn = dyn_cast<UnaryOperator>(Inc)) {
5520     int Direction;
5521     switch (IncUn->getOpcode()) {
5522     case UO_PreInc:
5523     case UO_PostInc:
5524       Direction = 1;
5525       break;
5526     case UO_PreDec:
5527     case UO_PostDec:
5528       Direction = -1;
5529       break;
5530     default:
5531       llvm_unreachable("unhandled unary increment operator");
5532     }
5533     Step = IntegerLiteral::Create(
5534         Ctx, llvm::APInt(Ctx.getIntWidth(LogicalTy), Direction), LogicalTy, {});
5535   } else if (auto *IncBin = dyn_cast<BinaryOperator>(Inc)) {
5536     if (IncBin->getOpcode() == BO_AddAssign) {
5537       Step = IncBin->getRHS();
5538     } else if (IncBin->getOpcode() == BO_SubAssign) {
5539       Step =
5540           AssertSuccess(BuildUnaryOp(nullptr, {}, UO_Minus, IncBin->getRHS()));
5541     } else
5542       llvm_unreachable("unhandled binary increment operator");
5543   } else if (auto *CondCXXOp = dyn_cast<CXXOperatorCallExpr>(Inc)) {
5544     switch (CondCXXOp->getOperator()) {
5545     case OO_PlusPlus:
5546       Step = IntegerLiteral::Create(
5547           Ctx, llvm::APInt(Ctx.getIntWidth(LogicalTy), 1), LogicalTy, {});
5548       break;
5549     case OO_MinusMinus:
5550       Step = IntegerLiteral::Create(
5551           Ctx, llvm::APInt(Ctx.getIntWidth(LogicalTy), -1), LogicalTy, {});
5552       break;
5553     case OO_PlusEqual:
5554       Step = CondCXXOp->getArg(1);
5555       break;
5556     case OO_MinusEqual:
5557       Step = AssertSuccess(
5558           BuildUnaryOp(nullptr, {}, UO_Minus, CondCXXOp->getArg(1)));
5559       break;
5560     default:
5561       llvm_unreachable("unhandled overloaded increment operator");
5562     }
5563   } else
5564     llvm_unreachable("unknown increment expression");
5565 
5566   CapturedStmt *DistanceFunc =
5567       buildDistanceFunc(*this, LogicalTy, CondRel, LHS, RHS, Step);
5568   CapturedStmt *LoopVarFunc = buildLoopVarFunc(
5569       *this, LVTy, LogicalTy, CounterRef, Step, isa<CXXForRangeStmt>(AStmt));
5570   DeclRefExpr *LVRef = BuildDeclRefExpr(LUVDecl, LUVDecl->getType(), VK_LValue,
5571                                         {}, nullptr, nullptr, {}, nullptr);
5572   return OMPCanonicalLoop::create(getASTContext(), AStmt, DistanceFunc,
5573                                   LoopVarFunc, LVRef);
5574 }
5575 
5576 static ExprResult buildUserDefinedMapperRef(Sema &SemaRef, Scope *S,
5577                                             CXXScopeSpec &MapperIdScopeSpec,
5578                                             const DeclarationNameInfo &MapperId,
5579                                             QualType Type,
5580                                             Expr *UnresolvedMapper);
5581 
5582 /// Perform DFS through the structure/class data members trying to find
5583 /// member(s) with user-defined 'default' mapper and generate implicit map
5584 /// clauses for such members with the found 'default' mapper.
5585 static void
5586 processImplicitMapsWithDefaultMappers(Sema &S, DSAStackTy *Stack,
5587                                       SmallVectorImpl<OMPClause *> &Clauses) {
5588   // Check for the deault mapper for data members.
5589   if (S.getLangOpts().OpenMP < 50)
5590     return;
5591   SmallVector<OMPClause *, 4> ImplicitMaps;
5592   for (int Cnt = 0, EndCnt = Clauses.size(); Cnt < EndCnt; ++Cnt) {
5593     auto *C = dyn_cast<OMPMapClause>(Clauses[Cnt]);
5594     if (!C)
5595       continue;
5596     SmallVector<Expr *, 4> SubExprs;
5597     auto *MI = C->mapperlist_begin();
5598     for (auto I = C->varlist_begin(), End = C->varlist_end(); I != End;
5599          ++I, ++MI) {
5600       // Expression is mapped using mapper - skip it.
5601       if (*MI)
5602         continue;
5603       Expr *E = *I;
5604       // Expression is dependent - skip it, build the mapper when it gets
5605       // instantiated.
5606       if (E->isTypeDependent() || E->isValueDependent() ||
5607           E->containsUnexpandedParameterPack())
5608         continue;
5609       // Array section - need to check for the mapping of the array section
5610       // element.
5611       QualType CanonType = E->getType().getCanonicalType();
5612       if (CanonType->isSpecificBuiltinType(BuiltinType::OMPArraySection)) {
5613         const auto *OASE = cast<OMPArraySectionExpr>(E->IgnoreParenImpCasts());
5614         QualType BaseType =
5615             OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
5616         QualType ElemType;
5617         if (const auto *ATy = BaseType->getAsArrayTypeUnsafe())
5618           ElemType = ATy->getElementType();
5619         else
5620           ElemType = BaseType->getPointeeType();
5621         CanonType = ElemType;
5622       }
5623 
5624       // DFS over data members in structures/classes.
5625       SmallVector<std::pair<QualType, FieldDecl *>, 4> Types(
5626           1, {CanonType, nullptr});
5627       llvm::DenseMap<const Type *, Expr *> Visited;
5628       SmallVector<std::pair<FieldDecl *, unsigned>, 4> ParentChain(
5629           1, {nullptr, 1});
5630       while (!Types.empty()) {
5631         QualType BaseType;
5632         FieldDecl *CurFD;
5633         std::tie(BaseType, CurFD) = Types.pop_back_val();
5634         while (ParentChain.back().second == 0)
5635           ParentChain.pop_back();
5636         --ParentChain.back().second;
5637         if (BaseType.isNull())
5638           continue;
5639         // Only structs/classes are allowed to have mappers.
5640         const RecordDecl *RD = BaseType.getCanonicalType()->getAsRecordDecl();
5641         if (!RD)
5642           continue;
5643         auto It = Visited.find(BaseType.getTypePtr());
5644         if (It == Visited.end()) {
5645           // Try to find the associated user-defined mapper.
5646           CXXScopeSpec MapperIdScopeSpec;
5647           DeclarationNameInfo DefaultMapperId;
5648           DefaultMapperId.setName(S.Context.DeclarationNames.getIdentifier(
5649               &S.Context.Idents.get("default")));
5650           DefaultMapperId.setLoc(E->getExprLoc());
5651           ExprResult ER = buildUserDefinedMapperRef(
5652               S, Stack->getCurScope(), MapperIdScopeSpec, DefaultMapperId,
5653               BaseType, /*UnresolvedMapper=*/nullptr);
5654           if (ER.isInvalid())
5655             continue;
5656           It = Visited.try_emplace(BaseType.getTypePtr(), ER.get()).first;
5657         }
5658         // Found default mapper.
5659         if (It->second) {
5660           auto *OE = new (S.Context) OpaqueValueExpr(E->getExprLoc(), CanonType,
5661                                                      VK_LValue, OK_Ordinary, E);
5662           OE->setIsUnique(/*V=*/true);
5663           Expr *BaseExpr = OE;
5664           for (const auto &P : ParentChain) {
5665             if (P.first) {
5666               BaseExpr = S.BuildMemberExpr(
5667                   BaseExpr, /*IsArrow=*/false, E->getExprLoc(),
5668                   NestedNameSpecifierLoc(), SourceLocation(), P.first,
5669                   DeclAccessPair::make(P.first, P.first->getAccess()),
5670                   /*HadMultipleCandidates=*/false, DeclarationNameInfo(),
5671                   P.first->getType(), VK_LValue, OK_Ordinary);
5672               BaseExpr = S.DefaultLvalueConversion(BaseExpr).get();
5673             }
5674           }
5675           if (CurFD)
5676             BaseExpr = S.BuildMemberExpr(
5677                 BaseExpr, /*IsArrow=*/false, E->getExprLoc(),
5678                 NestedNameSpecifierLoc(), SourceLocation(), CurFD,
5679                 DeclAccessPair::make(CurFD, CurFD->getAccess()),
5680                 /*HadMultipleCandidates=*/false, DeclarationNameInfo(),
5681                 CurFD->getType(), VK_LValue, OK_Ordinary);
5682           SubExprs.push_back(BaseExpr);
5683           continue;
5684         }
5685         // Check for the "default" mapper for data memebers.
5686         bool FirstIter = true;
5687         for (FieldDecl *FD : RD->fields()) {
5688           if (!FD)
5689             continue;
5690           QualType FieldTy = FD->getType();
5691           if (FieldTy.isNull() ||
5692               !(FieldTy->isStructureOrClassType() || FieldTy->isUnionType()))
5693             continue;
5694           if (FirstIter) {
5695             FirstIter = false;
5696             ParentChain.emplace_back(CurFD, 1);
5697           } else {
5698             ++ParentChain.back().second;
5699           }
5700           Types.emplace_back(FieldTy, FD);
5701         }
5702       }
5703     }
5704     if (SubExprs.empty())
5705       continue;
5706     CXXScopeSpec MapperIdScopeSpec;
5707     DeclarationNameInfo MapperId;
5708     if (OMPClause *NewClause = S.ActOnOpenMPMapClause(
5709             C->getMapTypeModifiers(), C->getMapTypeModifiersLoc(),
5710             MapperIdScopeSpec, MapperId, C->getMapType(),
5711             /*IsMapTypeImplicit=*/true, SourceLocation(), SourceLocation(),
5712             SubExprs, OMPVarListLocTy()))
5713       Clauses.push_back(NewClause);
5714   }
5715 }
5716 
5717 StmtResult Sema::ActOnOpenMPExecutableDirective(
5718     OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
5719     OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
5720     Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
5721   StmtResult Res = StmtError();
5722   // First check CancelRegion which is then used in checkNestingOfRegions.
5723   if (checkCancelRegion(*this, Kind, CancelRegion, StartLoc) ||
5724       checkNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion,
5725                             StartLoc))
5726     return StmtError();
5727 
5728   llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit;
5729   VarsWithInheritedDSAType VarsWithInheritedDSA;
5730   bool ErrorFound = false;
5731   ClausesWithImplicit.append(Clauses.begin(), Clauses.end());
5732   if (AStmt && !CurContext->isDependentContext() && Kind != OMPD_atomic &&
5733       Kind != OMPD_critical && Kind != OMPD_section && Kind != OMPD_master &&
5734       Kind != OMPD_masked && !isOpenMPLoopTransformationDirective(Kind)) {
5735     assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5736 
5737     // Check default data sharing attributes for referenced variables.
5738     DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt));
5739     int ThisCaptureLevel = getOpenMPCaptureLevels(Kind);
5740     Stmt *S = AStmt;
5741     while (--ThisCaptureLevel >= 0)
5742       S = cast<CapturedStmt>(S)->getCapturedStmt();
5743     DSAChecker.Visit(S);
5744     if (!isOpenMPTargetDataManagementDirective(Kind) &&
5745         !isOpenMPTaskingDirective(Kind)) {
5746       // Visit subcaptures to generate implicit clauses for captured vars.
5747       auto *CS = cast<CapturedStmt>(AStmt);
5748       SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
5749       getOpenMPCaptureRegions(CaptureRegions, Kind);
5750       // Ignore outer tasking regions for target directives.
5751       if (CaptureRegions.size() > 1 && CaptureRegions.front() == OMPD_task)
5752         CS = cast<CapturedStmt>(CS->getCapturedStmt());
5753       DSAChecker.visitSubCaptures(CS);
5754     }
5755     if (DSAChecker.isErrorFound())
5756       return StmtError();
5757     // Generate list of implicitly defined firstprivate variables.
5758     VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA();
5759 
5760     SmallVector<Expr *, 4> ImplicitFirstprivates(
5761         DSAChecker.getImplicitFirstprivate().begin(),
5762         DSAChecker.getImplicitFirstprivate().end());
5763     const unsigned DefaultmapKindNum = OMPC_DEFAULTMAP_pointer + 1;
5764     SmallVector<Expr *, 4> ImplicitMaps[DefaultmapKindNum][OMPC_MAP_delete];
5765     SmallVector<OpenMPMapModifierKind, NumberOfOMPMapClauseModifiers>
5766         ImplicitMapModifiers[DefaultmapKindNum];
5767     SmallVector<SourceLocation, NumberOfOMPMapClauseModifiers>
5768         ImplicitMapModifiersLoc[DefaultmapKindNum];
5769     // Get the original location of present modifier from Defaultmap clause.
5770     SourceLocation PresentModifierLocs[DefaultmapKindNum];
5771     for (OMPClause *C : Clauses) {
5772       if (auto *DMC = dyn_cast<OMPDefaultmapClause>(C))
5773         if (DMC->getDefaultmapModifier() == OMPC_DEFAULTMAP_MODIFIER_present)
5774           PresentModifierLocs[DMC->getDefaultmapKind()] =
5775               DMC->getDefaultmapModifierLoc();
5776     }
5777     for (unsigned VC = 0; VC < DefaultmapKindNum; ++VC) {
5778       auto Kind = static_cast<OpenMPDefaultmapClauseKind>(VC);
5779       for (unsigned I = 0; I < OMPC_MAP_delete; ++I) {
5780         ArrayRef<Expr *> ImplicitMap = DSAChecker.getImplicitMap(
5781             Kind, static_cast<OpenMPMapClauseKind>(I));
5782         ImplicitMaps[VC][I].append(ImplicitMap.begin(), ImplicitMap.end());
5783       }
5784       ArrayRef<OpenMPMapModifierKind> ImplicitModifier =
5785           DSAChecker.getImplicitMapModifier(Kind);
5786       ImplicitMapModifiers[VC].append(ImplicitModifier.begin(),
5787                                       ImplicitModifier.end());
5788       std::fill_n(std::back_inserter(ImplicitMapModifiersLoc[VC]),
5789                   ImplicitModifier.size(), PresentModifierLocs[VC]);
5790     }
5791     // Mark taskgroup task_reduction descriptors as implicitly firstprivate.
5792     for (OMPClause *C : Clauses) {
5793       if (auto *IRC = dyn_cast<OMPInReductionClause>(C)) {
5794         for (Expr *E : IRC->taskgroup_descriptors())
5795           if (E)
5796             ImplicitFirstprivates.emplace_back(E);
5797       }
5798       // OpenMP 5.0, 2.10.1 task Construct
5799       // [detach clause]... The event-handle will be considered as if it was
5800       // specified on a firstprivate clause.
5801       if (auto *DC = dyn_cast<OMPDetachClause>(C))
5802         ImplicitFirstprivates.push_back(DC->getEventHandler());
5803     }
5804     if (!ImplicitFirstprivates.empty()) {
5805       if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause(
5806               ImplicitFirstprivates, SourceLocation(), SourceLocation(),
5807               SourceLocation())) {
5808         ClausesWithImplicit.push_back(Implicit);
5809         ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() !=
5810                      ImplicitFirstprivates.size();
5811       } else {
5812         ErrorFound = true;
5813       }
5814     }
5815     // OpenMP 5.0 [2.19.7]
5816     // If a list item appears in a reduction, lastprivate or linear
5817     // clause on a combined target construct then it is treated as
5818     // if it also appears in a map clause with a map-type of tofrom
5819     if (getLangOpts().OpenMP >= 50 && Kind != OMPD_target &&
5820         isOpenMPTargetExecutionDirective(Kind)) {
5821       SmallVector<Expr *, 4> ImplicitExprs;
5822       for (OMPClause *C : Clauses) {
5823         if (auto *RC = dyn_cast<OMPReductionClause>(C))
5824           for (Expr *E : RC->varlists())
5825             if (!isa<DeclRefExpr>(E->IgnoreParenImpCasts()))
5826               ImplicitExprs.emplace_back(E);
5827       }
5828       if (!ImplicitExprs.empty()) {
5829         ArrayRef<Expr *> Exprs = ImplicitExprs;
5830         CXXScopeSpec MapperIdScopeSpec;
5831         DeclarationNameInfo MapperId;
5832         if (OMPClause *Implicit = ActOnOpenMPMapClause(
5833                 OMPC_MAP_MODIFIER_unknown, SourceLocation(), MapperIdScopeSpec,
5834                 MapperId, OMPC_MAP_tofrom,
5835                 /*IsMapTypeImplicit=*/true, SourceLocation(), SourceLocation(),
5836                 Exprs, OMPVarListLocTy(), /*NoDiagnose=*/true))
5837           ClausesWithImplicit.emplace_back(Implicit);
5838       }
5839     }
5840     for (unsigned I = 0, E = DefaultmapKindNum; I < E; ++I) {
5841       int ClauseKindCnt = -1;
5842       for (ArrayRef<Expr *> ImplicitMap : ImplicitMaps[I]) {
5843         ++ClauseKindCnt;
5844         if (ImplicitMap.empty())
5845           continue;
5846         CXXScopeSpec MapperIdScopeSpec;
5847         DeclarationNameInfo MapperId;
5848         auto Kind = static_cast<OpenMPMapClauseKind>(ClauseKindCnt);
5849         if (OMPClause *Implicit = ActOnOpenMPMapClause(
5850                 ImplicitMapModifiers[I], ImplicitMapModifiersLoc[I],
5851                 MapperIdScopeSpec, MapperId, Kind, /*IsMapTypeImplicit=*/true,
5852                 SourceLocation(), SourceLocation(), ImplicitMap,
5853                 OMPVarListLocTy())) {
5854           ClausesWithImplicit.emplace_back(Implicit);
5855           ErrorFound |= cast<OMPMapClause>(Implicit)->varlist_size() !=
5856                         ImplicitMap.size();
5857         } else {
5858           ErrorFound = true;
5859         }
5860       }
5861     }
5862     // Build expressions for implicit maps of data members with 'default'
5863     // mappers.
5864     if (LangOpts.OpenMP >= 50)
5865       processImplicitMapsWithDefaultMappers(*this, DSAStack,
5866                                             ClausesWithImplicit);
5867   }
5868 
5869   llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers;
5870   switch (Kind) {
5871   case OMPD_parallel:
5872     Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc,
5873                                        EndLoc);
5874     AllowedNameModifiers.push_back(OMPD_parallel);
5875     break;
5876   case OMPD_simd:
5877     Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
5878                                    VarsWithInheritedDSA);
5879     if (LangOpts.OpenMP >= 50)
5880       AllowedNameModifiers.push_back(OMPD_simd);
5881     break;
5882   case OMPD_tile:
5883     Res =
5884         ActOnOpenMPTileDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
5885     break;
5886   case OMPD_unroll:
5887     Res = ActOnOpenMPUnrollDirective(ClausesWithImplicit, AStmt, StartLoc,
5888                                      EndLoc);
5889     break;
5890   case OMPD_for:
5891     Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
5892                                   VarsWithInheritedDSA);
5893     break;
5894   case OMPD_for_simd:
5895     Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
5896                                       EndLoc, VarsWithInheritedDSA);
5897     if (LangOpts.OpenMP >= 50)
5898       AllowedNameModifiers.push_back(OMPD_simd);
5899     break;
5900   case OMPD_sections:
5901     Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc,
5902                                        EndLoc);
5903     break;
5904   case OMPD_section:
5905     assert(ClausesWithImplicit.empty() &&
5906            "No clauses are allowed for 'omp section' directive");
5907     Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc);
5908     break;
5909   case OMPD_single:
5910     Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc,
5911                                      EndLoc);
5912     break;
5913   case OMPD_master:
5914     assert(ClausesWithImplicit.empty() &&
5915            "No clauses are allowed for 'omp master' directive");
5916     Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc);
5917     break;
5918   case OMPD_masked:
5919     Res = ActOnOpenMPMaskedDirective(ClausesWithImplicit, AStmt, StartLoc,
5920                                      EndLoc);
5921     break;
5922   case OMPD_critical:
5923     Res = ActOnOpenMPCriticalDirective(DirName, ClausesWithImplicit, AStmt,
5924                                        StartLoc, EndLoc);
5925     break;
5926   case OMPD_parallel_for:
5927     Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc,
5928                                           EndLoc, VarsWithInheritedDSA);
5929     AllowedNameModifiers.push_back(OMPD_parallel);
5930     break;
5931   case OMPD_parallel_for_simd:
5932     Res = ActOnOpenMPParallelForSimdDirective(
5933         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
5934     AllowedNameModifiers.push_back(OMPD_parallel);
5935     if (LangOpts.OpenMP >= 50)
5936       AllowedNameModifiers.push_back(OMPD_simd);
5937     break;
5938   case OMPD_parallel_master:
5939     Res = ActOnOpenMPParallelMasterDirective(ClausesWithImplicit, AStmt,
5940                                                StartLoc, EndLoc);
5941     AllowedNameModifiers.push_back(OMPD_parallel);
5942     break;
5943   case OMPD_parallel_sections:
5944     Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt,
5945                                                StartLoc, EndLoc);
5946     AllowedNameModifiers.push_back(OMPD_parallel);
5947     break;
5948   case OMPD_task:
5949     Res =
5950         ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
5951     AllowedNameModifiers.push_back(OMPD_task);
5952     break;
5953   case OMPD_taskyield:
5954     assert(ClausesWithImplicit.empty() &&
5955            "No clauses are allowed for 'omp taskyield' directive");
5956     assert(AStmt == nullptr &&
5957            "No associated statement allowed for 'omp taskyield' directive");
5958     Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc);
5959     break;
5960   case OMPD_barrier:
5961     assert(ClausesWithImplicit.empty() &&
5962            "No clauses are allowed for 'omp barrier' directive");
5963     assert(AStmt == nullptr &&
5964            "No associated statement allowed for 'omp barrier' directive");
5965     Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc);
5966     break;
5967   case OMPD_taskwait:
5968     assert(ClausesWithImplicit.empty() &&
5969            "No clauses are allowed for 'omp taskwait' directive");
5970     assert(AStmt == nullptr &&
5971            "No associated statement allowed for 'omp taskwait' directive");
5972     Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc);
5973     break;
5974   case OMPD_taskgroup:
5975     Res = ActOnOpenMPTaskgroupDirective(ClausesWithImplicit, AStmt, StartLoc,
5976                                         EndLoc);
5977     break;
5978   case OMPD_flush:
5979     assert(AStmt == nullptr &&
5980            "No associated statement allowed for 'omp flush' directive");
5981     Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc);
5982     break;
5983   case OMPD_depobj:
5984     assert(AStmt == nullptr &&
5985            "No associated statement allowed for 'omp depobj' directive");
5986     Res = ActOnOpenMPDepobjDirective(ClausesWithImplicit, StartLoc, EndLoc);
5987     break;
5988   case OMPD_scan:
5989     assert(AStmt == nullptr &&
5990            "No associated statement allowed for 'omp scan' directive");
5991     Res = ActOnOpenMPScanDirective(ClausesWithImplicit, StartLoc, EndLoc);
5992     break;
5993   case OMPD_ordered:
5994     Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc,
5995                                       EndLoc);
5996     break;
5997   case OMPD_atomic:
5998     Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc,
5999                                      EndLoc);
6000     break;
6001   case OMPD_teams:
6002     Res =
6003         ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
6004     break;
6005   case OMPD_target:
6006     Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc,
6007                                      EndLoc);
6008     AllowedNameModifiers.push_back(OMPD_target);
6009     break;
6010   case OMPD_target_parallel:
6011     Res = ActOnOpenMPTargetParallelDirective(ClausesWithImplicit, AStmt,
6012                                              StartLoc, EndLoc);
6013     AllowedNameModifiers.push_back(OMPD_target);
6014     AllowedNameModifiers.push_back(OMPD_parallel);
6015     break;
6016   case OMPD_target_parallel_for:
6017     Res = ActOnOpenMPTargetParallelForDirective(
6018         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6019     AllowedNameModifiers.push_back(OMPD_target);
6020     AllowedNameModifiers.push_back(OMPD_parallel);
6021     break;
6022   case OMPD_cancellation_point:
6023     assert(ClausesWithImplicit.empty() &&
6024            "No clauses are allowed for 'omp cancellation point' directive");
6025     assert(AStmt == nullptr && "No associated statement allowed for 'omp "
6026                                "cancellation point' directive");
6027     Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion);
6028     break;
6029   case OMPD_cancel:
6030     assert(AStmt == nullptr &&
6031            "No associated statement allowed for 'omp cancel' directive");
6032     Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc,
6033                                      CancelRegion);
6034     AllowedNameModifiers.push_back(OMPD_cancel);
6035     break;
6036   case OMPD_target_data:
6037     Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc,
6038                                          EndLoc);
6039     AllowedNameModifiers.push_back(OMPD_target_data);
6040     break;
6041   case OMPD_target_enter_data:
6042     Res = ActOnOpenMPTargetEnterDataDirective(ClausesWithImplicit, StartLoc,
6043                                               EndLoc, AStmt);
6044     AllowedNameModifiers.push_back(OMPD_target_enter_data);
6045     break;
6046   case OMPD_target_exit_data:
6047     Res = ActOnOpenMPTargetExitDataDirective(ClausesWithImplicit, StartLoc,
6048                                              EndLoc, AStmt);
6049     AllowedNameModifiers.push_back(OMPD_target_exit_data);
6050     break;
6051   case OMPD_taskloop:
6052     Res = ActOnOpenMPTaskLoopDirective(ClausesWithImplicit, AStmt, StartLoc,
6053                                        EndLoc, VarsWithInheritedDSA);
6054     AllowedNameModifiers.push_back(OMPD_taskloop);
6055     break;
6056   case OMPD_taskloop_simd:
6057     Res = ActOnOpenMPTaskLoopSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
6058                                            EndLoc, VarsWithInheritedDSA);
6059     AllowedNameModifiers.push_back(OMPD_taskloop);
6060     if (LangOpts.OpenMP >= 50)
6061       AllowedNameModifiers.push_back(OMPD_simd);
6062     break;
6063   case OMPD_master_taskloop:
6064     Res = ActOnOpenMPMasterTaskLoopDirective(
6065         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6066     AllowedNameModifiers.push_back(OMPD_taskloop);
6067     break;
6068   case OMPD_master_taskloop_simd:
6069     Res = ActOnOpenMPMasterTaskLoopSimdDirective(
6070         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6071     AllowedNameModifiers.push_back(OMPD_taskloop);
6072     if (LangOpts.OpenMP >= 50)
6073       AllowedNameModifiers.push_back(OMPD_simd);
6074     break;
6075   case OMPD_parallel_master_taskloop:
6076     Res = ActOnOpenMPParallelMasterTaskLoopDirective(
6077         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6078     AllowedNameModifiers.push_back(OMPD_taskloop);
6079     AllowedNameModifiers.push_back(OMPD_parallel);
6080     break;
6081   case OMPD_parallel_master_taskloop_simd:
6082     Res = ActOnOpenMPParallelMasterTaskLoopSimdDirective(
6083         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6084     AllowedNameModifiers.push_back(OMPD_taskloop);
6085     AllowedNameModifiers.push_back(OMPD_parallel);
6086     if (LangOpts.OpenMP >= 50)
6087       AllowedNameModifiers.push_back(OMPD_simd);
6088     break;
6089   case OMPD_distribute:
6090     Res = ActOnOpenMPDistributeDirective(ClausesWithImplicit, AStmt, StartLoc,
6091                                          EndLoc, VarsWithInheritedDSA);
6092     break;
6093   case OMPD_target_update:
6094     Res = ActOnOpenMPTargetUpdateDirective(ClausesWithImplicit, StartLoc,
6095                                            EndLoc, AStmt);
6096     AllowedNameModifiers.push_back(OMPD_target_update);
6097     break;
6098   case OMPD_distribute_parallel_for:
6099     Res = ActOnOpenMPDistributeParallelForDirective(
6100         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6101     AllowedNameModifiers.push_back(OMPD_parallel);
6102     break;
6103   case OMPD_distribute_parallel_for_simd:
6104     Res = ActOnOpenMPDistributeParallelForSimdDirective(
6105         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6106     AllowedNameModifiers.push_back(OMPD_parallel);
6107     if (LangOpts.OpenMP >= 50)
6108       AllowedNameModifiers.push_back(OMPD_simd);
6109     break;
6110   case OMPD_distribute_simd:
6111     Res = ActOnOpenMPDistributeSimdDirective(
6112         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6113     if (LangOpts.OpenMP >= 50)
6114       AllowedNameModifiers.push_back(OMPD_simd);
6115     break;
6116   case OMPD_target_parallel_for_simd:
6117     Res = ActOnOpenMPTargetParallelForSimdDirective(
6118         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6119     AllowedNameModifiers.push_back(OMPD_target);
6120     AllowedNameModifiers.push_back(OMPD_parallel);
6121     if (LangOpts.OpenMP >= 50)
6122       AllowedNameModifiers.push_back(OMPD_simd);
6123     break;
6124   case OMPD_target_simd:
6125     Res = ActOnOpenMPTargetSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
6126                                          EndLoc, VarsWithInheritedDSA);
6127     AllowedNameModifiers.push_back(OMPD_target);
6128     if (LangOpts.OpenMP >= 50)
6129       AllowedNameModifiers.push_back(OMPD_simd);
6130     break;
6131   case OMPD_teams_distribute:
6132     Res = ActOnOpenMPTeamsDistributeDirective(
6133         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6134     break;
6135   case OMPD_teams_distribute_simd:
6136     Res = ActOnOpenMPTeamsDistributeSimdDirective(
6137         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6138     if (LangOpts.OpenMP >= 50)
6139       AllowedNameModifiers.push_back(OMPD_simd);
6140     break;
6141   case OMPD_teams_distribute_parallel_for_simd:
6142     Res = ActOnOpenMPTeamsDistributeParallelForSimdDirective(
6143         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6144     AllowedNameModifiers.push_back(OMPD_parallel);
6145     if (LangOpts.OpenMP >= 50)
6146       AllowedNameModifiers.push_back(OMPD_simd);
6147     break;
6148   case OMPD_teams_distribute_parallel_for:
6149     Res = ActOnOpenMPTeamsDistributeParallelForDirective(
6150         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6151     AllowedNameModifiers.push_back(OMPD_parallel);
6152     break;
6153   case OMPD_target_teams:
6154     Res = ActOnOpenMPTargetTeamsDirective(ClausesWithImplicit, AStmt, StartLoc,
6155                                           EndLoc);
6156     AllowedNameModifiers.push_back(OMPD_target);
6157     break;
6158   case OMPD_target_teams_distribute:
6159     Res = ActOnOpenMPTargetTeamsDistributeDirective(
6160         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6161     AllowedNameModifiers.push_back(OMPD_target);
6162     break;
6163   case OMPD_target_teams_distribute_parallel_for:
6164     Res = ActOnOpenMPTargetTeamsDistributeParallelForDirective(
6165         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6166     AllowedNameModifiers.push_back(OMPD_target);
6167     AllowedNameModifiers.push_back(OMPD_parallel);
6168     break;
6169   case OMPD_target_teams_distribute_parallel_for_simd:
6170     Res = ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
6171         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6172     AllowedNameModifiers.push_back(OMPD_target);
6173     AllowedNameModifiers.push_back(OMPD_parallel);
6174     if (LangOpts.OpenMP >= 50)
6175       AllowedNameModifiers.push_back(OMPD_simd);
6176     break;
6177   case OMPD_target_teams_distribute_simd:
6178     Res = ActOnOpenMPTargetTeamsDistributeSimdDirective(
6179         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6180     AllowedNameModifiers.push_back(OMPD_target);
6181     if (LangOpts.OpenMP >= 50)
6182       AllowedNameModifiers.push_back(OMPD_simd);
6183     break;
6184   case OMPD_interop:
6185     assert(AStmt == nullptr &&
6186            "No associated statement allowed for 'omp interop' directive");
6187     Res = ActOnOpenMPInteropDirective(ClausesWithImplicit, StartLoc, EndLoc);
6188     break;
6189   case OMPD_dispatch:
6190     Res = ActOnOpenMPDispatchDirective(ClausesWithImplicit, AStmt, StartLoc,
6191                                        EndLoc);
6192     break;
6193   case OMPD_declare_target:
6194   case OMPD_end_declare_target:
6195   case OMPD_threadprivate:
6196   case OMPD_allocate:
6197   case OMPD_declare_reduction:
6198   case OMPD_declare_mapper:
6199   case OMPD_declare_simd:
6200   case OMPD_requires:
6201   case OMPD_declare_variant:
6202   case OMPD_begin_declare_variant:
6203   case OMPD_end_declare_variant:
6204     llvm_unreachable("OpenMP Directive is not allowed");
6205   case OMPD_unknown:
6206   default:
6207     llvm_unreachable("Unknown OpenMP directive");
6208   }
6209 
6210   ErrorFound = Res.isInvalid() || ErrorFound;
6211 
6212   // Check variables in the clauses if default(none) or
6213   // default(firstprivate) was specified.
6214   if (DSAStack->getDefaultDSA() == DSA_none ||
6215       DSAStack->getDefaultDSA() == DSA_firstprivate) {
6216     DSAAttrChecker DSAChecker(DSAStack, *this, nullptr);
6217     for (OMPClause *C : Clauses) {
6218       switch (C->getClauseKind()) {
6219       case OMPC_num_threads:
6220       case OMPC_dist_schedule:
6221         // Do not analyse if no parent teams directive.
6222         if (isOpenMPTeamsDirective(Kind))
6223           break;
6224         continue;
6225       case OMPC_if:
6226         if (isOpenMPTeamsDirective(Kind) &&
6227             cast<OMPIfClause>(C)->getNameModifier() != OMPD_target)
6228           break;
6229         if (isOpenMPParallelDirective(Kind) &&
6230             isOpenMPTaskLoopDirective(Kind) &&
6231             cast<OMPIfClause>(C)->getNameModifier() != OMPD_parallel)
6232           break;
6233         continue;
6234       case OMPC_schedule:
6235       case OMPC_detach:
6236         break;
6237       case OMPC_grainsize:
6238       case OMPC_num_tasks:
6239       case OMPC_final:
6240       case OMPC_priority:
6241       case OMPC_novariants:
6242       case OMPC_nocontext:
6243         // Do not analyze if no parent parallel directive.
6244         if (isOpenMPParallelDirective(Kind))
6245           break;
6246         continue;
6247       case OMPC_ordered:
6248       case OMPC_device:
6249       case OMPC_num_teams:
6250       case OMPC_thread_limit:
6251       case OMPC_hint:
6252       case OMPC_collapse:
6253       case OMPC_safelen:
6254       case OMPC_simdlen:
6255       case OMPC_sizes:
6256       case OMPC_default:
6257       case OMPC_proc_bind:
6258       case OMPC_private:
6259       case OMPC_firstprivate:
6260       case OMPC_lastprivate:
6261       case OMPC_shared:
6262       case OMPC_reduction:
6263       case OMPC_task_reduction:
6264       case OMPC_in_reduction:
6265       case OMPC_linear:
6266       case OMPC_aligned:
6267       case OMPC_copyin:
6268       case OMPC_copyprivate:
6269       case OMPC_nowait:
6270       case OMPC_untied:
6271       case OMPC_mergeable:
6272       case OMPC_allocate:
6273       case OMPC_read:
6274       case OMPC_write:
6275       case OMPC_update:
6276       case OMPC_capture:
6277       case OMPC_seq_cst:
6278       case OMPC_acq_rel:
6279       case OMPC_acquire:
6280       case OMPC_release:
6281       case OMPC_relaxed:
6282       case OMPC_depend:
6283       case OMPC_threads:
6284       case OMPC_simd:
6285       case OMPC_map:
6286       case OMPC_nogroup:
6287       case OMPC_defaultmap:
6288       case OMPC_to:
6289       case OMPC_from:
6290       case OMPC_use_device_ptr:
6291       case OMPC_use_device_addr:
6292       case OMPC_is_device_ptr:
6293       case OMPC_nontemporal:
6294       case OMPC_order:
6295       case OMPC_destroy:
6296       case OMPC_inclusive:
6297       case OMPC_exclusive:
6298       case OMPC_uses_allocators:
6299       case OMPC_affinity:
6300         continue;
6301       case OMPC_allocator:
6302       case OMPC_flush:
6303       case OMPC_depobj:
6304       case OMPC_threadprivate:
6305       case OMPC_uniform:
6306       case OMPC_unknown:
6307       case OMPC_unified_address:
6308       case OMPC_unified_shared_memory:
6309       case OMPC_reverse_offload:
6310       case OMPC_dynamic_allocators:
6311       case OMPC_atomic_default_mem_order:
6312       case OMPC_device_type:
6313       case OMPC_match:
6314       default:
6315         llvm_unreachable("Unexpected clause");
6316       }
6317       for (Stmt *CC : C->children()) {
6318         if (CC)
6319           DSAChecker.Visit(CC);
6320       }
6321     }
6322     for (const auto &P : DSAChecker.getVarsWithInheritedDSA())
6323       VarsWithInheritedDSA[P.getFirst()] = P.getSecond();
6324   }
6325   for (const auto &P : VarsWithInheritedDSA) {
6326     if (P.getFirst()->isImplicit() || isa<OMPCapturedExprDecl>(P.getFirst()))
6327       continue;
6328     ErrorFound = true;
6329     if (DSAStack->getDefaultDSA() == DSA_none ||
6330         DSAStack->getDefaultDSA() == DSA_firstprivate) {
6331       Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable)
6332           << P.first << P.second->getSourceRange();
6333       Diag(DSAStack->getDefaultDSALocation(), diag::note_omp_default_dsa_none);
6334     } else if (getLangOpts().OpenMP >= 50) {
6335       Diag(P.second->getExprLoc(),
6336            diag::err_omp_defaultmap_no_attr_for_variable)
6337           << P.first << P.second->getSourceRange();
6338       Diag(DSAStack->getDefaultDSALocation(),
6339            diag::note_omp_defaultmap_attr_none);
6340     }
6341   }
6342 
6343   if (!AllowedNameModifiers.empty())
6344     ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) ||
6345                  ErrorFound;
6346 
6347   if (ErrorFound)
6348     return StmtError();
6349 
6350   if (!CurContext->isDependentContext() &&
6351       isOpenMPTargetExecutionDirective(Kind) &&
6352       !(DSAStack->hasRequiresDeclWithClause<OMPUnifiedSharedMemoryClause>() ||
6353         DSAStack->hasRequiresDeclWithClause<OMPUnifiedAddressClause>() ||
6354         DSAStack->hasRequiresDeclWithClause<OMPReverseOffloadClause>() ||
6355         DSAStack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>())) {
6356     // Register target to DSA Stack.
6357     DSAStack->addTargetDirLocation(StartLoc);
6358   }
6359 
6360   return Res;
6361 }
6362 
6363 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareSimdDirective(
6364     DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen,
6365     ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
6366     ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
6367     ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR) {
6368   assert(Aligneds.size() == Alignments.size());
6369   assert(Linears.size() == LinModifiers.size());
6370   assert(Linears.size() == Steps.size());
6371   if (!DG || DG.get().isNull())
6372     return DeclGroupPtrTy();
6373 
6374   const int SimdId = 0;
6375   if (!DG.get().isSingleDecl()) {
6376     Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd_variant)
6377         << SimdId;
6378     return DG;
6379   }
6380   Decl *ADecl = DG.get().getSingleDecl();
6381   if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
6382     ADecl = FTD->getTemplatedDecl();
6383 
6384   auto *FD = dyn_cast<FunctionDecl>(ADecl);
6385   if (!FD) {
6386     Diag(ADecl->getLocation(), diag::err_omp_function_expected) << SimdId;
6387     return DeclGroupPtrTy();
6388   }
6389 
6390   // OpenMP [2.8.2, declare simd construct, Description]
6391   // The parameter of the simdlen clause must be a constant positive integer
6392   // expression.
6393   ExprResult SL;
6394   if (Simdlen)
6395     SL = VerifyPositiveIntegerConstantInClause(Simdlen, OMPC_simdlen);
6396   // OpenMP [2.8.2, declare simd construct, Description]
6397   // The special this pointer can be used as if was one of the arguments to the
6398   // function in any of the linear, aligned, or uniform clauses.
6399   // The uniform clause declares one or more arguments to have an invariant
6400   // value for all concurrent invocations of the function in the execution of a
6401   // single SIMD loop.
6402   llvm::DenseMap<const Decl *, const Expr *> UniformedArgs;
6403   const Expr *UniformedLinearThis = nullptr;
6404   for (const Expr *E : Uniforms) {
6405     E = E->IgnoreParenImpCasts();
6406     if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
6407       if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
6408         if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
6409             FD->getParamDecl(PVD->getFunctionScopeIndex())
6410                     ->getCanonicalDecl() == PVD->getCanonicalDecl()) {
6411           UniformedArgs.try_emplace(PVD->getCanonicalDecl(), E);
6412           continue;
6413         }
6414     if (isa<CXXThisExpr>(E)) {
6415       UniformedLinearThis = E;
6416       continue;
6417     }
6418     Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
6419         << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
6420   }
6421   // OpenMP [2.8.2, declare simd construct, Description]
6422   // The aligned clause declares that the object to which each list item points
6423   // is aligned to the number of bytes expressed in the optional parameter of
6424   // the aligned clause.
6425   // The special this pointer can be used as if was one of the arguments to the
6426   // function in any of the linear, aligned, or uniform clauses.
6427   // The type of list items appearing in the aligned clause must be array,
6428   // pointer, reference to array, or reference to pointer.
6429   llvm::DenseMap<const Decl *, const Expr *> AlignedArgs;
6430   const Expr *AlignedThis = nullptr;
6431   for (const Expr *E : Aligneds) {
6432     E = E->IgnoreParenImpCasts();
6433     if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
6434       if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
6435         const VarDecl *CanonPVD = PVD->getCanonicalDecl();
6436         if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
6437             FD->getParamDecl(PVD->getFunctionScopeIndex())
6438                     ->getCanonicalDecl() == CanonPVD) {
6439           // OpenMP  [2.8.1, simd construct, Restrictions]
6440           // A list-item cannot appear in more than one aligned clause.
6441           if (AlignedArgs.count(CanonPVD) > 0) {
6442             Diag(E->getExprLoc(), diag::err_omp_used_in_clause_twice)
6443                 << 1 << getOpenMPClauseName(OMPC_aligned)
6444                 << E->getSourceRange();
6445             Diag(AlignedArgs[CanonPVD]->getExprLoc(),
6446                  diag::note_omp_explicit_dsa)
6447                 << getOpenMPClauseName(OMPC_aligned);
6448             continue;
6449           }
6450           AlignedArgs[CanonPVD] = E;
6451           QualType QTy = PVD->getType()
6452                              .getNonReferenceType()
6453                              .getUnqualifiedType()
6454                              .getCanonicalType();
6455           const Type *Ty = QTy.getTypePtrOrNull();
6456           if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
6457             Diag(E->getExprLoc(), diag::err_omp_aligned_expected_array_or_ptr)
6458                 << QTy << getLangOpts().CPlusPlus << E->getSourceRange();
6459             Diag(PVD->getLocation(), diag::note_previous_decl) << PVD;
6460           }
6461           continue;
6462         }
6463       }
6464     if (isa<CXXThisExpr>(E)) {
6465       if (AlignedThis) {
6466         Diag(E->getExprLoc(), diag::err_omp_used_in_clause_twice)
6467             << 2 << getOpenMPClauseName(OMPC_aligned) << E->getSourceRange();
6468         Diag(AlignedThis->getExprLoc(), diag::note_omp_explicit_dsa)
6469             << getOpenMPClauseName(OMPC_aligned);
6470       }
6471       AlignedThis = E;
6472       continue;
6473     }
6474     Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
6475         << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
6476   }
6477   // The optional parameter of the aligned clause, alignment, must be a constant
6478   // positive integer expression. If no optional parameter is specified,
6479   // implementation-defined default alignments for SIMD instructions on the
6480   // target platforms are assumed.
6481   SmallVector<const Expr *, 4> NewAligns;
6482   for (Expr *E : Alignments) {
6483     ExprResult Align;
6484     if (E)
6485       Align = VerifyPositiveIntegerConstantInClause(E, OMPC_aligned);
6486     NewAligns.push_back(Align.get());
6487   }
6488   // OpenMP [2.8.2, declare simd construct, Description]
6489   // The linear clause declares one or more list items to be private to a SIMD
6490   // lane and to have a linear relationship with respect to the iteration space
6491   // of a loop.
6492   // The special this pointer can be used as if was one of the arguments to the
6493   // function in any of the linear, aligned, or uniform clauses.
6494   // When a linear-step expression is specified in a linear clause it must be
6495   // either a constant integer expression or an integer-typed parameter that is
6496   // specified in a uniform clause on the directive.
6497   llvm::DenseMap<const Decl *, const Expr *> LinearArgs;
6498   const bool IsUniformedThis = UniformedLinearThis != nullptr;
6499   auto MI = LinModifiers.begin();
6500   for (const Expr *E : Linears) {
6501     auto LinKind = static_cast<OpenMPLinearClauseKind>(*MI);
6502     ++MI;
6503     E = E->IgnoreParenImpCasts();
6504     if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
6505       if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
6506         const VarDecl *CanonPVD = PVD->getCanonicalDecl();
6507         if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
6508             FD->getParamDecl(PVD->getFunctionScopeIndex())
6509                     ->getCanonicalDecl() == CanonPVD) {
6510           // OpenMP  [2.15.3.7, linear Clause, Restrictions]
6511           // A list-item cannot appear in more than one linear clause.
6512           if (LinearArgs.count(CanonPVD) > 0) {
6513             Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
6514                 << getOpenMPClauseName(OMPC_linear)
6515                 << getOpenMPClauseName(OMPC_linear) << E->getSourceRange();
6516             Diag(LinearArgs[CanonPVD]->getExprLoc(),
6517                  diag::note_omp_explicit_dsa)
6518                 << getOpenMPClauseName(OMPC_linear);
6519             continue;
6520           }
6521           // Each argument can appear in at most one uniform or linear clause.
6522           if (UniformedArgs.count(CanonPVD) > 0) {
6523             Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
6524                 << getOpenMPClauseName(OMPC_linear)
6525                 << getOpenMPClauseName(OMPC_uniform) << E->getSourceRange();
6526             Diag(UniformedArgs[CanonPVD]->getExprLoc(),
6527                  diag::note_omp_explicit_dsa)
6528                 << getOpenMPClauseName(OMPC_uniform);
6529             continue;
6530           }
6531           LinearArgs[CanonPVD] = E;
6532           if (E->isValueDependent() || E->isTypeDependent() ||
6533               E->isInstantiationDependent() ||
6534               E->containsUnexpandedParameterPack())
6535             continue;
6536           (void)CheckOpenMPLinearDecl(CanonPVD, E->getExprLoc(), LinKind,
6537                                       PVD->getOriginalType(),
6538                                       /*IsDeclareSimd=*/true);
6539           continue;
6540         }
6541       }
6542     if (isa<CXXThisExpr>(E)) {
6543       if (UniformedLinearThis) {
6544         Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
6545             << getOpenMPClauseName(OMPC_linear)
6546             << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform : OMPC_linear)
6547             << E->getSourceRange();
6548         Diag(UniformedLinearThis->getExprLoc(), diag::note_omp_explicit_dsa)
6549             << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform
6550                                                    : OMPC_linear);
6551         continue;
6552       }
6553       UniformedLinearThis = E;
6554       if (E->isValueDependent() || E->isTypeDependent() ||
6555           E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
6556         continue;
6557       (void)CheckOpenMPLinearDecl(/*D=*/nullptr, E->getExprLoc(), LinKind,
6558                                   E->getType(), /*IsDeclareSimd=*/true);
6559       continue;
6560     }
6561     Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
6562         << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
6563   }
6564   Expr *Step = nullptr;
6565   Expr *NewStep = nullptr;
6566   SmallVector<Expr *, 4> NewSteps;
6567   for (Expr *E : Steps) {
6568     // Skip the same step expression, it was checked already.
6569     if (Step == E || !E) {
6570       NewSteps.push_back(E ? NewStep : nullptr);
6571       continue;
6572     }
6573     Step = E;
6574     if (const auto *DRE = dyn_cast<DeclRefExpr>(Step))
6575       if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
6576         const VarDecl *CanonPVD = PVD->getCanonicalDecl();
6577         if (UniformedArgs.count(CanonPVD) == 0) {
6578           Diag(Step->getExprLoc(), diag::err_omp_expected_uniform_param)
6579               << Step->getSourceRange();
6580         } else if (E->isValueDependent() || E->isTypeDependent() ||
6581                    E->isInstantiationDependent() ||
6582                    E->containsUnexpandedParameterPack() ||
6583                    CanonPVD->getType()->hasIntegerRepresentation()) {
6584           NewSteps.push_back(Step);
6585         } else {
6586           Diag(Step->getExprLoc(), diag::err_omp_expected_int_param)
6587               << Step->getSourceRange();
6588         }
6589         continue;
6590       }
6591     NewStep = Step;
6592     if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
6593         !Step->isInstantiationDependent() &&
6594         !Step->containsUnexpandedParameterPack()) {
6595       NewStep = PerformOpenMPImplicitIntegerConversion(Step->getExprLoc(), Step)
6596                     .get();
6597       if (NewStep)
6598         NewStep =
6599             VerifyIntegerConstantExpression(NewStep, /*FIXME*/ AllowFold).get();
6600     }
6601     NewSteps.push_back(NewStep);
6602   }
6603   auto *NewAttr = OMPDeclareSimdDeclAttr::CreateImplicit(
6604       Context, BS, SL.get(), const_cast<Expr **>(Uniforms.data()),
6605       Uniforms.size(), const_cast<Expr **>(Aligneds.data()), Aligneds.size(),
6606       const_cast<Expr **>(NewAligns.data()), NewAligns.size(),
6607       const_cast<Expr **>(Linears.data()), Linears.size(),
6608       const_cast<unsigned *>(LinModifiers.data()), LinModifiers.size(),
6609       NewSteps.data(), NewSteps.size(), SR);
6610   ADecl->addAttr(NewAttr);
6611   return DG;
6612 }
6613 
6614 static void setPrototype(Sema &S, FunctionDecl *FD, FunctionDecl *FDWithProto,
6615                          QualType NewType) {
6616   assert(NewType->isFunctionProtoType() &&
6617          "Expected function type with prototype.");
6618   assert(FD->getType()->isFunctionNoProtoType() &&
6619          "Expected function with type with no prototype.");
6620   assert(FDWithProto->getType()->isFunctionProtoType() &&
6621          "Expected function with prototype.");
6622   // Synthesize parameters with the same types.
6623   FD->setType(NewType);
6624   SmallVector<ParmVarDecl *, 16> Params;
6625   for (const ParmVarDecl *P : FDWithProto->parameters()) {
6626     auto *Param = ParmVarDecl::Create(S.getASTContext(), FD, SourceLocation(),
6627                                       SourceLocation(), nullptr, P->getType(),
6628                                       /*TInfo=*/nullptr, SC_None, nullptr);
6629     Param->setScopeInfo(0, Params.size());
6630     Param->setImplicit();
6631     Params.push_back(Param);
6632   }
6633 
6634   FD->setParams(Params);
6635 }
6636 
6637 void Sema::ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(Decl *D) {
6638   if (D->isInvalidDecl())
6639     return;
6640   FunctionDecl *FD = nullptr;
6641   if (auto *UTemplDecl = dyn_cast<FunctionTemplateDecl>(D))
6642     FD = UTemplDecl->getTemplatedDecl();
6643   else
6644     FD = cast<FunctionDecl>(D);
6645   assert(FD && "Expected a function declaration!");
6646 
6647   // If we are intantiating templates we do *not* apply scoped assumptions but
6648   // only global ones. We apply scoped assumption to the template definition
6649   // though.
6650   if (!inTemplateInstantiation()) {
6651     for (AssumptionAttr *AA : OMPAssumeScoped)
6652       FD->addAttr(AA);
6653   }
6654   for (AssumptionAttr *AA : OMPAssumeGlobal)
6655     FD->addAttr(AA);
6656 }
6657 
6658 Sema::OMPDeclareVariantScope::OMPDeclareVariantScope(OMPTraitInfo &TI)
6659     : TI(&TI), NameSuffix(TI.getMangledName()) {}
6660 
6661 void Sema::ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(
6662     Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParamLists,
6663     SmallVectorImpl<FunctionDecl *> &Bases) {
6664   if (!D.getIdentifier())
6665     return;
6666 
6667   OMPDeclareVariantScope &DVScope = OMPDeclareVariantScopes.back();
6668 
6669   // Template specialization is an extension, check if we do it.
6670   bool IsTemplated = !TemplateParamLists.empty();
6671   if (IsTemplated &
6672       !DVScope.TI->isExtensionActive(
6673           llvm::omp::TraitProperty::implementation_extension_allow_templates))
6674     return;
6675 
6676   IdentifierInfo *BaseII = D.getIdentifier();
6677   LookupResult Lookup(*this, DeclarationName(BaseII), D.getIdentifierLoc(),
6678                       LookupOrdinaryName);
6679   LookupParsedName(Lookup, S, &D.getCXXScopeSpec());
6680 
6681   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
6682   QualType FType = TInfo->getType();
6683 
6684   bool IsConstexpr =
6685       D.getDeclSpec().getConstexprSpecifier() == ConstexprSpecKind::Constexpr;
6686   bool IsConsteval =
6687       D.getDeclSpec().getConstexprSpecifier() == ConstexprSpecKind::Consteval;
6688 
6689   for (auto *Candidate : Lookup) {
6690     auto *CandidateDecl = Candidate->getUnderlyingDecl();
6691     FunctionDecl *UDecl = nullptr;
6692     if (IsTemplated && isa<FunctionTemplateDecl>(CandidateDecl))
6693       UDecl = cast<FunctionTemplateDecl>(CandidateDecl)->getTemplatedDecl();
6694     else if (!IsTemplated)
6695       UDecl = dyn_cast<FunctionDecl>(CandidateDecl);
6696     if (!UDecl)
6697       continue;
6698 
6699     // Don't specialize constexpr/consteval functions with
6700     // non-constexpr/consteval functions.
6701     if (UDecl->isConstexpr() && !IsConstexpr)
6702       continue;
6703     if (UDecl->isConsteval() && !IsConsteval)
6704       continue;
6705 
6706     QualType UDeclTy = UDecl->getType();
6707     if (!UDeclTy->isDependentType()) {
6708       QualType NewType = Context.mergeFunctionTypes(
6709           FType, UDeclTy, /* OfBlockPointer */ false,
6710           /* Unqualified */ false, /* AllowCXX */ true);
6711       if (NewType.isNull())
6712         continue;
6713     }
6714 
6715     // Found a base!
6716     Bases.push_back(UDecl);
6717   }
6718 
6719   bool UseImplicitBase = !DVScope.TI->isExtensionActive(
6720       llvm::omp::TraitProperty::implementation_extension_disable_implicit_base);
6721   // If no base was found we create a declaration that we use as base.
6722   if (Bases.empty() && UseImplicitBase) {
6723     D.setFunctionDefinitionKind(FunctionDefinitionKind::Declaration);
6724     Decl *BaseD = HandleDeclarator(S, D, TemplateParamLists);
6725     BaseD->setImplicit(true);
6726     if (auto *BaseTemplD = dyn_cast<FunctionTemplateDecl>(BaseD))
6727       Bases.push_back(BaseTemplD->getTemplatedDecl());
6728     else
6729       Bases.push_back(cast<FunctionDecl>(BaseD));
6730   }
6731 
6732   std::string MangledName;
6733   MangledName += D.getIdentifier()->getName();
6734   MangledName += getOpenMPVariantManglingSeparatorStr();
6735   MangledName += DVScope.NameSuffix;
6736   IdentifierInfo &VariantII = Context.Idents.get(MangledName);
6737 
6738   VariantII.setMangledOpenMPVariantName(true);
6739   D.SetIdentifier(&VariantII, D.getBeginLoc());
6740 }
6741 
6742 void Sema::ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(
6743     Decl *D, SmallVectorImpl<FunctionDecl *> &Bases) {
6744   // Do not mark function as is used to prevent its emission if this is the
6745   // only place where it is used.
6746   EnterExpressionEvaluationContext Unevaluated(
6747       *this, Sema::ExpressionEvaluationContext::Unevaluated);
6748 
6749   FunctionDecl *FD = nullptr;
6750   if (auto *UTemplDecl = dyn_cast<FunctionTemplateDecl>(D))
6751     FD = UTemplDecl->getTemplatedDecl();
6752   else
6753     FD = cast<FunctionDecl>(D);
6754   auto *VariantFuncRef = DeclRefExpr::Create(
6755       Context, NestedNameSpecifierLoc(), SourceLocation(), FD,
6756       /* RefersToEnclosingVariableOrCapture */ false,
6757       /* NameLoc */ FD->getLocation(), FD->getType(),
6758       ExprValueKind::VK_PRValue);
6759 
6760   OMPDeclareVariantScope &DVScope = OMPDeclareVariantScopes.back();
6761   auto *OMPDeclareVariantA = OMPDeclareVariantAttr::CreateImplicit(
6762       Context, VariantFuncRef, DVScope.TI);
6763   for (FunctionDecl *BaseFD : Bases)
6764     BaseFD->addAttr(OMPDeclareVariantA);
6765 }
6766 
6767 ExprResult Sema::ActOnOpenMPCall(ExprResult Call, Scope *Scope,
6768                                  SourceLocation LParenLoc,
6769                                  MultiExprArg ArgExprs,
6770                                  SourceLocation RParenLoc, Expr *ExecConfig) {
6771   // The common case is a regular call we do not want to specialize at all. Try
6772   // to make that case fast by bailing early.
6773   CallExpr *CE = dyn_cast<CallExpr>(Call.get());
6774   if (!CE)
6775     return Call;
6776 
6777   FunctionDecl *CalleeFnDecl = CE->getDirectCallee();
6778   if (!CalleeFnDecl)
6779     return Call;
6780 
6781   if (!CalleeFnDecl->hasAttr<OMPDeclareVariantAttr>())
6782     return Call;
6783 
6784   ASTContext &Context = getASTContext();
6785   std::function<void(StringRef)> DiagUnknownTrait = [this,
6786                                                      CE](StringRef ISATrait) {
6787     // TODO Track the selector locations in a way that is accessible here to
6788     // improve the diagnostic location.
6789     Diag(CE->getBeginLoc(), diag::warn_unknown_declare_variant_isa_trait)
6790         << ISATrait;
6791   };
6792   TargetOMPContext OMPCtx(Context, std::move(DiagUnknownTrait),
6793                           getCurFunctionDecl());
6794 
6795   QualType CalleeFnType = CalleeFnDecl->getType();
6796 
6797   SmallVector<Expr *, 4> Exprs;
6798   SmallVector<VariantMatchInfo, 4> VMIs;
6799   while (CalleeFnDecl) {
6800     for (OMPDeclareVariantAttr *A :
6801          CalleeFnDecl->specific_attrs<OMPDeclareVariantAttr>()) {
6802       Expr *VariantRef = A->getVariantFuncRef();
6803 
6804       VariantMatchInfo VMI;
6805       OMPTraitInfo &TI = A->getTraitInfo();
6806       TI.getAsVariantMatchInfo(Context, VMI);
6807       if (!isVariantApplicableInContext(VMI, OMPCtx,
6808                                         /* DeviceSetOnly */ false))
6809         continue;
6810 
6811       VMIs.push_back(VMI);
6812       Exprs.push_back(VariantRef);
6813     }
6814 
6815     CalleeFnDecl = CalleeFnDecl->getPreviousDecl();
6816   }
6817 
6818   ExprResult NewCall;
6819   do {
6820     int BestIdx = getBestVariantMatchForContext(VMIs, OMPCtx);
6821     if (BestIdx < 0)
6822       return Call;
6823     Expr *BestExpr = cast<DeclRefExpr>(Exprs[BestIdx]);
6824     Decl *BestDecl = cast<DeclRefExpr>(BestExpr)->getDecl();
6825 
6826     {
6827       // Try to build a (member) call expression for the current best applicable
6828       // variant expression. We allow this to fail in which case we continue
6829       // with the next best variant expression. The fail case is part of the
6830       // implementation defined behavior in the OpenMP standard when it talks
6831       // about what differences in the function prototypes: "Any differences
6832       // that the specific OpenMP context requires in the prototype of the
6833       // variant from the base function prototype are implementation defined."
6834       // This wording is there to allow the specialized variant to have a
6835       // different type than the base function. This is intended and OK but if
6836       // we cannot create a call the difference is not in the "implementation
6837       // defined range" we allow.
6838       Sema::TentativeAnalysisScope Trap(*this);
6839 
6840       if (auto *SpecializedMethod = dyn_cast<CXXMethodDecl>(BestDecl)) {
6841         auto *MemberCall = dyn_cast<CXXMemberCallExpr>(CE);
6842         BestExpr = MemberExpr::CreateImplicit(
6843             Context, MemberCall->getImplicitObjectArgument(),
6844             /* IsArrow */ false, SpecializedMethod, Context.BoundMemberTy,
6845             MemberCall->getValueKind(), MemberCall->getObjectKind());
6846       }
6847       NewCall = BuildCallExpr(Scope, BestExpr, LParenLoc, ArgExprs, RParenLoc,
6848                               ExecConfig);
6849       if (NewCall.isUsable()) {
6850         if (CallExpr *NCE = dyn_cast<CallExpr>(NewCall.get())) {
6851           FunctionDecl *NewCalleeFnDecl = NCE->getDirectCallee();
6852           QualType NewType = Context.mergeFunctionTypes(
6853               CalleeFnType, NewCalleeFnDecl->getType(),
6854               /* OfBlockPointer */ false,
6855               /* Unqualified */ false, /* AllowCXX */ true);
6856           if (!NewType.isNull())
6857             break;
6858           // Don't use the call if the function type was not compatible.
6859           NewCall = nullptr;
6860         }
6861       }
6862     }
6863 
6864     VMIs.erase(VMIs.begin() + BestIdx);
6865     Exprs.erase(Exprs.begin() + BestIdx);
6866   } while (!VMIs.empty());
6867 
6868   if (!NewCall.isUsable())
6869     return Call;
6870   return PseudoObjectExpr::Create(Context, CE, {NewCall.get()}, 0);
6871 }
6872 
6873 Optional<std::pair<FunctionDecl *, Expr *>>
6874 Sema::checkOpenMPDeclareVariantFunction(Sema::DeclGroupPtrTy DG,
6875                                         Expr *VariantRef, OMPTraitInfo &TI,
6876                                         SourceRange SR) {
6877   if (!DG || DG.get().isNull())
6878     return None;
6879 
6880   const int VariantId = 1;
6881   // Must be applied only to single decl.
6882   if (!DG.get().isSingleDecl()) {
6883     Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd_variant)
6884         << VariantId << SR;
6885     return None;
6886   }
6887   Decl *ADecl = DG.get().getSingleDecl();
6888   if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
6889     ADecl = FTD->getTemplatedDecl();
6890 
6891   // Decl must be a function.
6892   auto *FD = dyn_cast<FunctionDecl>(ADecl);
6893   if (!FD) {
6894     Diag(ADecl->getLocation(), diag::err_omp_function_expected)
6895         << VariantId << SR;
6896     return None;
6897   }
6898 
6899   auto &&HasMultiVersionAttributes = [](const FunctionDecl *FD) {
6900     return FD->hasAttrs() &&
6901            (FD->hasAttr<CPUDispatchAttr>() || FD->hasAttr<CPUSpecificAttr>() ||
6902             FD->hasAttr<TargetAttr>());
6903   };
6904   // OpenMP is not compatible with CPU-specific attributes.
6905   if (HasMultiVersionAttributes(FD)) {
6906     Diag(FD->getLocation(), diag::err_omp_declare_variant_incompat_attributes)
6907         << SR;
6908     return None;
6909   }
6910 
6911   // Allow #pragma omp declare variant only if the function is not used.
6912   if (FD->isUsed(false))
6913     Diag(SR.getBegin(), diag::warn_omp_declare_variant_after_used)
6914         << FD->getLocation();
6915 
6916   // Check if the function was emitted already.
6917   const FunctionDecl *Definition;
6918   if (!FD->isThisDeclarationADefinition() && FD->isDefined(Definition) &&
6919       (LangOpts.EmitAllDecls || Context.DeclMustBeEmitted(Definition)))
6920     Diag(SR.getBegin(), diag::warn_omp_declare_variant_after_emitted)
6921         << FD->getLocation();
6922 
6923   // The VariantRef must point to function.
6924   if (!VariantRef) {
6925     Diag(SR.getBegin(), diag::err_omp_function_expected) << VariantId;
6926     return None;
6927   }
6928 
6929   auto ShouldDelayChecks = [](Expr *&E, bool) {
6930     return E && (E->isTypeDependent() || E->isValueDependent() ||
6931                  E->containsUnexpandedParameterPack() ||
6932                  E->isInstantiationDependent());
6933   };
6934   // Do not check templates, wait until instantiation.
6935   if (FD->isDependentContext() || ShouldDelayChecks(VariantRef, false) ||
6936       TI.anyScoreOrCondition(ShouldDelayChecks))
6937     return std::make_pair(FD, VariantRef);
6938 
6939   // Deal with non-constant score and user condition expressions.
6940   auto HandleNonConstantScoresAndConditions = [this](Expr *&E,
6941                                                      bool IsScore) -> bool {
6942     if (!E || E->isIntegerConstantExpr(Context))
6943       return false;
6944 
6945     if (IsScore) {
6946       // We warn on non-constant scores and pretend they were not present.
6947       Diag(E->getExprLoc(), diag::warn_omp_declare_variant_score_not_constant)
6948           << E;
6949       E = nullptr;
6950     } else {
6951       // We could replace a non-constant user condition with "false" but we
6952       // will soon need to handle these anyway for the dynamic version of
6953       // OpenMP context selectors.
6954       Diag(E->getExprLoc(),
6955            diag::err_omp_declare_variant_user_condition_not_constant)
6956           << E;
6957     }
6958     return true;
6959   };
6960   if (TI.anyScoreOrCondition(HandleNonConstantScoresAndConditions))
6961     return None;
6962 
6963   // Convert VariantRef expression to the type of the original function to
6964   // resolve possible conflicts.
6965   ExprResult VariantRefCast = VariantRef;
6966   if (LangOpts.CPlusPlus) {
6967     QualType FnPtrType;
6968     auto *Method = dyn_cast<CXXMethodDecl>(FD);
6969     if (Method && !Method->isStatic()) {
6970       const Type *ClassType =
6971           Context.getTypeDeclType(Method->getParent()).getTypePtr();
6972       FnPtrType = Context.getMemberPointerType(FD->getType(), ClassType);
6973       ExprResult ER;
6974       {
6975         // Build adrr_of unary op to correctly handle type checks for member
6976         // functions.
6977         Sema::TentativeAnalysisScope Trap(*this);
6978         ER = CreateBuiltinUnaryOp(VariantRef->getBeginLoc(), UO_AddrOf,
6979                                   VariantRef);
6980       }
6981       if (!ER.isUsable()) {
6982         Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected)
6983             << VariantId << VariantRef->getSourceRange();
6984         return None;
6985       }
6986       VariantRef = ER.get();
6987     } else {
6988       FnPtrType = Context.getPointerType(FD->getType());
6989     }
6990     QualType VarianPtrType = Context.getPointerType(VariantRef->getType());
6991     if (VarianPtrType.getUnqualifiedType() != FnPtrType.getUnqualifiedType()) {
6992       ImplicitConversionSequence ICS = TryImplicitConversion(
6993           VariantRef, FnPtrType.getUnqualifiedType(),
6994           /*SuppressUserConversions=*/false, AllowedExplicit::None,
6995           /*InOverloadResolution=*/false,
6996           /*CStyle=*/false,
6997           /*AllowObjCWritebackConversion=*/false);
6998       if (ICS.isFailure()) {
6999         Diag(VariantRef->getExprLoc(),
7000              diag::err_omp_declare_variant_incompat_types)
7001             << VariantRef->getType()
7002             << ((Method && !Method->isStatic()) ? FnPtrType : FD->getType())
7003             << VariantRef->getSourceRange();
7004         return None;
7005       }
7006       VariantRefCast = PerformImplicitConversion(
7007           VariantRef, FnPtrType.getUnqualifiedType(), AA_Converting);
7008       if (!VariantRefCast.isUsable())
7009         return None;
7010     }
7011     // Drop previously built artificial addr_of unary op for member functions.
7012     if (Method && !Method->isStatic()) {
7013       Expr *PossibleAddrOfVariantRef = VariantRefCast.get();
7014       if (auto *UO = dyn_cast<UnaryOperator>(
7015               PossibleAddrOfVariantRef->IgnoreImplicit()))
7016         VariantRefCast = UO->getSubExpr();
7017     }
7018   }
7019 
7020   ExprResult ER = CheckPlaceholderExpr(VariantRefCast.get());
7021   if (!ER.isUsable() ||
7022       !ER.get()->IgnoreParenImpCasts()->getType()->isFunctionType()) {
7023     Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected)
7024         << VariantId << VariantRef->getSourceRange();
7025     return None;
7026   }
7027 
7028   // The VariantRef must point to function.
7029   auto *DRE = dyn_cast<DeclRefExpr>(ER.get()->IgnoreParenImpCasts());
7030   if (!DRE) {
7031     Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected)
7032         << VariantId << VariantRef->getSourceRange();
7033     return None;
7034   }
7035   auto *NewFD = dyn_cast_or_null<FunctionDecl>(DRE->getDecl());
7036   if (!NewFD) {
7037     Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected)
7038         << VariantId << VariantRef->getSourceRange();
7039     return None;
7040   }
7041 
7042   // Check if function types are compatible in C.
7043   if (!LangOpts.CPlusPlus) {
7044     QualType NewType =
7045         Context.mergeFunctionTypes(FD->getType(), NewFD->getType());
7046     if (NewType.isNull()) {
7047       Diag(VariantRef->getExprLoc(),
7048            diag::err_omp_declare_variant_incompat_types)
7049           << NewFD->getType() << FD->getType() << VariantRef->getSourceRange();
7050       return None;
7051     }
7052     if (NewType->isFunctionProtoType()) {
7053       if (FD->getType()->isFunctionNoProtoType())
7054         setPrototype(*this, FD, NewFD, NewType);
7055       else if (NewFD->getType()->isFunctionNoProtoType())
7056         setPrototype(*this, NewFD, FD, NewType);
7057     }
7058   }
7059 
7060   // Check if variant function is not marked with declare variant directive.
7061   if (NewFD->hasAttrs() && NewFD->hasAttr<OMPDeclareVariantAttr>()) {
7062     Diag(VariantRef->getExprLoc(),
7063          diag::warn_omp_declare_variant_marked_as_declare_variant)
7064         << VariantRef->getSourceRange();
7065     SourceRange SR =
7066         NewFD->specific_attr_begin<OMPDeclareVariantAttr>()->getRange();
7067     Diag(SR.getBegin(), diag::note_omp_marked_declare_variant_here) << SR;
7068     return None;
7069   }
7070 
7071   enum DoesntSupport {
7072     VirtFuncs = 1,
7073     Constructors = 3,
7074     Destructors = 4,
7075     DeletedFuncs = 5,
7076     DefaultedFuncs = 6,
7077     ConstexprFuncs = 7,
7078     ConstevalFuncs = 8,
7079   };
7080   if (const auto *CXXFD = dyn_cast<CXXMethodDecl>(FD)) {
7081     if (CXXFD->isVirtual()) {
7082       Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
7083           << VirtFuncs;
7084       return None;
7085     }
7086 
7087     if (isa<CXXConstructorDecl>(FD)) {
7088       Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
7089           << Constructors;
7090       return None;
7091     }
7092 
7093     if (isa<CXXDestructorDecl>(FD)) {
7094       Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
7095           << Destructors;
7096       return None;
7097     }
7098   }
7099 
7100   if (FD->isDeleted()) {
7101     Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
7102         << DeletedFuncs;
7103     return None;
7104   }
7105 
7106   if (FD->isDefaulted()) {
7107     Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
7108         << DefaultedFuncs;
7109     return None;
7110   }
7111 
7112   if (FD->isConstexpr()) {
7113     Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
7114         << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
7115     return None;
7116   }
7117 
7118   // Check general compatibility.
7119   if (areMultiversionVariantFunctionsCompatible(
7120           FD, NewFD, PartialDiagnostic::NullDiagnostic(),
7121           PartialDiagnosticAt(SourceLocation(),
7122                               PartialDiagnostic::NullDiagnostic()),
7123           PartialDiagnosticAt(
7124               VariantRef->getExprLoc(),
7125               PDiag(diag::err_omp_declare_variant_doesnt_support)),
7126           PartialDiagnosticAt(VariantRef->getExprLoc(),
7127                               PDiag(diag::err_omp_declare_variant_diff)
7128                                   << FD->getLocation()),
7129           /*TemplatesSupported=*/true, /*ConstexprSupported=*/false,
7130           /*CLinkageMayDiffer=*/true))
7131     return None;
7132   return std::make_pair(FD, cast<Expr>(DRE));
7133 }
7134 
7135 void Sema::ActOnOpenMPDeclareVariantDirective(FunctionDecl *FD,
7136                                               Expr *VariantRef,
7137                                               OMPTraitInfo &TI,
7138                                               SourceRange SR) {
7139   auto *NewAttr =
7140       OMPDeclareVariantAttr::CreateImplicit(Context, VariantRef, &TI, SR);
7141   FD->addAttr(NewAttr);
7142 }
7143 
7144 StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
7145                                               Stmt *AStmt,
7146                                               SourceLocation StartLoc,
7147                                               SourceLocation EndLoc) {
7148   if (!AStmt)
7149     return StmtError();
7150 
7151   auto *CS = cast<CapturedStmt>(AStmt);
7152   // 1.2.2 OpenMP Language Terminology
7153   // Structured block - An executable statement with a single entry at the
7154   // top and a single exit at the bottom.
7155   // The point of exit cannot be a branch out of the structured block.
7156   // longjmp() and throw() must not violate the entry/exit criteria.
7157   CS->getCapturedDecl()->setNothrow();
7158 
7159   setFunctionHasBranchProtectedScope();
7160 
7161   return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
7162                                       DSAStack->getTaskgroupReductionRef(),
7163                                       DSAStack->isCancelRegion());
7164 }
7165 
7166 namespace {
7167 /// Iteration space of a single for loop.
7168 struct LoopIterationSpace final {
7169   /// True if the condition operator is the strict compare operator (<, > or
7170   /// !=).
7171   bool IsStrictCompare = false;
7172   /// Condition of the loop.
7173   Expr *PreCond = nullptr;
7174   /// This expression calculates the number of iterations in the loop.
7175   /// It is always possible to calculate it before starting the loop.
7176   Expr *NumIterations = nullptr;
7177   /// The loop counter variable.
7178   Expr *CounterVar = nullptr;
7179   /// Private loop counter variable.
7180   Expr *PrivateCounterVar = nullptr;
7181   /// This is initializer for the initial value of #CounterVar.
7182   Expr *CounterInit = nullptr;
7183   /// This is step for the #CounterVar used to generate its update:
7184   /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration.
7185   Expr *CounterStep = nullptr;
7186   /// Should step be subtracted?
7187   bool Subtract = false;
7188   /// Source range of the loop init.
7189   SourceRange InitSrcRange;
7190   /// Source range of the loop condition.
7191   SourceRange CondSrcRange;
7192   /// Source range of the loop increment.
7193   SourceRange IncSrcRange;
7194   /// Minimum value that can have the loop control variable. Used to support
7195   /// non-rectangular loops. Applied only for LCV with the non-iterator types,
7196   /// since only such variables can be used in non-loop invariant expressions.
7197   Expr *MinValue = nullptr;
7198   /// Maximum value that can have the loop control variable. Used to support
7199   /// non-rectangular loops. Applied only for LCV with the non-iterator type,
7200   /// since only such variables can be used in non-loop invariant expressions.
7201   Expr *MaxValue = nullptr;
7202   /// true, if the lower bound depends on the outer loop control var.
7203   bool IsNonRectangularLB = false;
7204   /// true, if the upper bound depends on the outer loop control var.
7205   bool IsNonRectangularUB = false;
7206   /// Index of the loop this loop depends on and forms non-rectangular loop
7207   /// nest.
7208   unsigned LoopDependentIdx = 0;
7209   /// Final condition for the non-rectangular loop nest support. It is used to
7210   /// check that the number of iterations for this particular counter must be
7211   /// finished.
7212   Expr *FinalCondition = nullptr;
7213 };
7214 
7215 /// Helper class for checking canonical form of the OpenMP loops and
7216 /// extracting iteration space of each loop in the loop nest, that will be used
7217 /// for IR generation.
7218 class OpenMPIterationSpaceChecker {
7219   /// Reference to Sema.
7220   Sema &SemaRef;
7221   /// Does the loop associated directive support non-rectangular loops?
7222   bool SupportsNonRectangular;
7223   /// Data-sharing stack.
7224   DSAStackTy &Stack;
7225   /// A location for diagnostics (when there is no some better location).
7226   SourceLocation DefaultLoc;
7227   /// A location for diagnostics (when increment is not compatible).
7228   SourceLocation ConditionLoc;
7229   /// A source location for referring to loop init later.
7230   SourceRange InitSrcRange;
7231   /// A source location for referring to condition later.
7232   SourceRange ConditionSrcRange;
7233   /// A source location for referring to increment later.
7234   SourceRange IncrementSrcRange;
7235   /// Loop variable.
7236   ValueDecl *LCDecl = nullptr;
7237   /// Reference to loop variable.
7238   Expr *LCRef = nullptr;
7239   /// Lower bound (initializer for the var).
7240   Expr *LB = nullptr;
7241   /// Upper bound.
7242   Expr *UB = nullptr;
7243   /// Loop step (increment).
7244   Expr *Step = nullptr;
7245   /// This flag is true when condition is one of:
7246   ///   Var <  UB
7247   ///   Var <= UB
7248   ///   UB  >  Var
7249   ///   UB  >= Var
7250   /// This will have no value when the condition is !=
7251   llvm::Optional<bool> TestIsLessOp;
7252   /// This flag is true when condition is strict ( < or > ).
7253   bool TestIsStrictOp = false;
7254   /// This flag is true when step is subtracted on each iteration.
7255   bool SubtractStep = false;
7256   /// The outer loop counter this loop depends on (if any).
7257   const ValueDecl *DepDecl = nullptr;
7258   /// Contains number of loop (starts from 1) on which loop counter init
7259   /// expression of this loop depends on.
7260   Optional<unsigned> InitDependOnLC;
7261   /// Contains number of loop (starts from 1) on which loop counter condition
7262   /// expression of this loop depends on.
7263   Optional<unsigned> CondDependOnLC;
7264   /// Checks if the provide statement depends on the loop counter.
7265   Optional<unsigned> doesDependOnLoopCounter(const Stmt *S, bool IsInitializer);
7266   /// Original condition required for checking of the exit condition for
7267   /// non-rectangular loop.
7268   Expr *Condition = nullptr;
7269 
7270 public:
7271   OpenMPIterationSpaceChecker(Sema &SemaRef, bool SupportsNonRectangular,
7272                               DSAStackTy &Stack, SourceLocation DefaultLoc)
7273       : SemaRef(SemaRef), SupportsNonRectangular(SupportsNonRectangular),
7274         Stack(Stack), DefaultLoc(DefaultLoc), ConditionLoc(DefaultLoc) {}
7275   /// Check init-expr for canonical loop form and save loop counter
7276   /// variable - #Var and its initialization value - #LB.
7277   bool checkAndSetInit(Stmt *S, bool EmitDiags = true);
7278   /// Check test-expr for canonical form, save upper-bound (#UB), flags
7279   /// for less/greater and for strict/non-strict comparison.
7280   bool checkAndSetCond(Expr *S);
7281   /// Check incr-expr for canonical loop form and return true if it
7282   /// does not conform, otherwise save loop step (#Step).
7283   bool checkAndSetInc(Expr *S);
7284   /// Return the loop counter variable.
7285   ValueDecl *getLoopDecl() const { return LCDecl; }
7286   /// Return the reference expression to loop counter variable.
7287   Expr *getLoopDeclRefExpr() const { return LCRef; }
7288   /// Source range of the loop init.
7289   SourceRange getInitSrcRange() const { return InitSrcRange; }
7290   /// Source range of the loop condition.
7291   SourceRange getConditionSrcRange() const { return ConditionSrcRange; }
7292   /// Source range of the loop increment.
7293   SourceRange getIncrementSrcRange() const { return IncrementSrcRange; }
7294   /// True if the step should be subtracted.
7295   bool shouldSubtractStep() const { return SubtractStep; }
7296   /// True, if the compare operator is strict (<, > or !=).
7297   bool isStrictTestOp() const { return TestIsStrictOp; }
7298   /// Build the expression to calculate the number of iterations.
7299   Expr *buildNumIterations(
7300       Scope *S, ArrayRef<LoopIterationSpace> ResultIterSpaces, bool LimitedType,
7301       llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
7302   /// Build the precondition expression for the loops.
7303   Expr *
7304   buildPreCond(Scope *S, Expr *Cond,
7305                llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
7306   /// Build reference expression to the counter be used for codegen.
7307   DeclRefExpr *
7308   buildCounterVar(llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
7309                   DSAStackTy &DSA) const;
7310   /// Build reference expression to the private counter be used for
7311   /// codegen.
7312   Expr *buildPrivateCounterVar() const;
7313   /// Build initialization of the counter be used for codegen.
7314   Expr *buildCounterInit() const;
7315   /// Build step of the counter be used for codegen.
7316   Expr *buildCounterStep() const;
7317   /// Build loop data with counter value for depend clauses in ordered
7318   /// directives.
7319   Expr *
7320   buildOrderedLoopData(Scope *S, Expr *Counter,
7321                        llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
7322                        SourceLocation Loc, Expr *Inc = nullptr,
7323                        OverloadedOperatorKind OOK = OO_Amp);
7324   /// Builds the minimum value for the loop counter.
7325   std::pair<Expr *, Expr *> buildMinMaxValues(
7326       Scope *S, llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
7327   /// Builds final condition for the non-rectangular loops.
7328   Expr *buildFinalCondition(Scope *S) const;
7329   /// Return true if any expression is dependent.
7330   bool dependent() const;
7331   /// Returns true if the initializer forms non-rectangular loop.
7332   bool doesInitDependOnLC() const { return InitDependOnLC.hasValue(); }
7333   /// Returns true if the condition forms non-rectangular loop.
7334   bool doesCondDependOnLC() const { return CondDependOnLC.hasValue(); }
7335   /// Returns index of the loop we depend on (starting from 1), or 0 otherwise.
7336   unsigned getLoopDependentIdx() const {
7337     return InitDependOnLC.getValueOr(CondDependOnLC.getValueOr(0));
7338   }
7339 
7340 private:
7341   /// Check the right-hand side of an assignment in the increment
7342   /// expression.
7343   bool checkAndSetIncRHS(Expr *RHS);
7344   /// Helper to set loop counter variable and its initializer.
7345   bool setLCDeclAndLB(ValueDecl *NewLCDecl, Expr *NewDeclRefExpr, Expr *NewLB,
7346                       bool EmitDiags);
7347   /// Helper to set upper bound.
7348   bool setUB(Expr *NewUB, llvm::Optional<bool> LessOp, bool StrictOp,
7349              SourceRange SR, SourceLocation SL);
7350   /// Helper to set loop increment.
7351   bool setStep(Expr *NewStep, bool Subtract);
7352 };
7353 
7354 bool OpenMPIterationSpaceChecker::dependent() const {
7355   if (!LCDecl) {
7356     assert(!LB && !UB && !Step);
7357     return false;
7358   }
7359   return LCDecl->getType()->isDependentType() ||
7360          (LB && LB->isValueDependent()) || (UB && UB->isValueDependent()) ||
7361          (Step && Step->isValueDependent());
7362 }
7363 
7364 bool OpenMPIterationSpaceChecker::setLCDeclAndLB(ValueDecl *NewLCDecl,
7365                                                  Expr *NewLCRefExpr,
7366                                                  Expr *NewLB, bool EmitDiags) {
7367   // State consistency checking to ensure correct usage.
7368   assert(LCDecl == nullptr && LB == nullptr && LCRef == nullptr &&
7369          UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
7370   if (!NewLCDecl || !NewLB || NewLB->containsErrors())
7371     return true;
7372   LCDecl = getCanonicalDecl(NewLCDecl);
7373   LCRef = NewLCRefExpr;
7374   if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB))
7375     if (const CXXConstructorDecl *Ctor = CE->getConstructor())
7376       if ((Ctor->isCopyOrMoveConstructor() ||
7377            Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
7378           CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
7379         NewLB = CE->getArg(0)->IgnoreParenImpCasts();
7380   LB = NewLB;
7381   if (EmitDiags)
7382     InitDependOnLC = doesDependOnLoopCounter(LB, /*IsInitializer=*/true);
7383   return false;
7384 }
7385 
7386 bool OpenMPIterationSpaceChecker::setUB(Expr *NewUB,
7387                                         llvm::Optional<bool> LessOp,
7388                                         bool StrictOp, SourceRange SR,
7389                                         SourceLocation SL) {
7390   // State consistency checking to ensure correct usage.
7391   assert(LCDecl != nullptr && LB != nullptr && UB == nullptr &&
7392          Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
7393   if (!NewUB || NewUB->containsErrors())
7394     return true;
7395   UB = NewUB;
7396   if (LessOp)
7397     TestIsLessOp = LessOp;
7398   TestIsStrictOp = StrictOp;
7399   ConditionSrcRange = SR;
7400   ConditionLoc = SL;
7401   CondDependOnLC = doesDependOnLoopCounter(UB, /*IsInitializer=*/false);
7402   return false;
7403 }
7404 
7405 bool OpenMPIterationSpaceChecker::setStep(Expr *NewStep, bool Subtract) {
7406   // State consistency checking to ensure correct usage.
7407   assert(LCDecl != nullptr && LB != nullptr && Step == nullptr);
7408   if (!NewStep || NewStep->containsErrors())
7409     return true;
7410   if (!NewStep->isValueDependent()) {
7411     // Check that the step is integer expression.
7412     SourceLocation StepLoc = NewStep->getBeginLoc();
7413     ExprResult Val = SemaRef.PerformOpenMPImplicitIntegerConversion(
7414         StepLoc, getExprAsWritten(NewStep));
7415     if (Val.isInvalid())
7416       return true;
7417     NewStep = Val.get();
7418 
7419     // OpenMP [2.6, Canonical Loop Form, Restrictions]
7420     //  If test-expr is of form var relational-op b and relational-op is < or
7421     //  <= then incr-expr must cause var to increase on each iteration of the
7422     //  loop. If test-expr is of form var relational-op b and relational-op is
7423     //  > or >= then incr-expr must cause var to decrease on each iteration of
7424     //  the loop.
7425     //  If test-expr is of form b relational-op var and relational-op is < or
7426     //  <= then incr-expr must cause var to decrease on each iteration of the
7427     //  loop. If test-expr is of form b relational-op var and relational-op is
7428     //  > or >= then incr-expr must cause var to increase on each iteration of
7429     //  the loop.
7430     Optional<llvm::APSInt> Result =
7431         NewStep->getIntegerConstantExpr(SemaRef.Context);
7432     bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation();
7433     bool IsConstNeg =
7434         Result && Result->isSigned() && (Subtract != Result->isNegative());
7435     bool IsConstPos =
7436         Result && Result->isSigned() && (Subtract == Result->isNegative());
7437     bool IsConstZero = Result && !Result->getBoolValue();
7438 
7439     // != with increment is treated as <; != with decrement is treated as >
7440     if (!TestIsLessOp.hasValue())
7441       TestIsLessOp = IsConstPos || (IsUnsigned && !Subtract);
7442     if (UB && (IsConstZero ||
7443                (TestIsLessOp.getValue() ?
7444                   (IsConstNeg || (IsUnsigned && Subtract)) :
7445                   (IsConstPos || (IsUnsigned && !Subtract))))) {
7446       SemaRef.Diag(NewStep->getExprLoc(),
7447                    diag::err_omp_loop_incr_not_compatible)
7448           << LCDecl << TestIsLessOp.getValue() << NewStep->getSourceRange();
7449       SemaRef.Diag(ConditionLoc,
7450                    diag::note_omp_loop_cond_requres_compatible_incr)
7451           << TestIsLessOp.getValue() << ConditionSrcRange;
7452       return true;
7453     }
7454     if (TestIsLessOp.getValue() == Subtract) {
7455       NewStep =
7456           SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus, NewStep)
7457               .get();
7458       Subtract = !Subtract;
7459     }
7460   }
7461 
7462   Step = NewStep;
7463   SubtractStep = Subtract;
7464   return false;
7465 }
7466 
7467 namespace {
7468 /// Checker for the non-rectangular loops. Checks if the initializer or
7469 /// condition expression references loop counter variable.
7470 class LoopCounterRefChecker final
7471     : public ConstStmtVisitor<LoopCounterRefChecker, bool> {
7472   Sema &SemaRef;
7473   DSAStackTy &Stack;
7474   const ValueDecl *CurLCDecl = nullptr;
7475   const ValueDecl *DepDecl = nullptr;
7476   const ValueDecl *PrevDepDecl = nullptr;
7477   bool IsInitializer = true;
7478   bool SupportsNonRectangular;
7479   unsigned BaseLoopId = 0;
7480   bool checkDecl(const Expr *E, const ValueDecl *VD) {
7481     if (getCanonicalDecl(VD) == getCanonicalDecl(CurLCDecl)) {
7482       SemaRef.Diag(E->getExprLoc(), diag::err_omp_stmt_depends_on_loop_counter)
7483           << (IsInitializer ? 0 : 1);
7484       return false;
7485     }
7486     const auto &&Data = Stack.isLoopControlVariable(VD);
7487     // OpenMP, 2.9.1 Canonical Loop Form, Restrictions.
7488     // The type of the loop iterator on which we depend may not have a random
7489     // access iterator type.
7490     if (Data.first && VD->getType()->isRecordType()) {
7491       SmallString<128> Name;
7492       llvm::raw_svector_ostream OS(Name);
7493       VD->getNameForDiagnostic(OS, SemaRef.getPrintingPolicy(),
7494                                /*Qualified=*/true);
7495       SemaRef.Diag(E->getExprLoc(),
7496                    diag::err_omp_wrong_dependency_iterator_type)
7497           << OS.str();
7498       SemaRef.Diag(VD->getLocation(), diag::note_previous_decl) << VD;
7499       return false;
7500     }
7501     if (Data.first && !SupportsNonRectangular) {
7502       SemaRef.Diag(E->getExprLoc(), diag::err_omp_invariant_dependency);
7503       return false;
7504     }
7505     if (Data.first &&
7506         (DepDecl || (PrevDepDecl &&
7507                      getCanonicalDecl(VD) != getCanonicalDecl(PrevDepDecl)))) {
7508       if (!DepDecl && PrevDepDecl)
7509         DepDecl = PrevDepDecl;
7510       SmallString<128> Name;
7511       llvm::raw_svector_ostream OS(Name);
7512       DepDecl->getNameForDiagnostic(OS, SemaRef.getPrintingPolicy(),
7513                                     /*Qualified=*/true);
7514       SemaRef.Diag(E->getExprLoc(),
7515                    diag::err_omp_invariant_or_linear_dependency)
7516           << OS.str();
7517       return false;
7518     }
7519     if (Data.first) {
7520       DepDecl = VD;
7521       BaseLoopId = Data.first;
7522     }
7523     return Data.first;
7524   }
7525 
7526 public:
7527   bool VisitDeclRefExpr(const DeclRefExpr *E) {
7528     const ValueDecl *VD = E->getDecl();
7529     if (isa<VarDecl>(VD))
7530       return checkDecl(E, VD);
7531     return false;
7532   }
7533   bool VisitMemberExpr(const MemberExpr *E) {
7534     if (isa<CXXThisExpr>(E->getBase()->IgnoreParens())) {
7535       const ValueDecl *VD = E->getMemberDecl();
7536       if (isa<VarDecl>(VD) || isa<FieldDecl>(VD))
7537         return checkDecl(E, VD);
7538     }
7539     return false;
7540   }
7541   bool VisitStmt(const Stmt *S) {
7542     bool Res = false;
7543     for (const Stmt *Child : S->children())
7544       Res = (Child && Visit(Child)) || Res;
7545     return Res;
7546   }
7547   explicit LoopCounterRefChecker(Sema &SemaRef, DSAStackTy &Stack,
7548                                  const ValueDecl *CurLCDecl, bool IsInitializer,
7549                                  const ValueDecl *PrevDepDecl = nullptr,
7550                                  bool SupportsNonRectangular = true)
7551       : SemaRef(SemaRef), Stack(Stack), CurLCDecl(CurLCDecl),
7552         PrevDepDecl(PrevDepDecl), IsInitializer(IsInitializer),
7553         SupportsNonRectangular(SupportsNonRectangular) {}
7554   unsigned getBaseLoopId() const {
7555     assert(CurLCDecl && "Expected loop dependency.");
7556     return BaseLoopId;
7557   }
7558   const ValueDecl *getDepDecl() const {
7559     assert(CurLCDecl && "Expected loop dependency.");
7560     return DepDecl;
7561   }
7562 };
7563 } // namespace
7564 
7565 Optional<unsigned>
7566 OpenMPIterationSpaceChecker::doesDependOnLoopCounter(const Stmt *S,
7567                                                      bool IsInitializer) {
7568   // Check for the non-rectangular loops.
7569   LoopCounterRefChecker LoopStmtChecker(SemaRef, Stack, LCDecl, IsInitializer,
7570                                         DepDecl, SupportsNonRectangular);
7571   if (LoopStmtChecker.Visit(S)) {
7572     DepDecl = LoopStmtChecker.getDepDecl();
7573     return LoopStmtChecker.getBaseLoopId();
7574   }
7575   return llvm::None;
7576 }
7577 
7578 bool OpenMPIterationSpaceChecker::checkAndSetInit(Stmt *S, bool EmitDiags) {
7579   // Check init-expr for canonical loop form and save loop counter
7580   // variable - #Var and its initialization value - #LB.
7581   // OpenMP [2.6] Canonical loop form. init-expr may be one of the following:
7582   //   var = lb
7583   //   integer-type var = lb
7584   //   random-access-iterator-type var = lb
7585   //   pointer-type var = lb
7586   //
7587   if (!S) {
7588     if (EmitDiags) {
7589       SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init);
7590     }
7591     return true;
7592   }
7593   if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
7594     if (!ExprTemp->cleanupsHaveSideEffects())
7595       S = ExprTemp->getSubExpr();
7596 
7597   InitSrcRange = S->getSourceRange();
7598   if (Expr *E = dyn_cast<Expr>(S))
7599     S = E->IgnoreParens();
7600   if (auto *BO = dyn_cast<BinaryOperator>(S)) {
7601     if (BO->getOpcode() == BO_Assign) {
7602       Expr *LHS = BO->getLHS()->IgnoreParens();
7603       if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
7604         if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
7605           if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
7606             return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
7607                                   EmitDiags);
7608         return setLCDeclAndLB(DRE->getDecl(), DRE, BO->getRHS(), EmitDiags);
7609       }
7610       if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
7611         if (ME->isArrow() &&
7612             isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
7613           return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
7614                                 EmitDiags);
7615       }
7616     }
7617   } else if (auto *DS = dyn_cast<DeclStmt>(S)) {
7618     if (DS->isSingleDecl()) {
7619       if (auto *Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) {
7620         if (Var->hasInit() && !Var->getType()->isReferenceType()) {
7621           // Accept non-canonical init form here but emit ext. warning.
7622           if (Var->getInitStyle() != VarDecl::CInit && EmitDiags)
7623             SemaRef.Diag(S->getBeginLoc(),
7624                          diag::ext_omp_loop_not_canonical_init)
7625                 << S->getSourceRange();
7626           return setLCDeclAndLB(
7627               Var,
7628               buildDeclRefExpr(SemaRef, Var,
7629                                Var->getType().getNonReferenceType(),
7630                                DS->getBeginLoc()),
7631               Var->getInit(), EmitDiags);
7632         }
7633       }
7634     }
7635   } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
7636     if (CE->getOperator() == OO_Equal) {
7637       Expr *LHS = CE->getArg(0);
7638       if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
7639         if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
7640           if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
7641             return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
7642                                   EmitDiags);
7643         return setLCDeclAndLB(DRE->getDecl(), DRE, CE->getArg(1), EmitDiags);
7644       }
7645       if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
7646         if (ME->isArrow() &&
7647             isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
7648           return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
7649                                 EmitDiags);
7650       }
7651     }
7652   }
7653 
7654   if (dependent() || SemaRef.CurContext->isDependentContext())
7655     return false;
7656   if (EmitDiags) {
7657     SemaRef.Diag(S->getBeginLoc(), diag::err_omp_loop_not_canonical_init)
7658         << S->getSourceRange();
7659   }
7660   return true;
7661 }
7662 
7663 /// Ignore parenthesizes, implicit casts, copy constructor and return the
7664 /// variable (which may be the loop variable) if possible.
7665 static const ValueDecl *getInitLCDecl(const Expr *E) {
7666   if (!E)
7667     return nullptr;
7668   E = getExprAsWritten(E);
7669   if (const auto *CE = dyn_cast_or_null<CXXConstructExpr>(E))
7670     if (const CXXConstructorDecl *Ctor = CE->getConstructor())
7671       if ((Ctor->isCopyOrMoveConstructor() ||
7672            Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
7673           CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
7674         E = CE->getArg(0)->IgnoreParenImpCasts();
7675   if (const auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) {
7676     if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
7677       return getCanonicalDecl(VD);
7678   }
7679   if (const auto *ME = dyn_cast_or_null<MemberExpr>(E))
7680     if (ME->isArrow() && isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
7681       return getCanonicalDecl(ME->getMemberDecl());
7682   return nullptr;
7683 }
7684 
7685 bool OpenMPIterationSpaceChecker::checkAndSetCond(Expr *S) {
7686   // Check test-expr for canonical form, save upper-bound UB, flags for
7687   // less/greater and for strict/non-strict comparison.
7688   // OpenMP [2.9] Canonical loop form. Test-expr may be one of the following:
7689   //   var relational-op b
7690   //   b relational-op var
7691   //
7692   bool IneqCondIsCanonical = SemaRef.getLangOpts().OpenMP >= 50;
7693   if (!S) {
7694     SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond)
7695         << (IneqCondIsCanonical ? 1 : 0) << LCDecl;
7696     return true;
7697   }
7698   Condition = S;
7699   S = getExprAsWritten(S);
7700   SourceLocation CondLoc = S->getBeginLoc();
7701   auto &&CheckAndSetCond = [this, IneqCondIsCanonical](
7702                                BinaryOperatorKind Opcode, const Expr *LHS,
7703                                const Expr *RHS, SourceRange SR,
7704                                SourceLocation OpLoc) -> llvm::Optional<bool> {
7705     if (BinaryOperator::isRelationalOp(Opcode)) {
7706       if (getInitLCDecl(LHS) == LCDecl)
7707         return setUB(const_cast<Expr *>(RHS),
7708                      (Opcode == BO_LT || Opcode == BO_LE),
7709                      (Opcode == BO_LT || Opcode == BO_GT), SR, OpLoc);
7710       if (getInitLCDecl(RHS) == LCDecl)
7711         return setUB(const_cast<Expr *>(LHS),
7712                      (Opcode == BO_GT || Opcode == BO_GE),
7713                      (Opcode == BO_LT || Opcode == BO_GT), SR, OpLoc);
7714     } else if (IneqCondIsCanonical && Opcode == BO_NE) {
7715       return setUB(const_cast<Expr *>(getInitLCDecl(LHS) == LCDecl ? RHS : LHS),
7716                    /*LessOp=*/llvm::None,
7717                    /*StrictOp=*/true, SR, OpLoc);
7718     }
7719     return llvm::None;
7720   };
7721   llvm::Optional<bool> Res;
7722   if (auto *RBO = dyn_cast<CXXRewrittenBinaryOperator>(S)) {
7723     CXXRewrittenBinaryOperator::DecomposedForm DF = RBO->getDecomposedForm();
7724     Res = CheckAndSetCond(DF.Opcode, DF.LHS, DF.RHS, RBO->getSourceRange(),
7725                           RBO->getOperatorLoc());
7726   } else if (auto *BO = dyn_cast<BinaryOperator>(S)) {
7727     Res = CheckAndSetCond(BO->getOpcode(), BO->getLHS(), BO->getRHS(),
7728                           BO->getSourceRange(), BO->getOperatorLoc());
7729   } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
7730     if (CE->getNumArgs() == 2) {
7731       Res = CheckAndSetCond(
7732           BinaryOperator::getOverloadedOpcode(CE->getOperator()), CE->getArg(0),
7733           CE->getArg(1), CE->getSourceRange(), CE->getOperatorLoc());
7734     }
7735   }
7736   if (Res.hasValue())
7737     return *Res;
7738   if (dependent() || SemaRef.CurContext->isDependentContext())
7739     return false;
7740   SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond)
7741       << (IneqCondIsCanonical ? 1 : 0) << S->getSourceRange() << LCDecl;
7742   return true;
7743 }
7744 
7745 bool OpenMPIterationSpaceChecker::checkAndSetIncRHS(Expr *RHS) {
7746   // RHS of canonical loop form increment can be:
7747   //   var + incr
7748   //   incr + var
7749   //   var - incr
7750   //
7751   RHS = RHS->IgnoreParenImpCasts();
7752   if (auto *BO = dyn_cast<BinaryOperator>(RHS)) {
7753     if (BO->isAdditiveOp()) {
7754       bool IsAdd = BO->getOpcode() == BO_Add;
7755       if (getInitLCDecl(BO->getLHS()) == LCDecl)
7756         return setStep(BO->getRHS(), !IsAdd);
7757       if (IsAdd && getInitLCDecl(BO->getRHS()) == LCDecl)
7758         return setStep(BO->getLHS(), /*Subtract=*/false);
7759     }
7760   } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(RHS)) {
7761     bool IsAdd = CE->getOperator() == OO_Plus;
7762     if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) {
7763       if (getInitLCDecl(CE->getArg(0)) == LCDecl)
7764         return setStep(CE->getArg(1), !IsAdd);
7765       if (IsAdd && getInitLCDecl(CE->getArg(1)) == LCDecl)
7766         return setStep(CE->getArg(0), /*Subtract=*/false);
7767     }
7768   }
7769   if (dependent() || SemaRef.CurContext->isDependentContext())
7770     return false;
7771   SemaRef.Diag(RHS->getBeginLoc(), diag::err_omp_loop_not_canonical_incr)
7772       << RHS->getSourceRange() << LCDecl;
7773   return true;
7774 }
7775 
7776 bool OpenMPIterationSpaceChecker::checkAndSetInc(Expr *S) {
7777   // Check incr-expr for canonical loop form and return true if it
7778   // does not conform.
7779   // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
7780   //   ++var
7781   //   var++
7782   //   --var
7783   //   var--
7784   //   var += incr
7785   //   var -= incr
7786   //   var = var + incr
7787   //   var = incr + var
7788   //   var = var - incr
7789   //
7790   if (!S) {
7791     SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << LCDecl;
7792     return true;
7793   }
7794   if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
7795     if (!ExprTemp->cleanupsHaveSideEffects())
7796       S = ExprTemp->getSubExpr();
7797 
7798   IncrementSrcRange = S->getSourceRange();
7799   S = S->IgnoreParens();
7800   if (auto *UO = dyn_cast<UnaryOperator>(S)) {
7801     if (UO->isIncrementDecrementOp() &&
7802         getInitLCDecl(UO->getSubExpr()) == LCDecl)
7803       return setStep(SemaRef
7804                          .ActOnIntegerConstant(UO->getBeginLoc(),
7805                                                (UO->isDecrementOp() ? -1 : 1))
7806                          .get(),
7807                      /*Subtract=*/false);
7808   } else if (auto *BO = dyn_cast<BinaryOperator>(S)) {
7809     switch (BO->getOpcode()) {
7810     case BO_AddAssign:
7811     case BO_SubAssign:
7812       if (getInitLCDecl(BO->getLHS()) == LCDecl)
7813         return setStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign);
7814       break;
7815     case BO_Assign:
7816       if (getInitLCDecl(BO->getLHS()) == LCDecl)
7817         return checkAndSetIncRHS(BO->getRHS());
7818       break;
7819     default:
7820       break;
7821     }
7822   } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
7823     switch (CE->getOperator()) {
7824     case OO_PlusPlus:
7825     case OO_MinusMinus:
7826       if (getInitLCDecl(CE->getArg(0)) == LCDecl)
7827         return setStep(SemaRef
7828                            .ActOnIntegerConstant(
7829                                CE->getBeginLoc(),
7830                                ((CE->getOperator() == OO_MinusMinus) ? -1 : 1))
7831                            .get(),
7832                        /*Subtract=*/false);
7833       break;
7834     case OO_PlusEqual:
7835     case OO_MinusEqual:
7836       if (getInitLCDecl(CE->getArg(0)) == LCDecl)
7837         return setStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual);
7838       break;
7839     case OO_Equal:
7840       if (getInitLCDecl(CE->getArg(0)) == LCDecl)
7841         return checkAndSetIncRHS(CE->getArg(1));
7842       break;
7843     default:
7844       break;
7845     }
7846   }
7847   if (dependent() || SemaRef.CurContext->isDependentContext())
7848     return false;
7849   SemaRef.Diag(S->getBeginLoc(), diag::err_omp_loop_not_canonical_incr)
7850       << S->getSourceRange() << LCDecl;
7851   return true;
7852 }
7853 
7854 static ExprResult
7855 tryBuildCapture(Sema &SemaRef, Expr *Capture,
7856                 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
7857   if (SemaRef.CurContext->isDependentContext() || Capture->containsErrors())
7858     return Capture;
7859   if (Capture->isEvaluatable(SemaRef.Context, Expr::SE_AllowSideEffects))
7860     return SemaRef.PerformImplicitConversion(
7861         Capture->IgnoreImpCasts(), Capture->getType(), Sema::AA_Converting,
7862         /*AllowExplicit=*/true);
7863   auto I = Captures.find(Capture);
7864   if (I != Captures.end())
7865     return buildCapture(SemaRef, Capture, I->second);
7866   DeclRefExpr *Ref = nullptr;
7867   ExprResult Res = buildCapture(SemaRef, Capture, Ref);
7868   Captures[Capture] = Ref;
7869   return Res;
7870 }
7871 
7872 /// Calculate number of iterations, transforming to unsigned, if number of
7873 /// iterations may be larger than the original type.
7874 static Expr *
7875 calculateNumIters(Sema &SemaRef, Scope *S, SourceLocation DefaultLoc,
7876                   Expr *Lower, Expr *Upper, Expr *Step, QualType LCTy,
7877                   bool TestIsStrictOp, bool RoundToStep,
7878                   llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
7879   ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures);
7880   if (!NewStep.isUsable())
7881     return nullptr;
7882   llvm::APSInt LRes, SRes;
7883   bool IsLowerConst = false, IsStepConst = false;
7884   if (Optional<llvm::APSInt> Res = Lower->getIntegerConstantExpr(SemaRef.Context)) {
7885     LRes = *Res;
7886     IsLowerConst = true;
7887   }
7888   if (Optional<llvm::APSInt> Res = Step->getIntegerConstantExpr(SemaRef.Context)) {
7889     SRes = *Res;
7890     IsStepConst = true;
7891   }
7892   bool NoNeedToConvert = IsLowerConst && !RoundToStep &&
7893                          ((!TestIsStrictOp && LRes.isNonNegative()) ||
7894                           (TestIsStrictOp && LRes.isStrictlyPositive()));
7895   bool NeedToReorganize = false;
7896   // Check if any subexpressions in Lower -Step [+ 1] lead to overflow.
7897   if (!NoNeedToConvert && IsLowerConst &&
7898       (TestIsStrictOp || (RoundToStep && IsStepConst))) {
7899     NoNeedToConvert = true;
7900     if (RoundToStep) {
7901       unsigned BW = LRes.getBitWidth() > SRes.getBitWidth()
7902                         ? LRes.getBitWidth()
7903                         : SRes.getBitWidth();
7904       LRes = LRes.extend(BW + 1);
7905       LRes.setIsSigned(true);
7906       SRes = SRes.extend(BW + 1);
7907       SRes.setIsSigned(true);
7908       LRes -= SRes;
7909       NoNeedToConvert = LRes.trunc(BW).extend(BW + 1) == LRes;
7910       LRes = LRes.trunc(BW);
7911     }
7912     if (TestIsStrictOp) {
7913       unsigned BW = LRes.getBitWidth();
7914       LRes = LRes.extend(BW + 1);
7915       LRes.setIsSigned(true);
7916       ++LRes;
7917       NoNeedToConvert =
7918           NoNeedToConvert && LRes.trunc(BW).extend(BW + 1) == LRes;
7919       // truncate to the original bitwidth.
7920       LRes = LRes.trunc(BW);
7921     }
7922     NeedToReorganize = NoNeedToConvert;
7923   }
7924   llvm::APSInt URes;
7925   bool IsUpperConst = false;
7926   if (Optional<llvm::APSInt> Res = Upper->getIntegerConstantExpr(SemaRef.Context)) {
7927     URes = *Res;
7928     IsUpperConst = true;
7929   }
7930   if (NoNeedToConvert && IsLowerConst && IsUpperConst &&
7931       (!RoundToStep || IsStepConst)) {
7932     unsigned BW = LRes.getBitWidth() > URes.getBitWidth() ? LRes.getBitWidth()
7933                                                           : URes.getBitWidth();
7934     LRes = LRes.extend(BW + 1);
7935     LRes.setIsSigned(true);
7936     URes = URes.extend(BW + 1);
7937     URes.setIsSigned(true);
7938     URes -= LRes;
7939     NoNeedToConvert = URes.trunc(BW).extend(BW + 1) == URes;
7940     NeedToReorganize = NoNeedToConvert;
7941   }
7942   // If the boundaries are not constant or (Lower - Step [+ 1]) is not constant
7943   // or less than zero (Upper - (Lower - Step [+ 1]) may overflow) - promote to
7944   // unsigned.
7945   if ((!NoNeedToConvert || (LRes.isNegative() && !IsUpperConst)) &&
7946       !LCTy->isDependentType() && LCTy->isIntegerType()) {
7947     QualType LowerTy = Lower->getType();
7948     QualType UpperTy = Upper->getType();
7949     uint64_t LowerSize = SemaRef.Context.getTypeSize(LowerTy);
7950     uint64_t UpperSize = SemaRef.Context.getTypeSize(UpperTy);
7951     if ((LowerSize <= UpperSize && UpperTy->hasSignedIntegerRepresentation()) ||
7952         (LowerSize > UpperSize && LowerTy->hasSignedIntegerRepresentation())) {
7953       QualType CastType = SemaRef.Context.getIntTypeForBitwidth(
7954           LowerSize > UpperSize ? LowerSize : UpperSize, /*Signed=*/0);
7955       Upper =
7956           SemaRef
7957               .PerformImplicitConversion(
7958                   SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Upper).get(),
7959                   CastType, Sema::AA_Converting)
7960               .get();
7961       Lower = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Lower).get();
7962       NewStep = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, NewStep.get());
7963     }
7964   }
7965   if (!Lower || !Upper || NewStep.isInvalid())
7966     return nullptr;
7967 
7968   ExprResult Diff;
7969   // If need to reorganize, then calculate the form as Upper - (Lower - Step [+
7970   // 1]).
7971   if (NeedToReorganize) {
7972     Diff = Lower;
7973 
7974     if (RoundToStep) {
7975       // Lower - Step
7976       Diff =
7977           SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Diff.get(), NewStep.get());
7978       if (!Diff.isUsable())
7979         return nullptr;
7980     }
7981 
7982     // Lower - Step [+ 1]
7983     if (TestIsStrictOp)
7984       Diff = SemaRef.BuildBinOp(
7985           S, DefaultLoc, BO_Add, Diff.get(),
7986           SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
7987     if (!Diff.isUsable())
7988       return nullptr;
7989 
7990     Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
7991     if (!Diff.isUsable())
7992       return nullptr;
7993 
7994     // Upper - (Lower - Step [+ 1]).
7995     Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Diff.get());
7996     if (!Diff.isUsable())
7997       return nullptr;
7998   } else {
7999     Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
8000 
8001     if (!Diff.isUsable() && LCTy->getAsCXXRecordDecl()) {
8002       // BuildBinOp already emitted error, this one is to point user to upper
8003       // and lower bound, and to tell what is passed to 'operator-'.
8004       SemaRef.Diag(Upper->getBeginLoc(), diag::err_omp_loop_diff_cxx)
8005           << Upper->getSourceRange() << Lower->getSourceRange();
8006       return nullptr;
8007     }
8008 
8009     if (!Diff.isUsable())
8010       return nullptr;
8011 
8012     // Upper - Lower [- 1]
8013     if (TestIsStrictOp)
8014       Diff = SemaRef.BuildBinOp(
8015           S, DefaultLoc, BO_Sub, Diff.get(),
8016           SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
8017     if (!Diff.isUsable())
8018       return nullptr;
8019 
8020     if (RoundToStep) {
8021       // Upper - Lower [- 1] + Step
8022       Diff =
8023           SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get());
8024       if (!Diff.isUsable())
8025         return nullptr;
8026     }
8027   }
8028 
8029   // Parentheses (for dumping/debugging purposes only).
8030   Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
8031   if (!Diff.isUsable())
8032     return nullptr;
8033 
8034   // (Upper - Lower [- 1] + Step) / Step or (Upper - Lower) / Step
8035   Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
8036   if (!Diff.isUsable())
8037     return nullptr;
8038 
8039   return Diff.get();
8040 }
8041 
8042 /// Build the expression to calculate the number of iterations.
8043 Expr *OpenMPIterationSpaceChecker::buildNumIterations(
8044     Scope *S, ArrayRef<LoopIterationSpace> ResultIterSpaces, bool LimitedType,
8045     llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
8046   QualType VarType = LCDecl->getType().getNonReferenceType();
8047   if (!VarType->isIntegerType() && !VarType->isPointerType() &&
8048       !SemaRef.getLangOpts().CPlusPlus)
8049     return nullptr;
8050   Expr *LBVal = LB;
8051   Expr *UBVal = UB;
8052   // LB = TestIsLessOp.getValue() ? min(LB(MinVal), LB(MaxVal)) :
8053   // max(LB(MinVal), LB(MaxVal))
8054   if (InitDependOnLC) {
8055     const LoopIterationSpace &IS = ResultIterSpaces[*InitDependOnLC - 1];
8056     if (!IS.MinValue || !IS.MaxValue)
8057       return nullptr;
8058     // OuterVar = Min
8059     ExprResult MinValue =
8060         SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MinValue);
8061     if (!MinValue.isUsable())
8062       return nullptr;
8063 
8064     ExprResult LBMinVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign,
8065                                              IS.CounterVar, MinValue.get());
8066     if (!LBMinVal.isUsable())
8067       return nullptr;
8068     // OuterVar = Min, LBVal
8069     LBMinVal =
8070         SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, LBMinVal.get(), LBVal);
8071     if (!LBMinVal.isUsable())
8072       return nullptr;
8073     // (OuterVar = Min, LBVal)
8074     LBMinVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, LBMinVal.get());
8075     if (!LBMinVal.isUsable())
8076       return nullptr;
8077 
8078     // OuterVar = Max
8079     ExprResult MaxValue =
8080         SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MaxValue);
8081     if (!MaxValue.isUsable())
8082       return nullptr;
8083 
8084     ExprResult LBMaxVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign,
8085                                              IS.CounterVar, MaxValue.get());
8086     if (!LBMaxVal.isUsable())
8087       return nullptr;
8088     // OuterVar = Max, LBVal
8089     LBMaxVal =
8090         SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, LBMaxVal.get(), LBVal);
8091     if (!LBMaxVal.isUsable())
8092       return nullptr;
8093     // (OuterVar = Max, LBVal)
8094     LBMaxVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, LBMaxVal.get());
8095     if (!LBMaxVal.isUsable())
8096       return nullptr;
8097 
8098     Expr *LBMin = tryBuildCapture(SemaRef, LBMinVal.get(), Captures).get();
8099     Expr *LBMax = tryBuildCapture(SemaRef, LBMaxVal.get(), Captures).get();
8100     if (!LBMin || !LBMax)
8101       return nullptr;
8102     // LB(MinVal) < LB(MaxVal)
8103     ExprResult MinLessMaxRes =
8104         SemaRef.BuildBinOp(S, DefaultLoc, BO_LT, LBMin, LBMax);
8105     if (!MinLessMaxRes.isUsable())
8106       return nullptr;
8107     Expr *MinLessMax =
8108         tryBuildCapture(SemaRef, MinLessMaxRes.get(), Captures).get();
8109     if (!MinLessMax)
8110       return nullptr;
8111     if (TestIsLessOp.getValue()) {
8112       // LB(MinVal) < LB(MaxVal) ? LB(MinVal) : LB(MaxVal) - min(LB(MinVal),
8113       // LB(MaxVal))
8114       ExprResult MinLB = SemaRef.ActOnConditionalOp(DefaultLoc, DefaultLoc,
8115                                                     MinLessMax, LBMin, LBMax);
8116       if (!MinLB.isUsable())
8117         return nullptr;
8118       LBVal = MinLB.get();
8119     } else {
8120       // LB(MinVal) < LB(MaxVal) ? LB(MaxVal) : LB(MinVal) - max(LB(MinVal),
8121       // LB(MaxVal))
8122       ExprResult MaxLB = SemaRef.ActOnConditionalOp(DefaultLoc, DefaultLoc,
8123                                                     MinLessMax, LBMax, LBMin);
8124       if (!MaxLB.isUsable())
8125         return nullptr;
8126       LBVal = MaxLB.get();
8127     }
8128   }
8129   // UB = TestIsLessOp.getValue() ? max(UB(MinVal), UB(MaxVal)) :
8130   // min(UB(MinVal), UB(MaxVal))
8131   if (CondDependOnLC) {
8132     const LoopIterationSpace &IS = ResultIterSpaces[*CondDependOnLC - 1];
8133     if (!IS.MinValue || !IS.MaxValue)
8134       return nullptr;
8135     // OuterVar = Min
8136     ExprResult MinValue =
8137         SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MinValue);
8138     if (!MinValue.isUsable())
8139       return nullptr;
8140 
8141     ExprResult UBMinVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign,
8142                                              IS.CounterVar, MinValue.get());
8143     if (!UBMinVal.isUsable())
8144       return nullptr;
8145     // OuterVar = Min, UBVal
8146     UBMinVal =
8147         SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, UBMinVal.get(), UBVal);
8148     if (!UBMinVal.isUsable())
8149       return nullptr;
8150     // (OuterVar = Min, UBVal)
8151     UBMinVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, UBMinVal.get());
8152     if (!UBMinVal.isUsable())
8153       return nullptr;
8154 
8155     // OuterVar = Max
8156     ExprResult MaxValue =
8157         SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MaxValue);
8158     if (!MaxValue.isUsable())
8159       return nullptr;
8160 
8161     ExprResult UBMaxVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign,
8162                                              IS.CounterVar, MaxValue.get());
8163     if (!UBMaxVal.isUsable())
8164       return nullptr;
8165     // OuterVar = Max, UBVal
8166     UBMaxVal =
8167         SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, UBMaxVal.get(), UBVal);
8168     if (!UBMaxVal.isUsable())
8169       return nullptr;
8170     // (OuterVar = Max, UBVal)
8171     UBMaxVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, UBMaxVal.get());
8172     if (!UBMaxVal.isUsable())
8173       return nullptr;
8174 
8175     Expr *UBMin = tryBuildCapture(SemaRef, UBMinVal.get(), Captures).get();
8176     Expr *UBMax = tryBuildCapture(SemaRef, UBMaxVal.get(), Captures).get();
8177     if (!UBMin || !UBMax)
8178       return nullptr;
8179     // UB(MinVal) > UB(MaxVal)
8180     ExprResult MinGreaterMaxRes =
8181         SemaRef.BuildBinOp(S, DefaultLoc, BO_GT, UBMin, UBMax);
8182     if (!MinGreaterMaxRes.isUsable())
8183       return nullptr;
8184     Expr *MinGreaterMax =
8185         tryBuildCapture(SemaRef, MinGreaterMaxRes.get(), Captures).get();
8186     if (!MinGreaterMax)
8187       return nullptr;
8188     if (TestIsLessOp.getValue()) {
8189       // UB(MinVal) > UB(MaxVal) ? UB(MinVal) : UB(MaxVal) - max(UB(MinVal),
8190       // UB(MaxVal))
8191       ExprResult MaxUB = SemaRef.ActOnConditionalOp(
8192           DefaultLoc, DefaultLoc, MinGreaterMax, UBMin, UBMax);
8193       if (!MaxUB.isUsable())
8194         return nullptr;
8195       UBVal = MaxUB.get();
8196     } else {
8197       // UB(MinVal) > UB(MaxVal) ? UB(MaxVal) : UB(MinVal) - min(UB(MinVal),
8198       // UB(MaxVal))
8199       ExprResult MinUB = SemaRef.ActOnConditionalOp(
8200           DefaultLoc, DefaultLoc, MinGreaterMax, UBMax, UBMin);
8201       if (!MinUB.isUsable())
8202         return nullptr;
8203       UBVal = MinUB.get();
8204     }
8205   }
8206   Expr *UBExpr = TestIsLessOp.getValue() ? UBVal : LBVal;
8207   Expr *LBExpr = TestIsLessOp.getValue() ? LBVal : UBVal;
8208   Expr *Upper = tryBuildCapture(SemaRef, UBExpr, Captures).get();
8209   Expr *Lower = tryBuildCapture(SemaRef, LBExpr, Captures).get();
8210   if (!Upper || !Lower)
8211     return nullptr;
8212 
8213   ExprResult Diff = calculateNumIters(SemaRef, S, DefaultLoc, Lower, Upper,
8214                                       Step, VarType, TestIsStrictOp,
8215                                       /*RoundToStep=*/true, Captures);
8216   if (!Diff.isUsable())
8217     return nullptr;
8218 
8219   // OpenMP runtime requires 32-bit or 64-bit loop variables.
8220   QualType Type = Diff.get()->getType();
8221   ASTContext &C = SemaRef.Context;
8222   bool UseVarType = VarType->hasIntegerRepresentation() &&
8223                     C.getTypeSize(Type) > C.getTypeSize(VarType);
8224   if (!Type->isIntegerType() || UseVarType) {
8225     unsigned NewSize =
8226         UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type);
8227     bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation()
8228                                : Type->hasSignedIntegerRepresentation();
8229     Type = C.getIntTypeForBitwidth(NewSize, IsSigned);
8230     if (!SemaRef.Context.hasSameType(Diff.get()->getType(), Type)) {
8231       Diff = SemaRef.PerformImplicitConversion(
8232           Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true);
8233       if (!Diff.isUsable())
8234         return nullptr;
8235     }
8236   }
8237   if (LimitedType) {
8238     unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32;
8239     if (NewSize != C.getTypeSize(Type)) {
8240       if (NewSize < C.getTypeSize(Type)) {
8241         assert(NewSize == 64 && "incorrect loop var size");
8242         SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var)
8243             << InitSrcRange << ConditionSrcRange;
8244       }
8245       QualType NewType = C.getIntTypeForBitwidth(
8246           NewSize, Type->hasSignedIntegerRepresentation() ||
8247                        C.getTypeSize(Type) < NewSize);
8248       if (!SemaRef.Context.hasSameType(Diff.get()->getType(), NewType)) {
8249         Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType,
8250                                                  Sema::AA_Converting, true);
8251         if (!Diff.isUsable())
8252           return nullptr;
8253       }
8254     }
8255   }
8256 
8257   return Diff.get();
8258 }
8259 
8260 std::pair<Expr *, Expr *> OpenMPIterationSpaceChecker::buildMinMaxValues(
8261     Scope *S, llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
8262   // Do not build for iterators, they cannot be used in non-rectangular loop
8263   // nests.
8264   if (LCDecl->getType()->isRecordType())
8265     return std::make_pair(nullptr, nullptr);
8266   // If we subtract, the min is in the condition, otherwise the min is in the
8267   // init value.
8268   Expr *MinExpr = nullptr;
8269   Expr *MaxExpr = nullptr;
8270   Expr *LBExpr = TestIsLessOp.getValue() ? LB : UB;
8271   Expr *UBExpr = TestIsLessOp.getValue() ? UB : LB;
8272   bool LBNonRect = TestIsLessOp.getValue() ? InitDependOnLC.hasValue()
8273                                            : CondDependOnLC.hasValue();
8274   bool UBNonRect = TestIsLessOp.getValue() ? CondDependOnLC.hasValue()
8275                                            : InitDependOnLC.hasValue();
8276   Expr *Lower =
8277       LBNonRect ? LBExpr : tryBuildCapture(SemaRef, LBExpr, Captures).get();
8278   Expr *Upper =
8279       UBNonRect ? UBExpr : tryBuildCapture(SemaRef, UBExpr, Captures).get();
8280   if (!Upper || !Lower)
8281     return std::make_pair(nullptr, nullptr);
8282 
8283   if (TestIsLessOp.getValue())
8284     MinExpr = Lower;
8285   else
8286     MaxExpr = Upper;
8287 
8288   // Build minimum/maximum value based on number of iterations.
8289   QualType VarType = LCDecl->getType().getNonReferenceType();
8290 
8291   ExprResult Diff = calculateNumIters(SemaRef, S, DefaultLoc, Lower, Upper,
8292                                       Step, VarType, TestIsStrictOp,
8293                                       /*RoundToStep=*/false, Captures);
8294   if (!Diff.isUsable())
8295     return std::make_pair(nullptr, nullptr);
8296 
8297   // ((Upper - Lower [- 1]) / Step) * Step
8298   // Parentheses (for dumping/debugging purposes only).
8299   Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
8300   if (!Diff.isUsable())
8301     return std::make_pair(nullptr, nullptr);
8302 
8303   ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures);
8304   if (!NewStep.isUsable())
8305     return std::make_pair(nullptr, nullptr);
8306   Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Mul, Diff.get(), NewStep.get());
8307   if (!Diff.isUsable())
8308     return std::make_pair(nullptr, nullptr);
8309 
8310   // Parentheses (for dumping/debugging purposes only).
8311   Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
8312   if (!Diff.isUsable())
8313     return std::make_pair(nullptr, nullptr);
8314 
8315   // Convert to the ptrdiff_t, if original type is pointer.
8316   if (VarType->isAnyPointerType() &&
8317       !SemaRef.Context.hasSameType(
8318           Diff.get()->getType(),
8319           SemaRef.Context.getUnsignedPointerDiffType())) {
8320     Diff = SemaRef.PerformImplicitConversion(
8321         Diff.get(), SemaRef.Context.getUnsignedPointerDiffType(),
8322         Sema::AA_Converting, /*AllowExplicit=*/true);
8323   }
8324   if (!Diff.isUsable())
8325     return std::make_pair(nullptr, nullptr);
8326 
8327   if (TestIsLessOp.getValue()) {
8328     // MinExpr = Lower;
8329     // MaxExpr = Lower + (((Upper - Lower [- 1]) / Step) * Step)
8330     Diff = SemaRef.BuildBinOp(
8331         S, DefaultLoc, BO_Add,
8332         SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Lower).get(),
8333         Diff.get());
8334     if (!Diff.isUsable())
8335       return std::make_pair(nullptr, nullptr);
8336   } else {
8337     // MaxExpr = Upper;
8338     // MinExpr = Upper - (((Upper - Lower [- 1]) / Step) * Step)
8339     Diff = SemaRef.BuildBinOp(
8340         S, DefaultLoc, BO_Sub,
8341         SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Upper).get(),
8342         Diff.get());
8343     if (!Diff.isUsable())
8344       return std::make_pair(nullptr, nullptr);
8345   }
8346 
8347   // Convert to the original type.
8348   if (SemaRef.Context.hasSameType(Diff.get()->getType(), VarType))
8349     Diff = SemaRef.PerformImplicitConversion(Diff.get(), VarType,
8350                                              Sema::AA_Converting,
8351                                              /*AllowExplicit=*/true);
8352   if (!Diff.isUsable())
8353     return std::make_pair(nullptr, nullptr);
8354 
8355   Sema::TentativeAnalysisScope Trap(SemaRef);
8356   Diff = SemaRef.ActOnFinishFullExpr(Diff.get(), /*DiscardedValue=*/false);
8357   if (!Diff.isUsable())
8358     return std::make_pair(nullptr, nullptr);
8359 
8360   if (TestIsLessOp.getValue())
8361     MaxExpr = Diff.get();
8362   else
8363     MinExpr = Diff.get();
8364 
8365   return std::make_pair(MinExpr, MaxExpr);
8366 }
8367 
8368 Expr *OpenMPIterationSpaceChecker::buildFinalCondition(Scope *S) const {
8369   if (InitDependOnLC || CondDependOnLC)
8370     return Condition;
8371   return nullptr;
8372 }
8373 
8374 Expr *OpenMPIterationSpaceChecker::buildPreCond(
8375     Scope *S, Expr *Cond,
8376     llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
8377   // Do not build a precondition when the condition/initialization is dependent
8378   // to prevent pessimistic early loop exit.
8379   // TODO: this can be improved by calculating min/max values but not sure that
8380   // it will be very effective.
8381   if (CondDependOnLC || InitDependOnLC)
8382     return SemaRef.PerformImplicitConversion(
8383         SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get(),
8384         SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
8385         /*AllowExplicit=*/true).get();
8386 
8387   // Try to build LB <op> UB, where <op> is <, >, <=, or >=.
8388   Sema::TentativeAnalysisScope Trap(SemaRef);
8389 
8390   ExprResult NewLB = tryBuildCapture(SemaRef, LB, Captures);
8391   ExprResult NewUB = tryBuildCapture(SemaRef, UB, Captures);
8392   if (!NewLB.isUsable() || !NewUB.isUsable())
8393     return nullptr;
8394 
8395   ExprResult CondExpr =
8396       SemaRef.BuildBinOp(S, DefaultLoc,
8397                          TestIsLessOp.getValue() ?
8398                            (TestIsStrictOp ? BO_LT : BO_LE) :
8399                            (TestIsStrictOp ? BO_GT : BO_GE),
8400                          NewLB.get(), NewUB.get());
8401   if (CondExpr.isUsable()) {
8402     if (!SemaRef.Context.hasSameUnqualifiedType(CondExpr.get()->getType(),
8403                                                 SemaRef.Context.BoolTy))
8404       CondExpr = SemaRef.PerformImplicitConversion(
8405           CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
8406           /*AllowExplicit=*/true);
8407   }
8408 
8409   // Otherwise use original loop condition and evaluate it in runtime.
8410   return CondExpr.isUsable() ? CondExpr.get() : Cond;
8411 }
8412 
8413 /// Build reference expression to the counter be used for codegen.
8414 DeclRefExpr *OpenMPIterationSpaceChecker::buildCounterVar(
8415     llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
8416     DSAStackTy &DSA) const {
8417   auto *VD = dyn_cast<VarDecl>(LCDecl);
8418   if (!VD) {
8419     VD = SemaRef.isOpenMPCapturedDecl(LCDecl);
8420     DeclRefExpr *Ref = buildDeclRefExpr(
8421         SemaRef, VD, VD->getType().getNonReferenceType(), DefaultLoc);
8422     const DSAStackTy::DSAVarData Data =
8423         DSA.getTopDSA(LCDecl, /*FromParent=*/false);
8424     // If the loop control decl is explicitly marked as private, do not mark it
8425     // as captured again.
8426     if (!isOpenMPPrivate(Data.CKind) || !Data.RefExpr)
8427       Captures.insert(std::make_pair(LCRef, Ref));
8428     return Ref;
8429   }
8430   return cast<DeclRefExpr>(LCRef);
8431 }
8432 
8433 Expr *OpenMPIterationSpaceChecker::buildPrivateCounterVar() const {
8434   if (LCDecl && !LCDecl->isInvalidDecl()) {
8435     QualType Type = LCDecl->getType().getNonReferenceType();
8436     VarDecl *PrivateVar = buildVarDecl(
8437         SemaRef, DefaultLoc, Type, LCDecl->getName(),
8438         LCDecl->hasAttrs() ? &LCDecl->getAttrs() : nullptr,
8439         isa<VarDecl>(LCDecl)
8440             ? buildDeclRefExpr(SemaRef, cast<VarDecl>(LCDecl), Type, DefaultLoc)
8441             : nullptr);
8442     if (PrivateVar->isInvalidDecl())
8443       return nullptr;
8444     return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc);
8445   }
8446   return nullptr;
8447 }
8448 
8449 /// Build initialization of the counter to be used for codegen.
8450 Expr *OpenMPIterationSpaceChecker::buildCounterInit() const { return LB; }
8451 
8452 /// Build step of the counter be used for codegen.
8453 Expr *OpenMPIterationSpaceChecker::buildCounterStep() const { return Step; }
8454 
8455 Expr *OpenMPIterationSpaceChecker::buildOrderedLoopData(
8456     Scope *S, Expr *Counter,
8457     llvm::MapVector<const Expr *, DeclRefExpr *> &Captures, SourceLocation Loc,
8458     Expr *Inc, OverloadedOperatorKind OOK) {
8459   Expr *Cnt = SemaRef.DefaultLvalueConversion(Counter).get();
8460   if (!Cnt)
8461     return nullptr;
8462   if (Inc) {
8463     assert((OOK == OO_Plus || OOK == OO_Minus) &&
8464            "Expected only + or - operations for depend clauses.");
8465     BinaryOperatorKind BOK = (OOK == OO_Plus) ? BO_Add : BO_Sub;
8466     Cnt = SemaRef.BuildBinOp(S, Loc, BOK, Cnt, Inc).get();
8467     if (!Cnt)
8468       return nullptr;
8469   }
8470   QualType VarType = LCDecl->getType().getNonReferenceType();
8471   if (!VarType->isIntegerType() && !VarType->isPointerType() &&
8472       !SemaRef.getLangOpts().CPlusPlus)
8473     return nullptr;
8474   // Upper - Lower
8475   Expr *Upper = TestIsLessOp.getValue()
8476                     ? Cnt
8477                     : tryBuildCapture(SemaRef, LB, Captures).get();
8478   Expr *Lower = TestIsLessOp.getValue()
8479                     ? tryBuildCapture(SemaRef, LB, Captures).get()
8480                     : Cnt;
8481   if (!Upper || !Lower)
8482     return nullptr;
8483 
8484   ExprResult Diff = calculateNumIters(
8485       SemaRef, S, DefaultLoc, Lower, Upper, Step, VarType,
8486       /*TestIsStrictOp=*/false, /*RoundToStep=*/false, Captures);
8487   if (!Diff.isUsable())
8488     return nullptr;
8489 
8490   return Diff.get();
8491 }
8492 } // namespace
8493 
8494 void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) {
8495   assert(getLangOpts().OpenMP && "OpenMP is not active.");
8496   assert(Init && "Expected loop in canonical form.");
8497   unsigned AssociatedLoops = DSAStack->getAssociatedLoops();
8498   if (AssociatedLoops > 0 &&
8499       isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
8500     DSAStack->loopStart();
8501     OpenMPIterationSpaceChecker ISC(*this, /*SupportsNonRectangular=*/true,
8502                                     *DSAStack, ForLoc);
8503     if (!ISC.checkAndSetInit(Init, /*EmitDiags=*/false)) {
8504       if (ValueDecl *D = ISC.getLoopDecl()) {
8505         auto *VD = dyn_cast<VarDecl>(D);
8506         DeclRefExpr *PrivateRef = nullptr;
8507         if (!VD) {
8508           if (VarDecl *Private = isOpenMPCapturedDecl(D)) {
8509             VD = Private;
8510           } else {
8511             PrivateRef = buildCapture(*this, D, ISC.getLoopDeclRefExpr(),
8512                                       /*WithInit=*/false);
8513             VD = cast<VarDecl>(PrivateRef->getDecl());
8514           }
8515         }
8516         DSAStack->addLoopControlVariable(D, VD);
8517         const Decl *LD = DSAStack->getPossiblyLoopCunter();
8518         if (LD != D->getCanonicalDecl()) {
8519           DSAStack->resetPossibleLoopCounter();
8520           if (auto *Var = dyn_cast_or_null<VarDecl>(LD))
8521             MarkDeclarationsReferencedInExpr(
8522                 buildDeclRefExpr(*this, const_cast<VarDecl *>(Var),
8523                                  Var->getType().getNonLValueExprType(Context),
8524                                  ForLoc, /*RefersToCapture=*/true));
8525         }
8526         OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
8527         // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables
8528         // Referenced in a Construct, C/C++]. The loop iteration variable in the
8529         // associated for-loop of a simd construct with just one associated
8530         // for-loop may be listed in a linear clause with a constant-linear-step
8531         // that is the increment of the associated for-loop. The loop iteration
8532         // variable(s) in the associated for-loop(s) of a for or parallel for
8533         // construct may be listed in a private or lastprivate clause.
8534         DSAStackTy::DSAVarData DVar =
8535             DSAStack->getTopDSA(D, /*FromParent=*/false);
8536         // If LoopVarRefExpr is nullptr it means the corresponding loop variable
8537         // is declared in the loop and it is predetermined as a private.
8538         Expr *LoopDeclRefExpr = ISC.getLoopDeclRefExpr();
8539         OpenMPClauseKind PredeterminedCKind =
8540             isOpenMPSimdDirective(DKind)
8541                 ? (DSAStack->hasMutipleLoops() ? OMPC_lastprivate : OMPC_linear)
8542                 : OMPC_private;
8543         if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
8544               DVar.CKind != PredeterminedCKind && DVar.RefExpr &&
8545               (LangOpts.OpenMP <= 45 || (DVar.CKind != OMPC_lastprivate &&
8546                                          DVar.CKind != OMPC_private))) ||
8547              ((isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop ||
8548                DKind == OMPD_master_taskloop ||
8549                DKind == OMPD_parallel_master_taskloop ||
8550                isOpenMPDistributeDirective(DKind)) &&
8551               !isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
8552               DVar.CKind != OMPC_private && DVar.CKind != OMPC_lastprivate)) &&
8553             (DVar.CKind != OMPC_private || DVar.RefExpr)) {
8554           Diag(Init->getBeginLoc(), diag::err_omp_loop_var_dsa)
8555               << getOpenMPClauseName(DVar.CKind)
8556               << getOpenMPDirectiveName(DKind)
8557               << getOpenMPClauseName(PredeterminedCKind);
8558           if (DVar.RefExpr == nullptr)
8559             DVar.CKind = PredeterminedCKind;
8560           reportOriginalDsa(*this, DSAStack, D, DVar,
8561                             /*IsLoopIterVar=*/true);
8562         } else if (LoopDeclRefExpr) {
8563           // Make the loop iteration variable private (for worksharing
8564           // constructs), linear (for simd directives with the only one
8565           // associated loop) or lastprivate (for simd directives with several
8566           // collapsed or ordered loops).
8567           if (DVar.CKind == OMPC_unknown)
8568             DSAStack->addDSA(D, LoopDeclRefExpr, PredeterminedCKind,
8569                              PrivateRef);
8570         }
8571       }
8572     }
8573     DSAStack->setAssociatedLoops(AssociatedLoops - 1);
8574   }
8575 }
8576 
8577 /// Called on a for stmt to check and extract its iteration space
8578 /// for further processing (such as collapsing).
8579 static bool checkOpenMPIterationSpace(
8580     OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA,
8581     unsigned CurrentNestedLoopCount, unsigned NestedLoopCount,
8582     unsigned TotalNestedLoopCount, Expr *CollapseLoopCountExpr,
8583     Expr *OrderedLoopCountExpr,
8584     Sema::VarsWithInheritedDSAType &VarsWithImplicitDSA,
8585     llvm::MutableArrayRef<LoopIterationSpace> ResultIterSpaces,
8586     llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
8587   bool SupportsNonRectangular = !isOpenMPLoopTransformationDirective(DKind);
8588   // OpenMP [2.9.1, Canonical Loop Form]
8589   //   for (init-expr; test-expr; incr-expr) structured-block
8590   //   for (range-decl: range-expr) structured-block
8591   if (auto *CanonLoop = dyn_cast_or_null<OMPCanonicalLoop>(S))
8592     S = CanonLoop->getLoopStmt();
8593   auto *For = dyn_cast_or_null<ForStmt>(S);
8594   auto *CXXFor = dyn_cast_or_null<CXXForRangeStmt>(S);
8595   // Ranged for is supported only in OpenMP 5.0.
8596   if (!For && (SemaRef.LangOpts.OpenMP <= 45 || !CXXFor)) {
8597     SemaRef.Diag(S->getBeginLoc(), diag::err_omp_not_for)
8598         << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr)
8599         << getOpenMPDirectiveName(DKind) << TotalNestedLoopCount
8600         << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount;
8601     if (TotalNestedLoopCount > 1) {
8602       if (CollapseLoopCountExpr && OrderedLoopCountExpr)
8603         SemaRef.Diag(DSA.getConstructLoc(),
8604                      diag::note_omp_collapse_ordered_expr)
8605             << 2 << CollapseLoopCountExpr->getSourceRange()
8606             << OrderedLoopCountExpr->getSourceRange();
8607       else if (CollapseLoopCountExpr)
8608         SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
8609                      diag::note_omp_collapse_ordered_expr)
8610             << 0 << CollapseLoopCountExpr->getSourceRange();
8611       else
8612         SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
8613                      diag::note_omp_collapse_ordered_expr)
8614             << 1 << OrderedLoopCountExpr->getSourceRange();
8615     }
8616     return true;
8617   }
8618   assert(((For && For->getBody()) || (CXXFor && CXXFor->getBody())) &&
8619          "No loop body.");
8620 
8621   OpenMPIterationSpaceChecker ISC(SemaRef, SupportsNonRectangular, DSA,
8622                                   For ? For->getForLoc() : CXXFor->getForLoc());
8623 
8624   // Check init.
8625   Stmt *Init = For ? For->getInit() : CXXFor->getBeginStmt();
8626   if (ISC.checkAndSetInit(Init))
8627     return true;
8628 
8629   bool HasErrors = false;
8630 
8631   // Check loop variable's type.
8632   if (ValueDecl *LCDecl = ISC.getLoopDecl()) {
8633     // OpenMP [2.6, Canonical Loop Form]
8634     // Var is one of the following:
8635     //   A variable of signed or unsigned integer type.
8636     //   For C++, a variable of a random access iterator type.
8637     //   For C, a variable of a pointer type.
8638     QualType VarType = LCDecl->getType().getNonReferenceType();
8639     if (!VarType->isDependentType() && !VarType->isIntegerType() &&
8640         !VarType->isPointerType() &&
8641         !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) {
8642       SemaRef.Diag(Init->getBeginLoc(), diag::err_omp_loop_variable_type)
8643           << SemaRef.getLangOpts().CPlusPlus;
8644       HasErrors = true;
8645     }
8646 
8647     // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in
8648     // a Construct
8649     // The loop iteration variable(s) in the associated for-loop(s) of a for or
8650     // parallel for construct is (are) private.
8651     // The loop iteration variable in the associated for-loop of a simd
8652     // construct with just one associated for-loop is linear with a
8653     // constant-linear-step that is the increment of the associated for-loop.
8654     // Exclude loop var from the list of variables with implicitly defined data
8655     // sharing attributes.
8656     VarsWithImplicitDSA.erase(LCDecl);
8657 
8658     assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars");
8659 
8660     // Check test-expr.
8661     HasErrors |= ISC.checkAndSetCond(For ? For->getCond() : CXXFor->getCond());
8662 
8663     // Check incr-expr.
8664     HasErrors |= ISC.checkAndSetInc(For ? For->getInc() : CXXFor->getInc());
8665   }
8666 
8667   if (ISC.dependent() || SemaRef.CurContext->isDependentContext() || HasErrors)
8668     return HasErrors;
8669 
8670   // Build the loop's iteration space representation.
8671   ResultIterSpaces[CurrentNestedLoopCount].PreCond = ISC.buildPreCond(
8672       DSA.getCurScope(), For ? For->getCond() : CXXFor->getCond(), Captures);
8673   ResultIterSpaces[CurrentNestedLoopCount].NumIterations =
8674       ISC.buildNumIterations(DSA.getCurScope(), ResultIterSpaces,
8675                              (isOpenMPWorksharingDirective(DKind) ||
8676                               isOpenMPTaskLoopDirective(DKind) ||
8677                               isOpenMPDistributeDirective(DKind) ||
8678                               isOpenMPLoopTransformationDirective(DKind)),
8679                              Captures);
8680   ResultIterSpaces[CurrentNestedLoopCount].CounterVar =
8681       ISC.buildCounterVar(Captures, DSA);
8682   ResultIterSpaces[CurrentNestedLoopCount].PrivateCounterVar =
8683       ISC.buildPrivateCounterVar();
8684   ResultIterSpaces[CurrentNestedLoopCount].CounterInit = ISC.buildCounterInit();
8685   ResultIterSpaces[CurrentNestedLoopCount].CounterStep = ISC.buildCounterStep();
8686   ResultIterSpaces[CurrentNestedLoopCount].InitSrcRange = ISC.getInitSrcRange();
8687   ResultIterSpaces[CurrentNestedLoopCount].CondSrcRange =
8688       ISC.getConditionSrcRange();
8689   ResultIterSpaces[CurrentNestedLoopCount].IncSrcRange =
8690       ISC.getIncrementSrcRange();
8691   ResultIterSpaces[CurrentNestedLoopCount].Subtract = ISC.shouldSubtractStep();
8692   ResultIterSpaces[CurrentNestedLoopCount].IsStrictCompare =
8693       ISC.isStrictTestOp();
8694   std::tie(ResultIterSpaces[CurrentNestedLoopCount].MinValue,
8695            ResultIterSpaces[CurrentNestedLoopCount].MaxValue) =
8696       ISC.buildMinMaxValues(DSA.getCurScope(), Captures);
8697   ResultIterSpaces[CurrentNestedLoopCount].FinalCondition =
8698       ISC.buildFinalCondition(DSA.getCurScope());
8699   ResultIterSpaces[CurrentNestedLoopCount].IsNonRectangularLB =
8700       ISC.doesInitDependOnLC();
8701   ResultIterSpaces[CurrentNestedLoopCount].IsNonRectangularUB =
8702       ISC.doesCondDependOnLC();
8703   ResultIterSpaces[CurrentNestedLoopCount].LoopDependentIdx =
8704       ISC.getLoopDependentIdx();
8705 
8706   HasErrors |=
8707       (ResultIterSpaces[CurrentNestedLoopCount].PreCond == nullptr ||
8708        ResultIterSpaces[CurrentNestedLoopCount].NumIterations == nullptr ||
8709        ResultIterSpaces[CurrentNestedLoopCount].CounterVar == nullptr ||
8710        ResultIterSpaces[CurrentNestedLoopCount].PrivateCounterVar == nullptr ||
8711        ResultIterSpaces[CurrentNestedLoopCount].CounterInit == nullptr ||
8712        ResultIterSpaces[CurrentNestedLoopCount].CounterStep == nullptr);
8713   if (!HasErrors && DSA.isOrderedRegion()) {
8714     if (DSA.getOrderedRegionParam().second->getNumForLoops()) {
8715       if (CurrentNestedLoopCount <
8716           DSA.getOrderedRegionParam().second->getLoopNumIterations().size()) {
8717         DSA.getOrderedRegionParam().second->setLoopNumIterations(
8718             CurrentNestedLoopCount,
8719             ResultIterSpaces[CurrentNestedLoopCount].NumIterations);
8720         DSA.getOrderedRegionParam().second->setLoopCounter(
8721             CurrentNestedLoopCount,
8722             ResultIterSpaces[CurrentNestedLoopCount].CounterVar);
8723       }
8724     }
8725     for (auto &Pair : DSA.getDoacrossDependClauses()) {
8726       if (CurrentNestedLoopCount >= Pair.first->getNumLoops()) {
8727         // Erroneous case - clause has some problems.
8728         continue;
8729       }
8730       if (Pair.first->getDependencyKind() == OMPC_DEPEND_sink &&
8731           Pair.second.size() <= CurrentNestedLoopCount) {
8732         // Erroneous case - clause has some problems.
8733         Pair.first->setLoopData(CurrentNestedLoopCount, nullptr);
8734         continue;
8735       }
8736       Expr *CntValue;
8737       if (Pair.first->getDependencyKind() == OMPC_DEPEND_source)
8738         CntValue = ISC.buildOrderedLoopData(
8739             DSA.getCurScope(),
8740             ResultIterSpaces[CurrentNestedLoopCount].CounterVar, Captures,
8741             Pair.first->getDependencyLoc());
8742       else
8743         CntValue = ISC.buildOrderedLoopData(
8744             DSA.getCurScope(),
8745             ResultIterSpaces[CurrentNestedLoopCount].CounterVar, Captures,
8746             Pair.first->getDependencyLoc(),
8747             Pair.second[CurrentNestedLoopCount].first,
8748             Pair.second[CurrentNestedLoopCount].second);
8749       Pair.first->setLoopData(CurrentNestedLoopCount, CntValue);
8750     }
8751   }
8752 
8753   return HasErrors;
8754 }
8755 
8756 /// Build 'VarRef = Start.
8757 static ExprResult
8758 buildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
8759                  ExprResult Start, bool IsNonRectangularLB,
8760                  llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
8761   // Build 'VarRef = Start.
8762   ExprResult NewStart = IsNonRectangularLB
8763                             ? Start.get()
8764                             : tryBuildCapture(SemaRef, Start.get(), Captures);
8765   if (!NewStart.isUsable())
8766     return ExprError();
8767   if (!SemaRef.Context.hasSameType(NewStart.get()->getType(),
8768                                    VarRef.get()->getType())) {
8769     NewStart = SemaRef.PerformImplicitConversion(
8770         NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting,
8771         /*AllowExplicit=*/true);
8772     if (!NewStart.isUsable())
8773       return ExprError();
8774   }
8775 
8776   ExprResult Init =
8777       SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
8778   return Init;
8779 }
8780 
8781 /// Build 'VarRef = Start + Iter * Step'.
8782 static ExprResult buildCounterUpdate(
8783     Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
8784     ExprResult Start, ExprResult Iter, ExprResult Step, bool Subtract,
8785     bool IsNonRectangularLB,
8786     llvm::MapVector<const Expr *, DeclRefExpr *> *Captures = nullptr) {
8787   // Add parentheses (for debugging purposes only).
8788   Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get());
8789   if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() ||
8790       !Step.isUsable())
8791     return ExprError();
8792 
8793   ExprResult NewStep = Step;
8794   if (Captures)
8795     NewStep = tryBuildCapture(SemaRef, Step.get(), *Captures);
8796   if (NewStep.isInvalid())
8797     return ExprError();
8798   ExprResult Update =
8799       SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get());
8800   if (!Update.isUsable())
8801     return ExprError();
8802 
8803   // Try to build 'VarRef = Start, VarRef (+|-)= Iter * Step' or
8804   // 'VarRef = Start (+|-) Iter * Step'.
8805   if (!Start.isUsable())
8806     return ExprError();
8807   ExprResult NewStart = SemaRef.ActOnParenExpr(Loc, Loc, Start.get());
8808   if (!NewStart.isUsable())
8809     return ExprError();
8810   if (Captures && !IsNonRectangularLB)
8811     NewStart = tryBuildCapture(SemaRef, Start.get(), *Captures);
8812   if (NewStart.isInvalid())
8813     return ExprError();
8814 
8815   // First attempt: try to build 'VarRef = Start, VarRef += Iter * Step'.
8816   ExprResult SavedUpdate = Update;
8817   ExprResult UpdateVal;
8818   if (VarRef.get()->getType()->isOverloadableType() ||
8819       NewStart.get()->getType()->isOverloadableType() ||
8820       Update.get()->getType()->isOverloadableType()) {
8821     Sema::TentativeAnalysisScope Trap(SemaRef);
8822 
8823     Update =
8824         SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
8825     if (Update.isUsable()) {
8826       UpdateVal =
8827           SemaRef.BuildBinOp(S, Loc, Subtract ? BO_SubAssign : BO_AddAssign,
8828                              VarRef.get(), SavedUpdate.get());
8829       if (UpdateVal.isUsable()) {
8830         Update = SemaRef.CreateBuiltinBinOp(Loc, BO_Comma, Update.get(),
8831                                             UpdateVal.get());
8832       }
8833     }
8834   }
8835 
8836   // Second attempt: try to build 'VarRef = Start (+|-) Iter * Step'.
8837   if (!Update.isUsable() || !UpdateVal.isUsable()) {
8838     Update = SemaRef.BuildBinOp(S, Loc, Subtract ? BO_Sub : BO_Add,
8839                                 NewStart.get(), SavedUpdate.get());
8840     if (!Update.isUsable())
8841       return ExprError();
8842 
8843     if (!SemaRef.Context.hasSameType(Update.get()->getType(),
8844                                      VarRef.get()->getType())) {
8845       Update = SemaRef.PerformImplicitConversion(
8846           Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true);
8847       if (!Update.isUsable())
8848         return ExprError();
8849     }
8850 
8851     Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get());
8852   }
8853   return Update;
8854 }
8855 
8856 /// Convert integer expression \a E to make it have at least \a Bits
8857 /// bits.
8858 static ExprResult widenIterationCount(unsigned Bits, Expr *E, Sema &SemaRef) {
8859   if (E == nullptr)
8860     return ExprError();
8861   ASTContext &C = SemaRef.Context;
8862   QualType OldType = E->getType();
8863   unsigned HasBits = C.getTypeSize(OldType);
8864   if (HasBits >= Bits)
8865     return ExprResult(E);
8866   // OK to convert to signed, because new type has more bits than old.
8867   QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true);
8868   return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting,
8869                                            true);
8870 }
8871 
8872 /// Check if the given expression \a E is a constant integer that fits
8873 /// into \a Bits bits.
8874 static bool fitsInto(unsigned Bits, bool Signed, const Expr *E, Sema &SemaRef) {
8875   if (E == nullptr)
8876     return false;
8877   if (Optional<llvm::APSInt> Result =
8878           E->getIntegerConstantExpr(SemaRef.Context))
8879     return Signed ? Result->isSignedIntN(Bits) : Result->isIntN(Bits);
8880   return false;
8881 }
8882 
8883 /// Build preinits statement for the given declarations.
8884 static Stmt *buildPreInits(ASTContext &Context,
8885                            MutableArrayRef<Decl *> PreInits) {
8886   if (!PreInits.empty()) {
8887     return new (Context) DeclStmt(
8888         DeclGroupRef::Create(Context, PreInits.begin(), PreInits.size()),
8889         SourceLocation(), SourceLocation());
8890   }
8891   return nullptr;
8892 }
8893 
8894 /// Build preinits statement for the given declarations.
8895 static Stmt *
8896 buildPreInits(ASTContext &Context,
8897               const llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
8898   if (!Captures.empty()) {
8899     SmallVector<Decl *, 16> PreInits;
8900     for (const auto &Pair : Captures)
8901       PreInits.push_back(Pair.second->getDecl());
8902     return buildPreInits(Context, PreInits);
8903   }
8904   return nullptr;
8905 }
8906 
8907 /// Build postupdate expression for the given list of postupdates expressions.
8908 static Expr *buildPostUpdate(Sema &S, ArrayRef<Expr *> PostUpdates) {
8909   Expr *PostUpdate = nullptr;
8910   if (!PostUpdates.empty()) {
8911     for (Expr *E : PostUpdates) {
8912       Expr *ConvE = S.BuildCStyleCastExpr(
8913                          E->getExprLoc(),
8914                          S.Context.getTrivialTypeSourceInfo(S.Context.VoidTy),
8915                          E->getExprLoc(), E)
8916                         .get();
8917       PostUpdate = PostUpdate
8918                        ? S.CreateBuiltinBinOp(ConvE->getExprLoc(), BO_Comma,
8919                                               PostUpdate, ConvE)
8920                              .get()
8921                        : ConvE;
8922     }
8923   }
8924   return PostUpdate;
8925 }
8926 
8927 /// Called on a for stmt to check itself and nested loops (if any).
8928 /// \return Returns 0 if one of the collapsed stmts is not canonical for loop,
8929 /// number of collapsed loops otherwise.
8930 static unsigned
8931 checkOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr,
8932                 Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef,
8933                 DSAStackTy &DSA,
8934                 Sema::VarsWithInheritedDSAType &VarsWithImplicitDSA,
8935                 OMPLoopBasedDirective::HelperExprs &Built) {
8936   unsigned NestedLoopCount = 1;
8937   bool SupportsNonPerfectlyNested = (SemaRef.LangOpts.OpenMP >= 50) &&
8938                                     !isOpenMPLoopTransformationDirective(DKind);
8939 
8940   if (CollapseLoopCountExpr) {
8941     // Found 'collapse' clause - calculate collapse number.
8942     Expr::EvalResult Result;
8943     if (!CollapseLoopCountExpr->isValueDependent() &&
8944         CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext())) {
8945       NestedLoopCount = Result.Val.getInt().getLimitedValue();
8946     } else {
8947       Built.clear(/*Size=*/1);
8948       return 1;
8949     }
8950   }
8951   unsigned OrderedLoopCount = 1;
8952   if (OrderedLoopCountExpr) {
8953     // Found 'ordered' clause - calculate collapse number.
8954     Expr::EvalResult EVResult;
8955     if (!OrderedLoopCountExpr->isValueDependent() &&
8956         OrderedLoopCountExpr->EvaluateAsInt(EVResult,
8957                                             SemaRef.getASTContext())) {
8958       llvm::APSInt Result = EVResult.Val.getInt();
8959       if (Result.getLimitedValue() < NestedLoopCount) {
8960         SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
8961                      diag::err_omp_wrong_ordered_loop_count)
8962             << OrderedLoopCountExpr->getSourceRange();
8963         SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
8964                      diag::note_collapse_loop_count)
8965             << CollapseLoopCountExpr->getSourceRange();
8966       }
8967       OrderedLoopCount = Result.getLimitedValue();
8968     } else {
8969       Built.clear(/*Size=*/1);
8970       return 1;
8971     }
8972   }
8973   // This is helper routine for loop directives (e.g., 'for', 'simd',
8974   // 'for simd', etc.).
8975   llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
8976   unsigned NumLoops = std::max(OrderedLoopCount, NestedLoopCount);
8977   SmallVector<LoopIterationSpace, 4> IterSpaces(NumLoops);
8978   if (!OMPLoopBasedDirective::doForAllLoops(
8979           AStmt->IgnoreContainers(!isOpenMPLoopTransformationDirective(DKind)),
8980           SupportsNonPerfectlyNested, NumLoops,
8981           [DKind, &SemaRef, &DSA, NumLoops, NestedLoopCount,
8982            CollapseLoopCountExpr, OrderedLoopCountExpr, &VarsWithImplicitDSA,
8983            &IterSpaces, &Captures](unsigned Cnt, Stmt *CurStmt) {
8984             if (checkOpenMPIterationSpace(
8985                     DKind, CurStmt, SemaRef, DSA, Cnt, NestedLoopCount,
8986                     NumLoops, CollapseLoopCountExpr, OrderedLoopCountExpr,
8987                     VarsWithImplicitDSA, IterSpaces, Captures))
8988               return true;
8989             if (Cnt > 0 && Cnt >= NestedLoopCount &&
8990                 IterSpaces[Cnt].CounterVar) {
8991               // Handle initialization of captured loop iterator variables.
8992               auto *DRE = cast<DeclRefExpr>(IterSpaces[Cnt].CounterVar);
8993               if (isa<OMPCapturedExprDecl>(DRE->getDecl())) {
8994                 Captures[DRE] = DRE;
8995               }
8996             }
8997             return false;
8998           },
8999           [&SemaRef, &Captures](OMPLoopBasedDirective *Transform) {
9000             Stmt *DependentPreInits;
9001             if (auto *Dir = dyn_cast<OMPTileDirective>(Transform)) {
9002               DependentPreInits = Dir->getPreInits();
9003             } else if (auto *Dir = dyn_cast<OMPUnrollDirective>(Transform)) {
9004               DependentPreInits = Dir->getPreInits();
9005             } else {
9006               llvm_unreachable("Unexpected loop transformation");
9007             }
9008             if (!DependentPreInits)
9009               return;
9010             for (Decl *C : cast<DeclStmt>(DependentPreInits)->getDeclGroup()) {
9011               auto *D = cast<VarDecl>(C);
9012               DeclRefExpr *Ref = buildDeclRefExpr(SemaRef, D, D->getType(),
9013                                                   Transform->getBeginLoc());
9014               Captures[Ref] = Ref;
9015             }
9016           }))
9017     return 0;
9018 
9019   Built.clear(/* size */ NestedLoopCount);
9020 
9021   if (SemaRef.CurContext->isDependentContext())
9022     return NestedLoopCount;
9023 
9024   // An example of what is generated for the following code:
9025   //
9026   //   #pragma omp simd collapse(2) ordered(2)
9027   //   for (i = 0; i < NI; ++i)
9028   //     for (k = 0; k < NK; ++k)
9029   //       for (j = J0; j < NJ; j+=2) {
9030   //         <loop body>
9031   //       }
9032   //
9033   // We generate the code below.
9034   // Note: the loop body may be outlined in CodeGen.
9035   // Note: some counters may be C++ classes, operator- is used to find number of
9036   // iterations and operator+= to calculate counter value.
9037   // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32
9038   // or i64 is currently supported).
9039   //
9040   //   #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2))
9041   //   for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) {
9042   //     .local.i = IV / ((NJ - J0 - 1 + 2) / 2);
9043   //     .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2;
9044   //     // similar updates for vars in clauses (e.g. 'linear')
9045   //     <loop body (using local i and j)>
9046   //   }
9047   //   i = NI; // assign final values of counters
9048   //   j = NJ;
9049   //
9050 
9051   // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are
9052   // the iteration counts of the collapsed for loops.
9053   // Precondition tests if there is at least one iteration (all conditions are
9054   // true).
9055   auto PreCond = ExprResult(IterSpaces[0].PreCond);
9056   Expr *N0 = IterSpaces[0].NumIterations;
9057   ExprResult LastIteration32 =
9058       widenIterationCount(/*Bits=*/32,
9059                           SemaRef
9060                               .PerformImplicitConversion(
9061                                   N0->IgnoreImpCasts(), N0->getType(),
9062                                   Sema::AA_Converting, /*AllowExplicit=*/true)
9063                               .get(),
9064                           SemaRef);
9065   ExprResult LastIteration64 = widenIterationCount(
9066       /*Bits=*/64,
9067       SemaRef
9068           .PerformImplicitConversion(N0->IgnoreImpCasts(), N0->getType(),
9069                                      Sema::AA_Converting,
9070                                      /*AllowExplicit=*/true)
9071           .get(),
9072       SemaRef);
9073 
9074   if (!LastIteration32.isUsable() || !LastIteration64.isUsable())
9075     return NestedLoopCount;
9076 
9077   ASTContext &C = SemaRef.Context;
9078   bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32;
9079 
9080   Scope *CurScope = DSA.getCurScope();
9081   for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) {
9082     if (PreCond.isUsable()) {
9083       PreCond =
9084           SemaRef.BuildBinOp(CurScope, PreCond.get()->getExprLoc(), BO_LAnd,
9085                              PreCond.get(), IterSpaces[Cnt].PreCond);
9086     }
9087     Expr *N = IterSpaces[Cnt].NumIterations;
9088     SourceLocation Loc = N->getExprLoc();
9089     AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32;
9090     if (LastIteration32.isUsable())
9091       LastIteration32 = SemaRef.BuildBinOp(
9092           CurScope, Loc, BO_Mul, LastIteration32.get(),
9093           SemaRef
9094               .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
9095                                          Sema::AA_Converting,
9096                                          /*AllowExplicit=*/true)
9097               .get());
9098     if (LastIteration64.isUsable())
9099       LastIteration64 = SemaRef.BuildBinOp(
9100           CurScope, Loc, BO_Mul, LastIteration64.get(),
9101           SemaRef
9102               .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
9103                                          Sema::AA_Converting,
9104                                          /*AllowExplicit=*/true)
9105               .get());
9106   }
9107 
9108   // Choose either the 32-bit or 64-bit version.
9109   ExprResult LastIteration = LastIteration64;
9110   if (SemaRef.getLangOpts().OpenMPOptimisticCollapse ||
9111       (LastIteration32.isUsable() &&
9112        C.getTypeSize(LastIteration32.get()->getType()) == 32 &&
9113        (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 ||
9114         fitsInto(
9115             /*Bits=*/32,
9116             LastIteration32.get()->getType()->hasSignedIntegerRepresentation(),
9117             LastIteration64.get(), SemaRef))))
9118     LastIteration = LastIteration32;
9119   QualType VType = LastIteration.get()->getType();
9120   QualType RealVType = VType;
9121   QualType StrideVType = VType;
9122   if (isOpenMPTaskLoopDirective(DKind)) {
9123     VType =
9124         SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
9125     StrideVType =
9126         SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
9127   }
9128 
9129   if (!LastIteration.isUsable())
9130     return 0;
9131 
9132   // Save the number of iterations.
9133   ExprResult NumIterations = LastIteration;
9134   {
9135     LastIteration = SemaRef.BuildBinOp(
9136         CurScope, LastIteration.get()->getExprLoc(), BO_Sub,
9137         LastIteration.get(),
9138         SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
9139     if (!LastIteration.isUsable())
9140       return 0;
9141   }
9142 
9143   // Calculate the last iteration number beforehand instead of doing this on
9144   // each iteration. Do not do this if the number of iterations may be kfold-ed.
9145   bool IsConstant = LastIteration.get()->isIntegerConstantExpr(SemaRef.Context);
9146   ExprResult CalcLastIteration;
9147   if (!IsConstant) {
9148     ExprResult SaveRef =
9149         tryBuildCapture(SemaRef, LastIteration.get(), Captures);
9150     LastIteration = SaveRef;
9151 
9152     // Prepare SaveRef + 1.
9153     NumIterations = SemaRef.BuildBinOp(
9154         CurScope, SaveRef.get()->getExprLoc(), BO_Add, SaveRef.get(),
9155         SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
9156     if (!NumIterations.isUsable())
9157       return 0;
9158   }
9159 
9160   SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin();
9161 
9162   // Build variables passed into runtime, necessary for worksharing directives.
9163   ExprResult LB, UB, IL, ST, EUB, CombLB, CombUB, PrevLB, PrevUB, CombEUB;
9164   if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
9165       isOpenMPDistributeDirective(DKind) ||
9166       isOpenMPLoopTransformationDirective(DKind)) {
9167     // Lower bound variable, initialized with zero.
9168     VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb");
9169     LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc);
9170     SemaRef.AddInitializerToDecl(LBDecl,
9171                                  SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
9172                                  /*DirectInit*/ false);
9173 
9174     // Upper bound variable, initialized with last iteration number.
9175     VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub");
9176     UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc);
9177     SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(),
9178                                  /*DirectInit*/ false);
9179 
9180     // A 32-bit variable-flag where runtime returns 1 for the last iteration.
9181     // This will be used to implement clause 'lastprivate'.
9182     QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true);
9183     VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last");
9184     IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc);
9185     SemaRef.AddInitializerToDecl(ILDecl,
9186                                  SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
9187                                  /*DirectInit*/ false);
9188 
9189     // Stride variable returned by runtime (we initialize it to 1 by default).
9190     VarDecl *STDecl =
9191         buildVarDecl(SemaRef, InitLoc, StrideVType, ".omp.stride");
9192     ST = buildDeclRefExpr(SemaRef, STDecl, StrideVType, InitLoc);
9193     SemaRef.AddInitializerToDecl(STDecl,
9194                                  SemaRef.ActOnIntegerConstant(InitLoc, 1).get(),
9195                                  /*DirectInit*/ false);
9196 
9197     // Build expression: UB = min(UB, LastIteration)
9198     // It is necessary for CodeGen of directives with static scheduling.
9199     ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT,
9200                                                 UB.get(), LastIteration.get());
9201     ExprResult CondOp = SemaRef.ActOnConditionalOp(
9202         LastIteration.get()->getExprLoc(), InitLoc, IsUBGreater.get(),
9203         LastIteration.get(), UB.get());
9204     EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(),
9205                              CondOp.get());
9206     EUB = SemaRef.ActOnFinishFullExpr(EUB.get(), /*DiscardedValue*/ false);
9207 
9208     // If we have a combined directive that combines 'distribute', 'for' or
9209     // 'simd' we need to be able to access the bounds of the schedule of the
9210     // enclosing region. E.g. in 'distribute parallel for' the bounds obtained
9211     // by scheduling 'distribute' have to be passed to the schedule of 'for'.
9212     if (isOpenMPLoopBoundSharingDirective(DKind)) {
9213       // Lower bound variable, initialized with zero.
9214       VarDecl *CombLBDecl =
9215           buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.lb");
9216       CombLB = buildDeclRefExpr(SemaRef, CombLBDecl, VType, InitLoc);
9217       SemaRef.AddInitializerToDecl(
9218           CombLBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
9219           /*DirectInit*/ false);
9220 
9221       // Upper bound variable, initialized with last iteration number.
9222       VarDecl *CombUBDecl =
9223           buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.ub");
9224       CombUB = buildDeclRefExpr(SemaRef, CombUBDecl, VType, InitLoc);
9225       SemaRef.AddInitializerToDecl(CombUBDecl, LastIteration.get(),
9226                                    /*DirectInit*/ false);
9227 
9228       ExprResult CombIsUBGreater = SemaRef.BuildBinOp(
9229           CurScope, InitLoc, BO_GT, CombUB.get(), LastIteration.get());
9230       ExprResult CombCondOp =
9231           SemaRef.ActOnConditionalOp(InitLoc, InitLoc, CombIsUBGreater.get(),
9232                                      LastIteration.get(), CombUB.get());
9233       CombEUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, CombUB.get(),
9234                                    CombCondOp.get());
9235       CombEUB =
9236           SemaRef.ActOnFinishFullExpr(CombEUB.get(), /*DiscardedValue*/ false);
9237 
9238       const CapturedDecl *CD = cast<CapturedStmt>(AStmt)->getCapturedDecl();
9239       // We expect to have at least 2 more parameters than the 'parallel'
9240       // directive does - the lower and upper bounds of the previous schedule.
9241       assert(CD->getNumParams() >= 4 &&
9242              "Unexpected number of parameters in loop combined directive");
9243 
9244       // Set the proper type for the bounds given what we learned from the
9245       // enclosed loops.
9246       ImplicitParamDecl *PrevLBDecl = CD->getParam(/*PrevLB=*/2);
9247       ImplicitParamDecl *PrevUBDecl = CD->getParam(/*PrevUB=*/3);
9248 
9249       // Previous lower and upper bounds are obtained from the region
9250       // parameters.
9251       PrevLB =
9252           buildDeclRefExpr(SemaRef, PrevLBDecl, PrevLBDecl->getType(), InitLoc);
9253       PrevUB =
9254           buildDeclRefExpr(SemaRef, PrevUBDecl, PrevUBDecl->getType(), InitLoc);
9255     }
9256   }
9257 
9258   // Build the iteration variable and its initialization before loop.
9259   ExprResult IV;
9260   ExprResult Init, CombInit;
9261   {
9262     VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, RealVType, ".omp.iv");
9263     IV = buildDeclRefExpr(SemaRef, IVDecl, RealVType, InitLoc);
9264     Expr *RHS = (isOpenMPWorksharingDirective(DKind) ||
9265                  isOpenMPTaskLoopDirective(DKind) ||
9266                  isOpenMPDistributeDirective(DKind) ||
9267                  isOpenMPLoopTransformationDirective(DKind))
9268                     ? LB.get()
9269                     : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
9270     Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS);
9271     Init = SemaRef.ActOnFinishFullExpr(Init.get(), /*DiscardedValue*/ false);
9272 
9273     if (isOpenMPLoopBoundSharingDirective(DKind)) {
9274       Expr *CombRHS =
9275           (isOpenMPWorksharingDirective(DKind) ||
9276            isOpenMPTaskLoopDirective(DKind) ||
9277            isOpenMPDistributeDirective(DKind))
9278               ? CombLB.get()
9279               : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
9280       CombInit =
9281           SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), CombRHS);
9282       CombInit =
9283           SemaRef.ActOnFinishFullExpr(CombInit.get(), /*DiscardedValue*/ false);
9284     }
9285   }
9286 
9287   bool UseStrictCompare =
9288       RealVType->hasUnsignedIntegerRepresentation() &&
9289       llvm::all_of(IterSpaces, [](const LoopIterationSpace &LIS) {
9290         return LIS.IsStrictCompare;
9291       });
9292   // Loop condition (IV < NumIterations) or (IV <= UB or IV < UB + 1 (for
9293   // unsigned IV)) for worksharing loops.
9294   SourceLocation CondLoc = AStmt->getBeginLoc();
9295   Expr *BoundUB = UB.get();
9296   if (UseStrictCompare) {
9297     BoundUB =
9298         SemaRef
9299             .BuildBinOp(CurScope, CondLoc, BO_Add, BoundUB,
9300                         SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
9301             .get();
9302     BoundUB =
9303         SemaRef.ActOnFinishFullExpr(BoundUB, /*DiscardedValue*/ false).get();
9304   }
9305   ExprResult Cond =
9306       (isOpenMPWorksharingDirective(DKind) ||
9307        isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind) ||
9308        isOpenMPLoopTransformationDirective(DKind))
9309           ? SemaRef.BuildBinOp(CurScope, CondLoc,
9310                                UseStrictCompare ? BO_LT : BO_LE, IV.get(),
9311                                BoundUB)
9312           : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
9313                                NumIterations.get());
9314   ExprResult CombDistCond;
9315   if (isOpenMPLoopBoundSharingDirective(DKind)) {
9316     CombDistCond = SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
9317                                       NumIterations.get());
9318   }
9319 
9320   ExprResult CombCond;
9321   if (isOpenMPLoopBoundSharingDirective(DKind)) {
9322     Expr *BoundCombUB = CombUB.get();
9323     if (UseStrictCompare) {
9324       BoundCombUB =
9325           SemaRef
9326               .BuildBinOp(
9327                   CurScope, CondLoc, BO_Add, BoundCombUB,
9328                   SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
9329               .get();
9330       BoundCombUB =
9331           SemaRef.ActOnFinishFullExpr(BoundCombUB, /*DiscardedValue*/ false)
9332               .get();
9333     }
9334     CombCond =
9335         SemaRef.BuildBinOp(CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE,
9336                            IV.get(), BoundCombUB);
9337   }
9338   // Loop increment (IV = IV + 1)
9339   SourceLocation IncLoc = AStmt->getBeginLoc();
9340   ExprResult Inc =
9341       SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(),
9342                          SemaRef.ActOnIntegerConstant(IncLoc, 1).get());
9343   if (!Inc.isUsable())
9344     return 0;
9345   Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get());
9346   Inc = SemaRef.ActOnFinishFullExpr(Inc.get(), /*DiscardedValue*/ false);
9347   if (!Inc.isUsable())
9348     return 0;
9349 
9350   // Increments for worksharing loops (LB = LB + ST; UB = UB + ST).
9351   // Used for directives with static scheduling.
9352   // In combined construct, add combined version that use CombLB and CombUB
9353   // base variables for the update
9354   ExprResult NextLB, NextUB, CombNextLB, CombNextUB;
9355   if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
9356       isOpenMPDistributeDirective(DKind) ||
9357       isOpenMPLoopTransformationDirective(DKind)) {
9358     // LB + ST
9359     NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get());
9360     if (!NextLB.isUsable())
9361       return 0;
9362     // LB = LB + ST
9363     NextLB =
9364         SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get());
9365     NextLB =
9366         SemaRef.ActOnFinishFullExpr(NextLB.get(), /*DiscardedValue*/ false);
9367     if (!NextLB.isUsable())
9368       return 0;
9369     // UB + ST
9370     NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get());
9371     if (!NextUB.isUsable())
9372       return 0;
9373     // UB = UB + ST
9374     NextUB =
9375         SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get());
9376     NextUB =
9377         SemaRef.ActOnFinishFullExpr(NextUB.get(), /*DiscardedValue*/ false);
9378     if (!NextUB.isUsable())
9379       return 0;
9380     if (isOpenMPLoopBoundSharingDirective(DKind)) {
9381       CombNextLB =
9382           SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombLB.get(), ST.get());
9383       if (!NextLB.isUsable())
9384         return 0;
9385       // LB = LB + ST
9386       CombNextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombLB.get(),
9387                                       CombNextLB.get());
9388       CombNextLB = SemaRef.ActOnFinishFullExpr(CombNextLB.get(),
9389                                                /*DiscardedValue*/ false);
9390       if (!CombNextLB.isUsable())
9391         return 0;
9392       // UB + ST
9393       CombNextUB =
9394           SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombUB.get(), ST.get());
9395       if (!CombNextUB.isUsable())
9396         return 0;
9397       // UB = UB + ST
9398       CombNextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombUB.get(),
9399                                       CombNextUB.get());
9400       CombNextUB = SemaRef.ActOnFinishFullExpr(CombNextUB.get(),
9401                                                /*DiscardedValue*/ false);
9402       if (!CombNextUB.isUsable())
9403         return 0;
9404     }
9405   }
9406 
9407   // Create increment expression for distribute loop when combined in a same
9408   // directive with for as IV = IV + ST; ensure upper bound expression based
9409   // on PrevUB instead of NumIterations - used to implement 'for' when found
9410   // in combination with 'distribute', like in 'distribute parallel for'
9411   SourceLocation DistIncLoc = AStmt->getBeginLoc();
9412   ExprResult DistCond, DistInc, PrevEUB, ParForInDistCond;
9413   if (isOpenMPLoopBoundSharingDirective(DKind)) {
9414     DistCond = SemaRef.BuildBinOp(
9415         CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE, IV.get(), BoundUB);
9416     assert(DistCond.isUsable() && "distribute cond expr was not built");
9417 
9418     DistInc =
9419         SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Add, IV.get(), ST.get());
9420     assert(DistInc.isUsable() && "distribute inc expr was not built");
9421     DistInc = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, IV.get(),
9422                                  DistInc.get());
9423     DistInc =
9424         SemaRef.ActOnFinishFullExpr(DistInc.get(), /*DiscardedValue*/ false);
9425     assert(DistInc.isUsable() && "distribute inc expr was not built");
9426 
9427     // Build expression: UB = min(UB, prevUB) for #for in composite or combined
9428     // construct
9429     ExprResult NewPrevUB = PrevUB;
9430     SourceLocation DistEUBLoc = AStmt->getBeginLoc();
9431     if (!SemaRef.Context.hasSameType(UB.get()->getType(),
9432                                      PrevUB.get()->getType())) {
9433       NewPrevUB = SemaRef.BuildCStyleCastExpr(
9434           DistEUBLoc,
9435           SemaRef.Context.getTrivialTypeSourceInfo(UB.get()->getType()),
9436           DistEUBLoc, NewPrevUB.get());
9437       if (!NewPrevUB.isUsable())
9438         return 0;
9439     }
9440     ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, DistEUBLoc, BO_GT,
9441                                                 UB.get(), NewPrevUB.get());
9442     ExprResult CondOp = SemaRef.ActOnConditionalOp(
9443         DistEUBLoc, DistEUBLoc, IsUBGreater.get(), NewPrevUB.get(), UB.get());
9444     PrevEUB = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, UB.get(),
9445                                  CondOp.get());
9446     PrevEUB =
9447         SemaRef.ActOnFinishFullExpr(PrevEUB.get(), /*DiscardedValue*/ false);
9448 
9449     // Build IV <= PrevUB or IV < PrevUB + 1 for unsigned IV to be used in
9450     // parallel for is in combination with a distribute directive with
9451     // schedule(static, 1)
9452     Expr *BoundPrevUB = PrevUB.get();
9453     if (UseStrictCompare) {
9454       BoundPrevUB =
9455           SemaRef
9456               .BuildBinOp(
9457                   CurScope, CondLoc, BO_Add, BoundPrevUB,
9458                   SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
9459               .get();
9460       BoundPrevUB =
9461           SemaRef.ActOnFinishFullExpr(BoundPrevUB, /*DiscardedValue*/ false)
9462               .get();
9463     }
9464     ParForInDistCond =
9465         SemaRef.BuildBinOp(CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE,
9466                            IV.get(), BoundPrevUB);
9467   }
9468 
9469   // Build updates and final values of the loop counters.
9470   bool HasErrors = false;
9471   Built.Counters.resize(NestedLoopCount);
9472   Built.Inits.resize(NestedLoopCount);
9473   Built.Updates.resize(NestedLoopCount);
9474   Built.Finals.resize(NestedLoopCount);
9475   Built.DependentCounters.resize(NestedLoopCount);
9476   Built.DependentInits.resize(NestedLoopCount);
9477   Built.FinalsConditions.resize(NestedLoopCount);
9478   {
9479     // We implement the following algorithm for obtaining the
9480     // original loop iteration variable values based on the
9481     // value of the collapsed loop iteration variable IV.
9482     //
9483     // Let n+1 be the number of collapsed loops in the nest.
9484     // Iteration variables (I0, I1, .... In)
9485     // Iteration counts (N0, N1, ... Nn)
9486     //
9487     // Acc = IV;
9488     //
9489     // To compute Ik for loop k, 0 <= k <= n, generate:
9490     //    Prod = N(k+1) * N(k+2) * ... * Nn;
9491     //    Ik = Acc / Prod;
9492     //    Acc -= Ik * Prod;
9493     //
9494     ExprResult Acc = IV;
9495     for (unsigned int Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
9496       LoopIterationSpace &IS = IterSpaces[Cnt];
9497       SourceLocation UpdLoc = IS.IncSrcRange.getBegin();
9498       ExprResult Iter;
9499 
9500       // Compute prod
9501       ExprResult Prod =
9502           SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
9503       for (unsigned int K = Cnt+1; K < NestedLoopCount; ++K)
9504         Prod = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Prod.get(),
9505                                   IterSpaces[K].NumIterations);
9506 
9507       // Iter = Acc / Prod
9508       // If there is at least one more inner loop to avoid
9509       // multiplication by 1.
9510       if (Cnt + 1 < NestedLoopCount)
9511         Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div,
9512                                   Acc.get(), Prod.get());
9513       else
9514         Iter = Acc;
9515       if (!Iter.isUsable()) {
9516         HasErrors = true;
9517         break;
9518       }
9519 
9520       // Update Acc:
9521       // Acc -= Iter * Prod
9522       // Check if there is at least one more inner loop to avoid
9523       // multiplication by 1.
9524       if (Cnt + 1 < NestedLoopCount)
9525         Prod = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul,
9526                                   Iter.get(), Prod.get());
9527       else
9528         Prod = Iter;
9529       Acc = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Sub,
9530                                Acc.get(), Prod.get());
9531 
9532       // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step
9533       auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl());
9534       DeclRefExpr *CounterVar = buildDeclRefExpr(
9535           SemaRef, VD, IS.CounterVar->getType(), IS.CounterVar->getExprLoc(),
9536           /*RefersToCapture=*/true);
9537       ExprResult Init =
9538           buildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar,
9539                            IS.CounterInit, IS.IsNonRectangularLB, Captures);
9540       if (!Init.isUsable()) {
9541         HasErrors = true;
9542         break;
9543       }
9544       ExprResult Update = buildCounterUpdate(
9545           SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, Iter,
9546           IS.CounterStep, IS.Subtract, IS.IsNonRectangularLB, &Captures);
9547       if (!Update.isUsable()) {
9548         HasErrors = true;
9549         break;
9550       }
9551 
9552       // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step
9553       ExprResult Final =
9554           buildCounterUpdate(SemaRef, CurScope, UpdLoc, CounterVar,
9555                              IS.CounterInit, IS.NumIterations, IS.CounterStep,
9556                              IS.Subtract, IS.IsNonRectangularLB, &Captures);
9557       if (!Final.isUsable()) {
9558         HasErrors = true;
9559         break;
9560       }
9561 
9562       if (!Update.isUsable() || !Final.isUsable()) {
9563         HasErrors = true;
9564         break;
9565       }
9566       // Save results
9567       Built.Counters[Cnt] = IS.CounterVar;
9568       Built.PrivateCounters[Cnt] = IS.PrivateCounterVar;
9569       Built.Inits[Cnt] = Init.get();
9570       Built.Updates[Cnt] = Update.get();
9571       Built.Finals[Cnt] = Final.get();
9572       Built.DependentCounters[Cnt] = nullptr;
9573       Built.DependentInits[Cnt] = nullptr;
9574       Built.FinalsConditions[Cnt] = nullptr;
9575       if (IS.IsNonRectangularLB || IS.IsNonRectangularUB) {
9576         Built.DependentCounters[Cnt] =
9577             Built.Counters[NestedLoopCount - 1 - IS.LoopDependentIdx];
9578         Built.DependentInits[Cnt] =
9579             Built.Inits[NestedLoopCount - 1 - IS.LoopDependentIdx];
9580         Built.FinalsConditions[Cnt] = IS.FinalCondition;
9581       }
9582     }
9583   }
9584 
9585   if (HasErrors)
9586     return 0;
9587 
9588   // Save results
9589   Built.IterationVarRef = IV.get();
9590   Built.LastIteration = LastIteration.get();
9591   Built.NumIterations = NumIterations.get();
9592   Built.CalcLastIteration = SemaRef
9593                                 .ActOnFinishFullExpr(CalcLastIteration.get(),
9594                                                      /*DiscardedValue=*/false)
9595                                 .get();
9596   Built.PreCond = PreCond.get();
9597   Built.PreInits = buildPreInits(C, Captures);
9598   Built.Cond = Cond.get();
9599   Built.Init = Init.get();
9600   Built.Inc = Inc.get();
9601   Built.LB = LB.get();
9602   Built.UB = UB.get();
9603   Built.IL = IL.get();
9604   Built.ST = ST.get();
9605   Built.EUB = EUB.get();
9606   Built.NLB = NextLB.get();
9607   Built.NUB = NextUB.get();
9608   Built.PrevLB = PrevLB.get();
9609   Built.PrevUB = PrevUB.get();
9610   Built.DistInc = DistInc.get();
9611   Built.PrevEUB = PrevEUB.get();
9612   Built.DistCombinedFields.LB = CombLB.get();
9613   Built.DistCombinedFields.UB = CombUB.get();
9614   Built.DistCombinedFields.EUB = CombEUB.get();
9615   Built.DistCombinedFields.Init = CombInit.get();
9616   Built.DistCombinedFields.Cond = CombCond.get();
9617   Built.DistCombinedFields.NLB = CombNextLB.get();
9618   Built.DistCombinedFields.NUB = CombNextUB.get();
9619   Built.DistCombinedFields.DistCond = CombDistCond.get();
9620   Built.DistCombinedFields.ParForInDistCond = ParForInDistCond.get();
9621 
9622   return NestedLoopCount;
9623 }
9624 
9625 static Expr *getCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) {
9626   auto CollapseClauses =
9627       OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses);
9628   if (CollapseClauses.begin() != CollapseClauses.end())
9629     return (*CollapseClauses.begin())->getNumForLoops();
9630   return nullptr;
9631 }
9632 
9633 static Expr *getOrderedNumberExpr(ArrayRef<OMPClause *> Clauses) {
9634   auto OrderedClauses =
9635       OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses);
9636   if (OrderedClauses.begin() != OrderedClauses.end())
9637     return (*OrderedClauses.begin())->getNumForLoops();
9638   return nullptr;
9639 }
9640 
9641 static bool checkSimdlenSafelenSpecified(Sema &S,
9642                                          const ArrayRef<OMPClause *> Clauses) {
9643   const OMPSafelenClause *Safelen = nullptr;
9644   const OMPSimdlenClause *Simdlen = nullptr;
9645 
9646   for (const OMPClause *Clause : Clauses) {
9647     if (Clause->getClauseKind() == OMPC_safelen)
9648       Safelen = cast<OMPSafelenClause>(Clause);
9649     else if (Clause->getClauseKind() == OMPC_simdlen)
9650       Simdlen = cast<OMPSimdlenClause>(Clause);
9651     if (Safelen && Simdlen)
9652       break;
9653   }
9654 
9655   if (Simdlen && Safelen) {
9656     const Expr *SimdlenLength = Simdlen->getSimdlen();
9657     const Expr *SafelenLength = Safelen->getSafelen();
9658     if (SimdlenLength->isValueDependent() || SimdlenLength->isTypeDependent() ||
9659         SimdlenLength->isInstantiationDependent() ||
9660         SimdlenLength->containsUnexpandedParameterPack())
9661       return false;
9662     if (SafelenLength->isValueDependent() || SafelenLength->isTypeDependent() ||
9663         SafelenLength->isInstantiationDependent() ||
9664         SafelenLength->containsUnexpandedParameterPack())
9665       return false;
9666     Expr::EvalResult SimdlenResult, SafelenResult;
9667     SimdlenLength->EvaluateAsInt(SimdlenResult, S.Context);
9668     SafelenLength->EvaluateAsInt(SafelenResult, S.Context);
9669     llvm::APSInt SimdlenRes = SimdlenResult.Val.getInt();
9670     llvm::APSInt SafelenRes = SafelenResult.Val.getInt();
9671     // OpenMP 4.5 [2.8.1, simd Construct, Restrictions]
9672     // If both simdlen and safelen clauses are specified, the value of the
9673     // simdlen parameter must be less than or equal to the value of the safelen
9674     // parameter.
9675     if (SimdlenRes > SafelenRes) {
9676       S.Diag(SimdlenLength->getExprLoc(),
9677              diag::err_omp_wrong_simdlen_safelen_values)
9678           << SimdlenLength->getSourceRange() << SafelenLength->getSourceRange();
9679       return true;
9680     }
9681   }
9682   return false;
9683 }
9684 
9685 StmtResult
9686 Sema::ActOnOpenMPSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
9687                                SourceLocation StartLoc, SourceLocation EndLoc,
9688                                VarsWithInheritedDSAType &VarsWithImplicitDSA) {
9689   if (!AStmt)
9690     return StmtError();
9691 
9692   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
9693   OMPLoopBasedDirective::HelperExprs B;
9694   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
9695   // define the nested loops number.
9696   unsigned NestedLoopCount = checkOpenMPLoop(
9697       OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
9698       AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
9699   if (NestedLoopCount == 0)
9700     return StmtError();
9701 
9702   assert((CurContext->isDependentContext() || B.builtAll()) &&
9703          "omp simd loop exprs were not built");
9704 
9705   if (!CurContext->isDependentContext()) {
9706     // Finalize the clauses that need pre-built expressions for CodeGen.
9707     for (OMPClause *C : Clauses) {
9708       if (auto *LC = dyn_cast<OMPLinearClause>(C))
9709         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
9710                                      B.NumIterations, *this, CurScope,
9711                                      DSAStack))
9712           return StmtError();
9713     }
9714   }
9715 
9716   if (checkSimdlenSafelenSpecified(*this, Clauses))
9717     return StmtError();
9718 
9719   setFunctionHasBranchProtectedScope();
9720   return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
9721                                   Clauses, AStmt, B);
9722 }
9723 
9724 StmtResult
9725 Sema::ActOnOpenMPForDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
9726                               SourceLocation StartLoc, SourceLocation EndLoc,
9727                               VarsWithInheritedDSAType &VarsWithImplicitDSA) {
9728   if (!AStmt)
9729     return StmtError();
9730 
9731   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
9732   OMPLoopBasedDirective::HelperExprs B;
9733   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
9734   // define the nested loops number.
9735   unsigned NestedLoopCount = checkOpenMPLoop(
9736       OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
9737       AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
9738   if (NestedLoopCount == 0)
9739     return StmtError();
9740 
9741   assert((CurContext->isDependentContext() || B.builtAll()) &&
9742          "omp for loop exprs were not built");
9743 
9744   if (!CurContext->isDependentContext()) {
9745     // Finalize the clauses that need pre-built expressions for CodeGen.
9746     for (OMPClause *C : Clauses) {
9747       if (auto *LC = dyn_cast<OMPLinearClause>(C))
9748         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
9749                                      B.NumIterations, *this, CurScope,
9750                                      DSAStack))
9751           return StmtError();
9752     }
9753   }
9754 
9755   setFunctionHasBranchProtectedScope();
9756   return OMPForDirective::Create(
9757       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
9758       DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion());
9759 }
9760 
9761 StmtResult Sema::ActOnOpenMPForSimdDirective(
9762     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
9763     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
9764   if (!AStmt)
9765     return StmtError();
9766 
9767   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
9768   OMPLoopBasedDirective::HelperExprs B;
9769   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
9770   // define the nested loops number.
9771   unsigned NestedLoopCount =
9772       checkOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses),
9773                       getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
9774                       VarsWithImplicitDSA, B);
9775   if (NestedLoopCount == 0)
9776     return StmtError();
9777 
9778   assert((CurContext->isDependentContext() || B.builtAll()) &&
9779          "omp for simd loop exprs were not built");
9780 
9781   if (!CurContext->isDependentContext()) {
9782     // Finalize the clauses that need pre-built expressions for CodeGen.
9783     for (OMPClause *C : Clauses) {
9784       if (auto *LC = dyn_cast<OMPLinearClause>(C))
9785         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
9786                                      B.NumIterations, *this, CurScope,
9787                                      DSAStack))
9788           return StmtError();
9789     }
9790   }
9791 
9792   if (checkSimdlenSafelenSpecified(*this, Clauses))
9793     return StmtError();
9794 
9795   setFunctionHasBranchProtectedScope();
9796   return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
9797                                      Clauses, AStmt, B);
9798 }
9799 
9800 StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
9801                                               Stmt *AStmt,
9802                                               SourceLocation StartLoc,
9803                                               SourceLocation EndLoc) {
9804   if (!AStmt)
9805     return StmtError();
9806 
9807   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
9808   auto BaseStmt = AStmt;
9809   while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
9810     BaseStmt = CS->getCapturedStmt();
9811   if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
9812     auto S = C->children();
9813     if (S.begin() == S.end())
9814       return StmtError();
9815     // All associated statements must be '#pragma omp section' except for
9816     // the first one.
9817     for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
9818       if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
9819         if (SectionStmt)
9820           Diag(SectionStmt->getBeginLoc(),
9821                diag::err_omp_sections_substmt_not_section);
9822         return StmtError();
9823       }
9824       cast<OMPSectionDirective>(SectionStmt)
9825           ->setHasCancel(DSAStack->isCancelRegion());
9826     }
9827   } else {
9828     Diag(AStmt->getBeginLoc(), diag::err_omp_sections_not_compound_stmt);
9829     return StmtError();
9830   }
9831 
9832   setFunctionHasBranchProtectedScope();
9833 
9834   return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
9835                                       DSAStack->getTaskgroupReductionRef(),
9836                                       DSAStack->isCancelRegion());
9837 }
9838 
9839 StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt,
9840                                              SourceLocation StartLoc,
9841                                              SourceLocation EndLoc) {
9842   if (!AStmt)
9843     return StmtError();
9844 
9845   setFunctionHasBranchProtectedScope();
9846   DSAStack->setParentCancelRegion(DSAStack->isCancelRegion());
9847 
9848   return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt,
9849                                      DSAStack->isCancelRegion());
9850 }
9851 
9852 static Expr *getDirectCallExpr(Expr *E) {
9853   E = E->IgnoreParenCasts()->IgnoreImplicit();
9854   if (auto *CE = dyn_cast<CallExpr>(E))
9855     if (CE->getDirectCallee())
9856       return E;
9857   return nullptr;
9858 }
9859 
9860 StmtResult Sema::ActOnOpenMPDispatchDirective(ArrayRef<OMPClause *> Clauses,
9861                                               Stmt *AStmt,
9862                                               SourceLocation StartLoc,
9863                                               SourceLocation EndLoc) {
9864   if (!AStmt)
9865     return StmtError();
9866 
9867   Stmt *S = cast<CapturedStmt>(AStmt)->getCapturedStmt();
9868 
9869   // 5.1 OpenMP
9870   // expression-stmt : an expression statement with one of the following forms:
9871   //   expression = target-call ( [expression-list] );
9872   //   target-call ( [expression-list] );
9873 
9874   SourceLocation TargetCallLoc;
9875 
9876   if (!CurContext->isDependentContext()) {
9877     Expr *TargetCall = nullptr;
9878 
9879     auto *E = dyn_cast<Expr>(S);
9880     if (!E) {
9881       Diag(S->getBeginLoc(), diag::err_omp_dispatch_statement_call);
9882       return StmtError();
9883     }
9884 
9885     E = E->IgnoreParenCasts()->IgnoreImplicit();
9886 
9887     if (auto *BO = dyn_cast<BinaryOperator>(E)) {
9888       if (BO->getOpcode() == BO_Assign)
9889         TargetCall = getDirectCallExpr(BO->getRHS());
9890     } else {
9891       if (auto *COCE = dyn_cast<CXXOperatorCallExpr>(E))
9892         if (COCE->getOperator() == OO_Equal)
9893           TargetCall = getDirectCallExpr(COCE->getArg(1));
9894       if (!TargetCall)
9895         TargetCall = getDirectCallExpr(E);
9896     }
9897     if (!TargetCall) {
9898       Diag(E->getBeginLoc(), diag::err_omp_dispatch_statement_call);
9899       return StmtError();
9900     }
9901     TargetCallLoc = TargetCall->getExprLoc();
9902   }
9903 
9904   setFunctionHasBranchProtectedScope();
9905 
9906   return OMPDispatchDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
9907                                       TargetCallLoc);
9908 }
9909 
9910 StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
9911                                             Stmt *AStmt,
9912                                             SourceLocation StartLoc,
9913                                             SourceLocation EndLoc) {
9914   if (!AStmt)
9915     return StmtError();
9916 
9917   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
9918 
9919   setFunctionHasBranchProtectedScope();
9920 
9921   // OpenMP [2.7.3, single Construct, Restrictions]
9922   // The copyprivate clause must not be used with the nowait clause.
9923   const OMPClause *Nowait = nullptr;
9924   const OMPClause *Copyprivate = nullptr;
9925   for (const OMPClause *Clause : Clauses) {
9926     if (Clause->getClauseKind() == OMPC_nowait)
9927       Nowait = Clause;
9928     else if (Clause->getClauseKind() == OMPC_copyprivate)
9929       Copyprivate = Clause;
9930     if (Copyprivate && Nowait) {
9931       Diag(Copyprivate->getBeginLoc(),
9932            diag::err_omp_single_copyprivate_with_nowait);
9933       Diag(Nowait->getBeginLoc(), diag::note_omp_nowait_clause_here);
9934       return StmtError();
9935     }
9936   }
9937 
9938   return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
9939 }
9940 
9941 StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt,
9942                                             SourceLocation StartLoc,
9943                                             SourceLocation EndLoc) {
9944   if (!AStmt)
9945     return StmtError();
9946 
9947   setFunctionHasBranchProtectedScope();
9948 
9949   return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt);
9950 }
9951 
9952 StmtResult Sema::ActOnOpenMPMaskedDirective(ArrayRef<OMPClause *> Clauses,
9953                                             Stmt *AStmt,
9954                                             SourceLocation StartLoc,
9955                                             SourceLocation EndLoc) {
9956   if (!AStmt)
9957     return StmtError();
9958 
9959   setFunctionHasBranchProtectedScope();
9960 
9961   return OMPMaskedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
9962 }
9963 
9964 StmtResult Sema::ActOnOpenMPCriticalDirective(
9965     const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses,
9966     Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
9967   if (!AStmt)
9968     return StmtError();
9969 
9970   bool ErrorFound = false;
9971   llvm::APSInt Hint;
9972   SourceLocation HintLoc;
9973   bool DependentHint = false;
9974   for (const OMPClause *C : Clauses) {
9975     if (C->getClauseKind() == OMPC_hint) {
9976       if (!DirName.getName()) {
9977         Diag(C->getBeginLoc(), diag::err_omp_hint_clause_no_name);
9978         ErrorFound = true;
9979       }
9980       Expr *E = cast<OMPHintClause>(C)->getHint();
9981       if (E->isTypeDependent() || E->isValueDependent() ||
9982           E->isInstantiationDependent()) {
9983         DependentHint = true;
9984       } else {
9985         Hint = E->EvaluateKnownConstInt(Context);
9986         HintLoc = C->getBeginLoc();
9987       }
9988     }
9989   }
9990   if (ErrorFound)
9991     return StmtError();
9992   const auto Pair = DSAStack->getCriticalWithHint(DirName);
9993   if (Pair.first && DirName.getName() && !DependentHint) {
9994     if (llvm::APSInt::compareValues(Hint, Pair.second) != 0) {
9995       Diag(StartLoc, diag::err_omp_critical_with_hint);
9996       if (HintLoc.isValid())
9997         Diag(HintLoc, diag::note_omp_critical_hint_here)
9998             << 0 << toString(Hint, /*Radix=*/10, /*Signed=*/false);
9999       else
10000         Diag(StartLoc, diag::note_omp_critical_no_hint) << 0;
10001       if (const auto *C = Pair.first->getSingleClause<OMPHintClause>()) {
10002         Diag(C->getBeginLoc(), diag::note_omp_critical_hint_here)
10003             << 1
10004             << toString(C->getHint()->EvaluateKnownConstInt(Context),
10005                         /*Radix=*/10, /*Signed=*/false);
10006       } else {
10007         Diag(Pair.first->getBeginLoc(), diag::note_omp_critical_no_hint) << 1;
10008       }
10009     }
10010   }
10011 
10012   setFunctionHasBranchProtectedScope();
10013 
10014   auto *Dir = OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc,
10015                                            Clauses, AStmt);
10016   if (!Pair.first && DirName.getName() && !DependentHint)
10017     DSAStack->addCriticalWithHint(Dir, Hint);
10018   return Dir;
10019 }
10020 
10021 StmtResult Sema::ActOnOpenMPParallelForDirective(
10022     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10023     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
10024   if (!AStmt)
10025     return StmtError();
10026 
10027   auto *CS = cast<CapturedStmt>(AStmt);
10028   // 1.2.2 OpenMP Language Terminology
10029   // Structured block - An executable statement with a single entry at the
10030   // top and a single exit at the bottom.
10031   // The point of exit cannot be a branch out of the structured block.
10032   // longjmp() and throw() must not violate the entry/exit criteria.
10033   CS->getCapturedDecl()->setNothrow();
10034 
10035   OMPLoopBasedDirective::HelperExprs B;
10036   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
10037   // define the nested loops number.
10038   unsigned NestedLoopCount =
10039       checkOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses),
10040                       getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
10041                       VarsWithImplicitDSA, B);
10042   if (NestedLoopCount == 0)
10043     return StmtError();
10044 
10045   assert((CurContext->isDependentContext() || B.builtAll()) &&
10046          "omp parallel for loop exprs were not built");
10047 
10048   if (!CurContext->isDependentContext()) {
10049     // Finalize the clauses that need pre-built expressions for CodeGen.
10050     for (OMPClause *C : Clauses) {
10051       if (auto *LC = dyn_cast<OMPLinearClause>(C))
10052         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
10053                                      B.NumIterations, *this, CurScope,
10054                                      DSAStack))
10055           return StmtError();
10056     }
10057   }
10058 
10059   setFunctionHasBranchProtectedScope();
10060   return OMPParallelForDirective::Create(
10061       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
10062       DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion());
10063 }
10064 
10065 StmtResult Sema::ActOnOpenMPParallelForSimdDirective(
10066     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10067     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
10068   if (!AStmt)
10069     return StmtError();
10070 
10071   auto *CS = cast<CapturedStmt>(AStmt);
10072   // 1.2.2 OpenMP Language Terminology
10073   // Structured block - An executable statement with a single entry at the
10074   // top and a single exit at the bottom.
10075   // The point of exit cannot be a branch out of the structured block.
10076   // longjmp() and throw() must not violate the entry/exit criteria.
10077   CS->getCapturedDecl()->setNothrow();
10078 
10079   OMPLoopBasedDirective::HelperExprs B;
10080   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
10081   // define the nested loops number.
10082   unsigned NestedLoopCount =
10083       checkOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses),
10084                       getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
10085                       VarsWithImplicitDSA, B);
10086   if (NestedLoopCount == 0)
10087     return StmtError();
10088 
10089   if (!CurContext->isDependentContext()) {
10090     // Finalize the clauses that need pre-built expressions for CodeGen.
10091     for (OMPClause *C : Clauses) {
10092       if (auto *LC = dyn_cast<OMPLinearClause>(C))
10093         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
10094                                      B.NumIterations, *this, CurScope,
10095                                      DSAStack))
10096           return StmtError();
10097     }
10098   }
10099 
10100   if (checkSimdlenSafelenSpecified(*this, Clauses))
10101     return StmtError();
10102 
10103   setFunctionHasBranchProtectedScope();
10104   return OMPParallelForSimdDirective::Create(
10105       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
10106 }
10107 
10108 StmtResult
10109 Sema::ActOnOpenMPParallelMasterDirective(ArrayRef<OMPClause *> Clauses,
10110                                          Stmt *AStmt, SourceLocation StartLoc,
10111                                          SourceLocation EndLoc) {
10112   if (!AStmt)
10113     return StmtError();
10114 
10115   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
10116   auto *CS = cast<CapturedStmt>(AStmt);
10117   // 1.2.2 OpenMP Language Terminology
10118   // Structured block - An executable statement with a single entry at the
10119   // top and a single exit at the bottom.
10120   // The point of exit cannot be a branch out of the structured block.
10121   // longjmp() and throw() must not violate the entry/exit criteria.
10122   CS->getCapturedDecl()->setNothrow();
10123 
10124   setFunctionHasBranchProtectedScope();
10125 
10126   return OMPParallelMasterDirective::Create(
10127       Context, StartLoc, EndLoc, Clauses, AStmt,
10128       DSAStack->getTaskgroupReductionRef());
10129 }
10130 
10131 StmtResult
10132 Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
10133                                            Stmt *AStmt, SourceLocation StartLoc,
10134                                            SourceLocation EndLoc) {
10135   if (!AStmt)
10136     return StmtError();
10137 
10138   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
10139   auto BaseStmt = AStmt;
10140   while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
10141     BaseStmt = CS->getCapturedStmt();
10142   if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
10143     auto S = C->children();
10144     if (S.begin() == S.end())
10145       return StmtError();
10146     // All associated statements must be '#pragma omp section' except for
10147     // the first one.
10148     for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
10149       if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
10150         if (SectionStmt)
10151           Diag(SectionStmt->getBeginLoc(),
10152                diag::err_omp_parallel_sections_substmt_not_section);
10153         return StmtError();
10154       }
10155       cast<OMPSectionDirective>(SectionStmt)
10156           ->setHasCancel(DSAStack->isCancelRegion());
10157     }
10158   } else {
10159     Diag(AStmt->getBeginLoc(),
10160          diag::err_omp_parallel_sections_not_compound_stmt);
10161     return StmtError();
10162   }
10163 
10164   setFunctionHasBranchProtectedScope();
10165 
10166   return OMPParallelSectionsDirective::Create(
10167       Context, StartLoc, EndLoc, Clauses, AStmt,
10168       DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion());
10169 }
10170 
10171 /// Find and diagnose mutually exclusive clause kinds.
10172 static bool checkMutuallyExclusiveClauses(
10173     Sema &S, ArrayRef<OMPClause *> Clauses,
10174     ArrayRef<OpenMPClauseKind> MutuallyExclusiveClauses) {
10175   const OMPClause *PrevClause = nullptr;
10176   bool ErrorFound = false;
10177   for (const OMPClause *C : Clauses) {
10178     if (llvm::is_contained(MutuallyExclusiveClauses, C->getClauseKind())) {
10179       if (!PrevClause) {
10180         PrevClause = C;
10181       } else if (PrevClause->getClauseKind() != C->getClauseKind()) {
10182         S.Diag(C->getBeginLoc(), diag::err_omp_clauses_mutually_exclusive)
10183             << getOpenMPClauseName(C->getClauseKind())
10184             << getOpenMPClauseName(PrevClause->getClauseKind());
10185         S.Diag(PrevClause->getBeginLoc(), diag::note_omp_previous_clause)
10186             << getOpenMPClauseName(PrevClause->getClauseKind());
10187         ErrorFound = true;
10188       }
10189     }
10190   }
10191   return ErrorFound;
10192 }
10193 
10194 StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
10195                                           Stmt *AStmt, SourceLocation StartLoc,
10196                                           SourceLocation EndLoc) {
10197   if (!AStmt)
10198     return StmtError();
10199 
10200   // OpenMP 5.0, 2.10.1 task Construct
10201   // If a detach clause appears on the directive, then a mergeable clause cannot
10202   // appear on the same directive.
10203   if (checkMutuallyExclusiveClauses(*this, Clauses,
10204                                     {OMPC_detach, OMPC_mergeable}))
10205     return StmtError();
10206 
10207   auto *CS = cast<CapturedStmt>(AStmt);
10208   // 1.2.2 OpenMP Language Terminology
10209   // Structured block - An executable statement with a single entry at the
10210   // top and a single exit at the bottom.
10211   // The point of exit cannot be a branch out of the structured block.
10212   // longjmp() and throw() must not violate the entry/exit criteria.
10213   CS->getCapturedDecl()->setNothrow();
10214 
10215   setFunctionHasBranchProtectedScope();
10216 
10217   return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
10218                                   DSAStack->isCancelRegion());
10219 }
10220 
10221 StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
10222                                                SourceLocation EndLoc) {
10223   return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc);
10224 }
10225 
10226 StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
10227                                              SourceLocation EndLoc) {
10228   return OMPBarrierDirective::Create(Context, StartLoc, EndLoc);
10229 }
10230 
10231 StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
10232                                               SourceLocation EndLoc) {
10233   return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc);
10234 }
10235 
10236 StmtResult Sema::ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses,
10237                                                Stmt *AStmt,
10238                                                SourceLocation StartLoc,
10239                                                SourceLocation EndLoc) {
10240   if (!AStmt)
10241     return StmtError();
10242 
10243   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
10244 
10245   setFunctionHasBranchProtectedScope();
10246 
10247   return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, Clauses,
10248                                        AStmt,
10249                                        DSAStack->getTaskgroupReductionRef());
10250 }
10251 
10252 StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
10253                                            SourceLocation StartLoc,
10254                                            SourceLocation EndLoc) {
10255   OMPFlushClause *FC = nullptr;
10256   OMPClause *OrderClause = nullptr;
10257   for (OMPClause *C : Clauses) {
10258     if (C->getClauseKind() == OMPC_flush)
10259       FC = cast<OMPFlushClause>(C);
10260     else
10261       OrderClause = C;
10262   }
10263   OpenMPClauseKind MemOrderKind = OMPC_unknown;
10264   SourceLocation MemOrderLoc;
10265   for (const OMPClause *C : Clauses) {
10266     if (C->getClauseKind() == OMPC_acq_rel ||
10267         C->getClauseKind() == OMPC_acquire ||
10268         C->getClauseKind() == OMPC_release) {
10269       if (MemOrderKind != OMPC_unknown) {
10270         Diag(C->getBeginLoc(), diag::err_omp_several_mem_order_clauses)
10271             << getOpenMPDirectiveName(OMPD_flush) << 1
10272             << SourceRange(C->getBeginLoc(), C->getEndLoc());
10273         Diag(MemOrderLoc, diag::note_omp_previous_mem_order_clause)
10274             << getOpenMPClauseName(MemOrderKind);
10275       } else {
10276         MemOrderKind = C->getClauseKind();
10277         MemOrderLoc = C->getBeginLoc();
10278       }
10279     }
10280   }
10281   if (FC && OrderClause) {
10282     Diag(FC->getLParenLoc(), diag::err_omp_flush_order_clause_and_list)
10283         << getOpenMPClauseName(OrderClause->getClauseKind());
10284     Diag(OrderClause->getBeginLoc(), diag::note_omp_flush_order_clause_here)
10285         << getOpenMPClauseName(OrderClause->getClauseKind());
10286     return StmtError();
10287   }
10288   return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses);
10289 }
10290 
10291 StmtResult Sema::ActOnOpenMPDepobjDirective(ArrayRef<OMPClause *> Clauses,
10292                                             SourceLocation StartLoc,
10293                                             SourceLocation EndLoc) {
10294   if (Clauses.empty()) {
10295     Diag(StartLoc, diag::err_omp_depobj_expected);
10296     return StmtError();
10297   } else if (Clauses[0]->getClauseKind() != OMPC_depobj) {
10298     Diag(Clauses[0]->getBeginLoc(), diag::err_omp_depobj_expected);
10299     return StmtError();
10300   }
10301   // Only depobj expression and another single clause is allowed.
10302   if (Clauses.size() > 2) {
10303     Diag(Clauses[2]->getBeginLoc(),
10304          diag::err_omp_depobj_single_clause_expected);
10305     return StmtError();
10306   } else if (Clauses.size() < 1) {
10307     Diag(Clauses[0]->getEndLoc(), diag::err_omp_depobj_single_clause_expected);
10308     return StmtError();
10309   }
10310   return OMPDepobjDirective::Create(Context, StartLoc, EndLoc, Clauses);
10311 }
10312 
10313 StmtResult Sema::ActOnOpenMPScanDirective(ArrayRef<OMPClause *> Clauses,
10314                                           SourceLocation StartLoc,
10315                                           SourceLocation EndLoc) {
10316   // Check that exactly one clause is specified.
10317   if (Clauses.size() != 1) {
10318     Diag(Clauses.empty() ? EndLoc : Clauses[1]->getBeginLoc(),
10319          diag::err_omp_scan_single_clause_expected);
10320     return StmtError();
10321   }
10322   // Check that scan directive is used in the scopeof the OpenMP loop body.
10323   if (Scope *S = DSAStack->getCurScope()) {
10324     Scope *ParentS = S->getParent();
10325     if (!ParentS || ParentS->getParent() != ParentS->getBreakParent() ||
10326         !ParentS->getBreakParent()->isOpenMPLoopScope())
10327       return StmtError(Diag(StartLoc, diag::err_omp_orphaned_device_directive)
10328                        << getOpenMPDirectiveName(OMPD_scan) << 5);
10329   }
10330   // Check that only one instance of scan directives is used in the same outer
10331   // region.
10332   if (DSAStack->doesParentHasScanDirective()) {
10333     Diag(StartLoc, diag::err_omp_several_directives_in_region) << "scan";
10334     Diag(DSAStack->getParentScanDirectiveLoc(),
10335          diag::note_omp_previous_directive)
10336         << "scan";
10337     return StmtError();
10338   }
10339   DSAStack->setParentHasScanDirective(StartLoc);
10340   return OMPScanDirective::Create(Context, StartLoc, EndLoc, Clauses);
10341 }
10342 
10343 StmtResult Sema::ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
10344                                              Stmt *AStmt,
10345                                              SourceLocation StartLoc,
10346                                              SourceLocation EndLoc) {
10347   const OMPClause *DependFound = nullptr;
10348   const OMPClause *DependSourceClause = nullptr;
10349   const OMPClause *DependSinkClause = nullptr;
10350   bool ErrorFound = false;
10351   const OMPThreadsClause *TC = nullptr;
10352   const OMPSIMDClause *SC = nullptr;
10353   for (const OMPClause *C : Clauses) {
10354     if (auto *DC = dyn_cast<OMPDependClause>(C)) {
10355       DependFound = C;
10356       if (DC->getDependencyKind() == OMPC_DEPEND_source) {
10357         if (DependSourceClause) {
10358           Diag(C->getBeginLoc(), diag::err_omp_more_one_clause)
10359               << getOpenMPDirectiveName(OMPD_ordered)
10360               << getOpenMPClauseName(OMPC_depend) << 2;
10361           ErrorFound = true;
10362         } else {
10363           DependSourceClause = C;
10364         }
10365         if (DependSinkClause) {
10366           Diag(C->getBeginLoc(), diag::err_omp_depend_sink_source_not_allowed)
10367               << 0;
10368           ErrorFound = true;
10369         }
10370       } else if (DC->getDependencyKind() == OMPC_DEPEND_sink) {
10371         if (DependSourceClause) {
10372           Diag(C->getBeginLoc(), diag::err_omp_depend_sink_source_not_allowed)
10373               << 1;
10374           ErrorFound = true;
10375         }
10376         DependSinkClause = C;
10377       }
10378     } else if (C->getClauseKind() == OMPC_threads) {
10379       TC = cast<OMPThreadsClause>(C);
10380     } else if (C->getClauseKind() == OMPC_simd) {
10381       SC = cast<OMPSIMDClause>(C);
10382     }
10383   }
10384   if (!ErrorFound && !SC &&
10385       isOpenMPSimdDirective(DSAStack->getParentDirective())) {
10386     // OpenMP [2.8.1,simd Construct, Restrictions]
10387     // An ordered construct with the simd clause is the only OpenMP construct
10388     // that can appear in the simd region.
10389     Diag(StartLoc, diag::err_omp_prohibited_region_simd)
10390         << (LangOpts.OpenMP >= 50 ? 1 : 0);
10391     ErrorFound = true;
10392   } else if (DependFound && (TC || SC)) {
10393     Diag(DependFound->getBeginLoc(), diag::err_omp_depend_clause_thread_simd)
10394         << getOpenMPClauseName(TC ? TC->getClauseKind() : SC->getClauseKind());
10395     ErrorFound = true;
10396   } else if (DependFound && !DSAStack->getParentOrderedRegionParam().first) {
10397     Diag(DependFound->getBeginLoc(),
10398          diag::err_omp_ordered_directive_without_param);
10399     ErrorFound = true;
10400   } else if (TC || Clauses.empty()) {
10401     if (const Expr *Param = DSAStack->getParentOrderedRegionParam().first) {
10402       SourceLocation ErrLoc = TC ? TC->getBeginLoc() : StartLoc;
10403       Diag(ErrLoc, diag::err_omp_ordered_directive_with_param)
10404           << (TC != nullptr);
10405       Diag(Param->getBeginLoc(), diag::note_omp_ordered_param) << 1;
10406       ErrorFound = true;
10407     }
10408   }
10409   if ((!AStmt && !DependFound) || ErrorFound)
10410     return StmtError();
10411 
10412   // OpenMP 5.0, 2.17.9, ordered Construct, Restrictions.
10413   // During execution of an iteration of a worksharing-loop or a loop nest
10414   // within a worksharing-loop, simd, or worksharing-loop SIMD region, a thread
10415   // must not execute more than one ordered region corresponding to an ordered
10416   // construct without a depend clause.
10417   if (!DependFound) {
10418     if (DSAStack->doesParentHasOrderedDirective()) {
10419       Diag(StartLoc, diag::err_omp_several_directives_in_region) << "ordered";
10420       Diag(DSAStack->getParentOrderedDirectiveLoc(),
10421            diag::note_omp_previous_directive)
10422           << "ordered";
10423       return StmtError();
10424     }
10425     DSAStack->setParentHasOrderedDirective(StartLoc);
10426   }
10427 
10428   if (AStmt) {
10429     assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
10430 
10431     setFunctionHasBranchProtectedScope();
10432   }
10433 
10434   return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
10435 }
10436 
10437 namespace {
10438 /// Helper class for checking expression in 'omp atomic [update]'
10439 /// construct.
10440 class OpenMPAtomicUpdateChecker {
10441   /// Error results for atomic update expressions.
10442   enum ExprAnalysisErrorCode {
10443     /// A statement is not an expression statement.
10444     NotAnExpression,
10445     /// Expression is not builtin binary or unary operation.
10446     NotABinaryOrUnaryExpression,
10447     /// Unary operation is not post-/pre- increment/decrement operation.
10448     NotAnUnaryIncDecExpression,
10449     /// An expression is not of scalar type.
10450     NotAScalarType,
10451     /// A binary operation is not an assignment operation.
10452     NotAnAssignmentOp,
10453     /// RHS part of the binary operation is not a binary expression.
10454     NotABinaryExpression,
10455     /// RHS part is not additive/multiplicative/shift/biwise binary
10456     /// expression.
10457     NotABinaryOperator,
10458     /// RHS binary operation does not have reference to the updated LHS
10459     /// part.
10460     NotAnUpdateExpression,
10461     /// No errors is found.
10462     NoError
10463   };
10464   /// Reference to Sema.
10465   Sema &SemaRef;
10466   /// A location for note diagnostics (when error is found).
10467   SourceLocation NoteLoc;
10468   /// 'x' lvalue part of the source atomic expression.
10469   Expr *X;
10470   /// 'expr' rvalue part of the source atomic expression.
10471   Expr *E;
10472   /// Helper expression of the form
10473   /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
10474   /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
10475   Expr *UpdateExpr;
10476   /// Is 'x' a LHS in a RHS part of full update expression. It is
10477   /// important for non-associative operations.
10478   bool IsXLHSInRHSPart;
10479   BinaryOperatorKind Op;
10480   SourceLocation OpLoc;
10481   /// true if the source expression is a postfix unary operation, false
10482   /// if it is a prefix unary operation.
10483   bool IsPostfixUpdate;
10484 
10485 public:
10486   OpenMPAtomicUpdateChecker(Sema &SemaRef)
10487       : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr),
10488         IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {}
10489   /// Check specified statement that it is suitable for 'atomic update'
10490   /// constructs and extract 'x', 'expr' and Operation from the original
10491   /// expression. If DiagId and NoteId == 0, then only check is performed
10492   /// without error notification.
10493   /// \param DiagId Diagnostic which should be emitted if error is found.
10494   /// \param NoteId Diagnostic note for the main error message.
10495   /// \return true if statement is not an update expression, false otherwise.
10496   bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0);
10497   /// Return the 'x' lvalue part of the source atomic expression.
10498   Expr *getX() const { return X; }
10499   /// Return the 'expr' rvalue part of the source atomic expression.
10500   Expr *getExpr() const { return E; }
10501   /// Return the update expression used in calculation of the updated
10502   /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
10503   /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
10504   Expr *getUpdateExpr() const { return UpdateExpr; }
10505   /// Return true if 'x' is LHS in RHS part of full update expression,
10506   /// false otherwise.
10507   bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; }
10508 
10509   /// true if the source expression is a postfix unary operation, false
10510   /// if it is a prefix unary operation.
10511   bool isPostfixUpdate() const { return IsPostfixUpdate; }
10512 
10513 private:
10514   bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0,
10515                             unsigned NoteId = 0);
10516 };
10517 } // namespace
10518 
10519 bool OpenMPAtomicUpdateChecker::checkBinaryOperation(
10520     BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) {
10521   ExprAnalysisErrorCode ErrorFound = NoError;
10522   SourceLocation ErrorLoc, NoteLoc;
10523   SourceRange ErrorRange, NoteRange;
10524   // Allowed constructs are:
10525   //  x = x binop expr;
10526   //  x = expr binop x;
10527   if (AtomicBinOp->getOpcode() == BO_Assign) {
10528     X = AtomicBinOp->getLHS();
10529     if (const auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>(
10530             AtomicBinOp->getRHS()->IgnoreParenImpCasts())) {
10531       if (AtomicInnerBinOp->isMultiplicativeOp() ||
10532           AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() ||
10533           AtomicInnerBinOp->isBitwiseOp()) {
10534         Op = AtomicInnerBinOp->getOpcode();
10535         OpLoc = AtomicInnerBinOp->getOperatorLoc();
10536         Expr *LHS = AtomicInnerBinOp->getLHS();
10537         Expr *RHS = AtomicInnerBinOp->getRHS();
10538         llvm::FoldingSetNodeID XId, LHSId, RHSId;
10539         X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(),
10540                                           /*Canonical=*/true);
10541         LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(),
10542                                             /*Canonical=*/true);
10543         RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(),
10544                                             /*Canonical=*/true);
10545         if (XId == LHSId) {
10546           E = RHS;
10547           IsXLHSInRHSPart = true;
10548         } else if (XId == RHSId) {
10549           E = LHS;
10550           IsXLHSInRHSPart = false;
10551         } else {
10552           ErrorLoc = AtomicInnerBinOp->getExprLoc();
10553           ErrorRange = AtomicInnerBinOp->getSourceRange();
10554           NoteLoc = X->getExprLoc();
10555           NoteRange = X->getSourceRange();
10556           ErrorFound = NotAnUpdateExpression;
10557         }
10558       } else {
10559         ErrorLoc = AtomicInnerBinOp->getExprLoc();
10560         ErrorRange = AtomicInnerBinOp->getSourceRange();
10561         NoteLoc = AtomicInnerBinOp->getOperatorLoc();
10562         NoteRange = SourceRange(NoteLoc, NoteLoc);
10563         ErrorFound = NotABinaryOperator;
10564       }
10565     } else {
10566       NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc();
10567       NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange();
10568       ErrorFound = NotABinaryExpression;
10569     }
10570   } else {
10571     ErrorLoc = AtomicBinOp->getExprLoc();
10572     ErrorRange = AtomicBinOp->getSourceRange();
10573     NoteLoc = AtomicBinOp->getOperatorLoc();
10574     NoteRange = SourceRange(NoteLoc, NoteLoc);
10575     ErrorFound = NotAnAssignmentOp;
10576   }
10577   if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
10578     SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
10579     SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
10580     return true;
10581   }
10582   if (SemaRef.CurContext->isDependentContext())
10583     E = X = UpdateExpr = nullptr;
10584   return ErrorFound != NoError;
10585 }
10586 
10587 bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId,
10588                                                unsigned NoteId) {
10589   ExprAnalysisErrorCode ErrorFound = NoError;
10590   SourceLocation ErrorLoc, NoteLoc;
10591   SourceRange ErrorRange, NoteRange;
10592   // Allowed constructs are:
10593   //  x++;
10594   //  x--;
10595   //  ++x;
10596   //  --x;
10597   //  x binop= expr;
10598   //  x = x binop expr;
10599   //  x = expr binop x;
10600   if (auto *AtomicBody = dyn_cast<Expr>(S)) {
10601     AtomicBody = AtomicBody->IgnoreParenImpCasts();
10602     if (AtomicBody->getType()->isScalarType() ||
10603         AtomicBody->isInstantiationDependent()) {
10604       if (const auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>(
10605               AtomicBody->IgnoreParenImpCasts())) {
10606         // Check for Compound Assignment Operation
10607         Op = BinaryOperator::getOpForCompoundAssignment(
10608             AtomicCompAssignOp->getOpcode());
10609         OpLoc = AtomicCompAssignOp->getOperatorLoc();
10610         E = AtomicCompAssignOp->getRHS();
10611         X = AtomicCompAssignOp->getLHS()->IgnoreParens();
10612         IsXLHSInRHSPart = true;
10613       } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>(
10614                      AtomicBody->IgnoreParenImpCasts())) {
10615         // Check for Binary Operation
10616         if (checkBinaryOperation(AtomicBinOp, DiagId, NoteId))
10617           return true;
10618       } else if (const auto *AtomicUnaryOp = dyn_cast<UnaryOperator>(
10619                      AtomicBody->IgnoreParenImpCasts())) {
10620         // Check for Unary Operation
10621         if (AtomicUnaryOp->isIncrementDecrementOp()) {
10622           IsPostfixUpdate = AtomicUnaryOp->isPostfix();
10623           Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub;
10624           OpLoc = AtomicUnaryOp->getOperatorLoc();
10625           X = AtomicUnaryOp->getSubExpr()->IgnoreParens();
10626           E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get();
10627           IsXLHSInRHSPart = true;
10628         } else {
10629           ErrorFound = NotAnUnaryIncDecExpression;
10630           ErrorLoc = AtomicUnaryOp->getExprLoc();
10631           ErrorRange = AtomicUnaryOp->getSourceRange();
10632           NoteLoc = AtomicUnaryOp->getOperatorLoc();
10633           NoteRange = SourceRange(NoteLoc, NoteLoc);
10634         }
10635       } else if (!AtomicBody->isInstantiationDependent()) {
10636         ErrorFound = NotABinaryOrUnaryExpression;
10637         NoteLoc = ErrorLoc = AtomicBody->getExprLoc();
10638         NoteRange = ErrorRange = AtomicBody->getSourceRange();
10639       }
10640     } else {
10641       ErrorFound = NotAScalarType;
10642       NoteLoc = ErrorLoc = AtomicBody->getBeginLoc();
10643       NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
10644     }
10645   } else {
10646     ErrorFound = NotAnExpression;
10647     NoteLoc = ErrorLoc = S->getBeginLoc();
10648     NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
10649   }
10650   if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
10651     SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
10652     SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
10653     return true;
10654   }
10655   if (SemaRef.CurContext->isDependentContext())
10656     E = X = UpdateExpr = nullptr;
10657   if (ErrorFound == NoError && E && X) {
10658     // Build an update expression of form 'OpaqueValueExpr(x) binop
10659     // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop
10660     // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression.
10661     auto *OVEX = new (SemaRef.getASTContext())
10662         OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_PRValue);
10663     auto *OVEExpr = new (SemaRef.getASTContext())
10664         OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_PRValue);
10665     ExprResult Update =
10666         SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr,
10667                                    IsXLHSInRHSPart ? OVEExpr : OVEX);
10668     if (Update.isInvalid())
10669       return true;
10670     Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(),
10671                                                Sema::AA_Casting);
10672     if (Update.isInvalid())
10673       return true;
10674     UpdateExpr = Update.get();
10675   }
10676   return ErrorFound != NoError;
10677 }
10678 
10679 StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
10680                                             Stmt *AStmt,
10681                                             SourceLocation StartLoc,
10682                                             SourceLocation EndLoc) {
10683   // Register location of the first atomic directive.
10684   DSAStack->addAtomicDirectiveLoc(StartLoc);
10685   if (!AStmt)
10686     return StmtError();
10687 
10688   // 1.2.2 OpenMP Language Terminology
10689   // Structured block - An executable statement with a single entry at the
10690   // top and a single exit at the bottom.
10691   // The point of exit cannot be a branch out of the structured block.
10692   // longjmp() and throw() must not violate the entry/exit criteria.
10693   OpenMPClauseKind AtomicKind = OMPC_unknown;
10694   SourceLocation AtomicKindLoc;
10695   OpenMPClauseKind MemOrderKind = OMPC_unknown;
10696   SourceLocation MemOrderLoc;
10697   for (const OMPClause *C : Clauses) {
10698     if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write ||
10699         C->getClauseKind() == OMPC_update ||
10700         C->getClauseKind() == OMPC_capture) {
10701       if (AtomicKind != OMPC_unknown) {
10702         Diag(C->getBeginLoc(), diag::err_omp_atomic_several_clauses)
10703             << SourceRange(C->getBeginLoc(), C->getEndLoc());
10704         Diag(AtomicKindLoc, diag::note_omp_previous_mem_order_clause)
10705             << getOpenMPClauseName(AtomicKind);
10706       } else {
10707         AtomicKind = C->getClauseKind();
10708         AtomicKindLoc = C->getBeginLoc();
10709       }
10710     }
10711     if (C->getClauseKind() == OMPC_seq_cst ||
10712         C->getClauseKind() == OMPC_acq_rel ||
10713         C->getClauseKind() == OMPC_acquire ||
10714         C->getClauseKind() == OMPC_release ||
10715         C->getClauseKind() == OMPC_relaxed) {
10716       if (MemOrderKind != OMPC_unknown) {
10717         Diag(C->getBeginLoc(), diag::err_omp_several_mem_order_clauses)
10718             << getOpenMPDirectiveName(OMPD_atomic) << 0
10719             << SourceRange(C->getBeginLoc(), C->getEndLoc());
10720         Diag(MemOrderLoc, diag::note_omp_previous_mem_order_clause)
10721             << getOpenMPClauseName(MemOrderKind);
10722       } else {
10723         MemOrderKind = C->getClauseKind();
10724         MemOrderLoc = C->getBeginLoc();
10725       }
10726     }
10727   }
10728   // OpenMP 5.0, 2.17.7 atomic Construct, Restrictions
10729   // If atomic-clause is read then memory-order-clause must not be acq_rel or
10730   // release.
10731   // If atomic-clause is write then memory-order-clause must not be acq_rel or
10732   // acquire.
10733   // If atomic-clause is update or not present then memory-order-clause must not
10734   // be acq_rel or acquire.
10735   if ((AtomicKind == OMPC_read &&
10736        (MemOrderKind == OMPC_acq_rel || MemOrderKind == OMPC_release)) ||
10737       ((AtomicKind == OMPC_write || AtomicKind == OMPC_update ||
10738         AtomicKind == OMPC_unknown) &&
10739        (MemOrderKind == OMPC_acq_rel || MemOrderKind == OMPC_acquire))) {
10740     SourceLocation Loc = AtomicKindLoc;
10741     if (AtomicKind == OMPC_unknown)
10742       Loc = StartLoc;
10743     Diag(Loc, diag::err_omp_atomic_incompatible_mem_order_clause)
10744         << getOpenMPClauseName(AtomicKind)
10745         << (AtomicKind == OMPC_unknown ? 1 : 0)
10746         << getOpenMPClauseName(MemOrderKind);
10747     Diag(MemOrderLoc, diag::note_omp_previous_mem_order_clause)
10748         << getOpenMPClauseName(MemOrderKind);
10749   }
10750 
10751   Stmt *Body = AStmt;
10752   if (auto *EWC = dyn_cast<ExprWithCleanups>(Body))
10753     Body = EWC->getSubExpr();
10754 
10755   Expr *X = nullptr;
10756   Expr *V = nullptr;
10757   Expr *E = nullptr;
10758   Expr *UE = nullptr;
10759   bool IsXLHSInRHSPart = false;
10760   bool IsPostfixUpdate = false;
10761   // OpenMP [2.12.6, atomic Construct]
10762   // In the next expressions:
10763   // * x and v (as applicable) are both l-value expressions with scalar type.
10764   // * During the execution of an atomic region, multiple syntactic
10765   // occurrences of x must designate the same storage location.
10766   // * Neither of v and expr (as applicable) may access the storage location
10767   // designated by x.
10768   // * Neither of x and expr (as applicable) may access the storage location
10769   // designated by v.
10770   // * expr is an expression with scalar type.
10771   // * binop is one of +, *, -, /, &, ^, |, <<, or >>.
10772   // * binop, binop=, ++, and -- are not overloaded operators.
10773   // * The expression x binop expr must be numerically equivalent to x binop
10774   // (expr). This requirement is satisfied if the operators in expr have
10775   // precedence greater than binop, or by using parentheses around expr or
10776   // subexpressions of expr.
10777   // * The expression expr binop x must be numerically equivalent to (expr)
10778   // binop x. This requirement is satisfied if the operators in expr have
10779   // precedence equal to or greater than binop, or by using parentheses around
10780   // expr or subexpressions of expr.
10781   // * For forms that allow multiple occurrences of x, the number of times
10782   // that x is evaluated is unspecified.
10783   if (AtomicKind == OMPC_read) {
10784     enum {
10785       NotAnExpression,
10786       NotAnAssignmentOp,
10787       NotAScalarType,
10788       NotAnLValue,
10789       NoError
10790     } ErrorFound = NoError;
10791     SourceLocation ErrorLoc, NoteLoc;
10792     SourceRange ErrorRange, NoteRange;
10793     // If clause is read:
10794     //  v = x;
10795     if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
10796       const auto *AtomicBinOp =
10797           dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
10798       if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
10799         X = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
10800         V = AtomicBinOp->getLHS()->IgnoreParenImpCasts();
10801         if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
10802             (V->isInstantiationDependent() || V->getType()->isScalarType())) {
10803           if (!X->isLValue() || !V->isLValue()) {
10804             const Expr *NotLValueExpr = X->isLValue() ? V : X;
10805             ErrorFound = NotAnLValue;
10806             ErrorLoc = AtomicBinOp->getExprLoc();
10807             ErrorRange = AtomicBinOp->getSourceRange();
10808             NoteLoc = NotLValueExpr->getExprLoc();
10809             NoteRange = NotLValueExpr->getSourceRange();
10810           }
10811         } else if (!X->isInstantiationDependent() ||
10812                    !V->isInstantiationDependent()) {
10813           const Expr *NotScalarExpr =
10814               (X->isInstantiationDependent() || X->getType()->isScalarType())
10815                   ? V
10816                   : X;
10817           ErrorFound = NotAScalarType;
10818           ErrorLoc = AtomicBinOp->getExprLoc();
10819           ErrorRange = AtomicBinOp->getSourceRange();
10820           NoteLoc = NotScalarExpr->getExprLoc();
10821           NoteRange = NotScalarExpr->getSourceRange();
10822         }
10823       } else if (!AtomicBody->isInstantiationDependent()) {
10824         ErrorFound = NotAnAssignmentOp;
10825         ErrorLoc = AtomicBody->getExprLoc();
10826         ErrorRange = AtomicBody->getSourceRange();
10827         NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
10828                               : AtomicBody->getExprLoc();
10829         NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
10830                                 : AtomicBody->getSourceRange();
10831       }
10832     } else {
10833       ErrorFound = NotAnExpression;
10834       NoteLoc = ErrorLoc = Body->getBeginLoc();
10835       NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
10836     }
10837     if (ErrorFound != NoError) {
10838       Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement)
10839           << ErrorRange;
10840       Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
10841                                                       << NoteRange;
10842       return StmtError();
10843     }
10844     if (CurContext->isDependentContext())
10845       V = X = nullptr;
10846   } else if (AtomicKind == OMPC_write) {
10847     enum {
10848       NotAnExpression,
10849       NotAnAssignmentOp,
10850       NotAScalarType,
10851       NotAnLValue,
10852       NoError
10853     } ErrorFound = NoError;
10854     SourceLocation ErrorLoc, NoteLoc;
10855     SourceRange ErrorRange, NoteRange;
10856     // If clause is write:
10857     //  x = expr;
10858     if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
10859       const auto *AtomicBinOp =
10860           dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
10861       if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
10862         X = AtomicBinOp->getLHS();
10863         E = AtomicBinOp->getRHS();
10864         if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
10865             (E->isInstantiationDependent() || E->getType()->isScalarType())) {
10866           if (!X->isLValue()) {
10867             ErrorFound = NotAnLValue;
10868             ErrorLoc = AtomicBinOp->getExprLoc();
10869             ErrorRange = AtomicBinOp->getSourceRange();
10870             NoteLoc = X->getExprLoc();
10871             NoteRange = X->getSourceRange();
10872           }
10873         } else if (!X->isInstantiationDependent() ||
10874                    !E->isInstantiationDependent()) {
10875           const Expr *NotScalarExpr =
10876               (X->isInstantiationDependent() || X->getType()->isScalarType())
10877                   ? E
10878                   : X;
10879           ErrorFound = NotAScalarType;
10880           ErrorLoc = AtomicBinOp->getExprLoc();
10881           ErrorRange = AtomicBinOp->getSourceRange();
10882           NoteLoc = NotScalarExpr->getExprLoc();
10883           NoteRange = NotScalarExpr->getSourceRange();
10884         }
10885       } else if (!AtomicBody->isInstantiationDependent()) {
10886         ErrorFound = NotAnAssignmentOp;
10887         ErrorLoc = AtomicBody->getExprLoc();
10888         ErrorRange = AtomicBody->getSourceRange();
10889         NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
10890                               : AtomicBody->getExprLoc();
10891         NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
10892                                 : AtomicBody->getSourceRange();
10893       }
10894     } else {
10895       ErrorFound = NotAnExpression;
10896       NoteLoc = ErrorLoc = Body->getBeginLoc();
10897       NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
10898     }
10899     if (ErrorFound != NoError) {
10900       Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement)
10901           << ErrorRange;
10902       Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
10903                                                       << NoteRange;
10904       return StmtError();
10905     }
10906     if (CurContext->isDependentContext())
10907       E = X = nullptr;
10908   } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) {
10909     // If clause is update:
10910     //  x++;
10911     //  x--;
10912     //  ++x;
10913     //  --x;
10914     //  x binop= expr;
10915     //  x = x binop expr;
10916     //  x = expr binop x;
10917     OpenMPAtomicUpdateChecker Checker(*this);
10918     if (Checker.checkStatement(
10919             Body, (AtomicKind == OMPC_update)
10920                       ? diag::err_omp_atomic_update_not_expression_statement
10921                       : diag::err_omp_atomic_not_expression_statement,
10922             diag::note_omp_atomic_update))
10923       return StmtError();
10924     if (!CurContext->isDependentContext()) {
10925       E = Checker.getExpr();
10926       X = Checker.getX();
10927       UE = Checker.getUpdateExpr();
10928       IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
10929     }
10930   } else if (AtomicKind == OMPC_capture) {
10931     enum {
10932       NotAnAssignmentOp,
10933       NotACompoundStatement,
10934       NotTwoSubstatements,
10935       NotASpecificExpression,
10936       NoError
10937     } ErrorFound = NoError;
10938     SourceLocation ErrorLoc, NoteLoc;
10939     SourceRange ErrorRange, NoteRange;
10940     if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
10941       // If clause is a capture:
10942       //  v = x++;
10943       //  v = x--;
10944       //  v = ++x;
10945       //  v = --x;
10946       //  v = x binop= expr;
10947       //  v = x = x binop expr;
10948       //  v = x = expr binop x;
10949       const auto *AtomicBinOp =
10950           dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
10951       if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
10952         V = AtomicBinOp->getLHS();
10953         Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
10954         OpenMPAtomicUpdateChecker Checker(*this);
10955         if (Checker.checkStatement(
10956                 Body, diag::err_omp_atomic_capture_not_expression_statement,
10957                 diag::note_omp_atomic_update))
10958           return StmtError();
10959         E = Checker.getExpr();
10960         X = Checker.getX();
10961         UE = Checker.getUpdateExpr();
10962         IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
10963         IsPostfixUpdate = Checker.isPostfixUpdate();
10964       } else if (!AtomicBody->isInstantiationDependent()) {
10965         ErrorLoc = AtomicBody->getExprLoc();
10966         ErrorRange = AtomicBody->getSourceRange();
10967         NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
10968                               : AtomicBody->getExprLoc();
10969         NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
10970                                 : AtomicBody->getSourceRange();
10971         ErrorFound = NotAnAssignmentOp;
10972       }
10973       if (ErrorFound != NoError) {
10974         Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement)
10975             << ErrorRange;
10976         Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
10977         return StmtError();
10978       }
10979       if (CurContext->isDependentContext())
10980         UE = V = E = X = nullptr;
10981     } else {
10982       // If clause is a capture:
10983       //  { v = x; x = expr; }
10984       //  { v = x; x++; }
10985       //  { v = x; x--; }
10986       //  { v = x; ++x; }
10987       //  { v = x; --x; }
10988       //  { v = x; x binop= expr; }
10989       //  { v = x; x = x binop expr; }
10990       //  { v = x; x = expr binop x; }
10991       //  { x++; v = x; }
10992       //  { x--; v = x; }
10993       //  { ++x; v = x; }
10994       //  { --x; v = x; }
10995       //  { x binop= expr; v = x; }
10996       //  { x = x binop expr; v = x; }
10997       //  { x = expr binop x; v = x; }
10998       if (auto *CS = dyn_cast<CompoundStmt>(Body)) {
10999         // Check that this is { expr1; expr2; }
11000         if (CS->size() == 2) {
11001           Stmt *First = CS->body_front();
11002           Stmt *Second = CS->body_back();
11003           if (auto *EWC = dyn_cast<ExprWithCleanups>(First))
11004             First = EWC->getSubExpr()->IgnoreParenImpCasts();
11005           if (auto *EWC = dyn_cast<ExprWithCleanups>(Second))
11006             Second = EWC->getSubExpr()->IgnoreParenImpCasts();
11007           // Need to find what subexpression is 'v' and what is 'x'.
11008           OpenMPAtomicUpdateChecker Checker(*this);
11009           bool IsUpdateExprFound = !Checker.checkStatement(Second);
11010           BinaryOperator *BinOp = nullptr;
11011           if (IsUpdateExprFound) {
11012             BinOp = dyn_cast<BinaryOperator>(First);
11013             IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
11014           }
11015           if (IsUpdateExprFound && !CurContext->isDependentContext()) {
11016             //  { v = x; x++; }
11017             //  { v = x; x--; }
11018             //  { v = x; ++x; }
11019             //  { v = x; --x; }
11020             //  { v = x; x binop= expr; }
11021             //  { v = x; x = x binop expr; }
11022             //  { v = x; x = expr binop x; }
11023             // Check that the first expression has form v = x.
11024             Expr *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
11025             llvm::FoldingSetNodeID XId, PossibleXId;
11026             Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
11027             PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
11028             IsUpdateExprFound = XId == PossibleXId;
11029             if (IsUpdateExprFound) {
11030               V = BinOp->getLHS();
11031               X = Checker.getX();
11032               E = Checker.getExpr();
11033               UE = Checker.getUpdateExpr();
11034               IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
11035               IsPostfixUpdate = true;
11036             }
11037           }
11038           if (!IsUpdateExprFound) {
11039             IsUpdateExprFound = !Checker.checkStatement(First);
11040             BinOp = nullptr;
11041             if (IsUpdateExprFound) {
11042               BinOp = dyn_cast<BinaryOperator>(Second);
11043               IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
11044             }
11045             if (IsUpdateExprFound && !CurContext->isDependentContext()) {
11046               //  { x++; v = x; }
11047               //  { x--; v = x; }
11048               //  { ++x; v = x; }
11049               //  { --x; v = x; }
11050               //  { x binop= expr; v = x; }
11051               //  { x = x binop expr; v = x; }
11052               //  { x = expr binop x; v = x; }
11053               // Check that the second expression has form v = x.
11054               Expr *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
11055               llvm::FoldingSetNodeID XId, PossibleXId;
11056               Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
11057               PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
11058               IsUpdateExprFound = XId == PossibleXId;
11059               if (IsUpdateExprFound) {
11060                 V = BinOp->getLHS();
11061                 X = Checker.getX();
11062                 E = Checker.getExpr();
11063                 UE = Checker.getUpdateExpr();
11064                 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
11065                 IsPostfixUpdate = false;
11066               }
11067             }
11068           }
11069           if (!IsUpdateExprFound) {
11070             //  { v = x; x = expr; }
11071             auto *FirstExpr = dyn_cast<Expr>(First);
11072             auto *SecondExpr = dyn_cast<Expr>(Second);
11073             if (!FirstExpr || !SecondExpr ||
11074                 !(FirstExpr->isInstantiationDependent() ||
11075                   SecondExpr->isInstantiationDependent())) {
11076               auto *FirstBinOp = dyn_cast<BinaryOperator>(First);
11077               if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) {
11078                 ErrorFound = NotAnAssignmentOp;
11079                 NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc()
11080                                                 : First->getBeginLoc();
11081                 NoteRange = ErrorRange = FirstBinOp
11082                                              ? FirstBinOp->getSourceRange()
11083                                              : SourceRange(ErrorLoc, ErrorLoc);
11084               } else {
11085                 auto *SecondBinOp = dyn_cast<BinaryOperator>(Second);
11086                 if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) {
11087                   ErrorFound = NotAnAssignmentOp;
11088                   NoteLoc = ErrorLoc = SecondBinOp
11089                                            ? SecondBinOp->getOperatorLoc()
11090                                            : Second->getBeginLoc();
11091                   NoteRange = ErrorRange =
11092                       SecondBinOp ? SecondBinOp->getSourceRange()
11093                                   : SourceRange(ErrorLoc, ErrorLoc);
11094                 } else {
11095                   Expr *PossibleXRHSInFirst =
11096                       FirstBinOp->getRHS()->IgnoreParenImpCasts();
11097                   Expr *PossibleXLHSInSecond =
11098                       SecondBinOp->getLHS()->IgnoreParenImpCasts();
11099                   llvm::FoldingSetNodeID X1Id, X2Id;
11100                   PossibleXRHSInFirst->Profile(X1Id, Context,
11101                                                /*Canonical=*/true);
11102                   PossibleXLHSInSecond->Profile(X2Id, Context,
11103                                                 /*Canonical=*/true);
11104                   IsUpdateExprFound = X1Id == X2Id;
11105                   if (IsUpdateExprFound) {
11106                     V = FirstBinOp->getLHS();
11107                     X = SecondBinOp->getLHS();
11108                     E = SecondBinOp->getRHS();
11109                     UE = nullptr;
11110                     IsXLHSInRHSPart = false;
11111                     IsPostfixUpdate = true;
11112                   } else {
11113                     ErrorFound = NotASpecificExpression;
11114                     ErrorLoc = FirstBinOp->getExprLoc();
11115                     ErrorRange = FirstBinOp->getSourceRange();
11116                     NoteLoc = SecondBinOp->getLHS()->getExprLoc();
11117                     NoteRange = SecondBinOp->getRHS()->getSourceRange();
11118                   }
11119                 }
11120               }
11121             }
11122           }
11123         } else {
11124           NoteLoc = ErrorLoc = Body->getBeginLoc();
11125           NoteRange = ErrorRange =
11126               SourceRange(Body->getBeginLoc(), Body->getBeginLoc());
11127           ErrorFound = NotTwoSubstatements;
11128         }
11129       } else {
11130         NoteLoc = ErrorLoc = Body->getBeginLoc();
11131         NoteRange = ErrorRange =
11132             SourceRange(Body->getBeginLoc(), Body->getBeginLoc());
11133         ErrorFound = NotACompoundStatement;
11134       }
11135       if (ErrorFound != NoError) {
11136         Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement)
11137             << ErrorRange;
11138         Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
11139         return StmtError();
11140       }
11141       if (CurContext->isDependentContext())
11142         UE = V = E = X = nullptr;
11143     }
11144   }
11145 
11146   setFunctionHasBranchProtectedScope();
11147 
11148   return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
11149                                     X, V, E, UE, IsXLHSInRHSPart,
11150                                     IsPostfixUpdate);
11151 }
11152 
11153 StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
11154                                             Stmt *AStmt,
11155                                             SourceLocation StartLoc,
11156                                             SourceLocation EndLoc) {
11157   if (!AStmt)
11158     return StmtError();
11159 
11160   auto *CS = cast<CapturedStmt>(AStmt);
11161   // 1.2.2 OpenMP Language Terminology
11162   // Structured block - An executable statement with a single entry at the
11163   // top and a single exit at the bottom.
11164   // The point of exit cannot be a branch out of the structured block.
11165   // longjmp() and throw() must not violate the entry/exit criteria.
11166   CS->getCapturedDecl()->setNothrow();
11167   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target);
11168        ThisCaptureLevel > 1; --ThisCaptureLevel) {
11169     CS = cast<CapturedStmt>(CS->getCapturedStmt());
11170     // 1.2.2 OpenMP Language Terminology
11171     // Structured block - An executable statement with a single entry at the
11172     // top and a single exit at the bottom.
11173     // The point of exit cannot be a branch out of the structured block.
11174     // longjmp() and throw() must not violate the entry/exit criteria.
11175     CS->getCapturedDecl()->setNothrow();
11176   }
11177 
11178   // OpenMP [2.16, Nesting of Regions]
11179   // If specified, a teams construct must be contained within a target
11180   // construct. That target construct must contain no statements or directives
11181   // outside of the teams construct.
11182   if (DSAStack->hasInnerTeamsRegion()) {
11183     const Stmt *S = CS->IgnoreContainers(/*IgnoreCaptured=*/true);
11184     bool OMPTeamsFound = true;
11185     if (const auto *CS = dyn_cast<CompoundStmt>(S)) {
11186       auto I = CS->body_begin();
11187       while (I != CS->body_end()) {
11188         const auto *OED = dyn_cast<OMPExecutableDirective>(*I);
11189         if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind()) ||
11190             OMPTeamsFound) {
11191 
11192           OMPTeamsFound = false;
11193           break;
11194         }
11195         ++I;
11196       }
11197       assert(I != CS->body_end() && "Not found statement");
11198       S = *I;
11199     } else {
11200       const auto *OED = dyn_cast<OMPExecutableDirective>(S);
11201       OMPTeamsFound = OED && isOpenMPTeamsDirective(OED->getDirectiveKind());
11202     }
11203     if (!OMPTeamsFound) {
11204       Diag(StartLoc, diag::err_omp_target_contains_not_only_teams);
11205       Diag(DSAStack->getInnerTeamsRegionLoc(),
11206            diag::note_omp_nested_teams_construct_here);
11207       Diag(S->getBeginLoc(), diag::note_omp_nested_statement_here)
11208           << isa<OMPExecutableDirective>(S);
11209       return StmtError();
11210     }
11211   }
11212 
11213   setFunctionHasBranchProtectedScope();
11214 
11215   return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
11216 }
11217 
11218 StmtResult
11219 Sema::ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
11220                                          Stmt *AStmt, SourceLocation StartLoc,
11221                                          SourceLocation EndLoc) {
11222   if (!AStmt)
11223     return StmtError();
11224 
11225   auto *CS = cast<CapturedStmt>(AStmt);
11226   // 1.2.2 OpenMP Language Terminology
11227   // Structured block - An executable statement with a single entry at the
11228   // top and a single exit at the bottom.
11229   // The point of exit cannot be a branch out of the structured block.
11230   // longjmp() and throw() must not violate the entry/exit criteria.
11231   CS->getCapturedDecl()->setNothrow();
11232   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel);
11233        ThisCaptureLevel > 1; --ThisCaptureLevel) {
11234     CS = cast<CapturedStmt>(CS->getCapturedStmt());
11235     // 1.2.2 OpenMP Language Terminology
11236     // Structured block - An executable statement with a single entry at the
11237     // top and a single exit at the bottom.
11238     // The point of exit cannot be a branch out of the structured block.
11239     // longjmp() and throw() must not violate the entry/exit criteria.
11240     CS->getCapturedDecl()->setNothrow();
11241   }
11242 
11243   setFunctionHasBranchProtectedScope();
11244 
11245   return OMPTargetParallelDirective::Create(
11246       Context, StartLoc, EndLoc, Clauses, AStmt,
11247       DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion());
11248 }
11249 
11250 StmtResult Sema::ActOnOpenMPTargetParallelForDirective(
11251     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11252     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
11253   if (!AStmt)
11254     return StmtError();
11255 
11256   auto *CS = cast<CapturedStmt>(AStmt);
11257   // 1.2.2 OpenMP Language Terminology
11258   // Structured block - An executable statement with a single entry at the
11259   // top and a single exit at the bottom.
11260   // The point of exit cannot be a branch out of the structured block.
11261   // longjmp() and throw() must not violate the entry/exit criteria.
11262   CS->getCapturedDecl()->setNothrow();
11263   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
11264        ThisCaptureLevel > 1; --ThisCaptureLevel) {
11265     CS = cast<CapturedStmt>(CS->getCapturedStmt());
11266     // 1.2.2 OpenMP Language Terminology
11267     // Structured block - An executable statement with a single entry at the
11268     // top and a single exit at the bottom.
11269     // The point of exit cannot be a branch out of the structured block.
11270     // longjmp() and throw() must not violate the entry/exit criteria.
11271     CS->getCapturedDecl()->setNothrow();
11272   }
11273 
11274   OMPLoopBasedDirective::HelperExprs B;
11275   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
11276   // define the nested loops number.
11277   unsigned NestedLoopCount =
11278       checkOpenMPLoop(OMPD_target_parallel_for, getCollapseNumberExpr(Clauses),
11279                       getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
11280                       VarsWithImplicitDSA, B);
11281   if (NestedLoopCount == 0)
11282     return StmtError();
11283 
11284   assert((CurContext->isDependentContext() || B.builtAll()) &&
11285          "omp target parallel for loop exprs were not built");
11286 
11287   if (!CurContext->isDependentContext()) {
11288     // Finalize the clauses that need pre-built expressions for CodeGen.
11289     for (OMPClause *C : Clauses) {
11290       if (auto *LC = dyn_cast<OMPLinearClause>(C))
11291         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
11292                                      B.NumIterations, *this, CurScope,
11293                                      DSAStack))
11294           return StmtError();
11295     }
11296   }
11297 
11298   setFunctionHasBranchProtectedScope();
11299   return OMPTargetParallelForDirective::Create(
11300       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
11301       DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion());
11302 }
11303 
11304 /// Check for existence of a map clause in the list of clauses.
11305 static bool hasClauses(ArrayRef<OMPClause *> Clauses,
11306                        const OpenMPClauseKind K) {
11307   return llvm::any_of(
11308       Clauses, [K](const OMPClause *C) { return C->getClauseKind() == K; });
11309 }
11310 
11311 template <typename... Params>
11312 static bool hasClauses(ArrayRef<OMPClause *> Clauses, const OpenMPClauseKind K,
11313                        const Params... ClauseTypes) {
11314   return hasClauses(Clauses, K) || hasClauses(Clauses, ClauseTypes...);
11315 }
11316 
11317 StmtResult Sema::ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
11318                                                 Stmt *AStmt,
11319                                                 SourceLocation StartLoc,
11320                                                 SourceLocation EndLoc) {
11321   if (!AStmt)
11322     return StmtError();
11323 
11324   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
11325 
11326   // OpenMP [2.12.2, target data Construct, Restrictions]
11327   // At least one map, use_device_addr or use_device_ptr clause must appear on
11328   // the directive.
11329   if (!hasClauses(Clauses, OMPC_map, OMPC_use_device_ptr) &&
11330       (LangOpts.OpenMP < 50 || !hasClauses(Clauses, OMPC_use_device_addr))) {
11331     StringRef Expected;
11332     if (LangOpts.OpenMP < 50)
11333       Expected = "'map' or 'use_device_ptr'";
11334     else
11335       Expected = "'map', 'use_device_ptr', or 'use_device_addr'";
11336     Diag(StartLoc, diag::err_omp_no_clause_for_directive)
11337         << Expected << getOpenMPDirectiveName(OMPD_target_data);
11338     return StmtError();
11339   }
11340 
11341   setFunctionHasBranchProtectedScope();
11342 
11343   return OMPTargetDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
11344                                         AStmt);
11345 }
11346 
11347 StmtResult
11348 Sema::ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
11349                                           SourceLocation StartLoc,
11350                                           SourceLocation EndLoc, Stmt *AStmt) {
11351   if (!AStmt)
11352     return StmtError();
11353 
11354   auto *CS = cast<CapturedStmt>(AStmt);
11355   // 1.2.2 OpenMP Language Terminology
11356   // Structured block - An executable statement with a single entry at the
11357   // top and a single exit at the bottom.
11358   // The point of exit cannot be a branch out of the structured block.
11359   // longjmp() and throw() must not violate the entry/exit criteria.
11360   CS->getCapturedDecl()->setNothrow();
11361   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_enter_data);
11362        ThisCaptureLevel > 1; --ThisCaptureLevel) {
11363     CS = cast<CapturedStmt>(CS->getCapturedStmt());
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 
11372   // OpenMP [2.10.2, Restrictions, p. 99]
11373   // At least one map clause must appear on the directive.
11374   if (!hasClauses(Clauses, OMPC_map)) {
11375     Diag(StartLoc, diag::err_omp_no_clause_for_directive)
11376         << "'map'" << getOpenMPDirectiveName(OMPD_target_enter_data);
11377     return StmtError();
11378   }
11379 
11380   return OMPTargetEnterDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
11381                                              AStmt);
11382 }
11383 
11384 StmtResult
11385 Sema::ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
11386                                          SourceLocation StartLoc,
11387                                          SourceLocation EndLoc, Stmt *AStmt) {
11388   if (!AStmt)
11389     return StmtError();
11390 
11391   auto *CS = cast<CapturedStmt>(AStmt);
11392   // 1.2.2 OpenMP Language Terminology
11393   // Structured block - An executable statement with a single entry at the
11394   // top and a single exit at the bottom.
11395   // The point of exit cannot be a branch out of the structured block.
11396   // longjmp() and throw() must not violate the entry/exit criteria.
11397   CS->getCapturedDecl()->setNothrow();
11398   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_exit_data);
11399        ThisCaptureLevel > 1; --ThisCaptureLevel) {
11400     CS = cast<CapturedStmt>(CS->getCapturedStmt());
11401     // 1.2.2 OpenMP Language Terminology
11402     // Structured block - An executable statement with a single entry at the
11403     // top and a single exit at the bottom.
11404     // The point of exit cannot be a branch out of the structured block.
11405     // longjmp() and throw() must not violate the entry/exit criteria.
11406     CS->getCapturedDecl()->setNothrow();
11407   }
11408 
11409   // OpenMP [2.10.3, Restrictions, p. 102]
11410   // At least one map clause must appear on the directive.
11411   if (!hasClauses(Clauses, OMPC_map)) {
11412     Diag(StartLoc, diag::err_omp_no_clause_for_directive)
11413         << "'map'" << getOpenMPDirectiveName(OMPD_target_exit_data);
11414     return StmtError();
11415   }
11416 
11417   return OMPTargetExitDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
11418                                             AStmt);
11419 }
11420 
11421 StmtResult Sema::ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
11422                                                   SourceLocation StartLoc,
11423                                                   SourceLocation EndLoc,
11424                                                   Stmt *AStmt) {
11425   if (!AStmt)
11426     return StmtError();
11427 
11428   auto *CS = cast<CapturedStmt>(AStmt);
11429   // 1.2.2 OpenMP Language Terminology
11430   // Structured block - An executable statement with a single entry at the
11431   // top and a single exit at the bottom.
11432   // The point of exit cannot be a branch out of the structured block.
11433   // longjmp() and throw() must not violate the entry/exit criteria.
11434   CS->getCapturedDecl()->setNothrow();
11435   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_update);
11436        ThisCaptureLevel > 1; --ThisCaptureLevel) {
11437     CS = cast<CapturedStmt>(CS->getCapturedStmt());
11438     // 1.2.2 OpenMP Language Terminology
11439     // Structured block - An executable statement with a single entry at the
11440     // top and a single exit at the bottom.
11441     // The point of exit cannot be a branch out of the structured block.
11442     // longjmp() and throw() must not violate the entry/exit criteria.
11443     CS->getCapturedDecl()->setNothrow();
11444   }
11445 
11446   if (!hasClauses(Clauses, OMPC_to, OMPC_from)) {
11447     Diag(StartLoc, diag::err_omp_at_least_one_motion_clause_required);
11448     return StmtError();
11449   }
11450   return OMPTargetUpdateDirective::Create(Context, StartLoc, EndLoc, Clauses,
11451                                           AStmt);
11452 }
11453 
11454 StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
11455                                            Stmt *AStmt, SourceLocation StartLoc,
11456                                            SourceLocation EndLoc) {
11457   if (!AStmt)
11458     return StmtError();
11459 
11460   auto *CS = cast<CapturedStmt>(AStmt);
11461   // 1.2.2 OpenMP Language Terminology
11462   // Structured block - An executable statement with a single entry at the
11463   // top and a single exit at the bottom.
11464   // The point of exit cannot be a branch out of the structured block.
11465   // longjmp() and throw() must not violate the entry/exit criteria.
11466   CS->getCapturedDecl()->setNothrow();
11467 
11468   setFunctionHasBranchProtectedScope();
11469 
11470   DSAStack->setParentTeamsRegionLoc(StartLoc);
11471 
11472   return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
11473 }
11474 
11475 StmtResult
11476 Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
11477                                             SourceLocation EndLoc,
11478                                             OpenMPDirectiveKind CancelRegion) {
11479   if (DSAStack->isParentNowaitRegion()) {
11480     Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0;
11481     return StmtError();
11482   }
11483   if (DSAStack->isParentOrderedRegion()) {
11484     Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0;
11485     return StmtError();
11486   }
11487   return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc,
11488                                                CancelRegion);
11489 }
11490 
11491 StmtResult Sema::ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
11492                                             SourceLocation StartLoc,
11493                                             SourceLocation EndLoc,
11494                                             OpenMPDirectiveKind CancelRegion) {
11495   if (DSAStack->isParentNowaitRegion()) {
11496     Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1;
11497     return StmtError();
11498   }
11499   if (DSAStack->isParentOrderedRegion()) {
11500     Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1;
11501     return StmtError();
11502   }
11503   DSAStack->setParentCancelRegion(/*Cancel=*/true);
11504   return OMPCancelDirective::Create(Context, StartLoc, EndLoc, Clauses,
11505                                     CancelRegion);
11506 }
11507 
11508 static bool checkReductionClauseWithNogroup(Sema &S,
11509                                             ArrayRef<OMPClause *> Clauses) {
11510   const OMPClause *ReductionClause = nullptr;
11511   const OMPClause *NogroupClause = nullptr;
11512   for (const OMPClause *C : Clauses) {
11513     if (C->getClauseKind() == OMPC_reduction) {
11514       ReductionClause = C;
11515       if (NogroupClause)
11516         break;
11517       continue;
11518     }
11519     if (C->getClauseKind() == OMPC_nogroup) {
11520       NogroupClause = C;
11521       if (ReductionClause)
11522         break;
11523       continue;
11524     }
11525   }
11526   if (ReductionClause && NogroupClause) {
11527     S.Diag(ReductionClause->getBeginLoc(), diag::err_omp_reduction_with_nogroup)
11528         << SourceRange(NogroupClause->getBeginLoc(),
11529                        NogroupClause->getEndLoc());
11530     return true;
11531   }
11532   return false;
11533 }
11534 
11535 StmtResult Sema::ActOnOpenMPTaskLoopDirective(
11536     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11537     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
11538   if (!AStmt)
11539     return StmtError();
11540 
11541   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
11542   OMPLoopBasedDirective::HelperExprs B;
11543   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
11544   // define the nested loops number.
11545   unsigned NestedLoopCount =
11546       checkOpenMPLoop(OMPD_taskloop, getCollapseNumberExpr(Clauses),
11547                       /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
11548                       VarsWithImplicitDSA, B);
11549   if (NestedLoopCount == 0)
11550     return StmtError();
11551 
11552   assert((CurContext->isDependentContext() || B.builtAll()) &&
11553          "omp for loop exprs were not built");
11554 
11555   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
11556   // The grainsize clause and num_tasks clause are mutually exclusive and may
11557   // not appear on the same taskloop directive.
11558   if (checkMutuallyExclusiveClauses(*this, Clauses,
11559                                     {OMPC_grainsize, OMPC_num_tasks}))
11560     return StmtError();
11561   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
11562   // If a reduction clause is present on the taskloop directive, the nogroup
11563   // clause must not be specified.
11564   if (checkReductionClauseWithNogroup(*this, Clauses))
11565     return StmtError();
11566 
11567   setFunctionHasBranchProtectedScope();
11568   return OMPTaskLoopDirective::Create(Context, StartLoc, EndLoc,
11569                                       NestedLoopCount, Clauses, AStmt, B,
11570                                       DSAStack->isCancelRegion());
11571 }
11572 
11573 StmtResult Sema::ActOnOpenMPTaskLoopSimdDirective(
11574     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11575     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
11576   if (!AStmt)
11577     return StmtError();
11578 
11579   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
11580   OMPLoopBasedDirective::HelperExprs B;
11581   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
11582   // define the nested loops number.
11583   unsigned NestedLoopCount =
11584       checkOpenMPLoop(OMPD_taskloop_simd, getCollapseNumberExpr(Clauses),
11585                       /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
11586                       VarsWithImplicitDSA, B);
11587   if (NestedLoopCount == 0)
11588     return StmtError();
11589 
11590   assert((CurContext->isDependentContext() || B.builtAll()) &&
11591          "omp for loop exprs were not built");
11592 
11593   if (!CurContext->isDependentContext()) {
11594     // Finalize the clauses that need pre-built expressions for CodeGen.
11595     for (OMPClause *C : Clauses) {
11596       if (auto *LC = dyn_cast<OMPLinearClause>(C))
11597         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
11598                                      B.NumIterations, *this, CurScope,
11599                                      DSAStack))
11600           return StmtError();
11601     }
11602   }
11603 
11604   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
11605   // The grainsize clause and num_tasks clause are mutually exclusive and may
11606   // not appear on the same taskloop directive.
11607   if (checkMutuallyExclusiveClauses(*this, Clauses,
11608                                     {OMPC_grainsize, OMPC_num_tasks}))
11609     return StmtError();
11610   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
11611   // If a reduction clause is present on the taskloop directive, the nogroup
11612   // clause must not be specified.
11613   if (checkReductionClauseWithNogroup(*this, Clauses))
11614     return StmtError();
11615   if (checkSimdlenSafelenSpecified(*this, Clauses))
11616     return StmtError();
11617 
11618   setFunctionHasBranchProtectedScope();
11619   return OMPTaskLoopSimdDirective::Create(Context, StartLoc, EndLoc,
11620                                           NestedLoopCount, Clauses, AStmt, B);
11621 }
11622 
11623 StmtResult Sema::ActOnOpenMPMasterTaskLoopDirective(
11624     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11625     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
11626   if (!AStmt)
11627     return StmtError();
11628 
11629   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
11630   OMPLoopBasedDirective::HelperExprs B;
11631   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
11632   // define the nested loops number.
11633   unsigned NestedLoopCount =
11634       checkOpenMPLoop(OMPD_master_taskloop, getCollapseNumberExpr(Clauses),
11635                       /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
11636                       VarsWithImplicitDSA, B);
11637   if (NestedLoopCount == 0)
11638     return StmtError();
11639 
11640   assert((CurContext->isDependentContext() || B.builtAll()) &&
11641          "omp for loop exprs were not built");
11642 
11643   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
11644   // The grainsize clause and num_tasks clause are mutually exclusive and may
11645   // not appear on the same taskloop directive.
11646   if (checkMutuallyExclusiveClauses(*this, Clauses,
11647                                     {OMPC_grainsize, OMPC_num_tasks}))
11648     return StmtError();
11649   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
11650   // If a reduction clause is present on the taskloop directive, the nogroup
11651   // clause must not be specified.
11652   if (checkReductionClauseWithNogroup(*this, Clauses))
11653     return StmtError();
11654 
11655   setFunctionHasBranchProtectedScope();
11656   return OMPMasterTaskLoopDirective::Create(Context, StartLoc, EndLoc,
11657                                             NestedLoopCount, Clauses, AStmt, B,
11658                                             DSAStack->isCancelRegion());
11659 }
11660 
11661 StmtResult Sema::ActOnOpenMPMasterTaskLoopSimdDirective(
11662     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11663     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
11664   if (!AStmt)
11665     return StmtError();
11666 
11667   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
11668   OMPLoopBasedDirective::HelperExprs B;
11669   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
11670   // define the nested loops number.
11671   unsigned NestedLoopCount =
11672       checkOpenMPLoop(OMPD_master_taskloop_simd, getCollapseNumberExpr(Clauses),
11673                       /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
11674                       VarsWithImplicitDSA, B);
11675   if (NestedLoopCount == 0)
11676     return StmtError();
11677 
11678   assert((CurContext->isDependentContext() || B.builtAll()) &&
11679          "omp for loop exprs were not built");
11680 
11681   if (!CurContext->isDependentContext()) {
11682     // Finalize the clauses that need pre-built expressions for CodeGen.
11683     for (OMPClause *C : Clauses) {
11684       if (auto *LC = dyn_cast<OMPLinearClause>(C))
11685         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
11686                                      B.NumIterations, *this, CurScope,
11687                                      DSAStack))
11688           return StmtError();
11689     }
11690   }
11691 
11692   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
11693   // The grainsize clause and num_tasks clause are mutually exclusive and may
11694   // not appear on the same taskloop directive.
11695   if (checkMutuallyExclusiveClauses(*this, Clauses,
11696                                     {OMPC_grainsize, OMPC_num_tasks}))
11697     return StmtError();
11698   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
11699   // If a reduction clause is present on the taskloop directive, the nogroup
11700   // clause must not be specified.
11701   if (checkReductionClauseWithNogroup(*this, Clauses))
11702     return StmtError();
11703   if (checkSimdlenSafelenSpecified(*this, Clauses))
11704     return StmtError();
11705 
11706   setFunctionHasBranchProtectedScope();
11707   return OMPMasterTaskLoopSimdDirective::Create(
11708       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
11709 }
11710 
11711 StmtResult Sema::ActOnOpenMPParallelMasterTaskLoopDirective(
11712     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11713     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
11714   if (!AStmt)
11715     return StmtError();
11716 
11717   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
11718   auto *CS = cast<CapturedStmt>(AStmt);
11719   // 1.2.2 OpenMP Language Terminology
11720   // Structured block - An executable statement with a single entry at the
11721   // top and a single exit at the bottom.
11722   // The point of exit cannot be a branch out of the structured block.
11723   // longjmp() and throw() must not violate the entry/exit criteria.
11724   CS->getCapturedDecl()->setNothrow();
11725   for (int ThisCaptureLevel =
11726            getOpenMPCaptureLevels(OMPD_parallel_master_taskloop);
11727        ThisCaptureLevel > 1; --ThisCaptureLevel) {
11728     CS = cast<CapturedStmt>(CS->getCapturedStmt());
11729     // 1.2.2 OpenMP Language Terminology
11730     // Structured block - An executable statement with a single entry at the
11731     // top and a single exit at the bottom.
11732     // The point of exit cannot be a branch out of the structured block.
11733     // longjmp() and throw() must not violate the entry/exit criteria.
11734     CS->getCapturedDecl()->setNothrow();
11735   }
11736 
11737   OMPLoopBasedDirective::HelperExprs B;
11738   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
11739   // define the nested loops number.
11740   unsigned NestedLoopCount = checkOpenMPLoop(
11741       OMPD_parallel_master_taskloop, getCollapseNumberExpr(Clauses),
11742       /*OrderedLoopCountExpr=*/nullptr, CS, *this, *DSAStack,
11743       VarsWithImplicitDSA, B);
11744   if (NestedLoopCount == 0)
11745     return StmtError();
11746 
11747   assert((CurContext->isDependentContext() || B.builtAll()) &&
11748          "omp for loop exprs were not built");
11749 
11750   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
11751   // The grainsize clause and num_tasks clause are mutually exclusive and may
11752   // not appear on the same taskloop directive.
11753   if (checkMutuallyExclusiveClauses(*this, Clauses,
11754                                     {OMPC_grainsize, OMPC_num_tasks}))
11755     return StmtError();
11756   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
11757   // If a reduction clause is present on the taskloop directive, the nogroup
11758   // clause must not be specified.
11759   if (checkReductionClauseWithNogroup(*this, Clauses))
11760     return StmtError();
11761 
11762   setFunctionHasBranchProtectedScope();
11763   return OMPParallelMasterTaskLoopDirective::Create(
11764       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
11765       DSAStack->isCancelRegion());
11766 }
11767 
11768 StmtResult Sema::ActOnOpenMPParallelMasterTaskLoopSimdDirective(
11769     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11770     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
11771   if (!AStmt)
11772     return StmtError();
11773 
11774   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
11775   auto *CS = cast<CapturedStmt>(AStmt);
11776   // 1.2.2 OpenMP Language Terminology
11777   // Structured block - An executable statement with a single entry at the
11778   // top and a single exit at the bottom.
11779   // The point of exit cannot be a branch out of the structured block.
11780   // longjmp() and throw() must not violate the entry/exit criteria.
11781   CS->getCapturedDecl()->setNothrow();
11782   for (int ThisCaptureLevel =
11783            getOpenMPCaptureLevels(OMPD_parallel_master_taskloop_simd);
11784        ThisCaptureLevel > 1; --ThisCaptureLevel) {
11785     CS = cast<CapturedStmt>(CS->getCapturedStmt());
11786     // 1.2.2 OpenMP Language Terminology
11787     // Structured block - An executable statement with a single entry at the
11788     // top and a single exit at the bottom.
11789     // The point of exit cannot be a branch out of the structured block.
11790     // longjmp() and throw() must not violate the entry/exit criteria.
11791     CS->getCapturedDecl()->setNothrow();
11792   }
11793 
11794   OMPLoopBasedDirective::HelperExprs B;
11795   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
11796   // define the nested loops number.
11797   unsigned NestedLoopCount = checkOpenMPLoop(
11798       OMPD_parallel_master_taskloop_simd, getCollapseNumberExpr(Clauses),
11799       /*OrderedLoopCountExpr=*/nullptr, CS, *this, *DSAStack,
11800       VarsWithImplicitDSA, B);
11801   if (NestedLoopCount == 0)
11802     return StmtError();
11803 
11804   assert((CurContext->isDependentContext() || B.builtAll()) &&
11805          "omp for loop exprs were not built");
11806 
11807   if (!CurContext->isDependentContext()) {
11808     // Finalize the clauses that need pre-built expressions for CodeGen.
11809     for (OMPClause *C : Clauses) {
11810       if (auto *LC = dyn_cast<OMPLinearClause>(C))
11811         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
11812                                      B.NumIterations, *this, CurScope,
11813                                      DSAStack))
11814           return StmtError();
11815     }
11816   }
11817 
11818   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
11819   // The grainsize clause and num_tasks clause are mutually exclusive and may
11820   // not appear on the same taskloop directive.
11821   if (checkMutuallyExclusiveClauses(*this, Clauses,
11822                                     {OMPC_grainsize, OMPC_num_tasks}))
11823     return StmtError();
11824   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
11825   // If a reduction clause is present on the taskloop directive, the nogroup
11826   // clause must not be specified.
11827   if (checkReductionClauseWithNogroup(*this, Clauses))
11828     return StmtError();
11829   if (checkSimdlenSafelenSpecified(*this, Clauses))
11830     return StmtError();
11831 
11832   setFunctionHasBranchProtectedScope();
11833   return OMPParallelMasterTaskLoopSimdDirective::Create(
11834       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
11835 }
11836 
11837 StmtResult Sema::ActOnOpenMPDistributeDirective(
11838     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11839     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
11840   if (!AStmt)
11841     return StmtError();
11842 
11843   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
11844   OMPLoopBasedDirective::HelperExprs B;
11845   // In presence of clause 'collapse' with number of loops, it will
11846   // define the nested loops number.
11847   unsigned NestedLoopCount =
11848       checkOpenMPLoop(OMPD_distribute, getCollapseNumberExpr(Clauses),
11849                       nullptr /*ordered not a clause on distribute*/, AStmt,
11850                       *this, *DSAStack, VarsWithImplicitDSA, B);
11851   if (NestedLoopCount == 0)
11852     return StmtError();
11853 
11854   assert((CurContext->isDependentContext() || B.builtAll()) &&
11855          "omp for loop exprs were not built");
11856 
11857   setFunctionHasBranchProtectedScope();
11858   return OMPDistributeDirective::Create(Context, StartLoc, EndLoc,
11859                                         NestedLoopCount, Clauses, AStmt, B);
11860 }
11861 
11862 StmtResult Sema::ActOnOpenMPDistributeParallelForDirective(
11863     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11864     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
11865   if (!AStmt)
11866     return StmtError();
11867 
11868   auto *CS = cast<CapturedStmt>(AStmt);
11869   // 1.2.2 OpenMP Language Terminology
11870   // Structured block - An executable statement with a single entry at the
11871   // top and a single exit at the bottom.
11872   // The point of exit cannot be a branch out of the structured block.
11873   // longjmp() and throw() must not violate the entry/exit criteria.
11874   CS->getCapturedDecl()->setNothrow();
11875   for (int ThisCaptureLevel =
11876            getOpenMPCaptureLevels(OMPD_distribute_parallel_for);
11877        ThisCaptureLevel > 1; --ThisCaptureLevel) {
11878     CS = cast<CapturedStmt>(CS->getCapturedStmt());
11879     // 1.2.2 OpenMP Language Terminology
11880     // Structured block - An executable statement with a single entry at the
11881     // top and a single exit at the bottom.
11882     // The point of exit cannot be a branch out of the structured block.
11883     // longjmp() and throw() must not violate the entry/exit criteria.
11884     CS->getCapturedDecl()->setNothrow();
11885   }
11886 
11887   OMPLoopBasedDirective::HelperExprs B;
11888   // In presence of clause 'collapse' with number of loops, it will
11889   // define the nested loops number.
11890   unsigned NestedLoopCount = checkOpenMPLoop(
11891       OMPD_distribute_parallel_for, getCollapseNumberExpr(Clauses),
11892       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
11893       VarsWithImplicitDSA, B);
11894   if (NestedLoopCount == 0)
11895     return StmtError();
11896 
11897   assert((CurContext->isDependentContext() || B.builtAll()) &&
11898          "omp for loop exprs were not built");
11899 
11900   setFunctionHasBranchProtectedScope();
11901   return OMPDistributeParallelForDirective::Create(
11902       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
11903       DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion());
11904 }
11905 
11906 StmtResult Sema::ActOnOpenMPDistributeParallelForSimdDirective(
11907     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11908     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
11909   if (!AStmt)
11910     return StmtError();
11911 
11912   auto *CS = cast<CapturedStmt>(AStmt);
11913   // 1.2.2 OpenMP Language Terminology
11914   // Structured block - An executable statement with a single entry at the
11915   // top and a single exit at the bottom.
11916   // The point of exit cannot be a branch out of the structured block.
11917   // longjmp() and throw() must not violate the entry/exit criteria.
11918   CS->getCapturedDecl()->setNothrow();
11919   for (int ThisCaptureLevel =
11920            getOpenMPCaptureLevels(OMPD_distribute_parallel_for_simd);
11921        ThisCaptureLevel > 1; --ThisCaptureLevel) {
11922     CS = cast<CapturedStmt>(CS->getCapturedStmt());
11923     // 1.2.2 OpenMP Language Terminology
11924     // Structured block - An executable statement with a single entry at the
11925     // top and a single exit at the bottom.
11926     // The point of exit cannot be a branch out of the structured block.
11927     // longjmp() and throw() must not violate the entry/exit criteria.
11928     CS->getCapturedDecl()->setNothrow();
11929   }
11930 
11931   OMPLoopBasedDirective::HelperExprs B;
11932   // In presence of clause 'collapse' with number of loops, it will
11933   // define the nested loops number.
11934   unsigned NestedLoopCount = checkOpenMPLoop(
11935       OMPD_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
11936       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
11937       VarsWithImplicitDSA, B);
11938   if (NestedLoopCount == 0)
11939     return StmtError();
11940 
11941   assert((CurContext->isDependentContext() || B.builtAll()) &&
11942          "omp for loop exprs were not built");
11943 
11944   if (!CurContext->isDependentContext()) {
11945     // Finalize the clauses that need pre-built expressions for CodeGen.
11946     for (OMPClause *C : Clauses) {
11947       if (auto *LC = dyn_cast<OMPLinearClause>(C))
11948         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
11949                                      B.NumIterations, *this, CurScope,
11950                                      DSAStack))
11951           return StmtError();
11952     }
11953   }
11954 
11955   if (checkSimdlenSafelenSpecified(*this, Clauses))
11956     return StmtError();
11957 
11958   setFunctionHasBranchProtectedScope();
11959   return OMPDistributeParallelForSimdDirective::Create(
11960       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
11961 }
11962 
11963 StmtResult Sema::ActOnOpenMPDistributeSimdDirective(
11964     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11965     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
11966   if (!AStmt)
11967     return StmtError();
11968 
11969   auto *CS = cast<CapturedStmt>(AStmt);
11970   // 1.2.2 OpenMP Language Terminology
11971   // Structured block - An executable statement with a single entry at the
11972   // top and a single exit at the bottom.
11973   // The point of exit cannot be a branch out of the structured block.
11974   // longjmp() and throw() must not violate the entry/exit criteria.
11975   CS->getCapturedDecl()->setNothrow();
11976   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_distribute_simd);
11977        ThisCaptureLevel > 1; --ThisCaptureLevel) {
11978     CS = cast<CapturedStmt>(CS->getCapturedStmt());
11979     // 1.2.2 OpenMP Language Terminology
11980     // Structured block - An executable statement with a single entry at the
11981     // top and a single exit at the bottom.
11982     // The point of exit cannot be a branch out of the structured block.
11983     // longjmp() and throw() must not violate the entry/exit criteria.
11984     CS->getCapturedDecl()->setNothrow();
11985   }
11986 
11987   OMPLoopBasedDirective::HelperExprs B;
11988   // In presence of clause 'collapse' with number of loops, it will
11989   // define the nested loops number.
11990   unsigned NestedLoopCount =
11991       checkOpenMPLoop(OMPD_distribute_simd, getCollapseNumberExpr(Clauses),
11992                       nullptr /*ordered not a clause on distribute*/, CS, *this,
11993                       *DSAStack, VarsWithImplicitDSA, B);
11994   if (NestedLoopCount == 0)
11995     return StmtError();
11996 
11997   assert((CurContext->isDependentContext() || B.builtAll()) &&
11998          "omp for loop exprs were not built");
11999 
12000   if (!CurContext->isDependentContext()) {
12001     // Finalize the clauses that need pre-built expressions for CodeGen.
12002     for (OMPClause *C : Clauses) {
12003       if (auto *LC = dyn_cast<OMPLinearClause>(C))
12004         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
12005                                      B.NumIterations, *this, CurScope,
12006                                      DSAStack))
12007           return StmtError();
12008     }
12009   }
12010 
12011   if (checkSimdlenSafelenSpecified(*this, Clauses))
12012     return StmtError();
12013 
12014   setFunctionHasBranchProtectedScope();
12015   return OMPDistributeSimdDirective::Create(Context, StartLoc, EndLoc,
12016                                             NestedLoopCount, Clauses, AStmt, B);
12017 }
12018 
12019 StmtResult Sema::ActOnOpenMPTargetParallelForSimdDirective(
12020     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
12021     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
12022   if (!AStmt)
12023     return StmtError();
12024 
12025   auto *CS = cast<CapturedStmt>(AStmt);
12026   // 1.2.2 OpenMP Language Terminology
12027   // Structured block - An executable statement with a single entry at the
12028   // top and a single exit at the bottom.
12029   // The point of exit cannot be a branch out of the structured block.
12030   // longjmp() and throw() must not violate the entry/exit criteria.
12031   CS->getCapturedDecl()->setNothrow();
12032   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
12033        ThisCaptureLevel > 1; --ThisCaptureLevel) {
12034     CS = cast<CapturedStmt>(CS->getCapturedStmt());
12035     // 1.2.2 OpenMP Language Terminology
12036     // Structured block - An executable statement with a single entry at the
12037     // top and a single exit at the bottom.
12038     // The point of exit cannot be a branch out of the structured block.
12039     // longjmp() and throw() must not violate the entry/exit criteria.
12040     CS->getCapturedDecl()->setNothrow();
12041   }
12042 
12043   OMPLoopBasedDirective::HelperExprs B;
12044   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
12045   // define the nested loops number.
12046   unsigned NestedLoopCount = checkOpenMPLoop(
12047       OMPD_target_parallel_for_simd, getCollapseNumberExpr(Clauses),
12048       getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
12049       VarsWithImplicitDSA, B);
12050   if (NestedLoopCount == 0)
12051     return StmtError();
12052 
12053   assert((CurContext->isDependentContext() || B.builtAll()) &&
12054          "omp target parallel for simd loop exprs were not built");
12055 
12056   if (!CurContext->isDependentContext()) {
12057     // Finalize the clauses that need pre-built expressions for CodeGen.
12058     for (OMPClause *C : Clauses) {
12059       if (auto *LC = dyn_cast<OMPLinearClause>(C))
12060         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
12061                                      B.NumIterations, *this, CurScope,
12062                                      DSAStack))
12063           return StmtError();
12064     }
12065   }
12066   if (checkSimdlenSafelenSpecified(*this, Clauses))
12067     return StmtError();
12068 
12069   setFunctionHasBranchProtectedScope();
12070   return OMPTargetParallelForSimdDirective::Create(
12071       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
12072 }
12073 
12074 StmtResult Sema::ActOnOpenMPTargetSimdDirective(
12075     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
12076     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
12077   if (!AStmt)
12078     return StmtError();
12079 
12080   auto *CS = cast<CapturedStmt>(AStmt);
12081   // 1.2.2 OpenMP Language Terminology
12082   // Structured block - An executable statement with a single entry at the
12083   // top and a single exit at the bottom.
12084   // The point of exit cannot be a branch out of the structured block.
12085   // longjmp() and throw() must not violate the entry/exit criteria.
12086   CS->getCapturedDecl()->setNothrow();
12087   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_simd);
12088        ThisCaptureLevel > 1; --ThisCaptureLevel) {
12089     CS = cast<CapturedStmt>(CS->getCapturedStmt());
12090     // 1.2.2 OpenMP Language Terminology
12091     // Structured block - An executable statement with a single entry at the
12092     // top and a single exit at the bottom.
12093     // The point of exit cannot be a branch out of the structured block.
12094     // longjmp() and throw() must not violate the entry/exit criteria.
12095     CS->getCapturedDecl()->setNothrow();
12096   }
12097 
12098   OMPLoopBasedDirective::HelperExprs B;
12099   // In presence of clause 'collapse' with number of loops, it will define the
12100   // nested loops number.
12101   unsigned NestedLoopCount =
12102       checkOpenMPLoop(OMPD_target_simd, getCollapseNumberExpr(Clauses),
12103                       getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
12104                       VarsWithImplicitDSA, B);
12105   if (NestedLoopCount == 0)
12106     return StmtError();
12107 
12108   assert((CurContext->isDependentContext() || B.builtAll()) &&
12109          "omp target simd loop exprs were not built");
12110 
12111   if (!CurContext->isDependentContext()) {
12112     // Finalize the clauses that need pre-built expressions for CodeGen.
12113     for (OMPClause *C : Clauses) {
12114       if (auto *LC = dyn_cast<OMPLinearClause>(C))
12115         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
12116                                      B.NumIterations, *this, CurScope,
12117                                      DSAStack))
12118           return StmtError();
12119     }
12120   }
12121 
12122   if (checkSimdlenSafelenSpecified(*this, Clauses))
12123     return StmtError();
12124 
12125   setFunctionHasBranchProtectedScope();
12126   return OMPTargetSimdDirective::Create(Context, StartLoc, EndLoc,
12127                                         NestedLoopCount, Clauses, AStmt, B);
12128 }
12129 
12130 StmtResult Sema::ActOnOpenMPTeamsDistributeDirective(
12131     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
12132     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
12133   if (!AStmt)
12134     return StmtError();
12135 
12136   auto *CS = cast<CapturedStmt>(AStmt);
12137   // 1.2.2 OpenMP Language Terminology
12138   // Structured block - An executable statement with a single entry at the
12139   // top and a single exit at the bottom.
12140   // The point of exit cannot be a branch out of the structured block.
12141   // longjmp() and throw() must not violate the entry/exit criteria.
12142   CS->getCapturedDecl()->setNothrow();
12143   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_teams_distribute);
12144        ThisCaptureLevel > 1; --ThisCaptureLevel) {
12145     CS = cast<CapturedStmt>(CS->getCapturedStmt());
12146     // 1.2.2 OpenMP Language Terminology
12147     // Structured block - An executable statement with a single entry at the
12148     // top and a single exit at the bottom.
12149     // The point of exit cannot be a branch out of the structured block.
12150     // longjmp() and throw() must not violate the entry/exit criteria.
12151     CS->getCapturedDecl()->setNothrow();
12152   }
12153 
12154   OMPLoopBasedDirective::HelperExprs B;
12155   // In presence of clause 'collapse' with number of loops, it will
12156   // define the nested loops number.
12157   unsigned NestedLoopCount =
12158       checkOpenMPLoop(OMPD_teams_distribute, getCollapseNumberExpr(Clauses),
12159                       nullptr /*ordered not a clause on distribute*/, CS, *this,
12160                       *DSAStack, VarsWithImplicitDSA, B);
12161   if (NestedLoopCount == 0)
12162     return StmtError();
12163 
12164   assert((CurContext->isDependentContext() || B.builtAll()) &&
12165          "omp teams distribute loop exprs were not built");
12166 
12167   setFunctionHasBranchProtectedScope();
12168 
12169   DSAStack->setParentTeamsRegionLoc(StartLoc);
12170 
12171   return OMPTeamsDistributeDirective::Create(
12172       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
12173 }
12174 
12175 StmtResult Sema::ActOnOpenMPTeamsDistributeSimdDirective(
12176     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
12177     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
12178   if (!AStmt)
12179     return StmtError();
12180 
12181   auto *CS = cast<CapturedStmt>(AStmt);
12182   // 1.2.2 OpenMP Language Terminology
12183   // Structured block - An executable statement with a single entry at the
12184   // top and a single exit at the bottom.
12185   // The point of exit cannot be a branch out of the structured block.
12186   // longjmp() and throw() must not violate the entry/exit criteria.
12187   CS->getCapturedDecl()->setNothrow();
12188   for (int ThisCaptureLevel =
12189            getOpenMPCaptureLevels(OMPD_teams_distribute_simd);
12190        ThisCaptureLevel > 1; --ThisCaptureLevel) {
12191     CS = cast<CapturedStmt>(CS->getCapturedStmt());
12192     // 1.2.2 OpenMP Language Terminology
12193     // Structured block - An executable statement with a single entry at the
12194     // top and a single exit at the bottom.
12195     // The point of exit cannot be a branch out of the structured block.
12196     // longjmp() and throw() must not violate the entry/exit criteria.
12197     CS->getCapturedDecl()->setNothrow();
12198   }
12199 
12200   OMPLoopBasedDirective::HelperExprs B;
12201   // In presence of clause 'collapse' with number of loops, it will
12202   // define the nested loops number.
12203   unsigned NestedLoopCount = checkOpenMPLoop(
12204       OMPD_teams_distribute_simd, getCollapseNumberExpr(Clauses),
12205       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
12206       VarsWithImplicitDSA, B);
12207 
12208   if (NestedLoopCount == 0)
12209     return StmtError();
12210 
12211   assert((CurContext->isDependentContext() || B.builtAll()) &&
12212          "omp teams distribute simd loop exprs were not built");
12213 
12214   if (!CurContext->isDependentContext()) {
12215     // Finalize the clauses that need pre-built expressions for CodeGen.
12216     for (OMPClause *C : Clauses) {
12217       if (auto *LC = dyn_cast<OMPLinearClause>(C))
12218         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
12219                                      B.NumIterations, *this, CurScope,
12220                                      DSAStack))
12221           return StmtError();
12222     }
12223   }
12224 
12225   if (checkSimdlenSafelenSpecified(*this, Clauses))
12226     return StmtError();
12227 
12228   setFunctionHasBranchProtectedScope();
12229 
12230   DSAStack->setParentTeamsRegionLoc(StartLoc);
12231 
12232   return OMPTeamsDistributeSimdDirective::Create(
12233       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
12234 }
12235 
12236 StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForSimdDirective(
12237     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
12238     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
12239   if (!AStmt)
12240     return StmtError();
12241 
12242   auto *CS = cast<CapturedStmt>(AStmt);
12243   // 1.2.2 OpenMP Language Terminology
12244   // Structured block - An executable statement with a single entry at the
12245   // top and a single exit at the bottom.
12246   // The point of exit cannot be a branch out of the structured block.
12247   // longjmp() and throw() must not violate the entry/exit criteria.
12248   CS->getCapturedDecl()->setNothrow();
12249 
12250   for (int ThisCaptureLevel =
12251            getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for_simd);
12252        ThisCaptureLevel > 1; --ThisCaptureLevel) {
12253     CS = cast<CapturedStmt>(CS->getCapturedStmt());
12254     // 1.2.2 OpenMP Language Terminology
12255     // Structured block - An executable statement with a single entry at the
12256     // top and a single exit at the bottom.
12257     // The point of exit cannot be a branch out of the structured block.
12258     // longjmp() and throw() must not violate the entry/exit criteria.
12259     CS->getCapturedDecl()->setNothrow();
12260   }
12261 
12262   OMPLoopBasedDirective::HelperExprs B;
12263   // In presence of clause 'collapse' with number of loops, it will
12264   // define the nested loops number.
12265   unsigned NestedLoopCount = checkOpenMPLoop(
12266       OMPD_teams_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
12267       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
12268       VarsWithImplicitDSA, B);
12269 
12270   if (NestedLoopCount == 0)
12271     return StmtError();
12272 
12273   assert((CurContext->isDependentContext() || B.builtAll()) &&
12274          "omp for loop exprs were not built");
12275 
12276   if (!CurContext->isDependentContext()) {
12277     // Finalize the clauses that need pre-built expressions for CodeGen.
12278     for (OMPClause *C : Clauses) {
12279       if (auto *LC = dyn_cast<OMPLinearClause>(C))
12280         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
12281                                      B.NumIterations, *this, CurScope,
12282                                      DSAStack))
12283           return StmtError();
12284     }
12285   }
12286 
12287   if (checkSimdlenSafelenSpecified(*this, Clauses))
12288     return StmtError();
12289 
12290   setFunctionHasBranchProtectedScope();
12291 
12292   DSAStack->setParentTeamsRegionLoc(StartLoc);
12293 
12294   return OMPTeamsDistributeParallelForSimdDirective::Create(
12295       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
12296 }
12297 
12298 StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForDirective(
12299     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
12300     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
12301   if (!AStmt)
12302     return StmtError();
12303 
12304   auto *CS = cast<CapturedStmt>(AStmt);
12305   // 1.2.2 OpenMP Language Terminology
12306   // Structured block - An executable statement with a single entry at the
12307   // top and a single exit at the bottom.
12308   // The point of exit cannot be a branch out of the structured block.
12309   // longjmp() and throw() must not violate the entry/exit criteria.
12310   CS->getCapturedDecl()->setNothrow();
12311 
12312   for (int ThisCaptureLevel =
12313            getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for);
12314        ThisCaptureLevel > 1; --ThisCaptureLevel) {
12315     CS = cast<CapturedStmt>(CS->getCapturedStmt());
12316     // 1.2.2 OpenMP Language Terminology
12317     // Structured block - An executable statement with a single entry at the
12318     // top and a single exit at the bottom.
12319     // The point of exit cannot be a branch out of the structured block.
12320     // longjmp() and throw() must not violate the entry/exit criteria.
12321     CS->getCapturedDecl()->setNothrow();
12322   }
12323 
12324   OMPLoopBasedDirective::HelperExprs B;
12325   // In presence of clause 'collapse' with number of loops, it will
12326   // define the nested loops number.
12327   unsigned NestedLoopCount = checkOpenMPLoop(
12328       OMPD_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
12329       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
12330       VarsWithImplicitDSA, B);
12331 
12332   if (NestedLoopCount == 0)
12333     return StmtError();
12334 
12335   assert((CurContext->isDependentContext() || B.builtAll()) &&
12336          "omp for loop exprs were not built");
12337 
12338   setFunctionHasBranchProtectedScope();
12339 
12340   DSAStack->setParentTeamsRegionLoc(StartLoc);
12341 
12342   return OMPTeamsDistributeParallelForDirective::Create(
12343       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
12344       DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion());
12345 }
12346 
12347 StmtResult Sema::ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses,
12348                                                  Stmt *AStmt,
12349                                                  SourceLocation StartLoc,
12350                                                  SourceLocation EndLoc) {
12351   if (!AStmt)
12352     return StmtError();
12353 
12354   auto *CS = cast<CapturedStmt>(AStmt);
12355   // 1.2.2 OpenMP Language Terminology
12356   // Structured block - An executable statement with a single entry at the
12357   // top and a single exit at the bottom.
12358   // The point of exit cannot be a branch out of the structured block.
12359   // longjmp() and throw() must not violate the entry/exit criteria.
12360   CS->getCapturedDecl()->setNothrow();
12361 
12362   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_teams);
12363        ThisCaptureLevel > 1; --ThisCaptureLevel) {
12364     CS = cast<CapturedStmt>(CS->getCapturedStmt());
12365     // 1.2.2 OpenMP Language Terminology
12366     // Structured block - An executable statement with a single entry at the
12367     // top and a single exit at the bottom.
12368     // The point of exit cannot be a branch out of the structured block.
12369     // longjmp() and throw() must not violate the entry/exit criteria.
12370     CS->getCapturedDecl()->setNothrow();
12371   }
12372   setFunctionHasBranchProtectedScope();
12373 
12374   return OMPTargetTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses,
12375                                          AStmt);
12376 }
12377 
12378 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeDirective(
12379     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
12380     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
12381   if (!AStmt)
12382     return StmtError();
12383 
12384   auto *CS = cast<CapturedStmt>(AStmt);
12385   // 1.2.2 OpenMP Language Terminology
12386   // Structured block - An executable statement with a single entry at the
12387   // top and a single exit at the bottom.
12388   // The point of exit cannot be a branch out of the structured block.
12389   // longjmp() and throw() must not violate the entry/exit criteria.
12390   CS->getCapturedDecl()->setNothrow();
12391   for (int ThisCaptureLevel =
12392            getOpenMPCaptureLevels(OMPD_target_teams_distribute);
12393        ThisCaptureLevel > 1; --ThisCaptureLevel) {
12394     CS = cast<CapturedStmt>(CS->getCapturedStmt());
12395     // 1.2.2 OpenMP Language Terminology
12396     // Structured block - An executable statement with a single entry at the
12397     // top and a single exit at the bottom.
12398     // The point of exit cannot be a branch out of the structured block.
12399     // longjmp() and throw() must not violate the entry/exit criteria.
12400     CS->getCapturedDecl()->setNothrow();
12401   }
12402 
12403   OMPLoopBasedDirective::HelperExprs B;
12404   // In presence of clause 'collapse' with number of loops, it will
12405   // define the nested loops number.
12406   unsigned NestedLoopCount = checkOpenMPLoop(
12407       OMPD_target_teams_distribute, getCollapseNumberExpr(Clauses),
12408       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
12409       VarsWithImplicitDSA, B);
12410   if (NestedLoopCount == 0)
12411     return StmtError();
12412 
12413   assert((CurContext->isDependentContext() || B.builtAll()) &&
12414          "omp target teams distribute loop exprs were not built");
12415 
12416   setFunctionHasBranchProtectedScope();
12417   return OMPTargetTeamsDistributeDirective::Create(
12418       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
12419 }
12420 
12421 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForDirective(
12422     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
12423     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
12424   if (!AStmt)
12425     return StmtError();
12426 
12427   auto *CS = cast<CapturedStmt>(AStmt);
12428   // 1.2.2 OpenMP Language Terminology
12429   // Structured block - An executable statement with a single entry at the
12430   // top and a single exit at the bottom.
12431   // The point of exit cannot be a branch out of the structured block.
12432   // longjmp() and throw() must not violate the entry/exit criteria.
12433   CS->getCapturedDecl()->setNothrow();
12434   for (int ThisCaptureLevel =
12435            getOpenMPCaptureLevels(OMPD_target_teams_distribute_parallel_for);
12436        ThisCaptureLevel > 1; --ThisCaptureLevel) {
12437     CS = cast<CapturedStmt>(CS->getCapturedStmt());
12438     // 1.2.2 OpenMP Language Terminology
12439     // Structured block - An executable statement with a single entry at the
12440     // top and a single exit at the bottom.
12441     // The point of exit cannot be a branch out of the structured block.
12442     // longjmp() and throw() must not violate the entry/exit criteria.
12443     CS->getCapturedDecl()->setNothrow();
12444   }
12445 
12446   OMPLoopBasedDirective::HelperExprs B;
12447   // In presence of clause 'collapse' with number of loops, it will
12448   // define the nested loops number.
12449   unsigned NestedLoopCount = checkOpenMPLoop(
12450       OMPD_target_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
12451       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
12452       VarsWithImplicitDSA, B);
12453   if (NestedLoopCount == 0)
12454     return StmtError();
12455 
12456   assert((CurContext->isDependentContext() || B.builtAll()) &&
12457          "omp target teams distribute parallel for loop exprs were not built");
12458 
12459   if (!CurContext->isDependentContext()) {
12460     // Finalize the clauses that need pre-built expressions for CodeGen.
12461     for (OMPClause *C : Clauses) {
12462       if (auto *LC = dyn_cast<OMPLinearClause>(C))
12463         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
12464                                      B.NumIterations, *this, CurScope,
12465                                      DSAStack))
12466           return StmtError();
12467     }
12468   }
12469 
12470   setFunctionHasBranchProtectedScope();
12471   return OMPTargetTeamsDistributeParallelForDirective::Create(
12472       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
12473       DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion());
12474 }
12475 
12476 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
12477     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
12478     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
12479   if (!AStmt)
12480     return StmtError();
12481 
12482   auto *CS = cast<CapturedStmt>(AStmt);
12483   // 1.2.2 OpenMP Language Terminology
12484   // Structured block - An executable statement with a single entry at the
12485   // top and a single exit at the bottom.
12486   // The point of exit cannot be a branch out of the structured block.
12487   // longjmp() and throw() must not violate the entry/exit criteria.
12488   CS->getCapturedDecl()->setNothrow();
12489   for (int ThisCaptureLevel = getOpenMPCaptureLevels(
12490            OMPD_target_teams_distribute_parallel_for_simd);
12491        ThisCaptureLevel > 1; --ThisCaptureLevel) {
12492     CS = cast<CapturedStmt>(CS->getCapturedStmt());
12493     // 1.2.2 OpenMP Language Terminology
12494     // Structured block - An executable statement with a single entry at the
12495     // top and a single exit at the bottom.
12496     // The point of exit cannot be a branch out of the structured block.
12497     // longjmp() and throw() must not violate the entry/exit criteria.
12498     CS->getCapturedDecl()->setNothrow();
12499   }
12500 
12501   OMPLoopBasedDirective::HelperExprs B;
12502   // In presence of clause 'collapse' with number of loops, it will
12503   // define the nested loops number.
12504   unsigned NestedLoopCount =
12505       checkOpenMPLoop(OMPD_target_teams_distribute_parallel_for_simd,
12506                       getCollapseNumberExpr(Clauses),
12507                       nullptr /*ordered not a clause on distribute*/, CS, *this,
12508                       *DSAStack, VarsWithImplicitDSA, B);
12509   if (NestedLoopCount == 0)
12510     return StmtError();
12511 
12512   assert((CurContext->isDependentContext() || B.builtAll()) &&
12513          "omp target teams distribute parallel for simd loop exprs were not "
12514          "built");
12515 
12516   if (!CurContext->isDependentContext()) {
12517     // Finalize the clauses that need pre-built expressions for CodeGen.
12518     for (OMPClause *C : Clauses) {
12519       if (auto *LC = dyn_cast<OMPLinearClause>(C))
12520         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
12521                                      B.NumIterations, *this, CurScope,
12522                                      DSAStack))
12523           return StmtError();
12524     }
12525   }
12526 
12527   if (checkSimdlenSafelenSpecified(*this, Clauses))
12528     return StmtError();
12529 
12530   setFunctionHasBranchProtectedScope();
12531   return OMPTargetTeamsDistributeParallelForSimdDirective::Create(
12532       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
12533 }
12534 
12535 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeSimdDirective(
12536     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
12537     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
12538   if (!AStmt)
12539     return StmtError();
12540 
12541   auto *CS = cast<CapturedStmt>(AStmt);
12542   // 1.2.2 OpenMP Language Terminology
12543   // Structured block - An executable statement with a single entry at the
12544   // top and a single exit at the bottom.
12545   // The point of exit cannot be a branch out of the structured block.
12546   // longjmp() and throw() must not violate the entry/exit criteria.
12547   CS->getCapturedDecl()->setNothrow();
12548   for (int ThisCaptureLevel =
12549            getOpenMPCaptureLevels(OMPD_target_teams_distribute_simd);
12550        ThisCaptureLevel > 1; --ThisCaptureLevel) {
12551     CS = cast<CapturedStmt>(CS->getCapturedStmt());
12552     // 1.2.2 OpenMP Language Terminology
12553     // Structured block - An executable statement with a single entry at the
12554     // top and a single exit at the bottom.
12555     // The point of exit cannot be a branch out of the structured block.
12556     // longjmp() and throw() must not violate the entry/exit criteria.
12557     CS->getCapturedDecl()->setNothrow();
12558   }
12559 
12560   OMPLoopBasedDirective::HelperExprs B;
12561   // In presence of clause 'collapse' with number of loops, it will
12562   // define the nested loops number.
12563   unsigned NestedLoopCount = checkOpenMPLoop(
12564       OMPD_target_teams_distribute_simd, getCollapseNumberExpr(Clauses),
12565       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
12566       VarsWithImplicitDSA, B);
12567   if (NestedLoopCount == 0)
12568     return StmtError();
12569 
12570   assert((CurContext->isDependentContext() || B.builtAll()) &&
12571          "omp target teams distribute simd loop exprs were not built");
12572 
12573   if (!CurContext->isDependentContext()) {
12574     // Finalize the clauses that need pre-built expressions for CodeGen.
12575     for (OMPClause *C : Clauses) {
12576       if (auto *LC = dyn_cast<OMPLinearClause>(C))
12577         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
12578                                      B.NumIterations, *this, CurScope,
12579                                      DSAStack))
12580           return StmtError();
12581     }
12582   }
12583 
12584   if (checkSimdlenSafelenSpecified(*this, Clauses))
12585     return StmtError();
12586 
12587   setFunctionHasBranchProtectedScope();
12588   return OMPTargetTeamsDistributeSimdDirective::Create(
12589       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
12590 }
12591 
12592 bool Sema::checkTransformableLoopNest(
12593     OpenMPDirectiveKind Kind, Stmt *AStmt, int NumLoops,
12594     SmallVectorImpl<OMPLoopBasedDirective::HelperExprs> &LoopHelpers,
12595     Stmt *&Body,
12596     SmallVectorImpl<SmallVector<llvm::PointerUnion<Stmt *, Decl *>, 0>>
12597         &OriginalInits) {
12598   OriginalInits.emplace_back();
12599   bool Result = OMPLoopBasedDirective::doForAllLoops(
12600       AStmt->IgnoreContainers(), /*TryImperfectlyNestedLoops=*/false, NumLoops,
12601       [this, &LoopHelpers, &Body, &OriginalInits, Kind](unsigned Cnt,
12602                                                         Stmt *CurStmt) {
12603         VarsWithInheritedDSAType TmpDSA;
12604         unsigned SingleNumLoops =
12605             checkOpenMPLoop(Kind, nullptr, nullptr, CurStmt, *this, *DSAStack,
12606                             TmpDSA, LoopHelpers[Cnt]);
12607         if (SingleNumLoops == 0)
12608           return true;
12609         assert(SingleNumLoops == 1 && "Expect single loop iteration space");
12610         if (auto *For = dyn_cast<ForStmt>(CurStmt)) {
12611           OriginalInits.back().push_back(For->getInit());
12612           Body = For->getBody();
12613         } else {
12614           assert(isa<CXXForRangeStmt>(CurStmt) &&
12615                  "Expected canonical for or range-based for loops.");
12616           auto *CXXFor = cast<CXXForRangeStmt>(CurStmt);
12617           OriginalInits.back().push_back(CXXFor->getBeginStmt());
12618           Body = CXXFor->getBody();
12619         }
12620         OriginalInits.emplace_back();
12621         return false;
12622       },
12623       [&OriginalInits](OMPLoopBasedDirective *Transform) {
12624         Stmt *DependentPreInits;
12625         if (auto *Dir = dyn_cast<OMPTileDirective>(Transform))
12626           DependentPreInits = Dir->getPreInits();
12627         else if (auto *Dir = dyn_cast<OMPUnrollDirective>(Transform))
12628           DependentPreInits = Dir->getPreInits();
12629         else
12630           llvm_unreachable("Unhandled loop transformation");
12631         if (!DependentPreInits)
12632           return;
12633         for (Decl *C : cast<DeclStmt>(DependentPreInits)->getDeclGroup())
12634           OriginalInits.back().push_back(C);
12635       });
12636   assert(OriginalInits.back().empty() && "No preinit after innermost loop");
12637   OriginalInits.pop_back();
12638   return Result;
12639 }
12640 
12641 StmtResult Sema::ActOnOpenMPTileDirective(ArrayRef<OMPClause *> Clauses,
12642                                           Stmt *AStmt, SourceLocation StartLoc,
12643                                           SourceLocation EndLoc) {
12644   auto SizesClauses =
12645       OMPExecutableDirective::getClausesOfKind<OMPSizesClause>(Clauses);
12646   if (SizesClauses.empty()) {
12647     // A missing 'sizes' clause is already reported by the parser.
12648     return StmtError();
12649   }
12650   const OMPSizesClause *SizesClause = *SizesClauses.begin();
12651   unsigned NumLoops = SizesClause->getNumSizes();
12652 
12653   // Empty statement should only be possible if there already was an error.
12654   if (!AStmt)
12655     return StmtError();
12656 
12657   // Verify and diagnose loop nest.
12658   SmallVector<OMPLoopBasedDirective::HelperExprs, 4> LoopHelpers(NumLoops);
12659   Stmt *Body = nullptr;
12660   SmallVector<SmallVector<llvm::PointerUnion<Stmt *, Decl *>, 0>, 4>
12661       OriginalInits;
12662   if (!checkTransformableLoopNest(OMPD_tile, AStmt, NumLoops, LoopHelpers, Body,
12663                                   OriginalInits))
12664     return StmtError();
12665 
12666   // Delay tiling to when template is completely instantiated.
12667   if (CurContext->isDependentContext())
12668     return OMPTileDirective::Create(Context, StartLoc, EndLoc, Clauses,
12669                                     NumLoops, AStmt, nullptr, nullptr);
12670 
12671   SmallVector<Decl *, 4> PreInits;
12672 
12673   // Create iteration variables for the generated loops.
12674   SmallVector<VarDecl *, 4> FloorIndVars;
12675   SmallVector<VarDecl *, 4> TileIndVars;
12676   FloorIndVars.resize(NumLoops);
12677   TileIndVars.resize(NumLoops);
12678   for (unsigned I = 0; I < NumLoops; ++I) {
12679     OMPLoopBasedDirective::HelperExprs &LoopHelper = LoopHelpers[I];
12680 
12681     assert(LoopHelper.Counters.size() == 1 &&
12682            "Expect single-dimensional loop iteration space");
12683     auto *OrigCntVar = cast<DeclRefExpr>(LoopHelper.Counters.front());
12684     std::string OrigVarName = OrigCntVar->getNameInfo().getAsString();
12685     DeclRefExpr *IterVarRef = cast<DeclRefExpr>(LoopHelper.IterationVarRef);
12686     QualType CntTy = IterVarRef->getType();
12687 
12688     // Iteration variable for the floor (i.e. outer) loop.
12689     {
12690       std::string FloorCntName =
12691           (Twine(".floor_") + llvm::utostr(I) + ".iv." + OrigVarName).str();
12692       VarDecl *FloorCntDecl =
12693           buildVarDecl(*this, {}, CntTy, FloorCntName, nullptr, OrigCntVar);
12694       FloorIndVars[I] = FloorCntDecl;
12695     }
12696 
12697     // Iteration variable for the tile (i.e. inner) loop.
12698     {
12699       std::string TileCntName =
12700           (Twine(".tile_") + llvm::utostr(I) + ".iv." + OrigVarName).str();
12701 
12702       // Reuse the iteration variable created by checkOpenMPLoop. It is also
12703       // used by the expressions to derive the original iteration variable's
12704       // value from the logical iteration number.
12705       auto *TileCntDecl = cast<VarDecl>(IterVarRef->getDecl());
12706       TileCntDecl->setDeclName(&PP.getIdentifierTable().get(TileCntName));
12707       TileIndVars[I] = TileCntDecl;
12708     }
12709     for (auto &P : OriginalInits[I]) {
12710       if (auto *D = P.dyn_cast<Decl *>())
12711         PreInits.push_back(D);
12712       else if (auto *PI = dyn_cast_or_null<DeclStmt>(P.dyn_cast<Stmt *>()))
12713         PreInits.append(PI->decl_begin(), PI->decl_end());
12714     }
12715     if (auto *PI = cast_or_null<DeclStmt>(LoopHelper.PreInits))
12716       PreInits.append(PI->decl_begin(), PI->decl_end());
12717     // Gather declarations for the data members used as counters.
12718     for (Expr *CounterRef : LoopHelper.Counters) {
12719       auto *CounterDecl = cast<DeclRefExpr>(CounterRef)->getDecl();
12720       if (isa<OMPCapturedExprDecl>(CounterDecl))
12721         PreInits.push_back(CounterDecl);
12722     }
12723   }
12724 
12725   // Once the original iteration values are set, append the innermost body.
12726   Stmt *Inner = Body;
12727 
12728   // Create tile loops from the inside to the outside.
12729   for (int I = NumLoops - 1; I >= 0; --I) {
12730     OMPLoopBasedDirective::HelperExprs &LoopHelper = LoopHelpers[I];
12731     Expr *NumIterations = LoopHelper.NumIterations;
12732     auto *OrigCntVar = cast<DeclRefExpr>(LoopHelper.Counters[0]);
12733     QualType CntTy = OrigCntVar->getType();
12734     Expr *DimTileSize = SizesClause->getSizesRefs()[I];
12735     Scope *CurScope = getCurScope();
12736 
12737     // Commonly used variables.
12738     DeclRefExpr *TileIV = buildDeclRefExpr(*this, TileIndVars[I], CntTy,
12739                                            OrigCntVar->getExprLoc());
12740     DeclRefExpr *FloorIV = buildDeclRefExpr(*this, FloorIndVars[I], CntTy,
12741                                             OrigCntVar->getExprLoc());
12742 
12743     // For init-statement: auto .tile.iv = .floor.iv
12744     AddInitializerToDecl(TileIndVars[I], DefaultLvalueConversion(FloorIV).get(),
12745                          /*DirectInit=*/false);
12746     Decl *CounterDecl = TileIndVars[I];
12747     StmtResult InitStmt = new (Context)
12748         DeclStmt(DeclGroupRef::Create(Context, &CounterDecl, 1),
12749                  OrigCntVar->getBeginLoc(), OrigCntVar->getEndLoc());
12750     if (!InitStmt.isUsable())
12751       return StmtError();
12752 
12753     // For cond-expression: .tile.iv < min(.floor.iv + DimTileSize,
12754     // NumIterations)
12755     ExprResult EndOfTile = BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(),
12756                                       BO_Add, FloorIV, DimTileSize);
12757     if (!EndOfTile.isUsable())
12758       return StmtError();
12759     ExprResult IsPartialTile =
12760         BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(), BO_LT,
12761                    NumIterations, EndOfTile.get());
12762     if (!IsPartialTile.isUsable())
12763       return StmtError();
12764     ExprResult MinTileAndIterSpace = ActOnConditionalOp(
12765         LoopHelper.Cond->getBeginLoc(), LoopHelper.Cond->getEndLoc(),
12766         IsPartialTile.get(), NumIterations, EndOfTile.get());
12767     if (!MinTileAndIterSpace.isUsable())
12768       return StmtError();
12769     ExprResult CondExpr = BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(),
12770                                      BO_LT, TileIV, MinTileAndIterSpace.get());
12771     if (!CondExpr.isUsable())
12772       return StmtError();
12773 
12774     // For incr-statement: ++.tile.iv
12775     ExprResult IncrStmt =
12776         BuildUnaryOp(CurScope, LoopHelper.Inc->getExprLoc(), UO_PreInc, TileIV);
12777     if (!IncrStmt.isUsable())
12778       return StmtError();
12779 
12780     // Statements to set the original iteration variable's value from the
12781     // logical iteration number.
12782     // Generated for loop is:
12783     // Original_for_init;
12784     // for (auto .tile.iv = .floor.iv; .tile.iv < min(.floor.iv + DimTileSize,
12785     // NumIterations); ++.tile.iv) {
12786     //   Original_Body;
12787     //   Original_counter_update;
12788     // }
12789     // FIXME: If the innermost body is an loop itself, inserting these
12790     // statements stops it being recognized  as a perfectly nested loop (e.g.
12791     // for applying tiling again). If this is the case, sink the expressions
12792     // further into the inner loop.
12793     SmallVector<Stmt *, 4> BodyParts;
12794     BodyParts.append(LoopHelper.Updates.begin(), LoopHelper.Updates.end());
12795     BodyParts.push_back(Inner);
12796     Inner = CompoundStmt::Create(Context, BodyParts, Inner->getBeginLoc(),
12797                                  Inner->getEndLoc());
12798     Inner = new (Context)
12799         ForStmt(Context, InitStmt.get(), CondExpr.get(), nullptr,
12800                 IncrStmt.get(), Inner, LoopHelper.Init->getBeginLoc(),
12801                 LoopHelper.Init->getBeginLoc(), LoopHelper.Inc->getEndLoc());
12802   }
12803 
12804   // Create floor loops from the inside to the outside.
12805   for (int I = NumLoops - 1; I >= 0; --I) {
12806     auto &LoopHelper = LoopHelpers[I];
12807     Expr *NumIterations = LoopHelper.NumIterations;
12808     DeclRefExpr *OrigCntVar = cast<DeclRefExpr>(LoopHelper.Counters[0]);
12809     QualType CntTy = OrigCntVar->getType();
12810     Expr *DimTileSize = SizesClause->getSizesRefs()[I];
12811     Scope *CurScope = getCurScope();
12812 
12813     // Commonly used variables.
12814     DeclRefExpr *FloorIV = buildDeclRefExpr(*this, FloorIndVars[I], CntTy,
12815                                             OrigCntVar->getExprLoc());
12816 
12817     // For init-statement: auto .floor.iv = 0
12818     AddInitializerToDecl(
12819         FloorIndVars[I],
12820         ActOnIntegerConstant(LoopHelper.Init->getExprLoc(), 0).get(),
12821         /*DirectInit=*/false);
12822     Decl *CounterDecl = FloorIndVars[I];
12823     StmtResult InitStmt = new (Context)
12824         DeclStmt(DeclGroupRef::Create(Context, &CounterDecl, 1),
12825                  OrigCntVar->getBeginLoc(), OrigCntVar->getEndLoc());
12826     if (!InitStmt.isUsable())
12827       return StmtError();
12828 
12829     // For cond-expression: .floor.iv < NumIterations
12830     ExprResult CondExpr = BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(),
12831                                      BO_LT, FloorIV, NumIterations);
12832     if (!CondExpr.isUsable())
12833       return StmtError();
12834 
12835     // For incr-statement: .floor.iv += DimTileSize
12836     ExprResult IncrStmt = BuildBinOp(CurScope, LoopHelper.Inc->getExprLoc(),
12837                                      BO_AddAssign, FloorIV, DimTileSize);
12838     if (!IncrStmt.isUsable())
12839       return StmtError();
12840 
12841     Inner = new (Context)
12842         ForStmt(Context, InitStmt.get(), CondExpr.get(), nullptr,
12843                 IncrStmt.get(), Inner, LoopHelper.Init->getBeginLoc(),
12844                 LoopHelper.Init->getBeginLoc(), LoopHelper.Inc->getEndLoc());
12845   }
12846 
12847   return OMPTileDirective::Create(Context, StartLoc, EndLoc, Clauses, NumLoops,
12848                                   AStmt, Inner,
12849                                   buildPreInits(Context, PreInits));
12850 }
12851 
12852 StmtResult Sema::ActOnOpenMPUnrollDirective(ArrayRef<OMPClause *> Clauses,
12853                                             Stmt *AStmt,
12854                                             SourceLocation StartLoc,
12855                                             SourceLocation EndLoc) {
12856   // Empty statement should only be possible if there already was an error.
12857   if (!AStmt)
12858     return StmtError();
12859 
12860   if (checkMutuallyExclusiveClauses(*this, Clauses, {OMPC_partial, OMPC_full}))
12861     return StmtError();
12862 
12863   const OMPFullClause *FullClause =
12864       OMPExecutableDirective::getSingleClause<OMPFullClause>(Clauses);
12865   const OMPPartialClause *PartialClause =
12866       OMPExecutableDirective::getSingleClause<OMPPartialClause>(Clauses);
12867   assert(!(FullClause && PartialClause) &&
12868          "mutual exclusivity must have been checked before");
12869 
12870   constexpr unsigned NumLoops = 1;
12871   Stmt *Body = nullptr;
12872   SmallVector<OMPLoopBasedDirective::HelperExprs, NumLoops> LoopHelpers(
12873       NumLoops);
12874   SmallVector<SmallVector<llvm::PointerUnion<Stmt *, Decl *>, 0>, NumLoops + 1>
12875       OriginalInits;
12876   if (!checkTransformableLoopNest(OMPD_unroll, AStmt, NumLoops, LoopHelpers,
12877                                   Body, OriginalInits))
12878     return StmtError();
12879 
12880   // Delay unrolling to when template is completely instantiated.
12881   if (CurContext->isDependentContext())
12882     return OMPUnrollDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
12883                                       nullptr, nullptr);
12884 
12885   OMPLoopBasedDirective::HelperExprs &LoopHelper = LoopHelpers.front();
12886 
12887   if (FullClause) {
12888     if (!VerifyPositiveIntegerConstantInClause(
12889              LoopHelper.NumIterations, OMPC_full, /*StrictlyPositive=*/false,
12890              /*SuppressExprDigs=*/true)
12891              .isUsable()) {
12892       Diag(AStmt->getBeginLoc(), diag::err_omp_unroll_full_variable_trip_count);
12893       Diag(FullClause->getBeginLoc(), diag::note_omp_directive_here)
12894           << "#pragma omp unroll full";
12895       return StmtError();
12896     }
12897   }
12898 
12899   // The generated loop may only be passed to other loop-associated directive
12900   // when a partial clause is specified. Without the requirement it is
12901   // sufficient to generate loop unroll metadata at code-generation.
12902   if (!PartialClause)
12903     return OMPUnrollDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
12904                                       nullptr, nullptr);
12905 
12906   // Otherwise, we need to provide a de-sugared/transformed AST that can be
12907   // associated with another loop directive.
12908   //
12909   // The canonical loop analysis return by checkTransformableLoopNest assumes
12910   // the following structure to be the same loop without transformations or
12911   // directives applied: \code OriginalInits; LoopHelper.PreInits;
12912   // LoopHelper.Counters;
12913   // for (; IV < LoopHelper.NumIterations; ++IV) {
12914   //   LoopHelper.Updates;
12915   //   Body;
12916   // }
12917   // \endcode
12918   // where IV is a variable declared and initialized to 0 in LoopHelper.PreInits
12919   // and referenced by LoopHelper.IterationVarRef.
12920   //
12921   // The unrolling directive transforms this into the following loop:
12922   // \code
12923   // OriginalInits;         \
12924   // LoopHelper.PreInits;    > NewPreInits
12925   // LoopHelper.Counters;   /
12926   // for (auto UIV = 0; UIV < LoopHelper.NumIterations; UIV+=Factor) {
12927   //   #pragma clang loop unroll_count(Factor)
12928   //   for (IV = UIV; IV < UIV + Factor && UIV < LoopHelper.NumIterations; ++IV)
12929   //   {
12930   //     LoopHelper.Updates;
12931   //     Body;
12932   //   }
12933   // }
12934   // \endcode
12935   // where UIV is a new logical iteration counter. IV must be the same VarDecl
12936   // as the original LoopHelper.IterationVarRef because LoopHelper.Updates
12937   // references it. If the partially unrolled loop is associated with another
12938   // loop directive (like an OMPForDirective), it will use checkOpenMPLoop to
12939   // analyze this loop, i.e. the outer loop must fulfill the constraints of an
12940   // OpenMP canonical loop. The inner loop is not an associable canonical loop
12941   // and only exists to defer its unrolling to LLVM's LoopUnroll instead of
12942   // doing it in the frontend (by adding loop metadata). NewPreInits becomes a
12943   // property of the OMPLoopBasedDirective instead of statements in
12944   // CompoundStatement. This is to allow the loop to become a non-outermost loop
12945   // of a canonical loop nest where these PreInits are emitted before the
12946   // outermost directive.
12947 
12948   // Determine the PreInit declarations.
12949   SmallVector<Decl *, 4> PreInits;
12950   assert(OriginalInits.size() == 1 &&
12951          "Expecting a single-dimensional loop iteration space");
12952   for (auto &P : OriginalInits[0]) {
12953     if (auto *D = P.dyn_cast<Decl *>())
12954       PreInits.push_back(D);
12955     else if (auto *PI = dyn_cast_or_null<DeclStmt>(P.dyn_cast<Stmt *>()))
12956       PreInits.append(PI->decl_begin(), PI->decl_end());
12957   }
12958   if (auto *PI = cast_or_null<DeclStmt>(LoopHelper.PreInits))
12959     PreInits.append(PI->decl_begin(), PI->decl_end());
12960   // Gather declarations for the data members used as counters.
12961   for (Expr *CounterRef : LoopHelper.Counters) {
12962     auto *CounterDecl = cast<DeclRefExpr>(CounterRef)->getDecl();
12963     if (isa<OMPCapturedExprDecl>(CounterDecl))
12964       PreInits.push_back(CounterDecl);
12965   }
12966 
12967   auto *IterationVarRef = cast<DeclRefExpr>(LoopHelper.IterationVarRef);
12968   QualType IVTy = IterationVarRef->getType();
12969   assert(LoopHelper.Counters.size() == 1 &&
12970          "Expecting a single-dimensional loop iteration space");
12971   auto *OrigVar = cast<DeclRefExpr>(LoopHelper.Counters.front());
12972 
12973   // Determine the unroll factor.
12974   uint64_t Factor;
12975   SourceLocation FactorLoc;
12976   if (Expr *FactorVal = PartialClause->getFactor()) {
12977     Factor =
12978         FactorVal->getIntegerConstantExpr(Context).getValue().getZExtValue();
12979     FactorLoc = FactorVal->getExprLoc();
12980   } else {
12981     // TODO: Use a better profitability model.
12982     Factor = 2;
12983   }
12984   assert(Factor > 0 && "Expected positive unroll factor");
12985   auto MakeFactorExpr = [this, Factor, IVTy, FactorLoc]() {
12986     return IntegerLiteral::Create(
12987         Context, llvm::APInt(Context.getIntWidth(IVTy), Factor), IVTy,
12988         FactorLoc);
12989   };
12990 
12991   // Iteration variable SourceLocations.
12992   SourceLocation OrigVarLoc = OrigVar->getExprLoc();
12993   SourceLocation OrigVarLocBegin = OrigVar->getBeginLoc();
12994   SourceLocation OrigVarLocEnd = OrigVar->getEndLoc();
12995 
12996   // Internal variable names.
12997   std::string OrigVarName = OrigVar->getNameInfo().getAsString();
12998   std::string OuterIVName = (Twine(".unrolled.iv.") + OrigVarName).str();
12999   std::string InnerIVName = (Twine(".unroll_inner.iv.") + OrigVarName).str();
13000   std::string InnerTripCountName =
13001       (Twine(".unroll_inner.tripcount.") + OrigVarName).str();
13002 
13003   // Create the iteration variable for the unrolled loop.
13004   VarDecl *OuterIVDecl =
13005       buildVarDecl(*this, {}, IVTy, OuterIVName, nullptr, OrigVar);
13006   auto MakeOuterRef = [this, OuterIVDecl, IVTy, OrigVarLoc]() {
13007     return buildDeclRefExpr(*this, OuterIVDecl, IVTy, OrigVarLoc);
13008   };
13009 
13010   // Iteration variable for the inner loop: Reuse the iteration variable created
13011   // by checkOpenMPLoop.
13012   auto *InnerIVDecl = cast<VarDecl>(IterationVarRef->getDecl());
13013   InnerIVDecl->setDeclName(&PP.getIdentifierTable().get(InnerIVName));
13014   auto MakeInnerRef = [this, InnerIVDecl, IVTy, OrigVarLoc]() {
13015     return buildDeclRefExpr(*this, InnerIVDecl, IVTy, OrigVarLoc);
13016   };
13017 
13018   // Make a copy of the NumIterations expression for each use: By the AST
13019   // constraints, every expression object in a DeclContext must be unique.
13020   CaptureVars CopyTransformer(*this);
13021   auto MakeNumIterations = [&CopyTransformer, &LoopHelper]() -> Expr * {
13022     return AssertSuccess(
13023         CopyTransformer.TransformExpr(LoopHelper.NumIterations));
13024   };
13025 
13026   // Inner For init-statement: auto .unroll_inner.iv = .unrolled.iv
13027   ExprResult LValueConv = DefaultLvalueConversion(MakeOuterRef());
13028   AddInitializerToDecl(InnerIVDecl, LValueConv.get(), /*DirectInit=*/false);
13029   StmtResult InnerInit = new (Context)
13030       DeclStmt(DeclGroupRef(InnerIVDecl), OrigVarLocBegin, OrigVarLocEnd);
13031   if (!InnerInit.isUsable())
13032     return StmtError();
13033 
13034   // Inner For cond-expression:
13035   // \code
13036   //   .unroll_inner.iv < .unrolled.iv + Factor &&
13037   //   .unroll_inner.iv < NumIterations
13038   // \endcode
13039   // This conjunction of two conditions allows ScalarEvolution to derive the
13040   // maximum trip count of the inner loop.
13041   ExprResult EndOfTile = BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(),
13042                                     BO_Add, MakeOuterRef(), MakeFactorExpr());
13043   if (!EndOfTile.isUsable())
13044     return StmtError();
13045   ExprResult InnerCond1 = BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(),
13046                                      BO_LE, MakeInnerRef(), EndOfTile.get());
13047   if (!InnerCond1.isUsable())
13048     return StmtError();
13049   ExprResult InnerCond2 =
13050       BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(), BO_LE, MakeInnerRef(),
13051                  MakeNumIterations());
13052   if (!InnerCond2.isUsable())
13053     return StmtError();
13054   ExprResult InnerCond =
13055       BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(), BO_LAnd,
13056                  InnerCond1.get(), InnerCond2.get());
13057   if (!InnerCond.isUsable())
13058     return StmtError();
13059 
13060   // Inner For incr-statement: ++.unroll_inner.iv
13061   ExprResult InnerIncr = BuildUnaryOp(CurScope, LoopHelper.Inc->getExprLoc(),
13062                                       UO_PreInc, MakeInnerRef());
13063   if (!InnerIncr.isUsable())
13064     return StmtError();
13065 
13066   // Inner For statement.
13067   SmallVector<Stmt *> InnerBodyStmts;
13068   InnerBodyStmts.append(LoopHelper.Updates.begin(), LoopHelper.Updates.end());
13069   InnerBodyStmts.push_back(Body);
13070   CompoundStmt *InnerBody = CompoundStmt::Create(
13071       Context, InnerBodyStmts, Body->getBeginLoc(), Body->getEndLoc());
13072   ForStmt *InnerFor = new (Context)
13073       ForStmt(Context, InnerInit.get(), InnerCond.get(), nullptr,
13074               InnerIncr.get(), InnerBody, LoopHelper.Init->getBeginLoc(),
13075               LoopHelper.Init->getBeginLoc(), LoopHelper.Inc->getEndLoc());
13076 
13077   // Unroll metadata for the inner loop.
13078   // This needs to take into account the remainder portion of the unrolled loop,
13079   // hence `unroll(full)` does not apply here, even though the LoopUnroll pass
13080   // supports multiple loop exits. Instead, unroll using a factor equivalent to
13081   // the maximum trip count, which will also generate a remainder loop. Just
13082   // `unroll(enable)` (which could have been useful if the user has not
13083   // specified a concrete factor; even though the outer loop cannot be
13084   // influenced anymore, would avoid more code bloat than necessary) will refuse
13085   // the loop because "Won't unroll; remainder loop could not be generated when
13086   // assuming runtime trip count". Even if it did work, it must not choose a
13087   // larger unroll factor than the maximum loop length, or it would always just
13088   // execute the remainder loop.
13089   LoopHintAttr *UnrollHintAttr =
13090       LoopHintAttr::CreateImplicit(Context, LoopHintAttr::UnrollCount,
13091                                    LoopHintAttr::Numeric, MakeFactorExpr());
13092   AttributedStmt *InnerUnrolled =
13093       AttributedStmt::Create(Context, StartLoc, {UnrollHintAttr}, InnerFor);
13094 
13095   // Outer For init-statement: auto .unrolled.iv = 0
13096   AddInitializerToDecl(
13097       OuterIVDecl, ActOnIntegerConstant(LoopHelper.Init->getExprLoc(), 0).get(),
13098       /*DirectInit=*/false);
13099   StmtResult OuterInit = new (Context)
13100       DeclStmt(DeclGroupRef(OuterIVDecl), OrigVarLocBegin, OrigVarLocEnd);
13101   if (!OuterInit.isUsable())
13102     return StmtError();
13103 
13104   // Outer For cond-expression: .unrolled.iv < NumIterations
13105   ExprResult OuterConde =
13106       BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(), BO_LT, MakeOuterRef(),
13107                  MakeNumIterations());
13108   if (!OuterConde.isUsable())
13109     return StmtError();
13110 
13111   // Outer For incr-statement: .unrolled.iv += Factor
13112   ExprResult OuterIncr =
13113       BuildBinOp(CurScope, LoopHelper.Inc->getExprLoc(), BO_AddAssign,
13114                  MakeOuterRef(), MakeFactorExpr());
13115   if (!OuterIncr.isUsable())
13116     return StmtError();
13117 
13118   // Outer For statement.
13119   ForStmt *OuterFor = new (Context)
13120       ForStmt(Context, OuterInit.get(), OuterConde.get(), nullptr,
13121               OuterIncr.get(), InnerUnrolled, LoopHelper.Init->getBeginLoc(),
13122               LoopHelper.Init->getBeginLoc(), LoopHelper.Inc->getEndLoc());
13123 
13124   return OMPUnrollDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
13125                                     OuterFor, buildPreInits(Context, PreInits));
13126 }
13127 
13128 OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
13129                                              SourceLocation StartLoc,
13130                                              SourceLocation LParenLoc,
13131                                              SourceLocation EndLoc) {
13132   OMPClause *Res = nullptr;
13133   switch (Kind) {
13134   case OMPC_final:
13135     Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc);
13136     break;
13137   case OMPC_num_threads:
13138     Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc);
13139     break;
13140   case OMPC_safelen:
13141     Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
13142     break;
13143   case OMPC_simdlen:
13144     Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc);
13145     break;
13146   case OMPC_allocator:
13147     Res = ActOnOpenMPAllocatorClause(Expr, StartLoc, LParenLoc, EndLoc);
13148     break;
13149   case OMPC_collapse:
13150     Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc);
13151     break;
13152   case OMPC_ordered:
13153     Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr);
13154     break;
13155   case OMPC_num_teams:
13156     Res = ActOnOpenMPNumTeamsClause(Expr, StartLoc, LParenLoc, EndLoc);
13157     break;
13158   case OMPC_thread_limit:
13159     Res = ActOnOpenMPThreadLimitClause(Expr, StartLoc, LParenLoc, EndLoc);
13160     break;
13161   case OMPC_priority:
13162     Res = ActOnOpenMPPriorityClause(Expr, StartLoc, LParenLoc, EndLoc);
13163     break;
13164   case OMPC_grainsize:
13165     Res = ActOnOpenMPGrainsizeClause(Expr, StartLoc, LParenLoc, EndLoc);
13166     break;
13167   case OMPC_num_tasks:
13168     Res = ActOnOpenMPNumTasksClause(Expr, StartLoc, LParenLoc, EndLoc);
13169     break;
13170   case OMPC_hint:
13171     Res = ActOnOpenMPHintClause(Expr, StartLoc, LParenLoc, EndLoc);
13172     break;
13173   case OMPC_depobj:
13174     Res = ActOnOpenMPDepobjClause(Expr, StartLoc, LParenLoc, EndLoc);
13175     break;
13176   case OMPC_detach:
13177     Res = ActOnOpenMPDetachClause(Expr, StartLoc, LParenLoc, EndLoc);
13178     break;
13179   case OMPC_novariants:
13180     Res = ActOnOpenMPNovariantsClause(Expr, StartLoc, LParenLoc, EndLoc);
13181     break;
13182   case OMPC_nocontext:
13183     Res = ActOnOpenMPNocontextClause(Expr, StartLoc, LParenLoc, EndLoc);
13184     break;
13185   case OMPC_filter:
13186     Res = ActOnOpenMPFilterClause(Expr, StartLoc, LParenLoc, EndLoc);
13187     break;
13188   case OMPC_partial:
13189     Res = ActOnOpenMPPartialClause(Expr, StartLoc, LParenLoc, EndLoc);
13190     break;
13191   case OMPC_device:
13192   case OMPC_if:
13193   case OMPC_default:
13194   case OMPC_proc_bind:
13195   case OMPC_schedule:
13196   case OMPC_private:
13197   case OMPC_firstprivate:
13198   case OMPC_lastprivate:
13199   case OMPC_shared:
13200   case OMPC_reduction:
13201   case OMPC_task_reduction:
13202   case OMPC_in_reduction:
13203   case OMPC_linear:
13204   case OMPC_aligned:
13205   case OMPC_copyin:
13206   case OMPC_copyprivate:
13207   case OMPC_nowait:
13208   case OMPC_untied:
13209   case OMPC_mergeable:
13210   case OMPC_threadprivate:
13211   case OMPC_sizes:
13212   case OMPC_allocate:
13213   case OMPC_flush:
13214   case OMPC_read:
13215   case OMPC_write:
13216   case OMPC_update:
13217   case OMPC_capture:
13218   case OMPC_seq_cst:
13219   case OMPC_acq_rel:
13220   case OMPC_acquire:
13221   case OMPC_release:
13222   case OMPC_relaxed:
13223   case OMPC_depend:
13224   case OMPC_threads:
13225   case OMPC_simd:
13226   case OMPC_map:
13227   case OMPC_nogroup:
13228   case OMPC_dist_schedule:
13229   case OMPC_defaultmap:
13230   case OMPC_unknown:
13231   case OMPC_uniform:
13232   case OMPC_to:
13233   case OMPC_from:
13234   case OMPC_use_device_ptr:
13235   case OMPC_use_device_addr:
13236   case OMPC_is_device_ptr:
13237   case OMPC_unified_address:
13238   case OMPC_unified_shared_memory:
13239   case OMPC_reverse_offload:
13240   case OMPC_dynamic_allocators:
13241   case OMPC_atomic_default_mem_order:
13242   case OMPC_device_type:
13243   case OMPC_match:
13244   case OMPC_nontemporal:
13245   case OMPC_order:
13246   case OMPC_destroy:
13247   case OMPC_inclusive:
13248   case OMPC_exclusive:
13249   case OMPC_uses_allocators:
13250   case OMPC_affinity:
13251   default:
13252     llvm_unreachable("Clause is not allowed.");
13253   }
13254   return Res;
13255 }
13256 
13257 // An OpenMP directive such as 'target parallel' has two captured regions:
13258 // for the 'target' and 'parallel' respectively.  This function returns
13259 // the region in which to capture expressions associated with a clause.
13260 // A return value of OMPD_unknown signifies that the expression should not
13261 // be captured.
13262 static OpenMPDirectiveKind getOpenMPCaptureRegionForClause(
13263     OpenMPDirectiveKind DKind, OpenMPClauseKind CKind, unsigned OpenMPVersion,
13264     OpenMPDirectiveKind NameModifier = OMPD_unknown) {
13265   OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
13266   switch (CKind) {
13267   case OMPC_if:
13268     switch (DKind) {
13269     case OMPD_target_parallel_for_simd:
13270       if (OpenMPVersion >= 50 &&
13271           (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)) {
13272         CaptureRegion = OMPD_parallel;
13273         break;
13274       }
13275       LLVM_FALLTHROUGH;
13276     case OMPD_target_parallel:
13277     case OMPD_target_parallel_for:
13278       // If this clause applies to the nested 'parallel' region, capture within
13279       // the 'target' region, otherwise do not capture.
13280       if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
13281         CaptureRegion = OMPD_target;
13282       break;
13283     case OMPD_target_teams_distribute_parallel_for_simd:
13284       if (OpenMPVersion >= 50 &&
13285           (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)) {
13286         CaptureRegion = OMPD_parallel;
13287         break;
13288       }
13289       LLVM_FALLTHROUGH;
13290     case OMPD_target_teams_distribute_parallel_for:
13291       // If this clause applies to the nested 'parallel' region, capture within
13292       // the 'teams' region, otherwise do not capture.
13293       if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
13294         CaptureRegion = OMPD_teams;
13295       break;
13296     case OMPD_teams_distribute_parallel_for_simd:
13297       if (OpenMPVersion >= 50 &&
13298           (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)) {
13299         CaptureRegion = OMPD_parallel;
13300         break;
13301       }
13302       LLVM_FALLTHROUGH;
13303     case OMPD_teams_distribute_parallel_for:
13304       CaptureRegion = OMPD_teams;
13305       break;
13306     case OMPD_target_update:
13307     case OMPD_target_enter_data:
13308     case OMPD_target_exit_data:
13309       CaptureRegion = OMPD_task;
13310       break;
13311     case OMPD_parallel_master_taskloop:
13312       if (NameModifier == OMPD_unknown || NameModifier == OMPD_taskloop)
13313         CaptureRegion = OMPD_parallel;
13314       break;
13315     case OMPD_parallel_master_taskloop_simd:
13316       if ((OpenMPVersion <= 45 && NameModifier == OMPD_unknown) ||
13317           NameModifier == OMPD_taskloop) {
13318         CaptureRegion = OMPD_parallel;
13319         break;
13320       }
13321       if (OpenMPVersion <= 45)
13322         break;
13323       if (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)
13324         CaptureRegion = OMPD_taskloop;
13325       break;
13326     case OMPD_parallel_for_simd:
13327       if (OpenMPVersion <= 45)
13328         break;
13329       if (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)
13330         CaptureRegion = OMPD_parallel;
13331       break;
13332     case OMPD_taskloop_simd:
13333     case OMPD_master_taskloop_simd:
13334       if (OpenMPVersion <= 45)
13335         break;
13336       if (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)
13337         CaptureRegion = OMPD_taskloop;
13338       break;
13339     case OMPD_distribute_parallel_for_simd:
13340       if (OpenMPVersion <= 45)
13341         break;
13342       if (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)
13343         CaptureRegion = OMPD_parallel;
13344       break;
13345     case OMPD_target_simd:
13346       if (OpenMPVersion >= 50 &&
13347           (NameModifier == OMPD_unknown || NameModifier == OMPD_simd))
13348         CaptureRegion = OMPD_target;
13349       break;
13350     case OMPD_teams_distribute_simd:
13351     case OMPD_target_teams_distribute_simd:
13352       if (OpenMPVersion >= 50 &&
13353           (NameModifier == OMPD_unknown || NameModifier == OMPD_simd))
13354         CaptureRegion = OMPD_teams;
13355       break;
13356     case OMPD_cancel:
13357     case OMPD_parallel:
13358     case OMPD_parallel_master:
13359     case OMPD_parallel_sections:
13360     case OMPD_parallel_for:
13361     case OMPD_target:
13362     case OMPD_target_teams:
13363     case OMPD_target_teams_distribute:
13364     case OMPD_distribute_parallel_for:
13365     case OMPD_task:
13366     case OMPD_taskloop:
13367     case OMPD_master_taskloop:
13368     case OMPD_target_data:
13369     case OMPD_simd:
13370     case OMPD_for_simd:
13371     case OMPD_distribute_simd:
13372       // Do not capture if-clause expressions.
13373       break;
13374     case OMPD_threadprivate:
13375     case OMPD_allocate:
13376     case OMPD_taskyield:
13377     case OMPD_barrier:
13378     case OMPD_taskwait:
13379     case OMPD_cancellation_point:
13380     case OMPD_flush:
13381     case OMPD_depobj:
13382     case OMPD_scan:
13383     case OMPD_declare_reduction:
13384     case OMPD_declare_mapper:
13385     case OMPD_declare_simd:
13386     case OMPD_declare_variant:
13387     case OMPD_begin_declare_variant:
13388     case OMPD_end_declare_variant:
13389     case OMPD_declare_target:
13390     case OMPD_end_declare_target:
13391     case OMPD_teams:
13392     case OMPD_tile:
13393     case OMPD_unroll:
13394     case OMPD_for:
13395     case OMPD_sections:
13396     case OMPD_section:
13397     case OMPD_single:
13398     case OMPD_master:
13399     case OMPD_masked:
13400     case OMPD_critical:
13401     case OMPD_taskgroup:
13402     case OMPD_distribute:
13403     case OMPD_ordered:
13404     case OMPD_atomic:
13405     case OMPD_teams_distribute:
13406     case OMPD_requires:
13407       llvm_unreachable("Unexpected OpenMP directive with if-clause");
13408     case OMPD_unknown:
13409     default:
13410       llvm_unreachable("Unknown OpenMP directive");
13411     }
13412     break;
13413   case OMPC_num_threads:
13414     switch (DKind) {
13415     case OMPD_target_parallel:
13416     case OMPD_target_parallel_for:
13417     case OMPD_target_parallel_for_simd:
13418       CaptureRegion = OMPD_target;
13419       break;
13420     case OMPD_teams_distribute_parallel_for:
13421     case OMPD_teams_distribute_parallel_for_simd:
13422     case OMPD_target_teams_distribute_parallel_for:
13423     case OMPD_target_teams_distribute_parallel_for_simd:
13424       CaptureRegion = OMPD_teams;
13425       break;
13426     case OMPD_parallel:
13427     case OMPD_parallel_master:
13428     case OMPD_parallel_sections:
13429     case OMPD_parallel_for:
13430     case OMPD_parallel_for_simd:
13431     case OMPD_distribute_parallel_for:
13432     case OMPD_distribute_parallel_for_simd:
13433     case OMPD_parallel_master_taskloop:
13434     case OMPD_parallel_master_taskloop_simd:
13435       // Do not capture num_threads-clause expressions.
13436       break;
13437     case OMPD_target_data:
13438     case OMPD_target_enter_data:
13439     case OMPD_target_exit_data:
13440     case OMPD_target_update:
13441     case OMPD_target:
13442     case OMPD_target_simd:
13443     case OMPD_target_teams:
13444     case OMPD_target_teams_distribute:
13445     case OMPD_target_teams_distribute_simd:
13446     case OMPD_cancel:
13447     case OMPD_task:
13448     case OMPD_taskloop:
13449     case OMPD_taskloop_simd:
13450     case OMPD_master_taskloop:
13451     case OMPD_master_taskloop_simd:
13452     case OMPD_threadprivate:
13453     case OMPD_allocate:
13454     case OMPD_taskyield:
13455     case OMPD_barrier:
13456     case OMPD_taskwait:
13457     case OMPD_cancellation_point:
13458     case OMPD_flush:
13459     case OMPD_depobj:
13460     case OMPD_scan:
13461     case OMPD_declare_reduction:
13462     case OMPD_declare_mapper:
13463     case OMPD_declare_simd:
13464     case OMPD_declare_variant:
13465     case OMPD_begin_declare_variant:
13466     case OMPD_end_declare_variant:
13467     case OMPD_declare_target:
13468     case OMPD_end_declare_target:
13469     case OMPD_teams:
13470     case OMPD_simd:
13471     case OMPD_tile:
13472     case OMPD_unroll:
13473     case OMPD_for:
13474     case OMPD_for_simd:
13475     case OMPD_sections:
13476     case OMPD_section:
13477     case OMPD_single:
13478     case OMPD_master:
13479     case OMPD_masked:
13480     case OMPD_critical:
13481     case OMPD_taskgroup:
13482     case OMPD_distribute:
13483     case OMPD_ordered:
13484     case OMPD_atomic:
13485     case OMPD_distribute_simd:
13486     case OMPD_teams_distribute:
13487     case OMPD_teams_distribute_simd:
13488     case OMPD_requires:
13489       llvm_unreachable("Unexpected OpenMP directive with num_threads-clause");
13490     case OMPD_unknown:
13491     default:
13492       llvm_unreachable("Unknown OpenMP directive");
13493     }
13494     break;
13495   case OMPC_num_teams:
13496     switch (DKind) {
13497     case OMPD_target_teams:
13498     case OMPD_target_teams_distribute:
13499     case OMPD_target_teams_distribute_simd:
13500     case OMPD_target_teams_distribute_parallel_for:
13501     case OMPD_target_teams_distribute_parallel_for_simd:
13502       CaptureRegion = OMPD_target;
13503       break;
13504     case OMPD_teams_distribute_parallel_for:
13505     case OMPD_teams_distribute_parallel_for_simd:
13506     case OMPD_teams:
13507     case OMPD_teams_distribute:
13508     case OMPD_teams_distribute_simd:
13509       // Do not capture num_teams-clause expressions.
13510       break;
13511     case OMPD_distribute_parallel_for:
13512     case OMPD_distribute_parallel_for_simd:
13513     case OMPD_task:
13514     case OMPD_taskloop:
13515     case OMPD_taskloop_simd:
13516     case OMPD_master_taskloop:
13517     case OMPD_master_taskloop_simd:
13518     case OMPD_parallel_master_taskloop:
13519     case OMPD_parallel_master_taskloop_simd:
13520     case OMPD_target_data:
13521     case OMPD_target_enter_data:
13522     case OMPD_target_exit_data:
13523     case OMPD_target_update:
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_target:
13531     case OMPD_target_simd:
13532     case OMPD_target_parallel:
13533     case OMPD_target_parallel_for:
13534     case OMPD_target_parallel_for_simd:
13535     case OMPD_threadprivate:
13536     case OMPD_allocate:
13537     case OMPD_taskyield:
13538     case OMPD_barrier:
13539     case OMPD_taskwait:
13540     case OMPD_cancellation_point:
13541     case OMPD_flush:
13542     case OMPD_depobj:
13543     case OMPD_scan:
13544     case OMPD_declare_reduction:
13545     case OMPD_declare_mapper:
13546     case OMPD_declare_simd:
13547     case OMPD_declare_variant:
13548     case OMPD_begin_declare_variant:
13549     case OMPD_end_declare_variant:
13550     case OMPD_declare_target:
13551     case OMPD_end_declare_target:
13552     case OMPD_simd:
13553     case OMPD_tile:
13554     case OMPD_unroll:
13555     case OMPD_for:
13556     case OMPD_for_simd:
13557     case OMPD_sections:
13558     case OMPD_section:
13559     case OMPD_single:
13560     case OMPD_master:
13561     case OMPD_masked:
13562     case OMPD_critical:
13563     case OMPD_taskgroup:
13564     case OMPD_distribute:
13565     case OMPD_ordered:
13566     case OMPD_atomic:
13567     case OMPD_distribute_simd:
13568     case OMPD_requires:
13569       llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
13570     case OMPD_unknown:
13571     default:
13572       llvm_unreachable("Unknown OpenMP directive");
13573     }
13574     break;
13575   case OMPC_thread_limit:
13576     switch (DKind) {
13577     case OMPD_target_teams:
13578     case OMPD_target_teams_distribute:
13579     case OMPD_target_teams_distribute_simd:
13580     case OMPD_target_teams_distribute_parallel_for:
13581     case OMPD_target_teams_distribute_parallel_for_simd:
13582       CaptureRegion = OMPD_target;
13583       break;
13584     case OMPD_teams_distribute_parallel_for:
13585     case OMPD_teams_distribute_parallel_for_simd:
13586     case OMPD_teams:
13587     case OMPD_teams_distribute:
13588     case OMPD_teams_distribute_simd:
13589       // Do not capture thread_limit-clause expressions.
13590       break;
13591     case OMPD_distribute_parallel_for:
13592     case OMPD_distribute_parallel_for_simd:
13593     case OMPD_task:
13594     case OMPD_taskloop:
13595     case OMPD_taskloop_simd:
13596     case OMPD_master_taskloop:
13597     case OMPD_master_taskloop_simd:
13598     case OMPD_parallel_master_taskloop:
13599     case OMPD_parallel_master_taskloop_simd:
13600     case OMPD_target_data:
13601     case OMPD_target_enter_data:
13602     case OMPD_target_exit_data:
13603     case OMPD_target_update:
13604     case OMPD_cancel:
13605     case OMPD_parallel:
13606     case OMPD_parallel_master:
13607     case OMPD_parallel_sections:
13608     case OMPD_parallel_for:
13609     case OMPD_parallel_for_simd:
13610     case OMPD_target:
13611     case OMPD_target_simd:
13612     case OMPD_target_parallel:
13613     case OMPD_target_parallel_for:
13614     case OMPD_target_parallel_for_simd:
13615     case OMPD_threadprivate:
13616     case OMPD_allocate:
13617     case OMPD_taskyield:
13618     case OMPD_barrier:
13619     case OMPD_taskwait:
13620     case OMPD_cancellation_point:
13621     case OMPD_flush:
13622     case OMPD_depobj:
13623     case OMPD_scan:
13624     case OMPD_declare_reduction:
13625     case OMPD_declare_mapper:
13626     case OMPD_declare_simd:
13627     case OMPD_declare_variant:
13628     case OMPD_begin_declare_variant:
13629     case OMPD_end_declare_variant:
13630     case OMPD_declare_target:
13631     case OMPD_end_declare_target:
13632     case OMPD_simd:
13633     case OMPD_tile:
13634     case OMPD_unroll:
13635     case OMPD_for:
13636     case OMPD_for_simd:
13637     case OMPD_sections:
13638     case OMPD_section:
13639     case OMPD_single:
13640     case OMPD_master:
13641     case OMPD_masked:
13642     case OMPD_critical:
13643     case OMPD_taskgroup:
13644     case OMPD_distribute:
13645     case OMPD_ordered:
13646     case OMPD_atomic:
13647     case OMPD_distribute_simd:
13648     case OMPD_requires:
13649       llvm_unreachable("Unexpected OpenMP directive with thread_limit-clause");
13650     case OMPD_unknown:
13651     default:
13652       llvm_unreachable("Unknown OpenMP directive");
13653     }
13654     break;
13655   case OMPC_schedule:
13656     switch (DKind) {
13657     case OMPD_parallel_for:
13658     case OMPD_parallel_for_simd:
13659     case OMPD_distribute_parallel_for:
13660     case OMPD_distribute_parallel_for_simd:
13661     case OMPD_teams_distribute_parallel_for:
13662     case OMPD_teams_distribute_parallel_for_simd:
13663     case OMPD_target_parallel_for:
13664     case OMPD_target_parallel_for_simd:
13665     case OMPD_target_teams_distribute_parallel_for:
13666     case OMPD_target_teams_distribute_parallel_for_simd:
13667       CaptureRegion = OMPD_parallel;
13668       break;
13669     case OMPD_for:
13670     case OMPD_for_simd:
13671       // Do not capture schedule-clause expressions.
13672       break;
13673     case OMPD_task:
13674     case OMPD_taskloop:
13675     case OMPD_taskloop_simd:
13676     case OMPD_master_taskloop:
13677     case OMPD_master_taskloop_simd:
13678     case OMPD_parallel_master_taskloop:
13679     case OMPD_parallel_master_taskloop_simd:
13680     case OMPD_target_data:
13681     case OMPD_target_enter_data:
13682     case OMPD_target_exit_data:
13683     case OMPD_target_update:
13684     case OMPD_teams:
13685     case OMPD_teams_distribute:
13686     case OMPD_teams_distribute_simd:
13687     case OMPD_target_teams_distribute:
13688     case OMPD_target_teams_distribute_simd:
13689     case OMPD_target:
13690     case OMPD_target_simd:
13691     case OMPD_target_parallel:
13692     case OMPD_cancel:
13693     case OMPD_parallel:
13694     case OMPD_parallel_master:
13695     case OMPD_parallel_sections:
13696     case OMPD_threadprivate:
13697     case OMPD_allocate:
13698     case OMPD_taskyield:
13699     case OMPD_barrier:
13700     case OMPD_taskwait:
13701     case OMPD_cancellation_point:
13702     case OMPD_flush:
13703     case OMPD_depobj:
13704     case OMPD_scan:
13705     case OMPD_declare_reduction:
13706     case OMPD_declare_mapper:
13707     case OMPD_declare_simd:
13708     case OMPD_declare_variant:
13709     case OMPD_begin_declare_variant:
13710     case OMPD_end_declare_variant:
13711     case OMPD_declare_target:
13712     case OMPD_end_declare_target:
13713     case OMPD_simd:
13714     case OMPD_tile:
13715     case OMPD_unroll:
13716     case OMPD_sections:
13717     case OMPD_section:
13718     case OMPD_single:
13719     case OMPD_master:
13720     case OMPD_masked:
13721     case OMPD_critical:
13722     case OMPD_taskgroup:
13723     case OMPD_distribute:
13724     case OMPD_ordered:
13725     case OMPD_atomic:
13726     case OMPD_distribute_simd:
13727     case OMPD_target_teams:
13728     case OMPD_requires:
13729       llvm_unreachable("Unexpected OpenMP directive with schedule clause");
13730     case OMPD_unknown:
13731     default:
13732       llvm_unreachable("Unknown OpenMP directive");
13733     }
13734     break;
13735   case OMPC_dist_schedule:
13736     switch (DKind) {
13737     case OMPD_teams_distribute_parallel_for:
13738     case OMPD_teams_distribute_parallel_for_simd:
13739     case OMPD_teams_distribute:
13740     case OMPD_teams_distribute_simd:
13741     case OMPD_target_teams_distribute_parallel_for:
13742     case OMPD_target_teams_distribute_parallel_for_simd:
13743     case OMPD_target_teams_distribute:
13744     case OMPD_target_teams_distribute_simd:
13745       CaptureRegion = OMPD_teams;
13746       break;
13747     case OMPD_distribute_parallel_for:
13748     case OMPD_distribute_parallel_for_simd:
13749     case OMPD_distribute:
13750     case OMPD_distribute_simd:
13751       // Do not capture dist_schedule-clause expressions.
13752       break;
13753     case OMPD_parallel_for:
13754     case OMPD_parallel_for_simd:
13755     case OMPD_target_parallel_for_simd:
13756     case OMPD_target_parallel_for:
13757     case OMPD_task:
13758     case OMPD_taskloop:
13759     case OMPD_taskloop_simd:
13760     case OMPD_master_taskloop:
13761     case OMPD_master_taskloop_simd:
13762     case OMPD_parallel_master_taskloop:
13763     case OMPD_parallel_master_taskloop_simd:
13764     case OMPD_target_data:
13765     case OMPD_target_enter_data:
13766     case OMPD_target_exit_data:
13767     case OMPD_target_update:
13768     case OMPD_teams:
13769     case OMPD_target:
13770     case OMPD_target_simd:
13771     case OMPD_target_parallel:
13772     case OMPD_cancel:
13773     case OMPD_parallel:
13774     case OMPD_parallel_master:
13775     case OMPD_parallel_sections:
13776     case OMPD_threadprivate:
13777     case OMPD_allocate:
13778     case OMPD_taskyield:
13779     case OMPD_barrier:
13780     case OMPD_taskwait:
13781     case OMPD_cancellation_point:
13782     case OMPD_flush:
13783     case OMPD_depobj:
13784     case OMPD_scan:
13785     case OMPD_declare_reduction:
13786     case OMPD_declare_mapper:
13787     case OMPD_declare_simd:
13788     case OMPD_declare_variant:
13789     case OMPD_begin_declare_variant:
13790     case OMPD_end_declare_variant:
13791     case OMPD_declare_target:
13792     case OMPD_end_declare_target:
13793     case OMPD_simd:
13794     case OMPD_tile:
13795     case OMPD_unroll:
13796     case OMPD_for:
13797     case OMPD_for_simd:
13798     case OMPD_sections:
13799     case OMPD_section:
13800     case OMPD_single:
13801     case OMPD_master:
13802     case OMPD_masked:
13803     case OMPD_critical:
13804     case OMPD_taskgroup:
13805     case OMPD_ordered:
13806     case OMPD_atomic:
13807     case OMPD_target_teams:
13808     case OMPD_requires:
13809       llvm_unreachable("Unexpected OpenMP directive with dist_schedule clause");
13810     case OMPD_unknown:
13811     default:
13812       llvm_unreachable("Unknown OpenMP directive");
13813     }
13814     break;
13815   case OMPC_device:
13816     switch (DKind) {
13817     case OMPD_target_update:
13818     case OMPD_target_enter_data:
13819     case OMPD_target_exit_data:
13820     case OMPD_target:
13821     case OMPD_target_simd:
13822     case OMPD_target_teams:
13823     case OMPD_target_parallel:
13824     case OMPD_target_teams_distribute:
13825     case OMPD_target_teams_distribute_simd:
13826     case OMPD_target_parallel_for:
13827     case OMPD_target_parallel_for_simd:
13828     case OMPD_target_teams_distribute_parallel_for:
13829     case OMPD_target_teams_distribute_parallel_for_simd:
13830     case OMPD_dispatch:
13831       CaptureRegion = OMPD_task;
13832       break;
13833     case OMPD_target_data:
13834     case OMPD_interop:
13835       // Do not capture device-clause expressions.
13836       break;
13837     case OMPD_teams_distribute_parallel_for:
13838     case OMPD_teams_distribute_parallel_for_simd:
13839     case OMPD_teams:
13840     case OMPD_teams_distribute:
13841     case OMPD_teams_distribute_simd:
13842     case OMPD_distribute_parallel_for:
13843     case OMPD_distribute_parallel_for_simd:
13844     case OMPD_task:
13845     case OMPD_taskloop:
13846     case OMPD_taskloop_simd:
13847     case OMPD_master_taskloop:
13848     case OMPD_master_taskloop_simd:
13849     case OMPD_parallel_master_taskloop:
13850     case OMPD_parallel_master_taskloop_simd:
13851     case OMPD_cancel:
13852     case OMPD_parallel:
13853     case OMPD_parallel_master:
13854     case OMPD_parallel_sections:
13855     case OMPD_parallel_for:
13856     case OMPD_parallel_for_simd:
13857     case OMPD_threadprivate:
13858     case OMPD_allocate:
13859     case OMPD_taskyield:
13860     case OMPD_barrier:
13861     case OMPD_taskwait:
13862     case OMPD_cancellation_point:
13863     case OMPD_flush:
13864     case OMPD_depobj:
13865     case OMPD_scan:
13866     case OMPD_declare_reduction:
13867     case OMPD_declare_mapper:
13868     case OMPD_declare_simd:
13869     case OMPD_declare_variant:
13870     case OMPD_begin_declare_variant:
13871     case OMPD_end_declare_variant:
13872     case OMPD_declare_target:
13873     case OMPD_end_declare_target:
13874     case OMPD_simd:
13875     case OMPD_tile:
13876     case OMPD_unroll:
13877     case OMPD_for:
13878     case OMPD_for_simd:
13879     case OMPD_sections:
13880     case OMPD_section:
13881     case OMPD_single:
13882     case OMPD_master:
13883     case OMPD_masked:
13884     case OMPD_critical:
13885     case OMPD_taskgroup:
13886     case OMPD_distribute:
13887     case OMPD_ordered:
13888     case OMPD_atomic:
13889     case OMPD_distribute_simd:
13890     case OMPD_requires:
13891       llvm_unreachable("Unexpected OpenMP directive with device-clause");
13892     case OMPD_unknown:
13893     default:
13894       llvm_unreachable("Unknown OpenMP directive");
13895     }
13896     break;
13897   case OMPC_grainsize:
13898   case OMPC_num_tasks:
13899   case OMPC_final:
13900   case OMPC_priority:
13901     switch (DKind) {
13902     case OMPD_task:
13903     case OMPD_taskloop:
13904     case OMPD_taskloop_simd:
13905     case OMPD_master_taskloop:
13906     case OMPD_master_taskloop_simd:
13907       break;
13908     case OMPD_parallel_master_taskloop:
13909     case OMPD_parallel_master_taskloop_simd:
13910       CaptureRegion = OMPD_parallel;
13911       break;
13912     case OMPD_target_update:
13913     case OMPD_target_enter_data:
13914     case OMPD_target_exit_data:
13915     case OMPD_target:
13916     case OMPD_target_simd:
13917     case OMPD_target_teams:
13918     case OMPD_target_parallel:
13919     case OMPD_target_teams_distribute:
13920     case OMPD_target_teams_distribute_simd:
13921     case OMPD_target_parallel_for:
13922     case OMPD_target_parallel_for_simd:
13923     case OMPD_target_teams_distribute_parallel_for:
13924     case OMPD_target_teams_distribute_parallel_for_simd:
13925     case OMPD_target_data:
13926     case OMPD_teams_distribute_parallel_for:
13927     case OMPD_teams_distribute_parallel_for_simd:
13928     case OMPD_teams:
13929     case OMPD_teams_distribute:
13930     case OMPD_teams_distribute_simd:
13931     case OMPD_distribute_parallel_for:
13932     case OMPD_distribute_parallel_for_simd:
13933     case OMPD_cancel:
13934     case OMPD_parallel:
13935     case OMPD_parallel_master:
13936     case OMPD_parallel_sections:
13937     case OMPD_parallel_for:
13938     case OMPD_parallel_for_simd:
13939     case OMPD_threadprivate:
13940     case OMPD_allocate:
13941     case OMPD_taskyield:
13942     case OMPD_barrier:
13943     case OMPD_taskwait:
13944     case OMPD_cancellation_point:
13945     case OMPD_flush:
13946     case OMPD_depobj:
13947     case OMPD_scan:
13948     case OMPD_declare_reduction:
13949     case OMPD_declare_mapper:
13950     case OMPD_declare_simd:
13951     case OMPD_declare_variant:
13952     case OMPD_begin_declare_variant:
13953     case OMPD_end_declare_variant:
13954     case OMPD_declare_target:
13955     case OMPD_end_declare_target:
13956     case OMPD_simd:
13957     case OMPD_tile:
13958     case OMPD_unroll:
13959     case OMPD_for:
13960     case OMPD_for_simd:
13961     case OMPD_sections:
13962     case OMPD_section:
13963     case OMPD_single:
13964     case OMPD_master:
13965     case OMPD_masked:
13966     case OMPD_critical:
13967     case OMPD_taskgroup:
13968     case OMPD_distribute:
13969     case OMPD_ordered:
13970     case OMPD_atomic:
13971     case OMPD_distribute_simd:
13972     case OMPD_requires:
13973       llvm_unreachable("Unexpected OpenMP directive with grainsize-clause");
13974     case OMPD_unknown:
13975     default:
13976       llvm_unreachable("Unknown OpenMP directive");
13977     }
13978     break;
13979   case OMPC_novariants:
13980   case OMPC_nocontext:
13981     switch (DKind) {
13982     case OMPD_dispatch:
13983       CaptureRegion = OMPD_task;
13984       break;
13985     default:
13986       llvm_unreachable("Unexpected OpenMP directive");
13987     }
13988     break;
13989   case OMPC_filter:
13990     // Do not capture filter-clause expressions.
13991     break;
13992   case OMPC_firstprivate:
13993   case OMPC_lastprivate:
13994   case OMPC_reduction:
13995   case OMPC_task_reduction:
13996   case OMPC_in_reduction:
13997   case OMPC_linear:
13998   case OMPC_default:
13999   case OMPC_proc_bind:
14000   case OMPC_safelen:
14001   case OMPC_simdlen:
14002   case OMPC_sizes:
14003   case OMPC_allocator:
14004   case OMPC_collapse:
14005   case OMPC_private:
14006   case OMPC_shared:
14007   case OMPC_aligned:
14008   case OMPC_copyin:
14009   case OMPC_copyprivate:
14010   case OMPC_ordered:
14011   case OMPC_nowait:
14012   case OMPC_untied:
14013   case OMPC_mergeable:
14014   case OMPC_threadprivate:
14015   case OMPC_allocate:
14016   case OMPC_flush:
14017   case OMPC_depobj:
14018   case OMPC_read:
14019   case OMPC_write:
14020   case OMPC_update:
14021   case OMPC_capture:
14022   case OMPC_seq_cst:
14023   case OMPC_acq_rel:
14024   case OMPC_acquire:
14025   case OMPC_release:
14026   case OMPC_relaxed:
14027   case OMPC_depend:
14028   case OMPC_threads:
14029   case OMPC_simd:
14030   case OMPC_map:
14031   case OMPC_nogroup:
14032   case OMPC_hint:
14033   case OMPC_defaultmap:
14034   case OMPC_unknown:
14035   case OMPC_uniform:
14036   case OMPC_to:
14037   case OMPC_from:
14038   case OMPC_use_device_ptr:
14039   case OMPC_use_device_addr:
14040   case OMPC_is_device_ptr:
14041   case OMPC_unified_address:
14042   case OMPC_unified_shared_memory:
14043   case OMPC_reverse_offload:
14044   case OMPC_dynamic_allocators:
14045   case OMPC_atomic_default_mem_order:
14046   case OMPC_device_type:
14047   case OMPC_match:
14048   case OMPC_nontemporal:
14049   case OMPC_order:
14050   case OMPC_destroy:
14051   case OMPC_detach:
14052   case OMPC_inclusive:
14053   case OMPC_exclusive:
14054   case OMPC_uses_allocators:
14055   case OMPC_affinity:
14056   default:
14057     llvm_unreachable("Unexpected OpenMP clause.");
14058   }
14059   return CaptureRegion;
14060 }
14061 
14062 OMPClause *Sema::ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
14063                                      Expr *Condition, SourceLocation StartLoc,
14064                                      SourceLocation LParenLoc,
14065                                      SourceLocation NameModifierLoc,
14066                                      SourceLocation ColonLoc,
14067                                      SourceLocation EndLoc) {
14068   Expr *ValExpr = Condition;
14069   Stmt *HelperValStmt = nullptr;
14070   OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
14071   if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
14072       !Condition->isInstantiationDependent() &&
14073       !Condition->containsUnexpandedParameterPack()) {
14074     ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
14075     if (Val.isInvalid())
14076       return nullptr;
14077 
14078     ValExpr = Val.get();
14079 
14080     OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
14081     CaptureRegion = getOpenMPCaptureRegionForClause(
14082         DKind, OMPC_if, LangOpts.OpenMP, NameModifier);
14083     if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
14084       ValExpr = MakeFullExpr(ValExpr).get();
14085       llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
14086       ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
14087       HelperValStmt = buildPreInits(Context, Captures);
14088     }
14089   }
14090 
14091   return new (Context)
14092       OMPIfClause(NameModifier, ValExpr, HelperValStmt, CaptureRegion, StartLoc,
14093                   LParenLoc, NameModifierLoc, ColonLoc, EndLoc);
14094 }
14095 
14096 OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition,
14097                                         SourceLocation StartLoc,
14098                                         SourceLocation LParenLoc,
14099                                         SourceLocation EndLoc) {
14100   Expr *ValExpr = Condition;
14101   Stmt *HelperValStmt = nullptr;
14102   OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
14103   if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
14104       !Condition->isInstantiationDependent() &&
14105       !Condition->containsUnexpandedParameterPack()) {
14106     ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
14107     if (Val.isInvalid())
14108       return nullptr;
14109 
14110     ValExpr = MakeFullExpr(Val.get()).get();
14111 
14112     OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
14113     CaptureRegion =
14114         getOpenMPCaptureRegionForClause(DKind, OMPC_final, LangOpts.OpenMP);
14115     if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
14116       ValExpr = MakeFullExpr(ValExpr).get();
14117       llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
14118       ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
14119       HelperValStmt = buildPreInits(Context, Captures);
14120     }
14121   }
14122 
14123   return new (Context) OMPFinalClause(ValExpr, HelperValStmt, CaptureRegion,
14124                                       StartLoc, LParenLoc, EndLoc);
14125 }
14126 
14127 ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc,
14128                                                         Expr *Op) {
14129   if (!Op)
14130     return ExprError();
14131 
14132   class IntConvertDiagnoser : public ICEConvertDiagnoser {
14133   public:
14134     IntConvertDiagnoser()
14135         : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {}
14136     SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
14137                                          QualType T) override {
14138       return S.Diag(Loc, diag::err_omp_not_integral) << T;
14139     }
14140     SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
14141                                              QualType T) override {
14142       return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
14143     }
14144     SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
14145                                                QualType T,
14146                                                QualType ConvTy) override {
14147       return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
14148     }
14149     SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
14150                                            QualType ConvTy) override {
14151       return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
14152              << ConvTy->isEnumeralType() << ConvTy;
14153     }
14154     SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
14155                                             QualType T) override {
14156       return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
14157     }
14158     SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
14159                                         QualType ConvTy) override {
14160       return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
14161              << ConvTy->isEnumeralType() << ConvTy;
14162     }
14163     SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType,
14164                                              QualType) override {
14165       llvm_unreachable("conversion functions are permitted");
14166     }
14167   } ConvertDiagnoser;
14168   return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
14169 }
14170 
14171 static bool
14172 isNonNegativeIntegerValue(Expr *&ValExpr, Sema &SemaRef, OpenMPClauseKind CKind,
14173                           bool StrictlyPositive, bool BuildCapture = false,
14174                           OpenMPDirectiveKind DKind = OMPD_unknown,
14175                           OpenMPDirectiveKind *CaptureRegion = nullptr,
14176                           Stmt **HelperValStmt = nullptr) {
14177   if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() &&
14178       !ValExpr->isInstantiationDependent()) {
14179     SourceLocation Loc = ValExpr->getExprLoc();
14180     ExprResult Value =
14181         SemaRef.PerformOpenMPImplicitIntegerConversion(Loc, ValExpr);
14182     if (Value.isInvalid())
14183       return false;
14184 
14185     ValExpr = Value.get();
14186     // The expression must evaluate to a non-negative integer value.
14187     if (Optional<llvm::APSInt> Result =
14188             ValExpr->getIntegerConstantExpr(SemaRef.Context)) {
14189       if (Result->isSigned() &&
14190           !((!StrictlyPositive && Result->isNonNegative()) ||
14191             (StrictlyPositive && Result->isStrictlyPositive()))) {
14192         SemaRef.Diag(Loc, diag::err_omp_negative_expression_in_clause)
14193             << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
14194             << ValExpr->getSourceRange();
14195         return false;
14196       }
14197     }
14198     if (!BuildCapture)
14199       return true;
14200     *CaptureRegion =
14201         getOpenMPCaptureRegionForClause(DKind, CKind, SemaRef.LangOpts.OpenMP);
14202     if (*CaptureRegion != OMPD_unknown &&
14203         !SemaRef.CurContext->isDependentContext()) {
14204       ValExpr = SemaRef.MakeFullExpr(ValExpr).get();
14205       llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
14206       ValExpr = tryBuildCapture(SemaRef, ValExpr, Captures).get();
14207       *HelperValStmt = buildPreInits(SemaRef.Context, Captures);
14208     }
14209   }
14210   return true;
14211 }
14212 
14213 OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
14214                                              SourceLocation StartLoc,
14215                                              SourceLocation LParenLoc,
14216                                              SourceLocation EndLoc) {
14217   Expr *ValExpr = NumThreads;
14218   Stmt *HelperValStmt = nullptr;
14219 
14220   // OpenMP [2.5, Restrictions]
14221   //  The num_threads expression must evaluate to a positive integer value.
14222   if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_threads,
14223                                  /*StrictlyPositive=*/true))
14224     return nullptr;
14225 
14226   OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
14227   OpenMPDirectiveKind CaptureRegion =
14228       getOpenMPCaptureRegionForClause(DKind, OMPC_num_threads, LangOpts.OpenMP);
14229   if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
14230     ValExpr = MakeFullExpr(ValExpr).get();
14231     llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
14232     ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
14233     HelperValStmt = buildPreInits(Context, Captures);
14234   }
14235 
14236   return new (Context) OMPNumThreadsClause(
14237       ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
14238 }
14239 
14240 ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
14241                                                        OpenMPClauseKind CKind,
14242                                                        bool StrictlyPositive,
14243                                                        bool SuppressExprDiags) {
14244   if (!E)
14245     return ExprError();
14246   if (E->isValueDependent() || E->isTypeDependent() ||
14247       E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
14248     return E;
14249 
14250   llvm::APSInt Result;
14251   ExprResult ICE;
14252   if (SuppressExprDiags) {
14253     // Use a custom diagnoser that suppresses 'note' diagnostics about the
14254     // expression.
14255     struct SuppressedDiagnoser : public Sema::VerifyICEDiagnoser {
14256       SuppressedDiagnoser() : VerifyICEDiagnoser(/*Suppress=*/true) {}
14257       Sema::SemaDiagnosticBuilder diagnoseNotICE(Sema &S,
14258                                                  SourceLocation Loc) override {
14259         llvm_unreachable("Diagnostic suppressed");
14260       }
14261     } Diagnoser;
14262     ICE = VerifyIntegerConstantExpression(E, &Result, Diagnoser, AllowFold);
14263   } else {
14264     ICE = VerifyIntegerConstantExpression(E, &Result, /*FIXME*/ AllowFold);
14265   }
14266   if (ICE.isInvalid())
14267     return ExprError();
14268 
14269   if ((StrictlyPositive && !Result.isStrictlyPositive()) ||
14270       (!StrictlyPositive && !Result.isNonNegative())) {
14271     Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
14272         << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
14273         << E->getSourceRange();
14274     return ExprError();
14275   }
14276   if (CKind == OMPC_aligned && !Result.isPowerOf2()) {
14277     Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two)
14278         << E->getSourceRange();
14279     return ExprError();
14280   }
14281   if (CKind == OMPC_collapse && DSAStack->getAssociatedLoops() == 1)
14282     DSAStack->setAssociatedLoops(Result.getExtValue());
14283   else if (CKind == OMPC_ordered)
14284     DSAStack->setAssociatedLoops(Result.getExtValue());
14285   return ICE;
14286 }
14287 
14288 OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
14289                                           SourceLocation LParenLoc,
14290                                           SourceLocation EndLoc) {
14291   // OpenMP [2.8.1, simd construct, Description]
14292   // The parameter of the safelen clause must be a constant
14293   // positive integer expression.
14294   ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen);
14295   if (Safelen.isInvalid())
14296     return nullptr;
14297   return new (Context)
14298       OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc);
14299 }
14300 
14301 OMPClause *Sema::ActOnOpenMPSimdlenClause(Expr *Len, SourceLocation StartLoc,
14302                                           SourceLocation LParenLoc,
14303                                           SourceLocation EndLoc) {
14304   // OpenMP [2.8.1, simd construct, Description]
14305   // The parameter of the simdlen clause must be a constant
14306   // positive integer expression.
14307   ExprResult Simdlen = VerifyPositiveIntegerConstantInClause(Len, OMPC_simdlen);
14308   if (Simdlen.isInvalid())
14309     return nullptr;
14310   return new (Context)
14311       OMPSimdlenClause(Simdlen.get(), StartLoc, LParenLoc, EndLoc);
14312 }
14313 
14314 /// Tries to find omp_allocator_handle_t type.
14315 static bool findOMPAllocatorHandleT(Sema &S, SourceLocation Loc,
14316                                     DSAStackTy *Stack) {
14317   QualType OMPAllocatorHandleT = Stack->getOMPAllocatorHandleT();
14318   if (!OMPAllocatorHandleT.isNull())
14319     return true;
14320   // Build the predefined allocator expressions.
14321   bool ErrorFound = false;
14322   for (int I = 0; I < OMPAllocateDeclAttr::OMPUserDefinedMemAlloc; ++I) {
14323     auto AllocatorKind = static_cast<OMPAllocateDeclAttr::AllocatorTypeTy>(I);
14324     StringRef Allocator =
14325         OMPAllocateDeclAttr::ConvertAllocatorTypeTyToStr(AllocatorKind);
14326     DeclarationName AllocatorName = &S.getASTContext().Idents.get(Allocator);
14327     auto *VD = dyn_cast_or_null<ValueDecl>(
14328         S.LookupSingleName(S.TUScope, AllocatorName, Loc, Sema::LookupAnyName));
14329     if (!VD) {
14330       ErrorFound = true;
14331       break;
14332     }
14333     QualType AllocatorType =
14334         VD->getType().getNonLValueExprType(S.getASTContext());
14335     ExprResult Res = S.BuildDeclRefExpr(VD, AllocatorType, VK_LValue, Loc);
14336     if (!Res.isUsable()) {
14337       ErrorFound = true;
14338       break;
14339     }
14340     if (OMPAllocatorHandleT.isNull())
14341       OMPAllocatorHandleT = AllocatorType;
14342     if (!S.getASTContext().hasSameType(OMPAllocatorHandleT, AllocatorType)) {
14343       ErrorFound = true;
14344       break;
14345     }
14346     Stack->setAllocator(AllocatorKind, Res.get());
14347   }
14348   if (ErrorFound) {
14349     S.Diag(Loc, diag::err_omp_implied_type_not_found)
14350         << "omp_allocator_handle_t";
14351     return false;
14352   }
14353   OMPAllocatorHandleT.addConst();
14354   Stack->setOMPAllocatorHandleT(OMPAllocatorHandleT);
14355   return true;
14356 }
14357 
14358 OMPClause *Sema::ActOnOpenMPAllocatorClause(Expr *A, SourceLocation StartLoc,
14359                                             SourceLocation LParenLoc,
14360                                             SourceLocation EndLoc) {
14361   // OpenMP [2.11.3, allocate Directive, Description]
14362   // allocator is an expression of omp_allocator_handle_t type.
14363   if (!findOMPAllocatorHandleT(*this, A->getExprLoc(), DSAStack))
14364     return nullptr;
14365 
14366   ExprResult Allocator = DefaultLvalueConversion(A);
14367   if (Allocator.isInvalid())
14368     return nullptr;
14369   Allocator = PerformImplicitConversion(Allocator.get(),
14370                                         DSAStack->getOMPAllocatorHandleT(),
14371                                         Sema::AA_Initializing,
14372                                         /*AllowExplicit=*/true);
14373   if (Allocator.isInvalid())
14374     return nullptr;
14375   return new (Context)
14376       OMPAllocatorClause(Allocator.get(), StartLoc, LParenLoc, EndLoc);
14377 }
14378 
14379 OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops,
14380                                            SourceLocation StartLoc,
14381                                            SourceLocation LParenLoc,
14382                                            SourceLocation EndLoc) {
14383   // OpenMP [2.7.1, loop construct, Description]
14384   // OpenMP [2.8.1, simd construct, Description]
14385   // OpenMP [2.9.6, distribute construct, Description]
14386   // The parameter of the collapse clause must be a constant
14387   // positive integer expression.
14388   ExprResult NumForLoopsResult =
14389       VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse);
14390   if (NumForLoopsResult.isInvalid())
14391     return nullptr;
14392   return new (Context)
14393       OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc);
14394 }
14395 
14396 OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc,
14397                                           SourceLocation EndLoc,
14398                                           SourceLocation LParenLoc,
14399                                           Expr *NumForLoops) {
14400   // OpenMP [2.7.1, loop construct, Description]
14401   // OpenMP [2.8.1, simd construct, Description]
14402   // OpenMP [2.9.6, distribute construct, Description]
14403   // The parameter of the ordered clause must be a constant
14404   // positive integer expression if any.
14405   if (NumForLoops && LParenLoc.isValid()) {
14406     ExprResult NumForLoopsResult =
14407         VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_ordered);
14408     if (NumForLoopsResult.isInvalid())
14409       return nullptr;
14410     NumForLoops = NumForLoopsResult.get();
14411   } else {
14412     NumForLoops = nullptr;
14413   }
14414   auto *Clause = OMPOrderedClause::Create(
14415       Context, NumForLoops, NumForLoops ? DSAStack->getAssociatedLoops() : 0,
14416       StartLoc, LParenLoc, EndLoc);
14417   DSAStack->setOrderedRegion(/*IsOrdered=*/true, NumForLoops, Clause);
14418   return Clause;
14419 }
14420 
14421 OMPClause *Sema::ActOnOpenMPSimpleClause(
14422     OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc,
14423     SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
14424   OMPClause *Res = nullptr;
14425   switch (Kind) {
14426   case OMPC_default:
14427     Res = ActOnOpenMPDefaultClause(static_cast<DefaultKind>(Argument),
14428                                    ArgumentLoc, StartLoc, LParenLoc, EndLoc);
14429     break;
14430   case OMPC_proc_bind:
14431     Res = ActOnOpenMPProcBindClause(static_cast<ProcBindKind>(Argument),
14432                                     ArgumentLoc, StartLoc, LParenLoc, EndLoc);
14433     break;
14434   case OMPC_atomic_default_mem_order:
14435     Res = ActOnOpenMPAtomicDefaultMemOrderClause(
14436         static_cast<OpenMPAtomicDefaultMemOrderClauseKind>(Argument),
14437         ArgumentLoc, StartLoc, LParenLoc, EndLoc);
14438     break;
14439   case OMPC_order:
14440     Res = ActOnOpenMPOrderClause(static_cast<OpenMPOrderClauseKind>(Argument),
14441                                  ArgumentLoc, StartLoc, LParenLoc, EndLoc);
14442     break;
14443   case OMPC_update:
14444     Res = ActOnOpenMPUpdateClause(static_cast<OpenMPDependClauseKind>(Argument),
14445                                   ArgumentLoc, StartLoc, LParenLoc, EndLoc);
14446     break;
14447   case OMPC_if:
14448   case OMPC_final:
14449   case OMPC_num_threads:
14450   case OMPC_safelen:
14451   case OMPC_simdlen:
14452   case OMPC_sizes:
14453   case OMPC_allocator:
14454   case OMPC_collapse:
14455   case OMPC_schedule:
14456   case OMPC_private:
14457   case OMPC_firstprivate:
14458   case OMPC_lastprivate:
14459   case OMPC_shared:
14460   case OMPC_reduction:
14461   case OMPC_task_reduction:
14462   case OMPC_in_reduction:
14463   case OMPC_linear:
14464   case OMPC_aligned:
14465   case OMPC_copyin:
14466   case OMPC_copyprivate:
14467   case OMPC_ordered:
14468   case OMPC_nowait:
14469   case OMPC_untied:
14470   case OMPC_mergeable:
14471   case OMPC_threadprivate:
14472   case OMPC_allocate:
14473   case OMPC_flush:
14474   case OMPC_depobj:
14475   case OMPC_read:
14476   case OMPC_write:
14477   case OMPC_capture:
14478   case OMPC_seq_cst:
14479   case OMPC_acq_rel:
14480   case OMPC_acquire:
14481   case OMPC_release:
14482   case OMPC_relaxed:
14483   case OMPC_depend:
14484   case OMPC_device:
14485   case OMPC_threads:
14486   case OMPC_simd:
14487   case OMPC_map:
14488   case OMPC_num_teams:
14489   case OMPC_thread_limit:
14490   case OMPC_priority:
14491   case OMPC_grainsize:
14492   case OMPC_nogroup:
14493   case OMPC_num_tasks:
14494   case OMPC_hint:
14495   case OMPC_dist_schedule:
14496   case OMPC_defaultmap:
14497   case OMPC_unknown:
14498   case OMPC_uniform:
14499   case OMPC_to:
14500   case OMPC_from:
14501   case OMPC_use_device_ptr:
14502   case OMPC_use_device_addr:
14503   case OMPC_is_device_ptr:
14504   case OMPC_unified_address:
14505   case OMPC_unified_shared_memory:
14506   case OMPC_reverse_offload:
14507   case OMPC_dynamic_allocators:
14508   case OMPC_device_type:
14509   case OMPC_match:
14510   case OMPC_nontemporal:
14511   case OMPC_destroy:
14512   case OMPC_novariants:
14513   case OMPC_nocontext:
14514   case OMPC_detach:
14515   case OMPC_inclusive:
14516   case OMPC_exclusive:
14517   case OMPC_uses_allocators:
14518   case OMPC_affinity:
14519   default:
14520     llvm_unreachable("Clause is not allowed.");
14521   }
14522   return Res;
14523 }
14524 
14525 static std::string
14526 getListOfPossibleValues(OpenMPClauseKind K, unsigned First, unsigned Last,
14527                         ArrayRef<unsigned> Exclude = llvm::None) {
14528   SmallString<256> Buffer;
14529   llvm::raw_svector_ostream Out(Buffer);
14530   unsigned Skipped = Exclude.size();
14531   auto S = Exclude.begin(), E = Exclude.end();
14532   for (unsigned I = First; I < Last; ++I) {
14533     if (std::find(S, E, I) != E) {
14534       --Skipped;
14535       continue;
14536     }
14537     Out << "'" << getOpenMPSimpleClauseTypeName(K, I) << "'";
14538     if (I + Skipped + 2 == Last)
14539       Out << " or ";
14540     else if (I + Skipped + 1 != Last)
14541       Out << ", ";
14542   }
14543   return std::string(Out.str());
14544 }
14545 
14546 OMPClause *Sema::ActOnOpenMPDefaultClause(DefaultKind Kind,
14547                                           SourceLocation KindKwLoc,
14548                                           SourceLocation StartLoc,
14549                                           SourceLocation LParenLoc,
14550                                           SourceLocation EndLoc) {
14551   if (Kind == OMP_DEFAULT_unknown) {
14552     Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
14553         << getListOfPossibleValues(OMPC_default, /*First=*/0,
14554                                    /*Last=*/unsigned(OMP_DEFAULT_unknown))
14555         << getOpenMPClauseName(OMPC_default);
14556     return nullptr;
14557   }
14558 
14559   switch (Kind) {
14560   case OMP_DEFAULT_none:
14561     DSAStack->setDefaultDSANone(KindKwLoc);
14562     break;
14563   case OMP_DEFAULT_shared:
14564     DSAStack->setDefaultDSAShared(KindKwLoc);
14565     break;
14566   case OMP_DEFAULT_firstprivate:
14567     DSAStack->setDefaultDSAFirstPrivate(KindKwLoc);
14568     break;
14569   default:
14570     llvm_unreachable("DSA unexpected in OpenMP default clause");
14571   }
14572 
14573   return new (Context)
14574       OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
14575 }
14576 
14577 OMPClause *Sema::ActOnOpenMPProcBindClause(ProcBindKind Kind,
14578                                            SourceLocation KindKwLoc,
14579                                            SourceLocation StartLoc,
14580                                            SourceLocation LParenLoc,
14581                                            SourceLocation EndLoc) {
14582   if (Kind == OMP_PROC_BIND_unknown) {
14583     Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
14584         << getListOfPossibleValues(OMPC_proc_bind,
14585                                    /*First=*/unsigned(OMP_PROC_BIND_master),
14586                                    /*Last=*/
14587                                    unsigned(LangOpts.OpenMP > 50
14588                                                 ? OMP_PROC_BIND_primary
14589                                                 : OMP_PROC_BIND_spread) +
14590                                        1)
14591         << getOpenMPClauseName(OMPC_proc_bind);
14592     return nullptr;
14593   }
14594   if (Kind == OMP_PROC_BIND_primary && LangOpts.OpenMP < 51)
14595     Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
14596         << getListOfPossibleValues(OMPC_proc_bind,
14597                                    /*First=*/unsigned(OMP_PROC_BIND_master),
14598                                    /*Last=*/
14599                                    unsigned(OMP_PROC_BIND_spread) + 1)
14600         << getOpenMPClauseName(OMPC_proc_bind);
14601   return new (Context)
14602       OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
14603 }
14604 
14605 OMPClause *Sema::ActOnOpenMPAtomicDefaultMemOrderClause(
14606     OpenMPAtomicDefaultMemOrderClauseKind Kind, SourceLocation KindKwLoc,
14607     SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
14608   if (Kind == OMPC_ATOMIC_DEFAULT_MEM_ORDER_unknown) {
14609     Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
14610         << getListOfPossibleValues(
14611                OMPC_atomic_default_mem_order, /*First=*/0,
14612                /*Last=*/OMPC_ATOMIC_DEFAULT_MEM_ORDER_unknown)
14613         << getOpenMPClauseName(OMPC_atomic_default_mem_order);
14614     return nullptr;
14615   }
14616   return new (Context) OMPAtomicDefaultMemOrderClause(Kind, KindKwLoc, StartLoc,
14617                                                       LParenLoc, EndLoc);
14618 }
14619 
14620 OMPClause *Sema::ActOnOpenMPOrderClause(OpenMPOrderClauseKind Kind,
14621                                         SourceLocation KindKwLoc,
14622                                         SourceLocation StartLoc,
14623                                         SourceLocation LParenLoc,
14624                                         SourceLocation EndLoc) {
14625   if (Kind == OMPC_ORDER_unknown) {
14626     static_assert(OMPC_ORDER_unknown > 0,
14627                   "OMPC_ORDER_unknown not greater than 0");
14628     Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
14629         << getListOfPossibleValues(OMPC_order, /*First=*/0,
14630                                    /*Last=*/OMPC_ORDER_unknown)
14631         << getOpenMPClauseName(OMPC_order);
14632     return nullptr;
14633   }
14634   return new (Context)
14635       OMPOrderClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
14636 }
14637 
14638 OMPClause *Sema::ActOnOpenMPUpdateClause(OpenMPDependClauseKind Kind,
14639                                          SourceLocation KindKwLoc,
14640                                          SourceLocation StartLoc,
14641                                          SourceLocation LParenLoc,
14642                                          SourceLocation EndLoc) {
14643   if (Kind == OMPC_DEPEND_unknown || Kind == OMPC_DEPEND_source ||
14644       Kind == OMPC_DEPEND_sink || Kind == OMPC_DEPEND_depobj) {
14645     unsigned Except[] = {OMPC_DEPEND_source, OMPC_DEPEND_sink,
14646                          OMPC_DEPEND_depobj};
14647     Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
14648         << getListOfPossibleValues(OMPC_depend, /*First=*/0,
14649                                    /*Last=*/OMPC_DEPEND_unknown, Except)
14650         << getOpenMPClauseName(OMPC_update);
14651     return nullptr;
14652   }
14653   return OMPUpdateClause::Create(Context, StartLoc, LParenLoc, KindKwLoc, Kind,
14654                                  EndLoc);
14655 }
14656 
14657 OMPClause *Sema::ActOnOpenMPSizesClause(ArrayRef<Expr *> SizeExprs,
14658                                         SourceLocation StartLoc,
14659                                         SourceLocation LParenLoc,
14660                                         SourceLocation EndLoc) {
14661   for (Expr *SizeExpr : SizeExprs) {
14662     ExprResult NumForLoopsResult = VerifyPositiveIntegerConstantInClause(
14663         SizeExpr, OMPC_sizes, /*StrictlyPositive=*/true);
14664     if (!NumForLoopsResult.isUsable())
14665       return nullptr;
14666   }
14667 
14668   DSAStack->setAssociatedLoops(SizeExprs.size());
14669   return OMPSizesClause::Create(Context, StartLoc, LParenLoc, EndLoc,
14670                                 SizeExprs);
14671 }
14672 
14673 OMPClause *Sema::ActOnOpenMPFullClause(SourceLocation StartLoc,
14674                                        SourceLocation EndLoc) {
14675   return OMPFullClause::Create(Context, StartLoc, EndLoc);
14676 }
14677 
14678 OMPClause *Sema::ActOnOpenMPPartialClause(Expr *FactorExpr,
14679                                           SourceLocation StartLoc,
14680                                           SourceLocation LParenLoc,
14681                                           SourceLocation EndLoc) {
14682   if (FactorExpr) {
14683     // If an argument is specified, it must be a constant (or an unevaluated
14684     // template expression).
14685     ExprResult FactorResult = VerifyPositiveIntegerConstantInClause(
14686         FactorExpr, OMPC_partial, /*StrictlyPositive=*/true);
14687     if (FactorResult.isInvalid())
14688       return nullptr;
14689     FactorExpr = FactorResult.get();
14690   }
14691 
14692   return OMPPartialClause::Create(Context, StartLoc, LParenLoc, EndLoc,
14693                                   FactorExpr);
14694 }
14695 
14696 OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause(
14697     OpenMPClauseKind Kind, ArrayRef<unsigned> Argument, Expr *Expr,
14698     SourceLocation StartLoc, SourceLocation LParenLoc,
14699     ArrayRef<SourceLocation> ArgumentLoc, SourceLocation DelimLoc,
14700     SourceLocation EndLoc) {
14701   OMPClause *Res = nullptr;
14702   switch (Kind) {
14703   case OMPC_schedule:
14704     enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements };
14705     assert(Argument.size() == NumberOfElements &&
14706            ArgumentLoc.size() == NumberOfElements);
14707     Res = ActOnOpenMPScheduleClause(
14708         static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier1]),
14709         static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier2]),
14710         static_cast<OpenMPScheduleClauseKind>(Argument[ScheduleKind]), Expr,
14711         StartLoc, LParenLoc, ArgumentLoc[Modifier1], ArgumentLoc[Modifier2],
14712         ArgumentLoc[ScheduleKind], DelimLoc, EndLoc);
14713     break;
14714   case OMPC_if:
14715     assert(Argument.size() == 1 && ArgumentLoc.size() == 1);
14716     Res = ActOnOpenMPIfClause(static_cast<OpenMPDirectiveKind>(Argument.back()),
14717                               Expr, StartLoc, LParenLoc, ArgumentLoc.back(),
14718                               DelimLoc, EndLoc);
14719     break;
14720   case OMPC_dist_schedule:
14721     Res = ActOnOpenMPDistScheduleClause(
14722         static_cast<OpenMPDistScheduleClauseKind>(Argument.back()), Expr,
14723         StartLoc, LParenLoc, ArgumentLoc.back(), DelimLoc, EndLoc);
14724     break;
14725   case OMPC_defaultmap:
14726     enum { Modifier, DefaultmapKind };
14727     Res = ActOnOpenMPDefaultmapClause(
14728         static_cast<OpenMPDefaultmapClauseModifier>(Argument[Modifier]),
14729         static_cast<OpenMPDefaultmapClauseKind>(Argument[DefaultmapKind]),
14730         StartLoc, LParenLoc, ArgumentLoc[Modifier], ArgumentLoc[DefaultmapKind],
14731         EndLoc);
14732     break;
14733   case OMPC_device:
14734     assert(Argument.size() == 1 && ArgumentLoc.size() == 1);
14735     Res = ActOnOpenMPDeviceClause(
14736         static_cast<OpenMPDeviceClauseModifier>(Argument.back()), Expr,
14737         StartLoc, LParenLoc, ArgumentLoc.back(), EndLoc);
14738     break;
14739   case OMPC_final:
14740   case OMPC_num_threads:
14741   case OMPC_safelen:
14742   case OMPC_simdlen:
14743   case OMPC_sizes:
14744   case OMPC_allocator:
14745   case OMPC_collapse:
14746   case OMPC_default:
14747   case OMPC_proc_bind:
14748   case OMPC_private:
14749   case OMPC_firstprivate:
14750   case OMPC_lastprivate:
14751   case OMPC_shared:
14752   case OMPC_reduction:
14753   case OMPC_task_reduction:
14754   case OMPC_in_reduction:
14755   case OMPC_linear:
14756   case OMPC_aligned:
14757   case OMPC_copyin:
14758   case OMPC_copyprivate:
14759   case OMPC_ordered:
14760   case OMPC_nowait:
14761   case OMPC_untied:
14762   case OMPC_mergeable:
14763   case OMPC_threadprivate:
14764   case OMPC_allocate:
14765   case OMPC_flush:
14766   case OMPC_depobj:
14767   case OMPC_read:
14768   case OMPC_write:
14769   case OMPC_update:
14770   case OMPC_capture:
14771   case OMPC_seq_cst:
14772   case OMPC_acq_rel:
14773   case OMPC_acquire:
14774   case OMPC_release:
14775   case OMPC_relaxed:
14776   case OMPC_depend:
14777   case OMPC_threads:
14778   case OMPC_simd:
14779   case OMPC_map:
14780   case OMPC_num_teams:
14781   case OMPC_thread_limit:
14782   case OMPC_priority:
14783   case OMPC_grainsize:
14784   case OMPC_nogroup:
14785   case OMPC_num_tasks:
14786   case OMPC_hint:
14787   case OMPC_unknown:
14788   case OMPC_uniform:
14789   case OMPC_to:
14790   case OMPC_from:
14791   case OMPC_use_device_ptr:
14792   case OMPC_use_device_addr:
14793   case OMPC_is_device_ptr:
14794   case OMPC_unified_address:
14795   case OMPC_unified_shared_memory:
14796   case OMPC_reverse_offload:
14797   case OMPC_dynamic_allocators:
14798   case OMPC_atomic_default_mem_order:
14799   case OMPC_device_type:
14800   case OMPC_match:
14801   case OMPC_nontemporal:
14802   case OMPC_order:
14803   case OMPC_destroy:
14804   case OMPC_novariants:
14805   case OMPC_nocontext:
14806   case OMPC_detach:
14807   case OMPC_inclusive:
14808   case OMPC_exclusive:
14809   case OMPC_uses_allocators:
14810   case OMPC_affinity:
14811   default:
14812     llvm_unreachable("Clause is not allowed.");
14813   }
14814   return Res;
14815 }
14816 
14817 static bool checkScheduleModifiers(Sema &S, OpenMPScheduleClauseModifier M1,
14818                                    OpenMPScheduleClauseModifier M2,
14819                                    SourceLocation M1Loc, SourceLocation M2Loc) {
14820   if (M1 == OMPC_SCHEDULE_MODIFIER_unknown && M1Loc.isValid()) {
14821     SmallVector<unsigned, 2> Excluded;
14822     if (M2 != OMPC_SCHEDULE_MODIFIER_unknown)
14823       Excluded.push_back(M2);
14824     if (M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic)
14825       Excluded.push_back(OMPC_SCHEDULE_MODIFIER_monotonic);
14826     if (M2 == OMPC_SCHEDULE_MODIFIER_monotonic)
14827       Excluded.push_back(OMPC_SCHEDULE_MODIFIER_nonmonotonic);
14828     S.Diag(M1Loc, diag::err_omp_unexpected_clause_value)
14829         << getListOfPossibleValues(OMPC_schedule,
14830                                    /*First=*/OMPC_SCHEDULE_MODIFIER_unknown + 1,
14831                                    /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
14832                                    Excluded)
14833         << getOpenMPClauseName(OMPC_schedule);
14834     return true;
14835   }
14836   return false;
14837 }
14838 
14839 OMPClause *Sema::ActOnOpenMPScheduleClause(
14840     OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
14841     OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
14842     SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
14843     SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) {
14844   if (checkScheduleModifiers(*this, M1, M2, M1Loc, M2Loc) ||
14845       checkScheduleModifiers(*this, M2, M1, M2Loc, M1Loc))
14846     return nullptr;
14847   // OpenMP, 2.7.1, Loop Construct, Restrictions
14848   // Either the monotonic modifier or the nonmonotonic modifier can be specified
14849   // but not both.
14850   if ((M1 == M2 && M1 != OMPC_SCHEDULE_MODIFIER_unknown) ||
14851       (M1 == OMPC_SCHEDULE_MODIFIER_monotonic &&
14852        M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) ||
14853       (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic &&
14854        M2 == OMPC_SCHEDULE_MODIFIER_monotonic)) {
14855     Diag(M2Loc, diag::err_omp_unexpected_schedule_modifier)
14856         << getOpenMPSimpleClauseTypeName(OMPC_schedule, M2)
14857         << getOpenMPSimpleClauseTypeName(OMPC_schedule, M1);
14858     return nullptr;
14859   }
14860   if (Kind == OMPC_SCHEDULE_unknown) {
14861     std::string Values;
14862     if (M1Loc.isInvalid() && M2Loc.isInvalid()) {
14863       unsigned Exclude[] = {OMPC_SCHEDULE_unknown};
14864       Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
14865                                        /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
14866                                        Exclude);
14867     } else {
14868       Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
14869                                        /*Last=*/OMPC_SCHEDULE_unknown);
14870     }
14871     Diag(KindLoc, diag::err_omp_unexpected_clause_value)
14872         << Values << getOpenMPClauseName(OMPC_schedule);
14873     return nullptr;
14874   }
14875   // OpenMP, 2.7.1, Loop Construct, Restrictions
14876   // The nonmonotonic modifier can only be specified with schedule(dynamic) or
14877   // schedule(guided).
14878   // OpenMP 5.0 does not have this restriction.
14879   if (LangOpts.OpenMP < 50 &&
14880       (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
14881        M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
14882       Kind != OMPC_SCHEDULE_dynamic && Kind != OMPC_SCHEDULE_guided) {
14883     Diag(M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ? M1Loc : M2Loc,
14884          diag::err_omp_schedule_nonmonotonic_static);
14885     return nullptr;
14886   }
14887   Expr *ValExpr = ChunkSize;
14888   Stmt *HelperValStmt = nullptr;
14889   if (ChunkSize) {
14890     if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
14891         !ChunkSize->isInstantiationDependent() &&
14892         !ChunkSize->containsUnexpandedParameterPack()) {
14893       SourceLocation ChunkSizeLoc = ChunkSize->getBeginLoc();
14894       ExprResult Val =
14895           PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
14896       if (Val.isInvalid())
14897         return nullptr;
14898 
14899       ValExpr = Val.get();
14900 
14901       // OpenMP [2.7.1, Restrictions]
14902       //  chunk_size must be a loop invariant integer expression with a positive
14903       //  value.
14904       if (Optional<llvm::APSInt> Result =
14905               ValExpr->getIntegerConstantExpr(Context)) {
14906         if (Result->isSigned() && !Result->isStrictlyPositive()) {
14907           Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
14908               << "schedule" << 1 << ChunkSize->getSourceRange();
14909           return nullptr;
14910         }
14911       } else if (getOpenMPCaptureRegionForClause(
14912                      DSAStack->getCurrentDirective(), OMPC_schedule,
14913                      LangOpts.OpenMP) != OMPD_unknown &&
14914                  !CurContext->isDependentContext()) {
14915         ValExpr = MakeFullExpr(ValExpr).get();
14916         llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
14917         ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
14918         HelperValStmt = buildPreInits(Context, Captures);
14919       }
14920     }
14921   }
14922 
14923   return new (Context)
14924       OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, Kind,
14925                         ValExpr, HelperValStmt, M1, M1Loc, M2, M2Loc);
14926 }
14927 
14928 OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind,
14929                                    SourceLocation StartLoc,
14930                                    SourceLocation EndLoc) {
14931   OMPClause *Res = nullptr;
14932   switch (Kind) {
14933   case OMPC_ordered:
14934     Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc);
14935     break;
14936   case OMPC_nowait:
14937     Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc);
14938     break;
14939   case OMPC_untied:
14940     Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc);
14941     break;
14942   case OMPC_mergeable:
14943     Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc);
14944     break;
14945   case OMPC_read:
14946     Res = ActOnOpenMPReadClause(StartLoc, EndLoc);
14947     break;
14948   case OMPC_write:
14949     Res = ActOnOpenMPWriteClause(StartLoc, EndLoc);
14950     break;
14951   case OMPC_update:
14952     Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc);
14953     break;
14954   case OMPC_capture:
14955     Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc);
14956     break;
14957   case OMPC_seq_cst:
14958     Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc);
14959     break;
14960   case OMPC_acq_rel:
14961     Res = ActOnOpenMPAcqRelClause(StartLoc, EndLoc);
14962     break;
14963   case OMPC_acquire:
14964     Res = ActOnOpenMPAcquireClause(StartLoc, EndLoc);
14965     break;
14966   case OMPC_release:
14967     Res = ActOnOpenMPReleaseClause(StartLoc, EndLoc);
14968     break;
14969   case OMPC_relaxed:
14970     Res = ActOnOpenMPRelaxedClause(StartLoc, EndLoc);
14971     break;
14972   case OMPC_threads:
14973     Res = ActOnOpenMPThreadsClause(StartLoc, EndLoc);
14974     break;
14975   case OMPC_simd:
14976     Res = ActOnOpenMPSIMDClause(StartLoc, EndLoc);
14977     break;
14978   case OMPC_nogroup:
14979     Res = ActOnOpenMPNogroupClause(StartLoc, EndLoc);
14980     break;
14981   case OMPC_unified_address:
14982     Res = ActOnOpenMPUnifiedAddressClause(StartLoc, EndLoc);
14983     break;
14984   case OMPC_unified_shared_memory:
14985     Res = ActOnOpenMPUnifiedSharedMemoryClause(StartLoc, EndLoc);
14986     break;
14987   case OMPC_reverse_offload:
14988     Res = ActOnOpenMPReverseOffloadClause(StartLoc, EndLoc);
14989     break;
14990   case OMPC_dynamic_allocators:
14991     Res = ActOnOpenMPDynamicAllocatorsClause(StartLoc, EndLoc);
14992     break;
14993   case OMPC_destroy:
14994     Res = ActOnOpenMPDestroyClause(/*InteropVar=*/nullptr, StartLoc,
14995                                    /*LParenLoc=*/SourceLocation(),
14996                                    /*VarLoc=*/SourceLocation(), EndLoc);
14997     break;
14998   case OMPC_full:
14999     Res = ActOnOpenMPFullClause(StartLoc, EndLoc);
15000     break;
15001   case OMPC_partial:
15002     Res = ActOnOpenMPPartialClause(nullptr, StartLoc, /*LParenLoc=*/{}, EndLoc);
15003     break;
15004   case OMPC_if:
15005   case OMPC_final:
15006   case OMPC_num_threads:
15007   case OMPC_safelen:
15008   case OMPC_simdlen:
15009   case OMPC_sizes:
15010   case OMPC_allocator:
15011   case OMPC_collapse:
15012   case OMPC_schedule:
15013   case OMPC_private:
15014   case OMPC_firstprivate:
15015   case OMPC_lastprivate:
15016   case OMPC_shared:
15017   case OMPC_reduction:
15018   case OMPC_task_reduction:
15019   case OMPC_in_reduction:
15020   case OMPC_linear:
15021   case OMPC_aligned:
15022   case OMPC_copyin:
15023   case OMPC_copyprivate:
15024   case OMPC_default:
15025   case OMPC_proc_bind:
15026   case OMPC_threadprivate:
15027   case OMPC_allocate:
15028   case OMPC_flush:
15029   case OMPC_depobj:
15030   case OMPC_depend:
15031   case OMPC_device:
15032   case OMPC_map:
15033   case OMPC_num_teams:
15034   case OMPC_thread_limit:
15035   case OMPC_priority:
15036   case OMPC_grainsize:
15037   case OMPC_num_tasks:
15038   case OMPC_hint:
15039   case OMPC_dist_schedule:
15040   case OMPC_defaultmap:
15041   case OMPC_unknown:
15042   case OMPC_uniform:
15043   case OMPC_to:
15044   case OMPC_from:
15045   case OMPC_use_device_ptr:
15046   case OMPC_use_device_addr:
15047   case OMPC_is_device_ptr:
15048   case OMPC_atomic_default_mem_order:
15049   case OMPC_device_type:
15050   case OMPC_match:
15051   case OMPC_nontemporal:
15052   case OMPC_order:
15053   case OMPC_novariants:
15054   case OMPC_nocontext:
15055   case OMPC_detach:
15056   case OMPC_inclusive:
15057   case OMPC_exclusive:
15058   case OMPC_uses_allocators:
15059   case OMPC_affinity:
15060   default:
15061     llvm_unreachable("Clause is not allowed.");
15062   }
15063   return Res;
15064 }
15065 
15066 OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc,
15067                                          SourceLocation EndLoc) {
15068   DSAStack->setNowaitRegion();
15069   return new (Context) OMPNowaitClause(StartLoc, EndLoc);
15070 }
15071 
15072 OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc,
15073                                          SourceLocation EndLoc) {
15074   return new (Context) OMPUntiedClause(StartLoc, EndLoc);
15075 }
15076 
15077 OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc,
15078                                             SourceLocation EndLoc) {
15079   return new (Context) OMPMergeableClause(StartLoc, EndLoc);
15080 }
15081 
15082 OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc,
15083                                        SourceLocation EndLoc) {
15084   return new (Context) OMPReadClause(StartLoc, EndLoc);
15085 }
15086 
15087 OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc,
15088                                         SourceLocation EndLoc) {
15089   return new (Context) OMPWriteClause(StartLoc, EndLoc);
15090 }
15091 
15092 OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc,
15093                                          SourceLocation EndLoc) {
15094   return OMPUpdateClause::Create(Context, StartLoc, EndLoc);
15095 }
15096 
15097 OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc,
15098                                           SourceLocation EndLoc) {
15099   return new (Context) OMPCaptureClause(StartLoc, EndLoc);
15100 }
15101 
15102 OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
15103                                          SourceLocation EndLoc) {
15104   return new (Context) OMPSeqCstClause(StartLoc, EndLoc);
15105 }
15106 
15107 OMPClause *Sema::ActOnOpenMPAcqRelClause(SourceLocation StartLoc,
15108                                          SourceLocation EndLoc) {
15109   return new (Context) OMPAcqRelClause(StartLoc, EndLoc);
15110 }
15111 
15112 OMPClause *Sema::ActOnOpenMPAcquireClause(SourceLocation StartLoc,
15113                                           SourceLocation EndLoc) {
15114   return new (Context) OMPAcquireClause(StartLoc, EndLoc);
15115 }
15116 
15117 OMPClause *Sema::ActOnOpenMPReleaseClause(SourceLocation StartLoc,
15118                                           SourceLocation EndLoc) {
15119   return new (Context) OMPReleaseClause(StartLoc, EndLoc);
15120 }
15121 
15122 OMPClause *Sema::ActOnOpenMPRelaxedClause(SourceLocation StartLoc,
15123                                           SourceLocation EndLoc) {
15124   return new (Context) OMPRelaxedClause(StartLoc, EndLoc);
15125 }
15126 
15127 OMPClause *Sema::ActOnOpenMPThreadsClause(SourceLocation StartLoc,
15128                                           SourceLocation EndLoc) {
15129   return new (Context) OMPThreadsClause(StartLoc, EndLoc);
15130 }
15131 
15132 OMPClause *Sema::ActOnOpenMPSIMDClause(SourceLocation StartLoc,
15133                                        SourceLocation EndLoc) {
15134   return new (Context) OMPSIMDClause(StartLoc, EndLoc);
15135 }
15136 
15137 OMPClause *Sema::ActOnOpenMPNogroupClause(SourceLocation StartLoc,
15138                                           SourceLocation EndLoc) {
15139   return new (Context) OMPNogroupClause(StartLoc, EndLoc);
15140 }
15141 
15142 OMPClause *Sema::ActOnOpenMPUnifiedAddressClause(SourceLocation StartLoc,
15143                                                  SourceLocation EndLoc) {
15144   return new (Context) OMPUnifiedAddressClause(StartLoc, EndLoc);
15145 }
15146 
15147 OMPClause *Sema::ActOnOpenMPUnifiedSharedMemoryClause(SourceLocation StartLoc,
15148                                                       SourceLocation EndLoc) {
15149   return new (Context) OMPUnifiedSharedMemoryClause(StartLoc, EndLoc);
15150 }
15151 
15152 OMPClause *Sema::ActOnOpenMPReverseOffloadClause(SourceLocation StartLoc,
15153                                                  SourceLocation EndLoc) {
15154   return new (Context) OMPReverseOffloadClause(StartLoc, EndLoc);
15155 }
15156 
15157 OMPClause *Sema::ActOnOpenMPDynamicAllocatorsClause(SourceLocation StartLoc,
15158                                                     SourceLocation EndLoc) {
15159   return new (Context) OMPDynamicAllocatorsClause(StartLoc, EndLoc);
15160 }
15161 
15162 StmtResult Sema::ActOnOpenMPInteropDirective(ArrayRef<OMPClause *> Clauses,
15163                                              SourceLocation StartLoc,
15164                                              SourceLocation EndLoc) {
15165 
15166   // OpenMP 5.1 [2.15.1, interop Construct, Restrictions]
15167   // At least one action-clause must appear on a directive.
15168   if (!hasClauses(Clauses, OMPC_init, OMPC_use, OMPC_destroy, OMPC_nowait)) {
15169     StringRef Expected = "'init', 'use', 'destroy', or 'nowait'";
15170     Diag(StartLoc, diag::err_omp_no_clause_for_directive)
15171         << Expected << getOpenMPDirectiveName(OMPD_interop);
15172     return StmtError();
15173   }
15174 
15175   // OpenMP 5.1 [2.15.1, interop Construct, Restrictions]
15176   // A depend clause can only appear on the directive if a targetsync
15177   // interop-type is present or the interop-var was initialized with
15178   // the targetsync interop-type.
15179 
15180   // If there is any 'init' clause diagnose if there is no 'init' clause with
15181   // interop-type of 'targetsync'. Cases involving other directives cannot be
15182   // diagnosed.
15183   const OMPDependClause *DependClause = nullptr;
15184   bool HasInitClause = false;
15185   bool IsTargetSync = false;
15186   for (const OMPClause *C : Clauses) {
15187     if (IsTargetSync)
15188       break;
15189     if (const auto *InitClause = dyn_cast<OMPInitClause>(C)) {
15190       HasInitClause = true;
15191       if (InitClause->getIsTargetSync())
15192         IsTargetSync = true;
15193     } else if (const auto *DC = dyn_cast<OMPDependClause>(C)) {
15194       DependClause = DC;
15195     }
15196   }
15197   if (DependClause && HasInitClause && !IsTargetSync) {
15198     Diag(DependClause->getBeginLoc(), diag::err_omp_interop_bad_depend_clause);
15199     return StmtError();
15200   }
15201 
15202   // OpenMP 5.1 [2.15.1, interop Construct, Restrictions]
15203   // Each interop-var may be specified for at most one action-clause of each
15204   // interop construct.
15205   llvm::SmallPtrSet<const VarDecl *, 4> InteropVars;
15206   for (const OMPClause *C : Clauses) {
15207     OpenMPClauseKind ClauseKind = C->getClauseKind();
15208     const DeclRefExpr *DRE = nullptr;
15209     SourceLocation VarLoc;
15210 
15211     if (ClauseKind == OMPC_init) {
15212       const auto *IC = cast<OMPInitClause>(C);
15213       VarLoc = IC->getVarLoc();
15214       DRE = dyn_cast_or_null<DeclRefExpr>(IC->getInteropVar());
15215     } else if (ClauseKind == OMPC_use) {
15216       const auto *UC = cast<OMPUseClause>(C);
15217       VarLoc = UC->getVarLoc();
15218       DRE = dyn_cast_or_null<DeclRefExpr>(UC->getInteropVar());
15219     } else if (ClauseKind == OMPC_destroy) {
15220       const auto *DC = cast<OMPDestroyClause>(C);
15221       VarLoc = DC->getVarLoc();
15222       DRE = dyn_cast_or_null<DeclRefExpr>(DC->getInteropVar());
15223     }
15224 
15225     if (!DRE)
15226       continue;
15227 
15228     if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
15229       if (!InteropVars.insert(VD->getCanonicalDecl()).second) {
15230         Diag(VarLoc, diag::err_omp_interop_var_multiple_actions) << VD;
15231         return StmtError();
15232       }
15233     }
15234   }
15235 
15236   return OMPInteropDirective::Create(Context, StartLoc, EndLoc, Clauses);
15237 }
15238 
15239 static bool isValidInteropVariable(Sema &SemaRef, Expr *InteropVarExpr,
15240                                    SourceLocation VarLoc,
15241                                    OpenMPClauseKind Kind) {
15242   if (InteropVarExpr->isValueDependent() || InteropVarExpr->isTypeDependent() ||
15243       InteropVarExpr->isInstantiationDependent() ||
15244       InteropVarExpr->containsUnexpandedParameterPack())
15245     return true;
15246 
15247   const auto *DRE = dyn_cast<DeclRefExpr>(InteropVarExpr);
15248   if (!DRE || !isa<VarDecl>(DRE->getDecl())) {
15249     SemaRef.Diag(VarLoc, diag::err_omp_interop_variable_expected) << 0;
15250     return false;
15251   }
15252 
15253   // Interop variable should be of type omp_interop_t.
15254   bool HasError = false;
15255   QualType InteropType;
15256   LookupResult Result(SemaRef, &SemaRef.Context.Idents.get("omp_interop_t"),
15257                       VarLoc, Sema::LookupOrdinaryName);
15258   if (SemaRef.LookupName(Result, SemaRef.getCurScope())) {
15259     NamedDecl *ND = Result.getFoundDecl();
15260     if (const auto *TD = dyn_cast<TypeDecl>(ND)) {
15261       InteropType = QualType(TD->getTypeForDecl(), 0);
15262     } else {
15263       HasError = true;
15264     }
15265   } else {
15266     HasError = true;
15267   }
15268 
15269   if (HasError) {
15270     SemaRef.Diag(VarLoc, diag::err_omp_implied_type_not_found)
15271         << "omp_interop_t";
15272     return false;
15273   }
15274 
15275   QualType VarType = InteropVarExpr->getType().getUnqualifiedType();
15276   if (!SemaRef.Context.hasSameType(InteropType, VarType)) {
15277     SemaRef.Diag(VarLoc, diag::err_omp_interop_variable_wrong_type);
15278     return false;
15279   }
15280 
15281   // OpenMP 5.1 [2.15.1, interop Construct, Restrictions]
15282   // The interop-var passed to init or destroy must be non-const.
15283   if ((Kind == OMPC_init || Kind == OMPC_destroy) &&
15284       isConstNotMutableType(SemaRef, InteropVarExpr->getType())) {
15285     SemaRef.Diag(VarLoc, diag::err_omp_interop_variable_expected)
15286         << /*non-const*/ 1;
15287     return false;
15288   }
15289   return true;
15290 }
15291 
15292 OMPClause *
15293 Sema::ActOnOpenMPInitClause(Expr *InteropVar, ArrayRef<Expr *> PrefExprs,
15294                             bool IsTarget, bool IsTargetSync,
15295                             SourceLocation StartLoc, SourceLocation LParenLoc,
15296                             SourceLocation VarLoc, SourceLocation EndLoc) {
15297 
15298   if (!isValidInteropVariable(*this, InteropVar, VarLoc, OMPC_init))
15299     return nullptr;
15300 
15301   // Check prefer_type values.  These foreign-runtime-id values are either
15302   // string literals or constant integral expressions.
15303   for (const Expr *E : PrefExprs) {
15304     if (E->isValueDependent() || E->isTypeDependent() ||
15305         E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
15306       continue;
15307     if (E->isIntegerConstantExpr(Context))
15308       continue;
15309     if (isa<StringLiteral>(E))
15310       continue;
15311     Diag(E->getExprLoc(), diag::err_omp_interop_prefer_type);
15312     return nullptr;
15313   }
15314 
15315   return OMPInitClause::Create(Context, InteropVar, PrefExprs, IsTarget,
15316                                IsTargetSync, StartLoc, LParenLoc, VarLoc,
15317                                EndLoc);
15318 }
15319 
15320 OMPClause *Sema::ActOnOpenMPUseClause(Expr *InteropVar, SourceLocation StartLoc,
15321                                       SourceLocation LParenLoc,
15322                                       SourceLocation VarLoc,
15323                                       SourceLocation EndLoc) {
15324 
15325   if (!isValidInteropVariable(*this, InteropVar, VarLoc, OMPC_use))
15326     return nullptr;
15327 
15328   return new (Context)
15329       OMPUseClause(InteropVar, StartLoc, LParenLoc, VarLoc, EndLoc);
15330 }
15331 
15332 OMPClause *Sema::ActOnOpenMPDestroyClause(Expr *InteropVar,
15333                                           SourceLocation StartLoc,
15334                                           SourceLocation LParenLoc,
15335                                           SourceLocation VarLoc,
15336                                           SourceLocation EndLoc) {
15337   if (InteropVar &&
15338       !isValidInteropVariable(*this, InteropVar, VarLoc, OMPC_destroy))
15339     return nullptr;
15340 
15341   return new (Context)
15342       OMPDestroyClause(InteropVar, StartLoc, LParenLoc, VarLoc, EndLoc);
15343 }
15344 
15345 OMPClause *Sema::ActOnOpenMPNovariantsClause(Expr *Condition,
15346                                              SourceLocation StartLoc,
15347                                              SourceLocation LParenLoc,
15348                                              SourceLocation EndLoc) {
15349   Expr *ValExpr = Condition;
15350   Stmt *HelperValStmt = nullptr;
15351   OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
15352   if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
15353       !Condition->isInstantiationDependent() &&
15354       !Condition->containsUnexpandedParameterPack()) {
15355     ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
15356     if (Val.isInvalid())
15357       return nullptr;
15358 
15359     ValExpr = MakeFullExpr(Val.get()).get();
15360 
15361     OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
15362     CaptureRegion = getOpenMPCaptureRegionForClause(DKind, OMPC_novariants,
15363                                                     LangOpts.OpenMP);
15364     if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
15365       ValExpr = MakeFullExpr(ValExpr).get();
15366       llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
15367       ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
15368       HelperValStmt = buildPreInits(Context, Captures);
15369     }
15370   }
15371 
15372   return new (Context) OMPNovariantsClause(
15373       ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
15374 }
15375 
15376 OMPClause *Sema::ActOnOpenMPNocontextClause(Expr *Condition,
15377                                             SourceLocation StartLoc,
15378                                             SourceLocation LParenLoc,
15379                                             SourceLocation EndLoc) {
15380   Expr *ValExpr = Condition;
15381   Stmt *HelperValStmt = nullptr;
15382   OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
15383   if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
15384       !Condition->isInstantiationDependent() &&
15385       !Condition->containsUnexpandedParameterPack()) {
15386     ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
15387     if (Val.isInvalid())
15388       return nullptr;
15389 
15390     ValExpr = MakeFullExpr(Val.get()).get();
15391 
15392     OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
15393     CaptureRegion =
15394         getOpenMPCaptureRegionForClause(DKind, OMPC_nocontext, LangOpts.OpenMP);
15395     if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
15396       ValExpr = MakeFullExpr(ValExpr).get();
15397       llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
15398       ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
15399       HelperValStmt = buildPreInits(Context, Captures);
15400     }
15401   }
15402 
15403   return new (Context) OMPNocontextClause(ValExpr, HelperValStmt, CaptureRegion,
15404                                           StartLoc, LParenLoc, EndLoc);
15405 }
15406 
15407 OMPClause *Sema::ActOnOpenMPFilterClause(Expr *ThreadID,
15408                                          SourceLocation StartLoc,
15409                                          SourceLocation LParenLoc,
15410                                          SourceLocation EndLoc) {
15411   Expr *ValExpr = ThreadID;
15412   Stmt *HelperValStmt = nullptr;
15413 
15414   OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
15415   OpenMPDirectiveKind CaptureRegion =
15416       getOpenMPCaptureRegionForClause(DKind, OMPC_filter, LangOpts.OpenMP);
15417   if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
15418     ValExpr = MakeFullExpr(ValExpr).get();
15419     llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
15420     ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
15421     HelperValStmt = buildPreInits(Context, Captures);
15422   }
15423 
15424   return new (Context) OMPFilterClause(ValExpr, HelperValStmt, CaptureRegion,
15425                                        StartLoc, LParenLoc, EndLoc);
15426 }
15427 
15428 OMPClause *Sema::ActOnOpenMPVarListClause(
15429     OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *DepModOrTailExpr,
15430     const OMPVarListLocTy &Locs, SourceLocation ColonLoc,
15431     CXXScopeSpec &ReductionOrMapperIdScopeSpec,
15432     DeclarationNameInfo &ReductionOrMapperId, int ExtraModifier,
15433     ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
15434     ArrayRef<SourceLocation> MapTypeModifiersLoc, bool IsMapTypeImplicit,
15435     SourceLocation ExtraModifierLoc,
15436     ArrayRef<OpenMPMotionModifierKind> MotionModifiers,
15437     ArrayRef<SourceLocation> MotionModifiersLoc) {
15438   SourceLocation StartLoc = Locs.StartLoc;
15439   SourceLocation LParenLoc = Locs.LParenLoc;
15440   SourceLocation EndLoc = Locs.EndLoc;
15441   OMPClause *Res = nullptr;
15442   switch (Kind) {
15443   case OMPC_private:
15444     Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
15445     break;
15446   case OMPC_firstprivate:
15447     Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
15448     break;
15449   case OMPC_lastprivate:
15450     assert(0 <= ExtraModifier && ExtraModifier <= OMPC_LASTPRIVATE_unknown &&
15451            "Unexpected lastprivate modifier.");
15452     Res = ActOnOpenMPLastprivateClause(
15453         VarList, static_cast<OpenMPLastprivateModifier>(ExtraModifier),
15454         ExtraModifierLoc, ColonLoc, StartLoc, LParenLoc, EndLoc);
15455     break;
15456   case OMPC_shared:
15457     Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
15458     break;
15459   case OMPC_reduction:
15460     assert(0 <= ExtraModifier && ExtraModifier <= OMPC_REDUCTION_unknown &&
15461            "Unexpected lastprivate modifier.");
15462     Res = ActOnOpenMPReductionClause(
15463         VarList, static_cast<OpenMPReductionClauseModifier>(ExtraModifier),
15464         StartLoc, LParenLoc, ExtraModifierLoc, ColonLoc, EndLoc,
15465         ReductionOrMapperIdScopeSpec, ReductionOrMapperId);
15466     break;
15467   case OMPC_task_reduction:
15468     Res = ActOnOpenMPTaskReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
15469                                          EndLoc, ReductionOrMapperIdScopeSpec,
15470                                          ReductionOrMapperId);
15471     break;
15472   case OMPC_in_reduction:
15473     Res = ActOnOpenMPInReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
15474                                        EndLoc, ReductionOrMapperIdScopeSpec,
15475                                        ReductionOrMapperId);
15476     break;
15477   case OMPC_linear:
15478     assert(0 <= ExtraModifier && ExtraModifier <= OMPC_LINEAR_unknown &&
15479            "Unexpected linear modifier.");
15480     Res = ActOnOpenMPLinearClause(
15481         VarList, DepModOrTailExpr, StartLoc, LParenLoc,
15482         static_cast<OpenMPLinearClauseKind>(ExtraModifier), ExtraModifierLoc,
15483         ColonLoc, EndLoc);
15484     break;
15485   case OMPC_aligned:
15486     Res = ActOnOpenMPAlignedClause(VarList, DepModOrTailExpr, StartLoc,
15487                                    LParenLoc, ColonLoc, EndLoc);
15488     break;
15489   case OMPC_copyin:
15490     Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
15491     break;
15492   case OMPC_copyprivate:
15493     Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
15494     break;
15495   case OMPC_flush:
15496     Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc);
15497     break;
15498   case OMPC_depend:
15499     assert(0 <= ExtraModifier && ExtraModifier <= OMPC_DEPEND_unknown &&
15500            "Unexpected depend modifier.");
15501     Res = ActOnOpenMPDependClause(
15502         DepModOrTailExpr, static_cast<OpenMPDependClauseKind>(ExtraModifier),
15503         ExtraModifierLoc, ColonLoc, VarList, StartLoc, LParenLoc, EndLoc);
15504     break;
15505   case OMPC_map:
15506     assert(0 <= ExtraModifier && ExtraModifier <= OMPC_MAP_unknown &&
15507            "Unexpected map modifier.");
15508     Res = ActOnOpenMPMapClause(
15509         MapTypeModifiers, MapTypeModifiersLoc, ReductionOrMapperIdScopeSpec,
15510         ReductionOrMapperId, static_cast<OpenMPMapClauseKind>(ExtraModifier),
15511         IsMapTypeImplicit, ExtraModifierLoc, ColonLoc, VarList, Locs);
15512     break;
15513   case OMPC_to:
15514     Res = ActOnOpenMPToClause(MotionModifiers, MotionModifiersLoc,
15515                               ReductionOrMapperIdScopeSpec, ReductionOrMapperId,
15516                               ColonLoc, VarList, Locs);
15517     break;
15518   case OMPC_from:
15519     Res = ActOnOpenMPFromClause(MotionModifiers, MotionModifiersLoc,
15520                                 ReductionOrMapperIdScopeSpec,
15521                                 ReductionOrMapperId, ColonLoc, VarList, Locs);
15522     break;
15523   case OMPC_use_device_ptr:
15524     Res = ActOnOpenMPUseDevicePtrClause(VarList, Locs);
15525     break;
15526   case OMPC_use_device_addr:
15527     Res = ActOnOpenMPUseDeviceAddrClause(VarList, Locs);
15528     break;
15529   case OMPC_is_device_ptr:
15530     Res = ActOnOpenMPIsDevicePtrClause(VarList, Locs);
15531     break;
15532   case OMPC_allocate:
15533     Res = ActOnOpenMPAllocateClause(DepModOrTailExpr, VarList, StartLoc,
15534                                     LParenLoc, ColonLoc, EndLoc);
15535     break;
15536   case OMPC_nontemporal:
15537     Res = ActOnOpenMPNontemporalClause(VarList, StartLoc, LParenLoc, EndLoc);
15538     break;
15539   case OMPC_inclusive:
15540     Res = ActOnOpenMPInclusiveClause(VarList, StartLoc, LParenLoc, EndLoc);
15541     break;
15542   case OMPC_exclusive:
15543     Res = ActOnOpenMPExclusiveClause(VarList, StartLoc, LParenLoc, EndLoc);
15544     break;
15545   case OMPC_affinity:
15546     Res = ActOnOpenMPAffinityClause(StartLoc, LParenLoc, ColonLoc, EndLoc,
15547                                     DepModOrTailExpr, VarList);
15548     break;
15549   case OMPC_if:
15550   case OMPC_depobj:
15551   case OMPC_final:
15552   case OMPC_num_threads:
15553   case OMPC_safelen:
15554   case OMPC_simdlen:
15555   case OMPC_sizes:
15556   case OMPC_allocator:
15557   case OMPC_collapse:
15558   case OMPC_default:
15559   case OMPC_proc_bind:
15560   case OMPC_schedule:
15561   case OMPC_ordered:
15562   case OMPC_nowait:
15563   case OMPC_untied:
15564   case OMPC_mergeable:
15565   case OMPC_threadprivate:
15566   case OMPC_read:
15567   case OMPC_write:
15568   case OMPC_update:
15569   case OMPC_capture:
15570   case OMPC_seq_cst:
15571   case OMPC_acq_rel:
15572   case OMPC_acquire:
15573   case OMPC_release:
15574   case OMPC_relaxed:
15575   case OMPC_device:
15576   case OMPC_threads:
15577   case OMPC_simd:
15578   case OMPC_num_teams:
15579   case OMPC_thread_limit:
15580   case OMPC_priority:
15581   case OMPC_grainsize:
15582   case OMPC_nogroup:
15583   case OMPC_num_tasks:
15584   case OMPC_hint:
15585   case OMPC_dist_schedule:
15586   case OMPC_defaultmap:
15587   case OMPC_unknown:
15588   case OMPC_uniform:
15589   case OMPC_unified_address:
15590   case OMPC_unified_shared_memory:
15591   case OMPC_reverse_offload:
15592   case OMPC_dynamic_allocators:
15593   case OMPC_atomic_default_mem_order:
15594   case OMPC_device_type:
15595   case OMPC_match:
15596   case OMPC_order:
15597   case OMPC_destroy:
15598   case OMPC_novariants:
15599   case OMPC_nocontext:
15600   case OMPC_detach:
15601   case OMPC_uses_allocators:
15602   default:
15603     llvm_unreachable("Clause is not allowed.");
15604   }
15605   return Res;
15606 }
15607 
15608 ExprResult Sema::getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
15609                                        ExprObjectKind OK, SourceLocation Loc) {
15610   ExprResult Res = BuildDeclRefExpr(
15611       Capture, Capture->getType().getNonReferenceType(), VK_LValue, Loc);
15612   if (!Res.isUsable())
15613     return ExprError();
15614   if (OK == OK_Ordinary && !getLangOpts().CPlusPlus) {
15615     Res = CreateBuiltinUnaryOp(Loc, UO_Deref, Res.get());
15616     if (!Res.isUsable())
15617       return ExprError();
15618   }
15619   if (VK != VK_LValue && Res.get()->isGLValue()) {
15620     Res = DefaultLvalueConversion(Res.get());
15621     if (!Res.isUsable())
15622       return ExprError();
15623   }
15624   return Res;
15625 }
15626 
15627 OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
15628                                           SourceLocation StartLoc,
15629                                           SourceLocation LParenLoc,
15630                                           SourceLocation EndLoc) {
15631   SmallVector<Expr *, 8> Vars;
15632   SmallVector<Expr *, 8> PrivateCopies;
15633   for (Expr *RefExpr : VarList) {
15634     assert(RefExpr && "NULL expr in OpenMP private clause.");
15635     SourceLocation ELoc;
15636     SourceRange ERange;
15637     Expr *SimpleRefExpr = RefExpr;
15638     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
15639     if (Res.second) {
15640       // It will be analyzed later.
15641       Vars.push_back(RefExpr);
15642       PrivateCopies.push_back(nullptr);
15643     }
15644     ValueDecl *D = Res.first;
15645     if (!D)
15646       continue;
15647 
15648     QualType Type = D->getType();
15649     auto *VD = dyn_cast<VarDecl>(D);
15650 
15651     // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
15652     //  A variable that appears in a private clause must not have an incomplete
15653     //  type or a reference type.
15654     if (RequireCompleteType(ELoc, Type, diag::err_omp_private_incomplete_type))
15655       continue;
15656     Type = Type.getNonReferenceType();
15657 
15658     // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
15659     // A variable that is privatized must not have a const-qualified type
15660     // unless it is of class type with a mutable member. This restriction does
15661     // not apply to the firstprivate clause.
15662     //
15663     // OpenMP 3.1 [2.9.3.3, private clause, Restrictions]
15664     // A variable that appears in a private clause must not have a
15665     // const-qualified type unless it is of class type with a mutable member.
15666     if (rejectConstNotMutableType(*this, D, Type, OMPC_private, ELoc))
15667       continue;
15668 
15669     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
15670     // in a Construct]
15671     //  Variables with the predetermined data-sharing attributes may not be
15672     //  listed in data-sharing attributes clauses, except for the cases
15673     //  listed below. For these exceptions only, listing a predetermined
15674     //  variable in a data-sharing attribute clause is allowed and overrides
15675     //  the variable's predetermined data-sharing attributes.
15676     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
15677     if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
15678       Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
15679                                           << getOpenMPClauseName(OMPC_private);
15680       reportOriginalDsa(*this, DSAStack, D, DVar);
15681       continue;
15682     }
15683 
15684     OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
15685     // Variably modified types are not supported for tasks.
15686     if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
15687         isOpenMPTaskingDirective(CurrDir)) {
15688       Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
15689           << getOpenMPClauseName(OMPC_private) << Type
15690           << getOpenMPDirectiveName(CurrDir);
15691       bool IsDecl =
15692           !VD ||
15693           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
15694       Diag(D->getLocation(),
15695            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
15696           << D;
15697       continue;
15698     }
15699 
15700     // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
15701     // A list item cannot appear in both a map clause and a data-sharing
15702     // attribute clause on the same construct
15703     //
15704     // OpenMP 5.0 [2.19.7.1, Restrictions, p.7]
15705     // A list item cannot appear in both a map clause and a data-sharing
15706     // attribute clause on the same construct unless the construct is a
15707     // combined construct.
15708     if ((LangOpts.OpenMP <= 45 && isOpenMPTargetExecutionDirective(CurrDir)) ||
15709         CurrDir == OMPD_target) {
15710       OpenMPClauseKind ConflictKind;
15711       if (DSAStack->checkMappableExprComponentListsForDecl(
15712               VD, /*CurrentRegionOnly=*/true,
15713               [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
15714                   OpenMPClauseKind WhereFoundClauseKind) -> bool {
15715                 ConflictKind = WhereFoundClauseKind;
15716                 return true;
15717               })) {
15718         Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
15719             << getOpenMPClauseName(OMPC_private)
15720             << getOpenMPClauseName(ConflictKind)
15721             << getOpenMPDirectiveName(CurrDir);
15722         reportOriginalDsa(*this, DSAStack, D, DVar);
15723         continue;
15724       }
15725     }
15726 
15727     // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
15728     //  A variable of class type (or array thereof) that appears in a private
15729     //  clause requires an accessible, unambiguous default constructor for the
15730     //  class type.
15731     // Generate helper private variable and initialize it with the default
15732     // value. The address of the original variable is replaced by the address of
15733     // the new private variable in CodeGen. This new variable is not added to
15734     // IdResolver, so the code in the OpenMP region uses original variable for
15735     // proper diagnostics.
15736     Type = Type.getUnqualifiedType();
15737     VarDecl *VDPrivate =
15738         buildVarDecl(*this, ELoc, Type, D->getName(),
15739                      D->hasAttrs() ? &D->getAttrs() : nullptr,
15740                      VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
15741     ActOnUninitializedDecl(VDPrivate);
15742     if (VDPrivate->isInvalidDecl())
15743       continue;
15744     DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
15745         *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
15746 
15747     DeclRefExpr *Ref = nullptr;
15748     if (!VD && !CurContext->isDependentContext())
15749       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
15750     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_private, Ref);
15751     Vars.push_back((VD || CurContext->isDependentContext())
15752                        ? RefExpr->IgnoreParens()
15753                        : Ref);
15754     PrivateCopies.push_back(VDPrivateRefExpr);
15755   }
15756 
15757   if (Vars.empty())
15758     return nullptr;
15759 
15760   return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
15761                                   PrivateCopies);
15762 }
15763 
15764 namespace {
15765 class DiagsUninitializedSeveretyRAII {
15766 private:
15767   DiagnosticsEngine &Diags;
15768   SourceLocation SavedLoc;
15769   bool IsIgnored = false;
15770 
15771 public:
15772   DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc,
15773                                  bool IsIgnored)
15774       : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) {
15775     if (!IsIgnored) {
15776       Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init,
15777                         /*Map*/ diag::Severity::Ignored, Loc);
15778     }
15779   }
15780   ~DiagsUninitializedSeveretyRAII() {
15781     if (!IsIgnored)
15782       Diags.popMappings(SavedLoc);
15783   }
15784 };
15785 }
15786 
15787 OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
15788                                                SourceLocation StartLoc,
15789                                                SourceLocation LParenLoc,
15790                                                SourceLocation EndLoc) {
15791   SmallVector<Expr *, 8> Vars;
15792   SmallVector<Expr *, 8> PrivateCopies;
15793   SmallVector<Expr *, 8> Inits;
15794   SmallVector<Decl *, 4> ExprCaptures;
15795   bool IsImplicitClause =
15796       StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid();
15797   SourceLocation ImplicitClauseLoc = DSAStack->getConstructLoc();
15798 
15799   for (Expr *RefExpr : VarList) {
15800     assert(RefExpr && "NULL expr in OpenMP firstprivate clause.");
15801     SourceLocation ELoc;
15802     SourceRange ERange;
15803     Expr *SimpleRefExpr = RefExpr;
15804     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
15805     if (Res.second) {
15806       // It will be analyzed later.
15807       Vars.push_back(RefExpr);
15808       PrivateCopies.push_back(nullptr);
15809       Inits.push_back(nullptr);
15810     }
15811     ValueDecl *D = Res.first;
15812     if (!D)
15813       continue;
15814 
15815     ELoc = IsImplicitClause ? ImplicitClauseLoc : ELoc;
15816     QualType Type = D->getType();
15817     auto *VD = dyn_cast<VarDecl>(D);
15818 
15819     // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
15820     //  A variable that appears in a private clause must not have an incomplete
15821     //  type or a reference type.
15822     if (RequireCompleteType(ELoc, Type,
15823                             diag::err_omp_firstprivate_incomplete_type))
15824       continue;
15825     Type = Type.getNonReferenceType();
15826 
15827     // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
15828     //  A variable of class type (or array thereof) that appears in a private
15829     //  clause requires an accessible, unambiguous copy constructor for the
15830     //  class type.
15831     QualType ElemType = Context.getBaseElementType(Type).getNonReferenceType();
15832 
15833     // If an implicit firstprivate variable found it was checked already.
15834     DSAStackTy::DSAVarData TopDVar;
15835     if (!IsImplicitClause) {
15836       DSAStackTy::DSAVarData DVar =
15837           DSAStack->getTopDSA(D, /*FromParent=*/false);
15838       TopDVar = DVar;
15839       OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
15840       bool IsConstant = ElemType.isConstant(Context);
15841       // OpenMP [2.4.13, Data-sharing Attribute Clauses]
15842       //  A list item that specifies a given variable may not appear in more
15843       // than one clause on the same directive, except that a variable may be
15844       //  specified in both firstprivate and lastprivate clauses.
15845       // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
15846       // A list item may appear in a firstprivate or lastprivate clause but not
15847       // both.
15848       if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
15849           (isOpenMPDistributeDirective(CurrDir) ||
15850            DVar.CKind != OMPC_lastprivate) &&
15851           DVar.RefExpr) {
15852         Diag(ELoc, diag::err_omp_wrong_dsa)
15853             << getOpenMPClauseName(DVar.CKind)
15854             << getOpenMPClauseName(OMPC_firstprivate);
15855         reportOriginalDsa(*this, DSAStack, D, DVar);
15856         continue;
15857       }
15858 
15859       // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
15860       // in a Construct]
15861       //  Variables with the predetermined data-sharing attributes may not be
15862       //  listed in data-sharing attributes clauses, except for the cases
15863       //  listed below. For these exceptions only, listing a predetermined
15864       //  variable in a data-sharing attribute clause is allowed and overrides
15865       //  the variable's predetermined data-sharing attributes.
15866       // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
15867       // in a Construct, C/C++, p.2]
15868       //  Variables with const-qualified type having no mutable member may be
15869       //  listed in a firstprivate clause, even if they are static data members.
15870       if (!(IsConstant || (VD && VD->isStaticDataMember())) && !DVar.RefExpr &&
15871           DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
15872         Diag(ELoc, diag::err_omp_wrong_dsa)
15873             << getOpenMPClauseName(DVar.CKind)
15874             << getOpenMPClauseName(OMPC_firstprivate);
15875         reportOriginalDsa(*this, DSAStack, D, DVar);
15876         continue;
15877       }
15878 
15879       // OpenMP [2.9.3.4, Restrictions, p.2]
15880       //  A list item that is private within a parallel region must not appear
15881       //  in a firstprivate clause on a worksharing construct if any of the
15882       //  worksharing regions arising from the worksharing construct ever bind
15883       //  to any of the parallel regions arising from the parallel construct.
15884       // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
15885       // A list item that is private within a teams region must not appear in a
15886       // firstprivate clause on a distribute construct if any of the distribute
15887       // regions arising from the distribute construct ever bind to any of the
15888       // teams regions arising from the teams construct.
15889       // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
15890       // A list item that appears in a reduction clause of a teams construct
15891       // must not appear in a firstprivate clause on a distribute construct if
15892       // any of the distribute regions arising from the distribute construct
15893       // ever bind to any of the teams regions arising from the teams construct.
15894       if ((isOpenMPWorksharingDirective(CurrDir) ||
15895            isOpenMPDistributeDirective(CurrDir)) &&
15896           !isOpenMPParallelDirective(CurrDir) &&
15897           !isOpenMPTeamsDirective(CurrDir)) {
15898         DVar = DSAStack->getImplicitDSA(D, true);
15899         if (DVar.CKind != OMPC_shared &&
15900             (isOpenMPParallelDirective(DVar.DKind) ||
15901              isOpenMPTeamsDirective(DVar.DKind) ||
15902              DVar.DKind == OMPD_unknown)) {
15903           Diag(ELoc, diag::err_omp_required_access)
15904               << getOpenMPClauseName(OMPC_firstprivate)
15905               << getOpenMPClauseName(OMPC_shared);
15906           reportOriginalDsa(*this, DSAStack, D, DVar);
15907           continue;
15908         }
15909       }
15910       // OpenMP [2.9.3.4, Restrictions, p.3]
15911       //  A list item that appears in a reduction clause of a parallel construct
15912       //  must not appear in a firstprivate clause on a worksharing or task
15913       //  construct if any of the worksharing or task regions arising from the
15914       //  worksharing or task construct ever bind to any of the parallel regions
15915       //  arising from the parallel construct.
15916       // OpenMP [2.9.3.4, Restrictions, p.4]
15917       //  A list item that appears in a reduction clause in worksharing
15918       //  construct must not appear in a firstprivate clause in a task construct
15919       //  encountered during execution of any of the worksharing regions arising
15920       //  from the worksharing construct.
15921       if (isOpenMPTaskingDirective(CurrDir)) {
15922         DVar = DSAStack->hasInnermostDSA(
15923             D,
15924             [](OpenMPClauseKind C, bool AppliedToPointee) {
15925               return C == OMPC_reduction && !AppliedToPointee;
15926             },
15927             [](OpenMPDirectiveKind K) {
15928               return isOpenMPParallelDirective(K) ||
15929                      isOpenMPWorksharingDirective(K) ||
15930                      isOpenMPTeamsDirective(K);
15931             },
15932             /*FromParent=*/true);
15933         if (DVar.CKind == OMPC_reduction &&
15934             (isOpenMPParallelDirective(DVar.DKind) ||
15935              isOpenMPWorksharingDirective(DVar.DKind) ||
15936              isOpenMPTeamsDirective(DVar.DKind))) {
15937           Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate)
15938               << getOpenMPDirectiveName(DVar.DKind);
15939           reportOriginalDsa(*this, DSAStack, D, DVar);
15940           continue;
15941         }
15942       }
15943 
15944       // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
15945       // A list item cannot appear in both a map clause and a data-sharing
15946       // attribute clause on the same construct
15947       //
15948       // OpenMP 5.0 [2.19.7.1, Restrictions, p.7]
15949       // A list item cannot appear in both a map clause and a data-sharing
15950       // attribute clause on the same construct unless the construct is a
15951       // combined construct.
15952       if ((LangOpts.OpenMP <= 45 &&
15953            isOpenMPTargetExecutionDirective(CurrDir)) ||
15954           CurrDir == OMPD_target) {
15955         OpenMPClauseKind ConflictKind;
15956         if (DSAStack->checkMappableExprComponentListsForDecl(
15957                 VD, /*CurrentRegionOnly=*/true,
15958                 [&ConflictKind](
15959                     OMPClauseMappableExprCommon::MappableExprComponentListRef,
15960                     OpenMPClauseKind WhereFoundClauseKind) {
15961                   ConflictKind = WhereFoundClauseKind;
15962                   return true;
15963                 })) {
15964           Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
15965               << getOpenMPClauseName(OMPC_firstprivate)
15966               << getOpenMPClauseName(ConflictKind)
15967               << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
15968           reportOriginalDsa(*this, DSAStack, D, DVar);
15969           continue;
15970         }
15971       }
15972     }
15973 
15974     // Variably modified types are not supported for tasks.
15975     if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
15976         isOpenMPTaskingDirective(DSAStack->getCurrentDirective())) {
15977       Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
15978           << getOpenMPClauseName(OMPC_firstprivate) << Type
15979           << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
15980       bool IsDecl =
15981           !VD ||
15982           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
15983       Diag(D->getLocation(),
15984            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
15985           << D;
15986       continue;
15987     }
15988 
15989     Type = Type.getUnqualifiedType();
15990     VarDecl *VDPrivate =
15991         buildVarDecl(*this, ELoc, Type, D->getName(),
15992                      D->hasAttrs() ? &D->getAttrs() : nullptr,
15993                      VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
15994     // Generate helper private variable and initialize it with the value of the
15995     // original variable. The address of the original variable is replaced by
15996     // the address of the new private variable in the CodeGen. This new variable
15997     // is not added to IdResolver, so the code in the OpenMP region uses
15998     // original variable for proper diagnostics and variable capturing.
15999     Expr *VDInitRefExpr = nullptr;
16000     // For arrays generate initializer for single element and replace it by the
16001     // original array element in CodeGen.
16002     if (Type->isArrayType()) {
16003       VarDecl *VDInit =
16004           buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, D->getName());
16005       VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc);
16006       Expr *Init = DefaultLvalueConversion(VDInitRefExpr).get();
16007       ElemType = ElemType.getUnqualifiedType();
16008       VarDecl *VDInitTemp = buildVarDecl(*this, RefExpr->getExprLoc(), ElemType,
16009                                          ".firstprivate.temp");
16010       InitializedEntity Entity =
16011           InitializedEntity::InitializeVariable(VDInitTemp);
16012       InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc);
16013 
16014       InitializationSequence InitSeq(*this, Entity, Kind, Init);
16015       ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init);
16016       if (Result.isInvalid())
16017         VDPrivate->setInvalidDecl();
16018       else
16019         VDPrivate->setInit(Result.getAs<Expr>());
16020       // Remove temp variable declaration.
16021       Context.Deallocate(VDInitTemp);
16022     } else {
16023       VarDecl *VDInit = buildVarDecl(*this, RefExpr->getExprLoc(), Type,
16024                                      ".firstprivate.temp");
16025       VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
16026                                        RefExpr->getExprLoc());
16027       AddInitializerToDecl(VDPrivate,
16028                            DefaultLvalueConversion(VDInitRefExpr).get(),
16029                            /*DirectInit=*/false);
16030     }
16031     if (VDPrivate->isInvalidDecl()) {
16032       if (IsImplicitClause) {
16033         Diag(RefExpr->getExprLoc(),
16034              diag::note_omp_task_predetermined_firstprivate_here);
16035       }
16036       continue;
16037     }
16038     CurContext->addDecl(VDPrivate);
16039     DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
16040         *this, VDPrivate, RefExpr->getType().getUnqualifiedType(),
16041         RefExpr->getExprLoc());
16042     DeclRefExpr *Ref = nullptr;
16043     if (!VD && !CurContext->isDependentContext()) {
16044       if (TopDVar.CKind == OMPC_lastprivate) {
16045         Ref = TopDVar.PrivateCopy;
16046       } else {
16047         Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
16048         if (!isOpenMPCapturedDecl(D))
16049           ExprCaptures.push_back(Ref->getDecl());
16050       }
16051     }
16052     if (!IsImplicitClause)
16053       DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
16054     Vars.push_back((VD || CurContext->isDependentContext())
16055                        ? RefExpr->IgnoreParens()
16056                        : Ref);
16057     PrivateCopies.push_back(VDPrivateRefExpr);
16058     Inits.push_back(VDInitRefExpr);
16059   }
16060 
16061   if (Vars.empty())
16062     return nullptr;
16063 
16064   return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
16065                                        Vars, PrivateCopies, Inits,
16066                                        buildPreInits(Context, ExprCaptures));
16067 }
16068 
16069 OMPClause *Sema::ActOnOpenMPLastprivateClause(
16070     ArrayRef<Expr *> VarList, OpenMPLastprivateModifier LPKind,
16071     SourceLocation LPKindLoc, SourceLocation ColonLoc, SourceLocation StartLoc,
16072     SourceLocation LParenLoc, SourceLocation EndLoc) {
16073   if (LPKind == OMPC_LASTPRIVATE_unknown && LPKindLoc.isValid()) {
16074     assert(ColonLoc.isValid() && "Colon location must be valid.");
16075     Diag(LPKindLoc, diag::err_omp_unexpected_clause_value)
16076         << getListOfPossibleValues(OMPC_lastprivate, /*First=*/0,
16077                                    /*Last=*/OMPC_LASTPRIVATE_unknown)
16078         << getOpenMPClauseName(OMPC_lastprivate);
16079     return nullptr;
16080   }
16081 
16082   SmallVector<Expr *, 8> Vars;
16083   SmallVector<Expr *, 8> SrcExprs;
16084   SmallVector<Expr *, 8> DstExprs;
16085   SmallVector<Expr *, 8> AssignmentOps;
16086   SmallVector<Decl *, 4> ExprCaptures;
16087   SmallVector<Expr *, 4> ExprPostUpdates;
16088   for (Expr *RefExpr : VarList) {
16089     assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
16090     SourceLocation ELoc;
16091     SourceRange ERange;
16092     Expr *SimpleRefExpr = RefExpr;
16093     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
16094     if (Res.second) {
16095       // It will be analyzed later.
16096       Vars.push_back(RefExpr);
16097       SrcExprs.push_back(nullptr);
16098       DstExprs.push_back(nullptr);
16099       AssignmentOps.push_back(nullptr);
16100     }
16101     ValueDecl *D = Res.first;
16102     if (!D)
16103       continue;
16104 
16105     QualType Type = D->getType();
16106     auto *VD = dyn_cast<VarDecl>(D);
16107 
16108     // OpenMP [2.14.3.5, Restrictions, C/C++, p.2]
16109     //  A variable that appears in a lastprivate clause must not have an
16110     //  incomplete type or a reference type.
16111     if (RequireCompleteType(ELoc, Type,
16112                             diag::err_omp_lastprivate_incomplete_type))
16113       continue;
16114     Type = Type.getNonReferenceType();
16115 
16116     // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
16117     // A variable that is privatized must not have a const-qualified type
16118     // unless it is of class type with a mutable member. This restriction does
16119     // not apply to the firstprivate clause.
16120     //
16121     // OpenMP 3.1 [2.9.3.5, lastprivate clause, Restrictions]
16122     // A variable that appears in a lastprivate clause must not have a
16123     // const-qualified type unless it is of class type with a mutable member.
16124     if (rejectConstNotMutableType(*this, D, Type, OMPC_lastprivate, ELoc))
16125       continue;
16126 
16127     // OpenMP 5.0 [2.19.4.5 lastprivate Clause, Restrictions]
16128     // A list item that appears in a lastprivate clause with the conditional
16129     // modifier must be a scalar variable.
16130     if (LPKind == OMPC_LASTPRIVATE_conditional && !Type->isScalarType()) {
16131       Diag(ELoc, diag::err_omp_lastprivate_conditional_non_scalar);
16132       bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
16133                                VarDecl::DeclarationOnly;
16134       Diag(D->getLocation(),
16135            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
16136           << D;
16137       continue;
16138     }
16139 
16140     OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
16141     // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
16142     // in a Construct]
16143     //  Variables with the predetermined data-sharing attributes may not be
16144     //  listed in data-sharing attributes clauses, except for the cases
16145     //  listed below.
16146     // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
16147     // A list item may appear in a firstprivate or lastprivate clause but not
16148     // both.
16149     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
16150     if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate &&
16151         (isOpenMPDistributeDirective(CurrDir) ||
16152          DVar.CKind != OMPC_firstprivate) &&
16153         (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
16154       Diag(ELoc, diag::err_omp_wrong_dsa)
16155           << getOpenMPClauseName(DVar.CKind)
16156           << getOpenMPClauseName(OMPC_lastprivate);
16157       reportOriginalDsa(*this, DSAStack, D, DVar);
16158       continue;
16159     }
16160 
16161     // OpenMP [2.14.3.5, Restrictions, p.2]
16162     // A list item that is private within a parallel region, or that appears in
16163     // the reduction clause of a parallel construct, must not appear in a
16164     // lastprivate clause on a worksharing construct if any of the corresponding
16165     // worksharing regions ever binds to any of the corresponding parallel
16166     // regions.
16167     DSAStackTy::DSAVarData TopDVar = DVar;
16168     if (isOpenMPWorksharingDirective(CurrDir) &&
16169         !isOpenMPParallelDirective(CurrDir) &&
16170         !isOpenMPTeamsDirective(CurrDir)) {
16171       DVar = DSAStack->getImplicitDSA(D, true);
16172       if (DVar.CKind != OMPC_shared) {
16173         Diag(ELoc, diag::err_omp_required_access)
16174             << getOpenMPClauseName(OMPC_lastprivate)
16175             << getOpenMPClauseName(OMPC_shared);
16176         reportOriginalDsa(*this, DSAStack, D, DVar);
16177         continue;
16178       }
16179     }
16180 
16181     // OpenMP [2.14.3.5, Restrictions, C++, p.1,2]
16182     //  A variable of class type (or array thereof) that appears in a
16183     //  lastprivate clause requires an accessible, unambiguous default
16184     //  constructor for the class type, unless the list item is also specified
16185     //  in a firstprivate clause.
16186     //  A variable of class type (or array thereof) that appears in a
16187     //  lastprivate clause requires an accessible, unambiguous copy assignment
16188     //  operator for the class type.
16189     Type = Context.getBaseElementType(Type).getNonReferenceType();
16190     VarDecl *SrcVD = buildVarDecl(*this, ERange.getBegin(),
16191                                   Type.getUnqualifiedType(), ".lastprivate.src",
16192                                   D->hasAttrs() ? &D->getAttrs() : nullptr);
16193     DeclRefExpr *PseudoSrcExpr =
16194         buildDeclRefExpr(*this, SrcVD, Type.getUnqualifiedType(), ELoc);
16195     VarDecl *DstVD =
16196         buildVarDecl(*this, ERange.getBegin(), Type, ".lastprivate.dst",
16197                      D->hasAttrs() ? &D->getAttrs() : nullptr);
16198     DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
16199     // For arrays generate assignment operation for single element and replace
16200     // it by the original array element in CodeGen.
16201     ExprResult AssignmentOp = BuildBinOp(/*S=*/nullptr, ELoc, BO_Assign,
16202                                          PseudoDstExpr, PseudoSrcExpr);
16203     if (AssignmentOp.isInvalid())
16204       continue;
16205     AssignmentOp =
16206         ActOnFinishFullExpr(AssignmentOp.get(), ELoc, /*DiscardedValue*/ false);
16207     if (AssignmentOp.isInvalid())
16208       continue;
16209 
16210     DeclRefExpr *Ref = nullptr;
16211     if (!VD && !CurContext->isDependentContext()) {
16212       if (TopDVar.CKind == OMPC_firstprivate) {
16213         Ref = TopDVar.PrivateCopy;
16214       } else {
16215         Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
16216         if (!isOpenMPCapturedDecl(D))
16217           ExprCaptures.push_back(Ref->getDecl());
16218       }
16219       if ((TopDVar.CKind == OMPC_firstprivate && !TopDVar.PrivateCopy) ||
16220           (!isOpenMPCapturedDecl(D) &&
16221            Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>())) {
16222         ExprResult RefRes = DefaultLvalueConversion(Ref);
16223         if (!RefRes.isUsable())
16224           continue;
16225         ExprResult PostUpdateRes =
16226             BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
16227                        RefRes.get());
16228         if (!PostUpdateRes.isUsable())
16229           continue;
16230         ExprPostUpdates.push_back(
16231             IgnoredValueConversions(PostUpdateRes.get()).get());
16232       }
16233     }
16234     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_lastprivate, Ref);
16235     Vars.push_back((VD || CurContext->isDependentContext())
16236                        ? RefExpr->IgnoreParens()
16237                        : Ref);
16238     SrcExprs.push_back(PseudoSrcExpr);
16239     DstExprs.push_back(PseudoDstExpr);
16240     AssignmentOps.push_back(AssignmentOp.get());
16241   }
16242 
16243   if (Vars.empty())
16244     return nullptr;
16245 
16246   return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
16247                                       Vars, SrcExprs, DstExprs, AssignmentOps,
16248                                       LPKind, LPKindLoc, ColonLoc,
16249                                       buildPreInits(Context, ExprCaptures),
16250                                       buildPostUpdate(*this, ExprPostUpdates));
16251 }
16252 
16253 OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
16254                                          SourceLocation StartLoc,
16255                                          SourceLocation LParenLoc,
16256                                          SourceLocation EndLoc) {
16257   SmallVector<Expr *, 8> Vars;
16258   for (Expr *RefExpr : VarList) {
16259     assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
16260     SourceLocation ELoc;
16261     SourceRange ERange;
16262     Expr *SimpleRefExpr = RefExpr;
16263     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
16264     if (Res.second) {
16265       // It will be analyzed later.
16266       Vars.push_back(RefExpr);
16267     }
16268     ValueDecl *D = Res.first;
16269     if (!D)
16270       continue;
16271 
16272     auto *VD = dyn_cast<VarDecl>(D);
16273     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
16274     // in a Construct]
16275     //  Variables with the predetermined data-sharing attributes may not be
16276     //  listed in data-sharing attributes clauses, except for the cases
16277     //  listed below. For these exceptions only, listing a predetermined
16278     //  variable in a data-sharing attribute clause is allowed and overrides
16279     //  the variable's predetermined data-sharing attributes.
16280     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
16281     if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared &&
16282         DVar.RefExpr) {
16283       Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
16284                                           << getOpenMPClauseName(OMPC_shared);
16285       reportOriginalDsa(*this, DSAStack, D, DVar);
16286       continue;
16287     }
16288 
16289     DeclRefExpr *Ref = nullptr;
16290     if (!VD && isOpenMPCapturedDecl(D) && !CurContext->isDependentContext())
16291       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
16292     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_shared, Ref);
16293     Vars.push_back((VD || !Ref || CurContext->isDependentContext())
16294                        ? RefExpr->IgnoreParens()
16295                        : Ref);
16296   }
16297 
16298   if (Vars.empty())
16299     return nullptr;
16300 
16301   return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
16302 }
16303 
16304 namespace {
16305 class DSARefChecker : public StmtVisitor<DSARefChecker, bool> {
16306   DSAStackTy *Stack;
16307 
16308 public:
16309   bool VisitDeclRefExpr(DeclRefExpr *E) {
16310     if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
16311       DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, /*FromParent=*/false);
16312       if (DVar.CKind == OMPC_shared && !DVar.RefExpr)
16313         return false;
16314       if (DVar.CKind != OMPC_unknown)
16315         return true;
16316       DSAStackTy::DSAVarData DVarPrivate = Stack->hasDSA(
16317           VD,
16318           [](OpenMPClauseKind C, bool AppliedToPointee) {
16319             return isOpenMPPrivate(C) && !AppliedToPointee;
16320           },
16321           [](OpenMPDirectiveKind) { return true; },
16322           /*FromParent=*/true);
16323       return DVarPrivate.CKind != OMPC_unknown;
16324     }
16325     return false;
16326   }
16327   bool VisitStmt(Stmt *S) {
16328     for (Stmt *Child : S->children()) {
16329       if (Child && Visit(Child))
16330         return true;
16331     }
16332     return false;
16333   }
16334   explicit DSARefChecker(DSAStackTy *S) : Stack(S) {}
16335 };
16336 } // namespace
16337 
16338 namespace {
16339 // Transform MemberExpression for specified FieldDecl of current class to
16340 // DeclRefExpr to specified OMPCapturedExprDecl.
16341 class TransformExprToCaptures : public TreeTransform<TransformExprToCaptures> {
16342   typedef TreeTransform<TransformExprToCaptures> BaseTransform;
16343   ValueDecl *Field = nullptr;
16344   DeclRefExpr *CapturedExpr = nullptr;
16345 
16346 public:
16347   TransformExprToCaptures(Sema &SemaRef, ValueDecl *FieldDecl)
16348       : BaseTransform(SemaRef), Field(FieldDecl), CapturedExpr(nullptr) {}
16349 
16350   ExprResult TransformMemberExpr(MemberExpr *E) {
16351     if (isa<CXXThisExpr>(E->getBase()->IgnoreParenImpCasts()) &&
16352         E->getMemberDecl() == Field) {
16353       CapturedExpr = buildCapture(SemaRef, Field, E, /*WithInit=*/false);
16354       return CapturedExpr;
16355     }
16356     return BaseTransform::TransformMemberExpr(E);
16357   }
16358   DeclRefExpr *getCapturedExpr() { return CapturedExpr; }
16359 };
16360 } // namespace
16361 
16362 template <typename T, typename U>
16363 static T filterLookupForUDReductionAndMapper(
16364     SmallVectorImpl<U> &Lookups, const llvm::function_ref<T(ValueDecl *)> Gen) {
16365   for (U &Set : Lookups) {
16366     for (auto *D : Set) {
16367       if (T Res = Gen(cast<ValueDecl>(D)))
16368         return Res;
16369     }
16370   }
16371   return T();
16372 }
16373 
16374 static NamedDecl *findAcceptableDecl(Sema &SemaRef, NamedDecl *D) {
16375   assert(!LookupResult::isVisible(SemaRef, D) && "not in slow case");
16376 
16377   for (auto RD : D->redecls()) {
16378     // Don't bother with extra checks if we already know this one isn't visible.
16379     if (RD == D)
16380       continue;
16381 
16382     auto ND = cast<NamedDecl>(RD);
16383     if (LookupResult::isVisible(SemaRef, ND))
16384       return ND;
16385   }
16386 
16387   return nullptr;
16388 }
16389 
16390 static void
16391 argumentDependentLookup(Sema &SemaRef, const DeclarationNameInfo &Id,
16392                         SourceLocation Loc, QualType Ty,
16393                         SmallVectorImpl<UnresolvedSet<8>> &Lookups) {
16394   // Find all of the associated namespaces and classes based on the
16395   // arguments we have.
16396   Sema::AssociatedNamespaceSet AssociatedNamespaces;
16397   Sema::AssociatedClassSet AssociatedClasses;
16398   OpaqueValueExpr OVE(Loc, Ty, VK_LValue);
16399   SemaRef.FindAssociatedClassesAndNamespaces(Loc, &OVE, AssociatedNamespaces,
16400                                              AssociatedClasses);
16401 
16402   // C++ [basic.lookup.argdep]p3:
16403   //   Let X be the lookup set produced by unqualified lookup (3.4.1)
16404   //   and let Y be the lookup set produced by argument dependent
16405   //   lookup (defined as follows). If X contains [...] then Y is
16406   //   empty. Otherwise Y is the set of declarations found in the
16407   //   namespaces associated with the argument types as described
16408   //   below. The set of declarations found by the lookup of the name
16409   //   is the union of X and Y.
16410   //
16411   // Here, we compute Y and add its members to the overloaded
16412   // candidate set.
16413   for (auto *NS : AssociatedNamespaces) {
16414     //   When considering an associated namespace, the lookup is the
16415     //   same as the lookup performed when the associated namespace is
16416     //   used as a qualifier (3.4.3.2) except that:
16417     //
16418     //     -- Any using-directives in the associated namespace are
16419     //        ignored.
16420     //
16421     //     -- Any namespace-scope friend functions declared in
16422     //        associated classes are visible within their respective
16423     //        namespaces even if they are not visible during an ordinary
16424     //        lookup (11.4).
16425     DeclContext::lookup_result R = NS->lookup(Id.getName());
16426     for (auto *D : R) {
16427       auto *Underlying = D;
16428       if (auto *USD = dyn_cast<UsingShadowDecl>(D))
16429         Underlying = USD->getTargetDecl();
16430 
16431       if (!isa<OMPDeclareReductionDecl>(Underlying) &&
16432           !isa<OMPDeclareMapperDecl>(Underlying))
16433         continue;
16434 
16435       if (!SemaRef.isVisible(D)) {
16436         D = findAcceptableDecl(SemaRef, D);
16437         if (!D)
16438           continue;
16439         if (auto *USD = dyn_cast<UsingShadowDecl>(D))
16440           Underlying = USD->getTargetDecl();
16441       }
16442       Lookups.emplace_back();
16443       Lookups.back().addDecl(Underlying);
16444     }
16445   }
16446 }
16447 
16448 static ExprResult
16449 buildDeclareReductionRef(Sema &SemaRef, SourceLocation Loc, SourceRange Range,
16450                          Scope *S, CXXScopeSpec &ReductionIdScopeSpec,
16451                          const DeclarationNameInfo &ReductionId, QualType Ty,
16452                          CXXCastPath &BasePath, Expr *UnresolvedReduction) {
16453   if (ReductionIdScopeSpec.isInvalid())
16454     return ExprError();
16455   SmallVector<UnresolvedSet<8>, 4> Lookups;
16456   if (S) {
16457     LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
16458     Lookup.suppressDiagnostics();
16459     while (S && SemaRef.LookupParsedName(Lookup, S, &ReductionIdScopeSpec)) {
16460       NamedDecl *D = Lookup.getRepresentativeDecl();
16461       do {
16462         S = S->getParent();
16463       } while (S && !S->isDeclScope(D));
16464       if (S)
16465         S = S->getParent();
16466       Lookups.emplace_back();
16467       Lookups.back().append(Lookup.begin(), Lookup.end());
16468       Lookup.clear();
16469     }
16470   } else if (auto *ULE =
16471                  cast_or_null<UnresolvedLookupExpr>(UnresolvedReduction)) {
16472     Lookups.push_back(UnresolvedSet<8>());
16473     Decl *PrevD = nullptr;
16474     for (NamedDecl *D : ULE->decls()) {
16475       if (D == PrevD)
16476         Lookups.push_back(UnresolvedSet<8>());
16477       else if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(D))
16478         Lookups.back().addDecl(DRD);
16479       PrevD = D;
16480     }
16481   }
16482   if (SemaRef.CurContext->isDependentContext() || Ty->isDependentType() ||
16483       Ty->isInstantiationDependentType() ||
16484       Ty->containsUnexpandedParameterPack() ||
16485       filterLookupForUDReductionAndMapper<bool>(Lookups, [](ValueDecl *D) {
16486         return !D->isInvalidDecl() &&
16487                (D->getType()->isDependentType() ||
16488                 D->getType()->isInstantiationDependentType() ||
16489                 D->getType()->containsUnexpandedParameterPack());
16490       })) {
16491     UnresolvedSet<8> ResSet;
16492     for (const UnresolvedSet<8> &Set : Lookups) {
16493       if (Set.empty())
16494         continue;
16495       ResSet.append(Set.begin(), Set.end());
16496       // The last item marks the end of all declarations at the specified scope.
16497       ResSet.addDecl(Set[Set.size() - 1]);
16498     }
16499     return UnresolvedLookupExpr::Create(
16500         SemaRef.Context, /*NamingClass=*/nullptr,
16501         ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), ReductionId,
16502         /*ADL=*/true, /*Overloaded=*/true, ResSet.begin(), ResSet.end());
16503   }
16504   // Lookup inside the classes.
16505   // C++ [over.match.oper]p3:
16506   //   For a unary operator @ with an operand of a type whose
16507   //   cv-unqualified version is T1, and for a binary operator @ with
16508   //   a left operand of a type whose cv-unqualified version is T1 and
16509   //   a right operand of a type whose cv-unqualified version is T2,
16510   //   three sets of candidate functions, designated member
16511   //   candidates, non-member candidates and built-in candidates, are
16512   //   constructed as follows:
16513   //     -- If T1 is a complete class type or a class currently being
16514   //        defined, the set of member candidates is the result of the
16515   //        qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
16516   //        the set of member candidates is empty.
16517   LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
16518   Lookup.suppressDiagnostics();
16519   if (const auto *TyRec = Ty->getAs<RecordType>()) {
16520     // Complete the type if it can be completed.
16521     // If the type is neither complete nor being defined, bail out now.
16522     if (SemaRef.isCompleteType(Loc, Ty) || TyRec->isBeingDefined() ||
16523         TyRec->getDecl()->getDefinition()) {
16524       Lookup.clear();
16525       SemaRef.LookupQualifiedName(Lookup, TyRec->getDecl());
16526       if (Lookup.empty()) {
16527         Lookups.emplace_back();
16528         Lookups.back().append(Lookup.begin(), Lookup.end());
16529       }
16530     }
16531   }
16532   // Perform ADL.
16533   if (SemaRef.getLangOpts().CPlusPlus)
16534     argumentDependentLookup(SemaRef, ReductionId, Loc, Ty, Lookups);
16535   if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
16536           Lookups, [&SemaRef, Ty](ValueDecl *D) -> ValueDecl * {
16537             if (!D->isInvalidDecl() &&
16538                 SemaRef.Context.hasSameType(D->getType(), Ty))
16539               return D;
16540             return nullptr;
16541           }))
16542     return SemaRef.BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(),
16543                                     VK_LValue, Loc);
16544   if (SemaRef.getLangOpts().CPlusPlus) {
16545     if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
16546             Lookups, [&SemaRef, Ty, Loc](ValueDecl *D) -> ValueDecl * {
16547               if (!D->isInvalidDecl() &&
16548                   SemaRef.IsDerivedFrom(Loc, Ty, D->getType()) &&
16549                   !Ty.isMoreQualifiedThan(D->getType()))
16550                 return D;
16551               return nullptr;
16552             })) {
16553       CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
16554                          /*DetectVirtual=*/false);
16555       if (SemaRef.IsDerivedFrom(Loc, Ty, VD->getType(), Paths)) {
16556         if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
16557                 VD->getType().getUnqualifiedType()))) {
16558           if (SemaRef.CheckBaseClassAccess(
16559                   Loc, VD->getType(), Ty, Paths.front(),
16560                   /*DiagID=*/0) != Sema::AR_inaccessible) {
16561             SemaRef.BuildBasePathArray(Paths, BasePath);
16562             return SemaRef.BuildDeclRefExpr(
16563                 VD, VD->getType().getNonReferenceType(), VK_LValue, Loc);
16564           }
16565         }
16566       }
16567     }
16568   }
16569   if (ReductionIdScopeSpec.isSet()) {
16570     SemaRef.Diag(Loc, diag::err_omp_not_resolved_reduction_identifier)
16571         << Ty << Range;
16572     return ExprError();
16573   }
16574   return ExprEmpty();
16575 }
16576 
16577 namespace {
16578 /// Data for the reduction-based clauses.
16579 struct ReductionData {
16580   /// List of original reduction items.
16581   SmallVector<Expr *, 8> Vars;
16582   /// List of private copies of the reduction items.
16583   SmallVector<Expr *, 8> Privates;
16584   /// LHS expressions for the reduction_op expressions.
16585   SmallVector<Expr *, 8> LHSs;
16586   /// RHS expressions for the reduction_op expressions.
16587   SmallVector<Expr *, 8> RHSs;
16588   /// Reduction operation expression.
16589   SmallVector<Expr *, 8> ReductionOps;
16590   /// inscan copy operation expressions.
16591   SmallVector<Expr *, 8> InscanCopyOps;
16592   /// inscan copy temp array expressions for prefix sums.
16593   SmallVector<Expr *, 8> InscanCopyArrayTemps;
16594   /// inscan copy temp array element expressions for prefix sums.
16595   SmallVector<Expr *, 8> InscanCopyArrayElems;
16596   /// Taskgroup descriptors for the corresponding reduction items in
16597   /// in_reduction clauses.
16598   SmallVector<Expr *, 8> TaskgroupDescriptors;
16599   /// List of captures for clause.
16600   SmallVector<Decl *, 4> ExprCaptures;
16601   /// List of postupdate expressions.
16602   SmallVector<Expr *, 4> ExprPostUpdates;
16603   /// Reduction modifier.
16604   unsigned RedModifier = 0;
16605   ReductionData() = delete;
16606   /// Reserves required memory for the reduction data.
16607   ReductionData(unsigned Size, unsigned Modifier = 0) : RedModifier(Modifier) {
16608     Vars.reserve(Size);
16609     Privates.reserve(Size);
16610     LHSs.reserve(Size);
16611     RHSs.reserve(Size);
16612     ReductionOps.reserve(Size);
16613     if (RedModifier == OMPC_REDUCTION_inscan) {
16614       InscanCopyOps.reserve(Size);
16615       InscanCopyArrayTemps.reserve(Size);
16616       InscanCopyArrayElems.reserve(Size);
16617     }
16618     TaskgroupDescriptors.reserve(Size);
16619     ExprCaptures.reserve(Size);
16620     ExprPostUpdates.reserve(Size);
16621   }
16622   /// Stores reduction item and reduction operation only (required for dependent
16623   /// reduction item).
16624   void push(Expr *Item, Expr *ReductionOp) {
16625     Vars.emplace_back(Item);
16626     Privates.emplace_back(nullptr);
16627     LHSs.emplace_back(nullptr);
16628     RHSs.emplace_back(nullptr);
16629     ReductionOps.emplace_back(ReductionOp);
16630     TaskgroupDescriptors.emplace_back(nullptr);
16631     if (RedModifier == OMPC_REDUCTION_inscan) {
16632       InscanCopyOps.push_back(nullptr);
16633       InscanCopyArrayTemps.push_back(nullptr);
16634       InscanCopyArrayElems.push_back(nullptr);
16635     }
16636   }
16637   /// Stores reduction data.
16638   void push(Expr *Item, Expr *Private, Expr *LHS, Expr *RHS, Expr *ReductionOp,
16639             Expr *TaskgroupDescriptor, Expr *CopyOp, Expr *CopyArrayTemp,
16640             Expr *CopyArrayElem) {
16641     Vars.emplace_back(Item);
16642     Privates.emplace_back(Private);
16643     LHSs.emplace_back(LHS);
16644     RHSs.emplace_back(RHS);
16645     ReductionOps.emplace_back(ReductionOp);
16646     TaskgroupDescriptors.emplace_back(TaskgroupDescriptor);
16647     if (RedModifier == OMPC_REDUCTION_inscan) {
16648       InscanCopyOps.push_back(CopyOp);
16649       InscanCopyArrayTemps.push_back(CopyArrayTemp);
16650       InscanCopyArrayElems.push_back(CopyArrayElem);
16651     } else {
16652       assert(CopyOp == nullptr && CopyArrayTemp == nullptr &&
16653              CopyArrayElem == nullptr &&
16654              "Copy operation must be used for inscan reductions only.");
16655     }
16656   }
16657 };
16658 } // namespace
16659 
16660 static bool checkOMPArraySectionConstantForReduction(
16661     ASTContext &Context, const OMPArraySectionExpr *OASE, bool &SingleElement,
16662     SmallVectorImpl<llvm::APSInt> &ArraySizes) {
16663   const Expr *Length = OASE->getLength();
16664   if (Length == nullptr) {
16665     // For array sections of the form [1:] or [:], we would need to analyze
16666     // the lower bound...
16667     if (OASE->getColonLocFirst().isValid())
16668       return false;
16669 
16670     // This is an array subscript which has implicit length 1!
16671     SingleElement = true;
16672     ArraySizes.push_back(llvm::APSInt::get(1));
16673   } else {
16674     Expr::EvalResult Result;
16675     if (!Length->EvaluateAsInt(Result, Context))
16676       return false;
16677 
16678     llvm::APSInt ConstantLengthValue = Result.Val.getInt();
16679     SingleElement = (ConstantLengthValue.getSExtValue() == 1);
16680     ArraySizes.push_back(ConstantLengthValue);
16681   }
16682 
16683   // Get the base of this array section and walk up from there.
16684   const Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
16685 
16686   // We require length = 1 for all array sections except the right-most to
16687   // guarantee that the memory region is contiguous and has no holes in it.
16688   while (const auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base)) {
16689     Length = TempOASE->getLength();
16690     if (Length == nullptr) {
16691       // For array sections of the form [1:] or [:], we would need to analyze
16692       // the lower bound...
16693       if (OASE->getColonLocFirst().isValid())
16694         return false;
16695 
16696       // This is an array subscript which has implicit length 1!
16697       ArraySizes.push_back(llvm::APSInt::get(1));
16698     } else {
16699       Expr::EvalResult Result;
16700       if (!Length->EvaluateAsInt(Result, Context))
16701         return false;
16702 
16703       llvm::APSInt ConstantLengthValue = Result.Val.getInt();
16704       if (ConstantLengthValue.getSExtValue() != 1)
16705         return false;
16706 
16707       ArraySizes.push_back(ConstantLengthValue);
16708     }
16709     Base = TempOASE->getBase()->IgnoreParenImpCasts();
16710   }
16711 
16712   // If we have a single element, we don't need to add the implicit lengths.
16713   if (!SingleElement) {
16714     while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) {
16715       // Has implicit length 1!
16716       ArraySizes.push_back(llvm::APSInt::get(1));
16717       Base = TempASE->getBase()->IgnoreParenImpCasts();
16718     }
16719   }
16720 
16721   // This array section can be privatized as a single value or as a constant
16722   // sized array.
16723   return true;
16724 }
16725 
16726 static BinaryOperatorKind
16727 getRelatedCompoundReductionOp(BinaryOperatorKind BOK) {
16728   if (BOK == BO_Add)
16729     return BO_AddAssign;
16730   if (BOK == BO_Mul)
16731     return BO_MulAssign;
16732   if (BOK == BO_And)
16733     return BO_AndAssign;
16734   if (BOK == BO_Or)
16735     return BO_OrAssign;
16736   if (BOK == BO_Xor)
16737     return BO_XorAssign;
16738   return BOK;
16739 }
16740 
16741 static bool actOnOMPReductionKindClause(
16742     Sema &S, DSAStackTy *Stack, OpenMPClauseKind ClauseKind,
16743     ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
16744     SourceLocation ColonLoc, SourceLocation EndLoc,
16745     CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
16746     ArrayRef<Expr *> UnresolvedReductions, ReductionData &RD) {
16747   DeclarationName DN = ReductionId.getName();
16748   OverloadedOperatorKind OOK = DN.getCXXOverloadedOperator();
16749   BinaryOperatorKind BOK = BO_Comma;
16750 
16751   ASTContext &Context = S.Context;
16752   // OpenMP [2.14.3.6, reduction clause]
16753   // C
16754   // reduction-identifier is either an identifier or one of the following
16755   // operators: +, -, *,  &, |, ^, && and ||
16756   // C++
16757   // reduction-identifier is either an id-expression or one of the following
16758   // operators: +, -, *, &, |, ^, && and ||
16759   switch (OOK) {
16760   case OO_Plus:
16761   case OO_Minus:
16762     BOK = BO_Add;
16763     break;
16764   case OO_Star:
16765     BOK = BO_Mul;
16766     break;
16767   case OO_Amp:
16768     BOK = BO_And;
16769     break;
16770   case OO_Pipe:
16771     BOK = BO_Or;
16772     break;
16773   case OO_Caret:
16774     BOK = BO_Xor;
16775     break;
16776   case OO_AmpAmp:
16777     BOK = BO_LAnd;
16778     break;
16779   case OO_PipePipe:
16780     BOK = BO_LOr;
16781     break;
16782   case OO_New:
16783   case OO_Delete:
16784   case OO_Array_New:
16785   case OO_Array_Delete:
16786   case OO_Slash:
16787   case OO_Percent:
16788   case OO_Tilde:
16789   case OO_Exclaim:
16790   case OO_Equal:
16791   case OO_Less:
16792   case OO_Greater:
16793   case OO_LessEqual:
16794   case OO_GreaterEqual:
16795   case OO_PlusEqual:
16796   case OO_MinusEqual:
16797   case OO_StarEqual:
16798   case OO_SlashEqual:
16799   case OO_PercentEqual:
16800   case OO_CaretEqual:
16801   case OO_AmpEqual:
16802   case OO_PipeEqual:
16803   case OO_LessLess:
16804   case OO_GreaterGreater:
16805   case OO_LessLessEqual:
16806   case OO_GreaterGreaterEqual:
16807   case OO_EqualEqual:
16808   case OO_ExclaimEqual:
16809   case OO_Spaceship:
16810   case OO_PlusPlus:
16811   case OO_MinusMinus:
16812   case OO_Comma:
16813   case OO_ArrowStar:
16814   case OO_Arrow:
16815   case OO_Call:
16816   case OO_Subscript:
16817   case OO_Conditional:
16818   case OO_Coawait:
16819   case NUM_OVERLOADED_OPERATORS:
16820     llvm_unreachable("Unexpected reduction identifier");
16821   case OO_None:
16822     if (IdentifierInfo *II = DN.getAsIdentifierInfo()) {
16823       if (II->isStr("max"))
16824         BOK = BO_GT;
16825       else if (II->isStr("min"))
16826         BOK = BO_LT;
16827     }
16828     break;
16829   }
16830   SourceRange ReductionIdRange;
16831   if (ReductionIdScopeSpec.isValid())
16832     ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc());
16833   else
16834     ReductionIdRange.setBegin(ReductionId.getBeginLoc());
16835   ReductionIdRange.setEnd(ReductionId.getEndLoc());
16836 
16837   auto IR = UnresolvedReductions.begin(), ER = UnresolvedReductions.end();
16838   bool FirstIter = true;
16839   for (Expr *RefExpr : VarList) {
16840     assert(RefExpr && "nullptr expr in OpenMP reduction clause.");
16841     // OpenMP [2.1, C/C++]
16842     //  A list item is a variable or array section, subject to the restrictions
16843     //  specified in Section 2.4 on page 42 and in each of the sections
16844     // describing clauses and directives for which a list appears.
16845     // OpenMP  [2.14.3.3, Restrictions, p.1]
16846     //  A variable that is part of another variable (as an array or
16847     //  structure element) cannot appear in a private clause.
16848     if (!FirstIter && IR != ER)
16849       ++IR;
16850     FirstIter = false;
16851     SourceLocation ELoc;
16852     SourceRange ERange;
16853     Expr *SimpleRefExpr = RefExpr;
16854     auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange,
16855                               /*AllowArraySection=*/true);
16856     if (Res.second) {
16857       // Try to find 'declare reduction' corresponding construct before using
16858       // builtin/overloaded operators.
16859       QualType Type = Context.DependentTy;
16860       CXXCastPath BasePath;
16861       ExprResult DeclareReductionRef = buildDeclareReductionRef(
16862           S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
16863           ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
16864       Expr *ReductionOp = nullptr;
16865       if (S.CurContext->isDependentContext() &&
16866           (DeclareReductionRef.isUnset() ||
16867            isa<UnresolvedLookupExpr>(DeclareReductionRef.get())))
16868         ReductionOp = DeclareReductionRef.get();
16869       // It will be analyzed later.
16870       RD.push(RefExpr, ReductionOp);
16871     }
16872     ValueDecl *D = Res.first;
16873     if (!D)
16874       continue;
16875 
16876     Expr *TaskgroupDescriptor = nullptr;
16877     QualType Type;
16878     auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr->IgnoreParens());
16879     auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr->IgnoreParens());
16880     if (ASE) {
16881       Type = ASE->getType().getNonReferenceType();
16882     } else if (OASE) {
16883       QualType BaseType =
16884           OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
16885       if (const auto *ATy = BaseType->getAsArrayTypeUnsafe())
16886         Type = ATy->getElementType();
16887       else
16888         Type = BaseType->getPointeeType();
16889       Type = Type.getNonReferenceType();
16890     } else {
16891       Type = Context.getBaseElementType(D->getType().getNonReferenceType());
16892     }
16893     auto *VD = dyn_cast<VarDecl>(D);
16894 
16895     // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
16896     //  A variable that appears in a private clause must not have an incomplete
16897     //  type or a reference type.
16898     if (S.RequireCompleteType(ELoc, D->getType(),
16899                               diag::err_omp_reduction_incomplete_type))
16900       continue;
16901     // OpenMP [2.14.3.6, reduction clause, Restrictions]
16902     // A list item that appears in a reduction clause must not be
16903     // const-qualified.
16904     if (rejectConstNotMutableType(S, D, Type, ClauseKind, ELoc,
16905                                   /*AcceptIfMutable*/ false, ASE || OASE))
16906       continue;
16907 
16908     OpenMPDirectiveKind CurrDir = Stack->getCurrentDirective();
16909     // OpenMP [2.9.3.6, Restrictions, C/C++, p.4]
16910     //  If a list-item is a reference type then it must bind to the same object
16911     //  for all threads of the team.
16912     if (!ASE && !OASE) {
16913       if (VD) {
16914         VarDecl *VDDef = VD->getDefinition();
16915         if (VD->getType()->isReferenceType() && VDDef && VDDef->hasInit()) {
16916           DSARefChecker Check(Stack);
16917           if (Check.Visit(VDDef->getInit())) {
16918             S.Diag(ELoc, diag::err_omp_reduction_ref_type_arg)
16919                 << getOpenMPClauseName(ClauseKind) << ERange;
16920             S.Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef;
16921             continue;
16922           }
16923         }
16924       }
16925 
16926       // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
16927       // in a Construct]
16928       //  Variables with the predetermined data-sharing attributes may not be
16929       //  listed in data-sharing attributes clauses, except for the cases
16930       //  listed below. For these exceptions only, listing a predetermined
16931       //  variable in a data-sharing attribute clause is allowed and overrides
16932       //  the variable's predetermined data-sharing attributes.
16933       // OpenMP [2.14.3.6, Restrictions, p.3]
16934       //  Any number of reduction clauses can be specified on the directive,
16935       //  but a list item can appear only once in the reduction clauses for that
16936       //  directive.
16937       DSAStackTy::DSAVarData DVar = Stack->getTopDSA(D, /*FromParent=*/false);
16938       if (DVar.CKind == OMPC_reduction) {
16939         S.Diag(ELoc, diag::err_omp_once_referenced)
16940             << getOpenMPClauseName(ClauseKind);
16941         if (DVar.RefExpr)
16942           S.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced);
16943         continue;
16944       }
16945       if (DVar.CKind != OMPC_unknown) {
16946         S.Diag(ELoc, diag::err_omp_wrong_dsa)
16947             << getOpenMPClauseName(DVar.CKind)
16948             << getOpenMPClauseName(OMPC_reduction);
16949         reportOriginalDsa(S, Stack, D, DVar);
16950         continue;
16951       }
16952 
16953       // OpenMP [2.14.3.6, Restrictions, p.1]
16954       //  A list item that appears in a reduction clause of a worksharing
16955       //  construct must be shared in the parallel regions to which any of the
16956       //  worksharing regions arising from the worksharing construct bind.
16957       if (isOpenMPWorksharingDirective(CurrDir) &&
16958           !isOpenMPParallelDirective(CurrDir) &&
16959           !isOpenMPTeamsDirective(CurrDir)) {
16960         DVar = Stack->getImplicitDSA(D, true);
16961         if (DVar.CKind != OMPC_shared) {
16962           S.Diag(ELoc, diag::err_omp_required_access)
16963               << getOpenMPClauseName(OMPC_reduction)
16964               << getOpenMPClauseName(OMPC_shared);
16965           reportOriginalDsa(S, Stack, D, DVar);
16966           continue;
16967         }
16968       }
16969     } else {
16970       // Threadprivates cannot be shared between threads, so dignose if the base
16971       // is a threadprivate variable.
16972       DSAStackTy::DSAVarData DVar = Stack->getTopDSA(D, /*FromParent=*/false);
16973       if (DVar.CKind == OMPC_threadprivate) {
16974         S.Diag(ELoc, diag::err_omp_wrong_dsa)
16975             << getOpenMPClauseName(DVar.CKind)
16976             << getOpenMPClauseName(OMPC_reduction);
16977         reportOriginalDsa(S, Stack, D, DVar);
16978         continue;
16979       }
16980     }
16981 
16982     // Try to find 'declare reduction' corresponding construct before using
16983     // builtin/overloaded operators.
16984     CXXCastPath BasePath;
16985     ExprResult DeclareReductionRef = buildDeclareReductionRef(
16986         S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
16987         ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
16988     if (DeclareReductionRef.isInvalid())
16989       continue;
16990     if (S.CurContext->isDependentContext() &&
16991         (DeclareReductionRef.isUnset() ||
16992          isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) {
16993       RD.push(RefExpr, DeclareReductionRef.get());
16994       continue;
16995     }
16996     if (BOK == BO_Comma && DeclareReductionRef.isUnset()) {
16997       // Not allowed reduction identifier is found.
16998       S.Diag(ReductionId.getBeginLoc(),
16999              diag::err_omp_unknown_reduction_identifier)
17000           << Type << ReductionIdRange;
17001       continue;
17002     }
17003 
17004     // OpenMP [2.14.3.6, reduction clause, Restrictions]
17005     // The type of a list item that appears in a reduction clause must be valid
17006     // for the reduction-identifier. For a max or min reduction in C, the type
17007     // of the list item must be an allowed arithmetic data type: char, int,
17008     // float, double, or _Bool, possibly modified with long, short, signed, or
17009     // unsigned. For a max or min reduction in C++, the type of the list item
17010     // must be an allowed arithmetic data type: char, wchar_t, int, float,
17011     // double, or bool, possibly modified with long, short, signed, or unsigned.
17012     if (DeclareReductionRef.isUnset()) {
17013       if ((BOK == BO_GT || BOK == BO_LT) &&
17014           !(Type->isScalarType() ||
17015             (S.getLangOpts().CPlusPlus && Type->isArithmeticType()))) {
17016         S.Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg)
17017             << getOpenMPClauseName(ClauseKind) << S.getLangOpts().CPlusPlus;
17018         if (!ASE && !OASE) {
17019           bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
17020                                    VarDecl::DeclarationOnly;
17021           S.Diag(D->getLocation(),
17022                  IsDecl ? diag::note_previous_decl : diag::note_defined_here)
17023               << D;
17024         }
17025         continue;
17026       }
17027       if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) &&
17028           !S.getLangOpts().CPlusPlus && Type->isFloatingType()) {
17029         S.Diag(ELoc, diag::err_omp_clause_floating_type_arg)
17030             << getOpenMPClauseName(ClauseKind);
17031         if (!ASE && !OASE) {
17032           bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
17033                                    VarDecl::DeclarationOnly;
17034           S.Diag(D->getLocation(),
17035                  IsDecl ? diag::note_previous_decl : diag::note_defined_here)
17036               << D;
17037         }
17038         continue;
17039       }
17040     }
17041 
17042     Type = Type.getNonLValueExprType(Context).getUnqualifiedType();
17043     VarDecl *LHSVD = buildVarDecl(S, ELoc, Type, ".reduction.lhs",
17044                                   D->hasAttrs() ? &D->getAttrs() : nullptr);
17045     VarDecl *RHSVD = buildVarDecl(S, ELoc, Type, D->getName(),
17046                                   D->hasAttrs() ? &D->getAttrs() : nullptr);
17047     QualType PrivateTy = Type;
17048 
17049     // Try if we can determine constant lengths for all array sections and avoid
17050     // the VLA.
17051     bool ConstantLengthOASE = false;
17052     if (OASE) {
17053       bool SingleElement;
17054       llvm::SmallVector<llvm::APSInt, 4> ArraySizes;
17055       ConstantLengthOASE = checkOMPArraySectionConstantForReduction(
17056           Context, OASE, SingleElement, ArraySizes);
17057 
17058       // If we don't have a single element, we must emit a constant array type.
17059       if (ConstantLengthOASE && !SingleElement) {
17060         for (llvm::APSInt &Size : ArraySizes)
17061           PrivateTy = Context.getConstantArrayType(PrivateTy, Size, nullptr,
17062                                                    ArrayType::Normal,
17063                                                    /*IndexTypeQuals=*/0);
17064       }
17065     }
17066 
17067     if ((OASE && !ConstantLengthOASE) ||
17068         (!OASE && !ASE &&
17069          D->getType().getNonReferenceType()->isVariablyModifiedType())) {
17070       if (!Context.getTargetInfo().isVLASupported()) {
17071         if (isOpenMPTargetExecutionDirective(Stack->getCurrentDirective())) {
17072           S.Diag(ELoc, diag::err_omp_reduction_vla_unsupported) << !!OASE;
17073           S.Diag(ELoc, diag::note_vla_unsupported);
17074           continue;
17075         } else {
17076           S.targetDiag(ELoc, diag::err_omp_reduction_vla_unsupported) << !!OASE;
17077           S.targetDiag(ELoc, diag::note_vla_unsupported);
17078         }
17079       }
17080       // For arrays/array sections only:
17081       // Create pseudo array type for private copy. The size for this array will
17082       // be generated during codegen.
17083       // For array subscripts or single variables Private Ty is the same as Type
17084       // (type of the variable or single array element).
17085       PrivateTy = Context.getVariableArrayType(
17086           Type,
17087           new (Context)
17088               OpaqueValueExpr(ELoc, Context.getSizeType(), VK_PRValue),
17089           ArrayType::Normal, /*IndexTypeQuals=*/0, SourceRange());
17090     } else if (!ASE && !OASE &&
17091                Context.getAsArrayType(D->getType().getNonReferenceType())) {
17092       PrivateTy = D->getType().getNonReferenceType();
17093     }
17094     // Private copy.
17095     VarDecl *PrivateVD =
17096         buildVarDecl(S, ELoc, PrivateTy, D->getName(),
17097                      D->hasAttrs() ? &D->getAttrs() : nullptr,
17098                      VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
17099     // Add initializer for private variable.
17100     Expr *Init = nullptr;
17101     DeclRefExpr *LHSDRE = buildDeclRefExpr(S, LHSVD, Type, ELoc);
17102     DeclRefExpr *RHSDRE = buildDeclRefExpr(S, RHSVD, Type, ELoc);
17103     if (DeclareReductionRef.isUsable()) {
17104       auto *DRDRef = DeclareReductionRef.getAs<DeclRefExpr>();
17105       auto *DRD = cast<OMPDeclareReductionDecl>(DRDRef->getDecl());
17106       if (DRD->getInitializer()) {
17107         Init = DRDRef;
17108         RHSVD->setInit(DRDRef);
17109         RHSVD->setInitStyle(VarDecl::CallInit);
17110       }
17111     } else {
17112       switch (BOK) {
17113       case BO_Add:
17114       case BO_Xor:
17115       case BO_Or:
17116       case BO_LOr:
17117         // '+', '-', '^', '|', '||' reduction ops - initializer is '0'.
17118         if (Type->isScalarType() || Type->isAnyComplexType())
17119           Init = S.ActOnIntegerConstant(ELoc, /*Val=*/0).get();
17120         break;
17121       case BO_Mul:
17122       case BO_LAnd:
17123         if (Type->isScalarType() || Type->isAnyComplexType()) {
17124           // '*' and '&&' reduction ops - initializer is '1'.
17125           Init = S.ActOnIntegerConstant(ELoc, /*Val=*/1).get();
17126         }
17127         break;
17128       case BO_And: {
17129         // '&' reduction op - initializer is '~0'.
17130         QualType OrigType = Type;
17131         if (auto *ComplexTy = OrigType->getAs<ComplexType>())
17132           Type = ComplexTy->getElementType();
17133         if (Type->isRealFloatingType()) {
17134           llvm::APFloat InitValue = llvm::APFloat::getAllOnesValue(
17135               Context.getFloatTypeSemantics(Type),
17136               Context.getTypeSize(Type));
17137           Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
17138                                          Type, ELoc);
17139         } else if (Type->isScalarType()) {
17140           uint64_t Size = Context.getTypeSize(Type);
17141           QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0);
17142           llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size);
17143           Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
17144         }
17145         if (Init && OrigType->isAnyComplexType()) {
17146           // Init = 0xFFFF + 0xFFFFi;
17147           auto *Im = new (Context) ImaginaryLiteral(Init, OrigType);
17148           Init = S.CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get();
17149         }
17150         Type = OrigType;
17151         break;
17152       }
17153       case BO_LT:
17154       case BO_GT: {
17155         // 'min' reduction op - initializer is 'Largest representable number in
17156         // the reduction list item type'.
17157         // 'max' reduction op - initializer is 'Least representable number in
17158         // the reduction list item type'.
17159         if (Type->isIntegerType() || Type->isPointerType()) {
17160           bool IsSigned = Type->hasSignedIntegerRepresentation();
17161           uint64_t Size = Context.getTypeSize(Type);
17162           QualType IntTy =
17163               Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned);
17164           llvm::APInt InitValue =
17165               (BOK != BO_LT) ? IsSigned ? llvm::APInt::getSignedMinValue(Size)
17166                                         : llvm::APInt::getMinValue(Size)
17167                              : IsSigned ? llvm::APInt::getSignedMaxValue(Size)
17168                                         : llvm::APInt::getMaxValue(Size);
17169           Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
17170           if (Type->isPointerType()) {
17171             // Cast to pointer type.
17172             ExprResult CastExpr = S.BuildCStyleCastExpr(
17173                 ELoc, Context.getTrivialTypeSourceInfo(Type, ELoc), ELoc, Init);
17174             if (CastExpr.isInvalid())
17175               continue;
17176             Init = CastExpr.get();
17177           }
17178         } else if (Type->isRealFloatingType()) {
17179           llvm::APFloat InitValue = llvm::APFloat::getLargest(
17180               Context.getFloatTypeSemantics(Type), BOK != BO_LT);
17181           Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
17182                                          Type, ELoc);
17183         }
17184         break;
17185       }
17186       case BO_PtrMemD:
17187       case BO_PtrMemI:
17188       case BO_MulAssign:
17189       case BO_Div:
17190       case BO_Rem:
17191       case BO_Sub:
17192       case BO_Shl:
17193       case BO_Shr:
17194       case BO_LE:
17195       case BO_GE:
17196       case BO_EQ:
17197       case BO_NE:
17198       case BO_Cmp:
17199       case BO_AndAssign:
17200       case BO_XorAssign:
17201       case BO_OrAssign:
17202       case BO_Assign:
17203       case BO_AddAssign:
17204       case BO_SubAssign:
17205       case BO_DivAssign:
17206       case BO_RemAssign:
17207       case BO_ShlAssign:
17208       case BO_ShrAssign:
17209       case BO_Comma:
17210         llvm_unreachable("Unexpected reduction operation");
17211       }
17212     }
17213     if (Init && DeclareReductionRef.isUnset()) {
17214       S.AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false);
17215       // Store initializer for single element in private copy. Will be used
17216       // during codegen.
17217       PrivateVD->setInit(RHSVD->getInit());
17218       PrivateVD->setInitStyle(RHSVD->getInitStyle());
17219     } else if (!Init) {
17220       S.ActOnUninitializedDecl(RHSVD);
17221       // Store initializer for single element in private copy. Will be used
17222       // during codegen.
17223       PrivateVD->setInit(RHSVD->getInit());
17224       PrivateVD->setInitStyle(RHSVD->getInitStyle());
17225     }
17226     if (RHSVD->isInvalidDecl())
17227       continue;
17228     if (!RHSVD->hasInit() && DeclareReductionRef.isUnset()) {
17229       S.Diag(ELoc, diag::err_omp_reduction_id_not_compatible)
17230           << Type << ReductionIdRange;
17231       bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
17232                                VarDecl::DeclarationOnly;
17233       S.Diag(D->getLocation(),
17234              IsDecl ? diag::note_previous_decl : diag::note_defined_here)
17235           << D;
17236       continue;
17237     }
17238     DeclRefExpr *PrivateDRE = buildDeclRefExpr(S, PrivateVD, PrivateTy, ELoc);
17239     ExprResult ReductionOp;
17240     if (DeclareReductionRef.isUsable()) {
17241       QualType RedTy = DeclareReductionRef.get()->getType();
17242       QualType PtrRedTy = Context.getPointerType(RedTy);
17243       ExprResult LHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, LHSDRE);
17244       ExprResult RHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RHSDRE);
17245       if (!BasePath.empty()) {
17246         LHS = S.DefaultLvalueConversion(LHS.get());
17247         RHS = S.DefaultLvalueConversion(RHS.get());
17248         LHS = ImplicitCastExpr::Create(
17249             Context, PtrRedTy, CK_UncheckedDerivedToBase, LHS.get(), &BasePath,
17250             LHS.get()->getValueKind(), FPOptionsOverride());
17251         RHS = ImplicitCastExpr::Create(
17252             Context, PtrRedTy, CK_UncheckedDerivedToBase, RHS.get(), &BasePath,
17253             RHS.get()->getValueKind(), FPOptionsOverride());
17254       }
17255       FunctionProtoType::ExtProtoInfo EPI;
17256       QualType Params[] = {PtrRedTy, PtrRedTy};
17257       QualType FnTy = Context.getFunctionType(Context.VoidTy, Params, EPI);
17258       auto *OVE = new (Context) OpaqueValueExpr(
17259           ELoc, Context.getPointerType(FnTy), VK_PRValue, OK_Ordinary,
17260           S.DefaultLvalueConversion(DeclareReductionRef.get()).get());
17261       Expr *Args[] = {LHS.get(), RHS.get()};
17262       ReductionOp =
17263           CallExpr::Create(Context, OVE, Args, Context.VoidTy, VK_PRValue, ELoc,
17264                            S.CurFPFeatureOverrides());
17265     } else {
17266       BinaryOperatorKind CombBOK = getRelatedCompoundReductionOp(BOK);
17267       if (Type->isRecordType() && CombBOK != BOK) {
17268         Sema::TentativeAnalysisScope Trap(S);
17269         ReductionOp =
17270             S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(),
17271                          CombBOK, LHSDRE, RHSDRE);
17272       }
17273       if (!ReductionOp.isUsable()) {
17274         ReductionOp =
17275             S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(), BOK,
17276                          LHSDRE, RHSDRE);
17277         if (ReductionOp.isUsable()) {
17278           if (BOK != BO_LT && BOK != BO_GT) {
17279             ReductionOp =
17280                 S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(),
17281                              BO_Assign, LHSDRE, ReductionOp.get());
17282           } else {
17283             auto *ConditionalOp = new (Context)
17284                 ConditionalOperator(ReductionOp.get(), ELoc, LHSDRE, ELoc,
17285                                     RHSDRE, Type, VK_LValue, OK_Ordinary);
17286             ReductionOp =
17287                 S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(),
17288                              BO_Assign, LHSDRE, ConditionalOp);
17289           }
17290         }
17291       }
17292       if (ReductionOp.isUsable())
17293         ReductionOp = S.ActOnFinishFullExpr(ReductionOp.get(),
17294                                             /*DiscardedValue*/ false);
17295       if (!ReductionOp.isUsable())
17296         continue;
17297     }
17298 
17299     // Add copy operations for inscan reductions.
17300     // LHS = RHS;
17301     ExprResult CopyOpRes, TempArrayRes, TempArrayElem;
17302     if (ClauseKind == OMPC_reduction &&
17303         RD.RedModifier == OMPC_REDUCTION_inscan) {
17304       ExprResult RHS = S.DefaultLvalueConversion(RHSDRE);
17305       CopyOpRes = S.BuildBinOp(Stack->getCurScope(), ELoc, BO_Assign, LHSDRE,
17306                                RHS.get());
17307       if (!CopyOpRes.isUsable())
17308         continue;
17309       CopyOpRes =
17310           S.ActOnFinishFullExpr(CopyOpRes.get(), /*DiscardedValue=*/true);
17311       if (!CopyOpRes.isUsable())
17312         continue;
17313       // For simd directive and simd-based directives in simd mode no need to
17314       // construct temp array, need just a single temp element.
17315       if (Stack->getCurrentDirective() == OMPD_simd ||
17316           (S.getLangOpts().OpenMPSimd &&
17317            isOpenMPSimdDirective(Stack->getCurrentDirective()))) {
17318         VarDecl *TempArrayVD =
17319             buildVarDecl(S, ELoc, PrivateTy, D->getName(),
17320                          D->hasAttrs() ? &D->getAttrs() : nullptr);
17321         // Add a constructor to the temp decl.
17322         S.ActOnUninitializedDecl(TempArrayVD);
17323         TempArrayRes = buildDeclRefExpr(S, TempArrayVD, PrivateTy, ELoc);
17324       } else {
17325         // Build temp array for prefix sum.
17326         auto *Dim = new (S.Context)
17327             OpaqueValueExpr(ELoc, S.Context.getSizeType(), VK_PRValue);
17328         QualType ArrayTy =
17329             S.Context.getVariableArrayType(PrivateTy, Dim, ArrayType::Normal,
17330                                            /*IndexTypeQuals=*/0, {ELoc, ELoc});
17331         VarDecl *TempArrayVD =
17332             buildVarDecl(S, ELoc, ArrayTy, D->getName(),
17333                          D->hasAttrs() ? &D->getAttrs() : nullptr);
17334         // Add a constructor to the temp decl.
17335         S.ActOnUninitializedDecl(TempArrayVD);
17336         TempArrayRes = buildDeclRefExpr(S, TempArrayVD, ArrayTy, ELoc);
17337         TempArrayElem =
17338             S.DefaultFunctionArrayLvalueConversion(TempArrayRes.get());
17339         auto *Idx = new (S.Context)
17340             OpaqueValueExpr(ELoc, S.Context.getSizeType(), VK_PRValue);
17341         TempArrayElem = S.CreateBuiltinArraySubscriptExpr(TempArrayElem.get(),
17342                                                           ELoc, Idx, ELoc);
17343       }
17344     }
17345 
17346     // OpenMP [2.15.4.6, Restrictions, p.2]
17347     // A list item that appears in an in_reduction clause of a task construct
17348     // must appear in a task_reduction clause of a construct associated with a
17349     // taskgroup region that includes the participating task in its taskgroup
17350     // set. The construct associated with the innermost region that meets this
17351     // condition must specify the same reduction-identifier as the in_reduction
17352     // clause.
17353     if (ClauseKind == OMPC_in_reduction) {
17354       SourceRange ParentSR;
17355       BinaryOperatorKind ParentBOK;
17356       const Expr *ParentReductionOp = nullptr;
17357       Expr *ParentBOKTD = nullptr, *ParentReductionOpTD = nullptr;
17358       DSAStackTy::DSAVarData ParentBOKDSA =
17359           Stack->getTopMostTaskgroupReductionData(D, ParentSR, ParentBOK,
17360                                                   ParentBOKTD);
17361       DSAStackTy::DSAVarData ParentReductionOpDSA =
17362           Stack->getTopMostTaskgroupReductionData(
17363               D, ParentSR, ParentReductionOp, ParentReductionOpTD);
17364       bool IsParentBOK = ParentBOKDSA.DKind != OMPD_unknown;
17365       bool IsParentReductionOp = ParentReductionOpDSA.DKind != OMPD_unknown;
17366       if ((DeclareReductionRef.isUnset() && IsParentReductionOp) ||
17367           (DeclareReductionRef.isUsable() && IsParentBOK) ||
17368           (IsParentBOK && BOK != ParentBOK) || IsParentReductionOp) {
17369         bool EmitError = true;
17370         if (IsParentReductionOp && DeclareReductionRef.isUsable()) {
17371           llvm::FoldingSetNodeID RedId, ParentRedId;
17372           ParentReductionOp->Profile(ParentRedId, Context, /*Canonical=*/true);
17373           DeclareReductionRef.get()->Profile(RedId, Context,
17374                                              /*Canonical=*/true);
17375           EmitError = RedId != ParentRedId;
17376         }
17377         if (EmitError) {
17378           S.Diag(ReductionId.getBeginLoc(),
17379                  diag::err_omp_reduction_identifier_mismatch)
17380               << ReductionIdRange << RefExpr->getSourceRange();
17381           S.Diag(ParentSR.getBegin(),
17382                  diag::note_omp_previous_reduction_identifier)
17383               << ParentSR
17384               << (IsParentBOK ? ParentBOKDSA.RefExpr
17385                               : ParentReductionOpDSA.RefExpr)
17386                      ->getSourceRange();
17387           continue;
17388         }
17389       }
17390       TaskgroupDescriptor = IsParentBOK ? ParentBOKTD : ParentReductionOpTD;
17391     }
17392 
17393     DeclRefExpr *Ref = nullptr;
17394     Expr *VarsExpr = RefExpr->IgnoreParens();
17395     if (!VD && !S.CurContext->isDependentContext()) {
17396       if (ASE || OASE) {
17397         TransformExprToCaptures RebuildToCapture(S, D);
17398         VarsExpr =
17399             RebuildToCapture.TransformExpr(RefExpr->IgnoreParens()).get();
17400         Ref = RebuildToCapture.getCapturedExpr();
17401       } else {
17402         VarsExpr = Ref = buildCapture(S, D, SimpleRefExpr, /*WithInit=*/false);
17403       }
17404       if (!S.isOpenMPCapturedDecl(D)) {
17405         RD.ExprCaptures.emplace_back(Ref->getDecl());
17406         if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
17407           ExprResult RefRes = S.DefaultLvalueConversion(Ref);
17408           if (!RefRes.isUsable())
17409             continue;
17410           ExprResult PostUpdateRes =
17411               S.BuildBinOp(Stack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
17412                            RefRes.get());
17413           if (!PostUpdateRes.isUsable())
17414             continue;
17415           if (isOpenMPTaskingDirective(Stack->getCurrentDirective()) ||
17416               Stack->getCurrentDirective() == OMPD_taskgroup) {
17417             S.Diag(RefExpr->getExprLoc(),
17418                    diag::err_omp_reduction_non_addressable_expression)
17419                 << RefExpr->getSourceRange();
17420             continue;
17421           }
17422           RD.ExprPostUpdates.emplace_back(
17423               S.IgnoredValueConversions(PostUpdateRes.get()).get());
17424         }
17425       }
17426     }
17427     // All reduction items are still marked as reduction (to do not increase
17428     // code base size).
17429     unsigned Modifier = RD.RedModifier;
17430     // Consider task_reductions as reductions with task modifier. Required for
17431     // correct analysis of in_reduction clauses.
17432     if (CurrDir == OMPD_taskgroup && ClauseKind == OMPC_task_reduction)
17433       Modifier = OMPC_REDUCTION_task;
17434     Stack->addDSA(D, RefExpr->IgnoreParens(), OMPC_reduction, Ref, Modifier,
17435                   ASE || OASE);
17436     if (Modifier == OMPC_REDUCTION_task &&
17437         (CurrDir == OMPD_taskgroup ||
17438          ((isOpenMPParallelDirective(CurrDir) ||
17439            isOpenMPWorksharingDirective(CurrDir)) &&
17440           !isOpenMPSimdDirective(CurrDir)))) {
17441       if (DeclareReductionRef.isUsable())
17442         Stack->addTaskgroupReductionData(D, ReductionIdRange,
17443                                          DeclareReductionRef.get());
17444       else
17445         Stack->addTaskgroupReductionData(D, ReductionIdRange, BOK);
17446     }
17447     RD.push(VarsExpr, PrivateDRE, LHSDRE, RHSDRE, ReductionOp.get(),
17448             TaskgroupDescriptor, CopyOpRes.get(), TempArrayRes.get(),
17449             TempArrayElem.get());
17450   }
17451   return RD.Vars.empty();
17452 }
17453 
17454 OMPClause *Sema::ActOnOpenMPReductionClause(
17455     ArrayRef<Expr *> VarList, OpenMPReductionClauseModifier Modifier,
17456     SourceLocation StartLoc, SourceLocation LParenLoc,
17457     SourceLocation ModifierLoc, SourceLocation ColonLoc, SourceLocation EndLoc,
17458     CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
17459     ArrayRef<Expr *> UnresolvedReductions) {
17460   if (ModifierLoc.isValid() && Modifier == OMPC_REDUCTION_unknown) {
17461     Diag(LParenLoc, diag::err_omp_unexpected_clause_value)
17462         << getListOfPossibleValues(OMPC_reduction, /*First=*/0,
17463                                    /*Last=*/OMPC_REDUCTION_unknown)
17464         << getOpenMPClauseName(OMPC_reduction);
17465     return nullptr;
17466   }
17467   // OpenMP 5.0, 2.19.5.4 reduction Clause, Restrictions
17468   // A reduction clause with the inscan reduction-modifier may only appear on a
17469   // worksharing-loop construct, a worksharing-loop SIMD construct, a simd
17470   // construct, a parallel worksharing-loop construct or a parallel
17471   // worksharing-loop SIMD construct.
17472   if (Modifier == OMPC_REDUCTION_inscan &&
17473       (DSAStack->getCurrentDirective() != OMPD_for &&
17474        DSAStack->getCurrentDirective() != OMPD_for_simd &&
17475        DSAStack->getCurrentDirective() != OMPD_simd &&
17476        DSAStack->getCurrentDirective() != OMPD_parallel_for &&
17477        DSAStack->getCurrentDirective() != OMPD_parallel_for_simd)) {
17478     Diag(ModifierLoc, diag::err_omp_wrong_inscan_reduction);
17479     return nullptr;
17480   }
17481 
17482   ReductionData RD(VarList.size(), Modifier);
17483   if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_reduction, VarList,
17484                                   StartLoc, LParenLoc, ColonLoc, EndLoc,
17485                                   ReductionIdScopeSpec, ReductionId,
17486                                   UnresolvedReductions, RD))
17487     return nullptr;
17488 
17489   return OMPReductionClause::Create(
17490       Context, StartLoc, LParenLoc, ModifierLoc, ColonLoc, EndLoc, Modifier,
17491       RD.Vars, ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
17492       RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, RD.InscanCopyOps,
17493       RD.InscanCopyArrayTemps, RD.InscanCopyArrayElems,
17494       buildPreInits(Context, RD.ExprCaptures),
17495       buildPostUpdate(*this, RD.ExprPostUpdates));
17496 }
17497 
17498 OMPClause *Sema::ActOnOpenMPTaskReductionClause(
17499     ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
17500     SourceLocation ColonLoc, SourceLocation EndLoc,
17501     CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
17502     ArrayRef<Expr *> UnresolvedReductions) {
17503   ReductionData RD(VarList.size());
17504   if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_task_reduction, VarList,
17505                                   StartLoc, LParenLoc, ColonLoc, EndLoc,
17506                                   ReductionIdScopeSpec, ReductionId,
17507                                   UnresolvedReductions, RD))
17508     return nullptr;
17509 
17510   return OMPTaskReductionClause::Create(
17511       Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
17512       ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
17513       RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
17514       buildPreInits(Context, RD.ExprCaptures),
17515       buildPostUpdate(*this, RD.ExprPostUpdates));
17516 }
17517 
17518 OMPClause *Sema::ActOnOpenMPInReductionClause(
17519     ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
17520     SourceLocation ColonLoc, SourceLocation EndLoc,
17521     CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
17522     ArrayRef<Expr *> UnresolvedReductions) {
17523   ReductionData RD(VarList.size());
17524   if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_in_reduction, VarList,
17525                                   StartLoc, LParenLoc, ColonLoc, EndLoc,
17526                                   ReductionIdScopeSpec, ReductionId,
17527                                   UnresolvedReductions, RD))
17528     return nullptr;
17529 
17530   return OMPInReductionClause::Create(
17531       Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
17532       ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
17533       RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, RD.TaskgroupDescriptors,
17534       buildPreInits(Context, RD.ExprCaptures),
17535       buildPostUpdate(*this, RD.ExprPostUpdates));
17536 }
17537 
17538 bool Sema::CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
17539                                      SourceLocation LinLoc) {
17540   if ((!LangOpts.CPlusPlus && LinKind != OMPC_LINEAR_val) ||
17541       LinKind == OMPC_LINEAR_unknown) {
17542     Diag(LinLoc, diag::err_omp_wrong_linear_modifier) << LangOpts.CPlusPlus;
17543     return true;
17544   }
17545   return false;
17546 }
17547 
17548 bool Sema::CheckOpenMPLinearDecl(const ValueDecl *D, SourceLocation ELoc,
17549                                  OpenMPLinearClauseKind LinKind, QualType Type,
17550                                  bool IsDeclareSimd) {
17551   const auto *VD = dyn_cast_or_null<VarDecl>(D);
17552   // A variable must not have an incomplete type or a reference type.
17553   if (RequireCompleteType(ELoc, Type, diag::err_omp_linear_incomplete_type))
17554     return true;
17555   if ((LinKind == OMPC_LINEAR_uval || LinKind == OMPC_LINEAR_ref) &&
17556       !Type->isReferenceType()) {
17557     Diag(ELoc, diag::err_omp_wrong_linear_modifier_non_reference)
17558         << Type << getOpenMPSimpleClauseTypeName(OMPC_linear, LinKind);
17559     return true;
17560   }
17561   Type = Type.getNonReferenceType();
17562 
17563   // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
17564   // A variable that is privatized must not have a const-qualified type
17565   // unless it is of class type with a mutable member. This restriction does
17566   // not apply to the firstprivate clause, nor to the linear clause on
17567   // declarative directives (like declare simd).
17568   if (!IsDeclareSimd &&
17569       rejectConstNotMutableType(*this, D, Type, OMPC_linear, ELoc))
17570     return true;
17571 
17572   // A list item must be of integral or pointer type.
17573   Type = Type.getUnqualifiedType().getCanonicalType();
17574   const auto *Ty = Type.getTypePtrOrNull();
17575   if (!Ty || (LinKind != OMPC_LINEAR_ref && !Ty->isDependentType() &&
17576               !Ty->isIntegralType(Context) && !Ty->isPointerType())) {
17577     Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << Type;
17578     if (D) {
17579       bool IsDecl =
17580           !VD ||
17581           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
17582       Diag(D->getLocation(),
17583            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
17584           << D;
17585     }
17586     return true;
17587   }
17588   return false;
17589 }
17590 
17591 OMPClause *Sema::ActOnOpenMPLinearClause(
17592     ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc,
17593     SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind,
17594     SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
17595   SmallVector<Expr *, 8> Vars;
17596   SmallVector<Expr *, 8> Privates;
17597   SmallVector<Expr *, 8> Inits;
17598   SmallVector<Decl *, 4> ExprCaptures;
17599   SmallVector<Expr *, 4> ExprPostUpdates;
17600   if (CheckOpenMPLinearModifier(LinKind, LinLoc))
17601     LinKind = OMPC_LINEAR_val;
17602   for (Expr *RefExpr : VarList) {
17603     assert(RefExpr && "NULL expr in OpenMP linear clause.");
17604     SourceLocation ELoc;
17605     SourceRange ERange;
17606     Expr *SimpleRefExpr = RefExpr;
17607     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
17608     if (Res.second) {
17609       // It will be analyzed later.
17610       Vars.push_back(RefExpr);
17611       Privates.push_back(nullptr);
17612       Inits.push_back(nullptr);
17613     }
17614     ValueDecl *D = Res.first;
17615     if (!D)
17616       continue;
17617 
17618     QualType Type = D->getType();
17619     auto *VD = dyn_cast<VarDecl>(D);
17620 
17621     // OpenMP [2.14.3.7, linear clause]
17622     //  A list-item cannot appear in more than one linear clause.
17623     //  A list-item that appears in a linear clause cannot appear in any
17624     //  other data-sharing attribute clause.
17625     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
17626     if (DVar.RefExpr) {
17627       Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
17628                                           << getOpenMPClauseName(OMPC_linear);
17629       reportOriginalDsa(*this, DSAStack, D, DVar);
17630       continue;
17631     }
17632 
17633     if (CheckOpenMPLinearDecl(D, ELoc, LinKind, Type))
17634       continue;
17635     Type = Type.getNonReferenceType().getUnqualifiedType().getCanonicalType();
17636 
17637     // Build private copy of original var.
17638     VarDecl *Private =
17639         buildVarDecl(*this, ELoc, Type, D->getName(),
17640                      D->hasAttrs() ? &D->getAttrs() : nullptr,
17641                      VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
17642     DeclRefExpr *PrivateRef = buildDeclRefExpr(*this, Private, Type, ELoc);
17643     // Build var to save initial value.
17644     VarDecl *Init = buildVarDecl(*this, ELoc, Type, ".linear.start");
17645     Expr *InitExpr;
17646     DeclRefExpr *Ref = nullptr;
17647     if (!VD && !CurContext->isDependentContext()) {
17648       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
17649       if (!isOpenMPCapturedDecl(D)) {
17650         ExprCaptures.push_back(Ref->getDecl());
17651         if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
17652           ExprResult RefRes = DefaultLvalueConversion(Ref);
17653           if (!RefRes.isUsable())
17654             continue;
17655           ExprResult PostUpdateRes =
17656               BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
17657                          SimpleRefExpr, RefRes.get());
17658           if (!PostUpdateRes.isUsable())
17659             continue;
17660           ExprPostUpdates.push_back(
17661               IgnoredValueConversions(PostUpdateRes.get()).get());
17662         }
17663       }
17664     }
17665     if (LinKind == OMPC_LINEAR_uval)
17666       InitExpr = VD ? VD->getInit() : SimpleRefExpr;
17667     else
17668       InitExpr = VD ? SimpleRefExpr : Ref;
17669     AddInitializerToDecl(Init, DefaultLvalueConversion(InitExpr).get(),
17670                          /*DirectInit=*/false);
17671     DeclRefExpr *InitRef = buildDeclRefExpr(*this, Init, Type, ELoc);
17672 
17673     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_linear, Ref);
17674     Vars.push_back((VD || CurContext->isDependentContext())
17675                        ? RefExpr->IgnoreParens()
17676                        : Ref);
17677     Privates.push_back(PrivateRef);
17678     Inits.push_back(InitRef);
17679   }
17680 
17681   if (Vars.empty())
17682     return nullptr;
17683 
17684   Expr *StepExpr = Step;
17685   Expr *CalcStepExpr = nullptr;
17686   if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
17687       !Step->isInstantiationDependent() &&
17688       !Step->containsUnexpandedParameterPack()) {
17689     SourceLocation StepLoc = Step->getBeginLoc();
17690     ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step);
17691     if (Val.isInvalid())
17692       return nullptr;
17693     StepExpr = Val.get();
17694 
17695     // Build var to save the step value.
17696     VarDecl *SaveVar =
17697         buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step");
17698     ExprResult SaveRef =
17699         buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc);
17700     ExprResult CalcStep =
17701         BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr);
17702     CalcStep = ActOnFinishFullExpr(CalcStep.get(), /*DiscardedValue*/ false);
17703 
17704     // Warn about zero linear step (it would be probably better specified as
17705     // making corresponding variables 'const').
17706     if (Optional<llvm::APSInt> Result =
17707             StepExpr->getIntegerConstantExpr(Context)) {
17708       if (!Result->isNegative() && !Result->isStrictlyPositive())
17709         Diag(StepLoc, diag::warn_omp_linear_step_zero)
17710             << Vars[0] << (Vars.size() > 1);
17711     } else if (CalcStep.isUsable()) {
17712       // Calculate the step beforehand instead of doing this on each iteration.
17713       // (This is not used if the number of iterations may be kfold-ed).
17714       CalcStepExpr = CalcStep.get();
17715     }
17716   }
17717 
17718   return OMPLinearClause::Create(Context, StartLoc, LParenLoc, LinKind, LinLoc,
17719                                  ColonLoc, EndLoc, Vars, Privates, Inits,
17720                                  StepExpr, CalcStepExpr,
17721                                  buildPreInits(Context, ExprCaptures),
17722                                  buildPostUpdate(*this, ExprPostUpdates));
17723 }
17724 
17725 static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
17726                                      Expr *NumIterations, Sema &SemaRef,
17727                                      Scope *S, DSAStackTy *Stack) {
17728   // Walk the vars and build update/final expressions for the CodeGen.
17729   SmallVector<Expr *, 8> Updates;
17730   SmallVector<Expr *, 8> Finals;
17731   SmallVector<Expr *, 8> UsedExprs;
17732   Expr *Step = Clause.getStep();
17733   Expr *CalcStep = Clause.getCalcStep();
17734   // OpenMP [2.14.3.7, linear clause]
17735   // If linear-step is not specified it is assumed to be 1.
17736   if (!Step)
17737     Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
17738   else if (CalcStep)
17739     Step = cast<BinaryOperator>(CalcStep)->getLHS();
17740   bool HasErrors = false;
17741   auto CurInit = Clause.inits().begin();
17742   auto CurPrivate = Clause.privates().begin();
17743   OpenMPLinearClauseKind LinKind = Clause.getModifier();
17744   for (Expr *RefExpr : Clause.varlists()) {
17745     SourceLocation ELoc;
17746     SourceRange ERange;
17747     Expr *SimpleRefExpr = RefExpr;
17748     auto Res = getPrivateItem(SemaRef, SimpleRefExpr, ELoc, ERange);
17749     ValueDecl *D = Res.first;
17750     if (Res.second || !D) {
17751       Updates.push_back(nullptr);
17752       Finals.push_back(nullptr);
17753       HasErrors = true;
17754       continue;
17755     }
17756     auto &&Info = Stack->isLoopControlVariable(D);
17757     // OpenMP [2.15.11, distribute simd Construct]
17758     // A list item may not appear in a linear clause, unless it is the loop
17759     // iteration variable.
17760     if (isOpenMPDistributeDirective(Stack->getCurrentDirective()) &&
17761         isOpenMPSimdDirective(Stack->getCurrentDirective()) && !Info.first) {
17762       SemaRef.Diag(ELoc,
17763                    diag::err_omp_linear_distribute_var_non_loop_iteration);
17764       Updates.push_back(nullptr);
17765       Finals.push_back(nullptr);
17766       HasErrors = true;
17767       continue;
17768     }
17769     Expr *InitExpr = *CurInit;
17770 
17771     // Build privatized reference to the current linear var.
17772     auto *DE = cast<DeclRefExpr>(SimpleRefExpr);
17773     Expr *CapturedRef;
17774     if (LinKind == OMPC_LINEAR_uval)
17775       CapturedRef = cast<VarDecl>(DE->getDecl())->getInit();
17776     else
17777       CapturedRef =
17778           buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()),
17779                            DE->getType().getUnqualifiedType(), DE->getExprLoc(),
17780                            /*RefersToCapture=*/true);
17781 
17782     // Build update: Var = InitExpr + IV * Step
17783     ExprResult Update;
17784     if (!Info.first)
17785       Update = buildCounterUpdate(
17786           SemaRef, S, RefExpr->getExprLoc(), *CurPrivate, InitExpr, IV, Step,
17787           /*Subtract=*/false, /*IsNonRectangularLB=*/false);
17788     else
17789       Update = *CurPrivate;
17790     Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getBeginLoc(),
17791                                          /*DiscardedValue*/ false);
17792 
17793     // Build final: Var = InitExpr + NumIterations * Step
17794     ExprResult Final;
17795     if (!Info.first)
17796       Final =
17797           buildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), CapturedRef,
17798                              InitExpr, NumIterations, Step, /*Subtract=*/false,
17799                              /*IsNonRectangularLB=*/false);
17800     else
17801       Final = *CurPrivate;
17802     Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getBeginLoc(),
17803                                         /*DiscardedValue*/ false);
17804 
17805     if (!Update.isUsable() || !Final.isUsable()) {
17806       Updates.push_back(nullptr);
17807       Finals.push_back(nullptr);
17808       UsedExprs.push_back(nullptr);
17809       HasErrors = true;
17810     } else {
17811       Updates.push_back(Update.get());
17812       Finals.push_back(Final.get());
17813       if (!Info.first)
17814         UsedExprs.push_back(SimpleRefExpr);
17815     }
17816     ++CurInit;
17817     ++CurPrivate;
17818   }
17819   if (Expr *S = Clause.getStep())
17820     UsedExprs.push_back(S);
17821   // Fill the remaining part with the nullptr.
17822   UsedExprs.append(Clause.varlist_size() + 1 - UsedExprs.size(), nullptr);
17823   Clause.setUpdates(Updates);
17824   Clause.setFinals(Finals);
17825   Clause.setUsedExprs(UsedExprs);
17826   return HasErrors;
17827 }
17828 
17829 OMPClause *Sema::ActOnOpenMPAlignedClause(
17830     ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc,
17831     SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
17832   SmallVector<Expr *, 8> Vars;
17833   for (Expr *RefExpr : VarList) {
17834     assert(RefExpr && "NULL expr in OpenMP linear clause.");
17835     SourceLocation ELoc;
17836     SourceRange ERange;
17837     Expr *SimpleRefExpr = RefExpr;
17838     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
17839     if (Res.second) {
17840       // It will be analyzed later.
17841       Vars.push_back(RefExpr);
17842     }
17843     ValueDecl *D = Res.first;
17844     if (!D)
17845       continue;
17846 
17847     QualType QType = D->getType();
17848     auto *VD = dyn_cast<VarDecl>(D);
17849 
17850     // OpenMP  [2.8.1, simd construct, Restrictions]
17851     // The type of list items appearing in the aligned clause must be
17852     // array, pointer, reference to array, or reference to pointer.
17853     QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType();
17854     const Type *Ty = QType.getTypePtrOrNull();
17855     if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
17856       Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr)
17857           << QType << getLangOpts().CPlusPlus << ERange;
17858       bool IsDecl =
17859           !VD ||
17860           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
17861       Diag(D->getLocation(),
17862            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
17863           << D;
17864       continue;
17865     }
17866 
17867     // OpenMP  [2.8.1, simd construct, Restrictions]
17868     // A list-item cannot appear in more than one aligned clause.
17869     if (const Expr *PrevRef = DSAStack->addUniqueAligned(D, SimpleRefExpr)) {
17870       Diag(ELoc, diag::err_omp_used_in_clause_twice)
17871           << 0 << getOpenMPClauseName(OMPC_aligned) << ERange;
17872       Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
17873           << getOpenMPClauseName(OMPC_aligned);
17874       continue;
17875     }
17876 
17877     DeclRefExpr *Ref = nullptr;
17878     if (!VD && isOpenMPCapturedDecl(D))
17879       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
17880     Vars.push_back(DefaultFunctionArrayConversion(
17881                        (VD || !Ref) ? RefExpr->IgnoreParens() : Ref)
17882                        .get());
17883   }
17884 
17885   // OpenMP [2.8.1, simd construct, Description]
17886   // The parameter of the aligned clause, alignment, must be a constant
17887   // positive integer expression.
17888   // If no optional parameter is specified, implementation-defined default
17889   // alignments for SIMD instructions on the target platforms are assumed.
17890   if (Alignment != nullptr) {
17891     ExprResult AlignResult =
17892         VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned);
17893     if (AlignResult.isInvalid())
17894       return nullptr;
17895     Alignment = AlignResult.get();
17896   }
17897   if (Vars.empty())
17898     return nullptr;
17899 
17900   return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
17901                                   EndLoc, Vars, Alignment);
17902 }
17903 
17904 OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
17905                                          SourceLocation StartLoc,
17906                                          SourceLocation LParenLoc,
17907                                          SourceLocation EndLoc) {
17908   SmallVector<Expr *, 8> Vars;
17909   SmallVector<Expr *, 8> SrcExprs;
17910   SmallVector<Expr *, 8> DstExprs;
17911   SmallVector<Expr *, 8> AssignmentOps;
17912   for (Expr *RefExpr : VarList) {
17913     assert(RefExpr && "NULL expr in OpenMP copyin clause.");
17914     if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
17915       // It will be analyzed later.
17916       Vars.push_back(RefExpr);
17917       SrcExprs.push_back(nullptr);
17918       DstExprs.push_back(nullptr);
17919       AssignmentOps.push_back(nullptr);
17920       continue;
17921     }
17922 
17923     SourceLocation ELoc = RefExpr->getExprLoc();
17924     // OpenMP [2.1, C/C++]
17925     //  A list item is a variable name.
17926     // OpenMP  [2.14.4.1, Restrictions, p.1]
17927     //  A list item that appears in a copyin clause must be threadprivate.
17928     auto *DE = dyn_cast<DeclRefExpr>(RefExpr);
17929     if (!DE || !isa<VarDecl>(DE->getDecl())) {
17930       Diag(ELoc, diag::err_omp_expected_var_name_member_expr)
17931           << 0 << RefExpr->getSourceRange();
17932       continue;
17933     }
17934 
17935     Decl *D = DE->getDecl();
17936     auto *VD = cast<VarDecl>(D);
17937 
17938     QualType Type = VD->getType();
17939     if (Type->isDependentType() || Type->isInstantiationDependentType()) {
17940       // It will be analyzed later.
17941       Vars.push_back(DE);
17942       SrcExprs.push_back(nullptr);
17943       DstExprs.push_back(nullptr);
17944       AssignmentOps.push_back(nullptr);
17945       continue;
17946     }
17947 
17948     // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
17949     //  A list item that appears in a copyin clause must be threadprivate.
17950     if (!DSAStack->isThreadPrivate(VD)) {
17951       Diag(ELoc, diag::err_omp_required_access)
17952           << getOpenMPClauseName(OMPC_copyin)
17953           << getOpenMPDirectiveName(OMPD_threadprivate);
17954       continue;
17955     }
17956 
17957     // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
17958     //  A variable of class type (or array thereof) that appears in a
17959     //  copyin clause requires an accessible, unambiguous copy assignment
17960     //  operator for the class type.
17961     QualType ElemType = Context.getBaseElementType(Type).getNonReferenceType();
17962     VarDecl *SrcVD =
17963         buildVarDecl(*this, DE->getBeginLoc(), ElemType.getUnqualifiedType(),
17964                      ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr);
17965     DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr(
17966         *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc());
17967     VarDecl *DstVD =
17968         buildVarDecl(*this, DE->getBeginLoc(), ElemType, ".copyin.dst",
17969                      VD->hasAttrs() ? &VD->getAttrs() : nullptr);
17970     DeclRefExpr *PseudoDstExpr =
17971         buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc());
17972     // For arrays generate assignment operation for single element and replace
17973     // it by the original array element in CodeGen.
17974     ExprResult AssignmentOp =
17975         BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign, PseudoDstExpr,
17976                    PseudoSrcExpr);
17977     if (AssignmentOp.isInvalid())
17978       continue;
17979     AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
17980                                        /*DiscardedValue*/ false);
17981     if (AssignmentOp.isInvalid())
17982       continue;
17983 
17984     DSAStack->addDSA(VD, DE, OMPC_copyin);
17985     Vars.push_back(DE);
17986     SrcExprs.push_back(PseudoSrcExpr);
17987     DstExprs.push_back(PseudoDstExpr);
17988     AssignmentOps.push_back(AssignmentOp.get());
17989   }
17990 
17991   if (Vars.empty())
17992     return nullptr;
17993 
17994   return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
17995                                  SrcExprs, DstExprs, AssignmentOps);
17996 }
17997 
17998 OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
17999                                               SourceLocation StartLoc,
18000                                               SourceLocation LParenLoc,
18001                                               SourceLocation EndLoc) {
18002   SmallVector<Expr *, 8> Vars;
18003   SmallVector<Expr *, 8> SrcExprs;
18004   SmallVector<Expr *, 8> DstExprs;
18005   SmallVector<Expr *, 8> AssignmentOps;
18006   for (Expr *RefExpr : VarList) {
18007     assert(RefExpr && "NULL expr in OpenMP linear clause.");
18008     SourceLocation ELoc;
18009     SourceRange ERange;
18010     Expr *SimpleRefExpr = RefExpr;
18011     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
18012     if (Res.second) {
18013       // It will be analyzed later.
18014       Vars.push_back(RefExpr);
18015       SrcExprs.push_back(nullptr);
18016       DstExprs.push_back(nullptr);
18017       AssignmentOps.push_back(nullptr);
18018     }
18019     ValueDecl *D = Res.first;
18020     if (!D)
18021       continue;
18022 
18023     QualType Type = D->getType();
18024     auto *VD = dyn_cast<VarDecl>(D);
18025 
18026     // OpenMP [2.14.4.2, Restrictions, p.2]
18027     //  A list item that appears in a copyprivate clause may not appear in a
18028     //  private or firstprivate clause on the single construct.
18029     if (!VD || !DSAStack->isThreadPrivate(VD)) {
18030       DSAStackTy::DSAVarData DVar =
18031           DSAStack->getTopDSA(D, /*FromParent=*/false);
18032       if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate &&
18033           DVar.RefExpr) {
18034         Diag(ELoc, diag::err_omp_wrong_dsa)
18035             << getOpenMPClauseName(DVar.CKind)
18036             << getOpenMPClauseName(OMPC_copyprivate);
18037         reportOriginalDsa(*this, DSAStack, D, DVar);
18038         continue;
18039       }
18040 
18041       // OpenMP [2.11.4.2, Restrictions, p.1]
18042       //  All list items that appear in a copyprivate clause must be either
18043       //  threadprivate or private in the enclosing context.
18044       if (DVar.CKind == OMPC_unknown) {
18045         DVar = DSAStack->getImplicitDSA(D, false);
18046         if (DVar.CKind == OMPC_shared) {
18047           Diag(ELoc, diag::err_omp_required_access)
18048               << getOpenMPClauseName(OMPC_copyprivate)
18049               << "threadprivate or private in the enclosing context";
18050           reportOriginalDsa(*this, DSAStack, D, DVar);
18051           continue;
18052         }
18053       }
18054     }
18055 
18056     // Variably modified types are not supported.
18057     if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) {
18058       Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
18059           << getOpenMPClauseName(OMPC_copyprivate) << Type
18060           << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
18061       bool IsDecl =
18062           !VD ||
18063           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
18064       Diag(D->getLocation(),
18065            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
18066           << D;
18067       continue;
18068     }
18069 
18070     // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
18071     //  A variable of class type (or array thereof) that appears in a
18072     //  copyin clause requires an accessible, unambiguous copy assignment
18073     //  operator for the class type.
18074     Type = Context.getBaseElementType(Type.getNonReferenceType())
18075                .getUnqualifiedType();
18076     VarDecl *SrcVD =
18077         buildVarDecl(*this, RefExpr->getBeginLoc(), Type, ".copyprivate.src",
18078                      D->hasAttrs() ? &D->getAttrs() : nullptr);
18079     DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr(*this, SrcVD, Type, ELoc);
18080     VarDecl *DstVD =
18081         buildVarDecl(*this, RefExpr->getBeginLoc(), Type, ".copyprivate.dst",
18082                      D->hasAttrs() ? &D->getAttrs() : nullptr);
18083     DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
18084     ExprResult AssignmentOp = BuildBinOp(
18085         DSAStack->getCurScope(), ELoc, BO_Assign, PseudoDstExpr, PseudoSrcExpr);
18086     if (AssignmentOp.isInvalid())
18087       continue;
18088     AssignmentOp =
18089         ActOnFinishFullExpr(AssignmentOp.get(), ELoc, /*DiscardedValue*/ false);
18090     if (AssignmentOp.isInvalid())
18091       continue;
18092 
18093     // No need to mark vars as copyprivate, they are already threadprivate or
18094     // implicitly private.
18095     assert(VD || isOpenMPCapturedDecl(D));
18096     Vars.push_back(
18097         VD ? RefExpr->IgnoreParens()
18098            : buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false));
18099     SrcExprs.push_back(PseudoSrcExpr);
18100     DstExprs.push_back(PseudoDstExpr);
18101     AssignmentOps.push_back(AssignmentOp.get());
18102   }
18103 
18104   if (Vars.empty())
18105     return nullptr;
18106 
18107   return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
18108                                       Vars, SrcExprs, DstExprs, AssignmentOps);
18109 }
18110 
18111 OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
18112                                         SourceLocation StartLoc,
18113                                         SourceLocation LParenLoc,
18114                                         SourceLocation EndLoc) {
18115   if (VarList.empty())
18116     return nullptr;
18117 
18118   return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList);
18119 }
18120 
18121 /// Tries to find omp_depend_t. type.
18122 static bool findOMPDependT(Sema &S, SourceLocation Loc, DSAStackTy *Stack,
18123                            bool Diagnose = true) {
18124   QualType OMPDependT = Stack->getOMPDependT();
18125   if (!OMPDependT.isNull())
18126     return true;
18127   IdentifierInfo *II = &S.PP.getIdentifierTable().get("omp_depend_t");
18128   ParsedType PT = S.getTypeName(*II, Loc, S.getCurScope());
18129   if (!PT.getAsOpaquePtr() || PT.get().isNull()) {
18130     if (Diagnose)
18131       S.Diag(Loc, diag::err_omp_implied_type_not_found) << "omp_depend_t";
18132     return false;
18133   }
18134   Stack->setOMPDependT(PT.get());
18135   return true;
18136 }
18137 
18138 OMPClause *Sema::ActOnOpenMPDepobjClause(Expr *Depobj, SourceLocation StartLoc,
18139                                          SourceLocation LParenLoc,
18140                                          SourceLocation EndLoc) {
18141   if (!Depobj)
18142     return nullptr;
18143 
18144   bool OMPDependTFound = findOMPDependT(*this, StartLoc, DSAStack);
18145 
18146   // OpenMP 5.0, 2.17.10.1 depobj Construct
18147   // depobj is an lvalue expression of type omp_depend_t.
18148   if (!Depobj->isTypeDependent() && !Depobj->isValueDependent() &&
18149       !Depobj->isInstantiationDependent() &&
18150       !Depobj->containsUnexpandedParameterPack() &&
18151       (OMPDependTFound &&
18152        !Context.typesAreCompatible(DSAStack->getOMPDependT(), Depobj->getType(),
18153                                    /*CompareUnqualified=*/true))) {
18154     Diag(Depobj->getExprLoc(), diag::err_omp_expected_omp_depend_t_lvalue)
18155         << 0 << Depobj->getType() << Depobj->getSourceRange();
18156   }
18157 
18158   if (!Depobj->isLValue()) {
18159     Diag(Depobj->getExprLoc(), diag::err_omp_expected_omp_depend_t_lvalue)
18160         << 1 << Depobj->getSourceRange();
18161   }
18162 
18163   return OMPDepobjClause::Create(Context, StartLoc, LParenLoc, EndLoc, Depobj);
18164 }
18165 
18166 OMPClause *
18167 Sema::ActOnOpenMPDependClause(Expr *DepModifier, OpenMPDependClauseKind DepKind,
18168                               SourceLocation DepLoc, SourceLocation ColonLoc,
18169                               ArrayRef<Expr *> VarList, SourceLocation StartLoc,
18170                               SourceLocation LParenLoc, SourceLocation EndLoc) {
18171   if (DSAStack->getCurrentDirective() == OMPD_ordered &&
18172       DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink) {
18173     Diag(DepLoc, diag::err_omp_unexpected_clause_value)
18174         << "'source' or 'sink'" << getOpenMPClauseName(OMPC_depend);
18175     return nullptr;
18176   }
18177   if ((DSAStack->getCurrentDirective() != OMPD_ordered ||
18178        DSAStack->getCurrentDirective() == OMPD_depobj) &&
18179       (DepKind == OMPC_DEPEND_unknown || DepKind == OMPC_DEPEND_source ||
18180        DepKind == OMPC_DEPEND_sink ||
18181        ((LangOpts.OpenMP < 50 ||
18182          DSAStack->getCurrentDirective() == OMPD_depobj) &&
18183         DepKind == OMPC_DEPEND_depobj))) {
18184     SmallVector<unsigned, 3> Except;
18185     Except.push_back(OMPC_DEPEND_source);
18186     Except.push_back(OMPC_DEPEND_sink);
18187     if (LangOpts.OpenMP < 50 || DSAStack->getCurrentDirective() == OMPD_depobj)
18188       Except.push_back(OMPC_DEPEND_depobj);
18189     std::string Expected = (LangOpts.OpenMP >= 50 && !DepModifier)
18190                                ? "depend modifier(iterator) or "
18191                                : "";
18192     Diag(DepLoc, diag::err_omp_unexpected_clause_value)
18193         << Expected + getListOfPossibleValues(OMPC_depend, /*First=*/0,
18194                                               /*Last=*/OMPC_DEPEND_unknown,
18195                                               Except)
18196         << getOpenMPClauseName(OMPC_depend);
18197     return nullptr;
18198   }
18199   if (DepModifier &&
18200       (DepKind == OMPC_DEPEND_source || DepKind == OMPC_DEPEND_sink)) {
18201     Diag(DepModifier->getExprLoc(),
18202          diag::err_omp_depend_sink_source_with_modifier);
18203     return nullptr;
18204   }
18205   if (DepModifier &&
18206       !DepModifier->getType()->isSpecificBuiltinType(BuiltinType::OMPIterator))
18207     Diag(DepModifier->getExprLoc(), diag::err_omp_depend_modifier_not_iterator);
18208 
18209   SmallVector<Expr *, 8> Vars;
18210   DSAStackTy::OperatorOffsetTy OpsOffs;
18211   llvm::APSInt DepCounter(/*BitWidth=*/32);
18212   llvm::APSInt TotalDepCount(/*BitWidth=*/32);
18213   if (DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) {
18214     if (const Expr *OrderedCountExpr =
18215             DSAStack->getParentOrderedRegionParam().first) {
18216       TotalDepCount = OrderedCountExpr->EvaluateKnownConstInt(Context);
18217       TotalDepCount.setIsUnsigned(/*Val=*/true);
18218     }
18219   }
18220   for (Expr *RefExpr : VarList) {
18221     assert(RefExpr && "NULL expr in OpenMP shared clause.");
18222     if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
18223       // It will be analyzed later.
18224       Vars.push_back(RefExpr);
18225       continue;
18226     }
18227 
18228     SourceLocation ELoc = RefExpr->getExprLoc();
18229     Expr *SimpleExpr = RefExpr->IgnoreParenCasts();
18230     if (DepKind == OMPC_DEPEND_sink) {
18231       if (DSAStack->getParentOrderedRegionParam().first &&
18232           DepCounter >= TotalDepCount) {
18233         Diag(ELoc, diag::err_omp_depend_sink_unexpected_expr);
18234         continue;
18235       }
18236       ++DepCounter;
18237       // OpenMP  [2.13.9, Summary]
18238       // depend(dependence-type : vec), where dependence-type is:
18239       // 'sink' and where vec is the iteration vector, which has the form:
18240       //  x1 [+- d1], x2 [+- d2 ], . . . , xn [+- dn]
18241       // where n is the value specified by the ordered clause in the loop
18242       // directive, xi denotes the loop iteration variable of the i-th nested
18243       // loop associated with the loop directive, and di is a constant
18244       // non-negative integer.
18245       if (CurContext->isDependentContext()) {
18246         // It will be analyzed later.
18247         Vars.push_back(RefExpr);
18248         continue;
18249       }
18250       SimpleExpr = SimpleExpr->IgnoreImplicit();
18251       OverloadedOperatorKind OOK = OO_None;
18252       SourceLocation OOLoc;
18253       Expr *LHS = SimpleExpr;
18254       Expr *RHS = nullptr;
18255       if (auto *BO = dyn_cast<BinaryOperator>(SimpleExpr)) {
18256         OOK = BinaryOperator::getOverloadedOperator(BO->getOpcode());
18257         OOLoc = BO->getOperatorLoc();
18258         LHS = BO->getLHS()->IgnoreParenImpCasts();
18259         RHS = BO->getRHS()->IgnoreParenImpCasts();
18260       } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(SimpleExpr)) {
18261         OOK = OCE->getOperator();
18262         OOLoc = OCE->getOperatorLoc();
18263         LHS = OCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
18264         RHS = OCE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
18265       } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SimpleExpr)) {
18266         OOK = MCE->getMethodDecl()
18267                   ->getNameInfo()
18268                   .getName()
18269                   .getCXXOverloadedOperator();
18270         OOLoc = MCE->getCallee()->getExprLoc();
18271         LHS = MCE->getImplicitObjectArgument()->IgnoreParenImpCasts();
18272         RHS = MCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
18273       }
18274       SourceLocation ELoc;
18275       SourceRange ERange;
18276       auto Res = getPrivateItem(*this, LHS, ELoc, ERange);
18277       if (Res.second) {
18278         // It will be analyzed later.
18279         Vars.push_back(RefExpr);
18280       }
18281       ValueDecl *D = Res.first;
18282       if (!D)
18283         continue;
18284 
18285       if (OOK != OO_Plus && OOK != OO_Minus && (RHS || OOK != OO_None)) {
18286         Diag(OOLoc, diag::err_omp_depend_sink_expected_plus_minus);
18287         continue;
18288       }
18289       if (RHS) {
18290         ExprResult RHSRes = VerifyPositiveIntegerConstantInClause(
18291             RHS, OMPC_depend, /*StrictlyPositive=*/false);
18292         if (RHSRes.isInvalid())
18293           continue;
18294       }
18295       if (!CurContext->isDependentContext() &&
18296           DSAStack->getParentOrderedRegionParam().first &&
18297           DepCounter != DSAStack->isParentLoopControlVariable(D).first) {
18298         const ValueDecl *VD =
18299             DSAStack->getParentLoopControlVariable(DepCounter.getZExtValue());
18300         if (VD)
18301           Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration)
18302               << 1 << VD;
18303         else
18304           Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration) << 0;
18305         continue;
18306       }
18307       OpsOffs.emplace_back(RHS, OOK);
18308     } else {
18309       bool OMPDependTFound = LangOpts.OpenMP >= 50;
18310       if (OMPDependTFound)
18311         OMPDependTFound = findOMPDependT(*this, StartLoc, DSAStack,
18312                                          DepKind == OMPC_DEPEND_depobj);
18313       if (DepKind == OMPC_DEPEND_depobj) {
18314         // OpenMP 5.0, 2.17.11 depend Clause, Restrictions, C/C++
18315         // List items used in depend clauses with the depobj dependence type
18316         // must be expressions of the omp_depend_t type.
18317         if (!RefExpr->isValueDependent() && !RefExpr->isTypeDependent() &&
18318             !RefExpr->isInstantiationDependent() &&
18319             !RefExpr->containsUnexpandedParameterPack() &&
18320             (OMPDependTFound &&
18321              !Context.hasSameUnqualifiedType(DSAStack->getOMPDependT(),
18322                                              RefExpr->getType()))) {
18323           Diag(ELoc, diag::err_omp_expected_omp_depend_t_lvalue)
18324               << 0 << RefExpr->getType() << RefExpr->getSourceRange();
18325           continue;
18326         }
18327         if (!RefExpr->isLValue()) {
18328           Diag(ELoc, diag::err_omp_expected_omp_depend_t_lvalue)
18329               << 1 << RefExpr->getType() << RefExpr->getSourceRange();
18330           continue;
18331         }
18332       } else {
18333         // OpenMP 5.0 [2.17.11, Restrictions]
18334         // List items used in depend clauses cannot be zero-length array
18335         // sections.
18336         QualType ExprTy = RefExpr->getType().getNonReferenceType();
18337         const auto *OASE = dyn_cast<OMPArraySectionExpr>(SimpleExpr);
18338         if (OASE) {
18339           QualType BaseType =
18340               OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
18341           if (const auto *ATy = BaseType->getAsArrayTypeUnsafe())
18342             ExprTy = ATy->getElementType();
18343           else
18344             ExprTy = BaseType->getPointeeType();
18345           ExprTy = ExprTy.getNonReferenceType();
18346           const Expr *Length = OASE->getLength();
18347           Expr::EvalResult Result;
18348           if (Length && !Length->isValueDependent() &&
18349               Length->EvaluateAsInt(Result, Context) &&
18350               Result.Val.getInt().isNullValue()) {
18351             Diag(ELoc,
18352                  diag::err_omp_depend_zero_length_array_section_not_allowed)
18353                 << SimpleExpr->getSourceRange();
18354             continue;
18355           }
18356         }
18357 
18358         // OpenMP 5.0, 2.17.11 depend Clause, Restrictions, C/C++
18359         // List items used in depend clauses with the in, out, inout or
18360         // mutexinoutset dependence types cannot be expressions of the
18361         // omp_depend_t type.
18362         if (!RefExpr->isValueDependent() && !RefExpr->isTypeDependent() &&
18363             !RefExpr->isInstantiationDependent() &&
18364             !RefExpr->containsUnexpandedParameterPack() &&
18365             (OMPDependTFound &&
18366              DSAStack->getOMPDependT().getTypePtr() == ExprTy.getTypePtr())) {
18367           Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
18368               << (LangOpts.OpenMP >= 50 ? 1 : 0) << 1
18369               << RefExpr->getSourceRange();
18370           continue;
18371         }
18372 
18373         auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr);
18374         if (!RefExpr->IgnoreParenImpCasts()->isLValue() ||
18375             (ASE && !ASE->getBase()->isTypeDependent() &&
18376              !ASE->getBase()
18377                   ->getType()
18378                   .getNonReferenceType()
18379                   ->isPointerType() &&
18380              !ASE->getBase()->getType().getNonReferenceType()->isArrayType())) {
18381           Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
18382               << (LangOpts.OpenMP >= 50 ? 1 : 0)
18383               << (LangOpts.OpenMP >= 50 ? 1 : 0) << RefExpr->getSourceRange();
18384           continue;
18385         }
18386 
18387         ExprResult Res;
18388         {
18389           Sema::TentativeAnalysisScope Trap(*this);
18390           Res = CreateBuiltinUnaryOp(ELoc, UO_AddrOf,
18391                                      RefExpr->IgnoreParenImpCasts());
18392         }
18393         if (!Res.isUsable() && !isa<OMPArraySectionExpr>(SimpleExpr) &&
18394             !isa<OMPArrayShapingExpr>(SimpleExpr)) {
18395           Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
18396               << (LangOpts.OpenMP >= 50 ? 1 : 0)
18397               << (LangOpts.OpenMP >= 50 ? 1 : 0) << RefExpr->getSourceRange();
18398           continue;
18399         }
18400       }
18401     }
18402     Vars.push_back(RefExpr->IgnoreParenImpCasts());
18403   }
18404 
18405   if (!CurContext->isDependentContext() && DepKind == OMPC_DEPEND_sink &&
18406       TotalDepCount > VarList.size() &&
18407       DSAStack->getParentOrderedRegionParam().first &&
18408       DSAStack->getParentLoopControlVariable(VarList.size() + 1)) {
18409     Diag(EndLoc, diag::err_omp_depend_sink_expected_loop_iteration)
18410         << 1 << DSAStack->getParentLoopControlVariable(VarList.size() + 1);
18411   }
18412   if (DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink &&
18413       Vars.empty())
18414     return nullptr;
18415 
18416   auto *C = OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc,
18417                                     DepModifier, DepKind, DepLoc, ColonLoc,
18418                                     Vars, TotalDepCount.getZExtValue());
18419   if ((DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) &&
18420       DSAStack->isParentOrderedRegion())
18421     DSAStack->addDoacrossDependClause(C, OpsOffs);
18422   return C;
18423 }
18424 
18425 OMPClause *Sema::ActOnOpenMPDeviceClause(OpenMPDeviceClauseModifier Modifier,
18426                                          Expr *Device, SourceLocation StartLoc,
18427                                          SourceLocation LParenLoc,
18428                                          SourceLocation ModifierLoc,
18429                                          SourceLocation EndLoc) {
18430   assert((ModifierLoc.isInvalid() || LangOpts.OpenMP >= 50) &&
18431          "Unexpected device modifier in OpenMP < 50.");
18432 
18433   bool ErrorFound = false;
18434   if (ModifierLoc.isValid() && Modifier == OMPC_DEVICE_unknown) {
18435     std::string Values =
18436         getListOfPossibleValues(OMPC_device, /*First=*/0, OMPC_DEVICE_unknown);
18437     Diag(ModifierLoc, diag::err_omp_unexpected_clause_value)
18438         << Values << getOpenMPClauseName(OMPC_device);
18439     ErrorFound = true;
18440   }
18441 
18442   Expr *ValExpr = Device;
18443   Stmt *HelperValStmt = nullptr;
18444 
18445   // OpenMP [2.9.1, Restrictions]
18446   // The device expression must evaluate to a non-negative integer value.
18447   ErrorFound = !isNonNegativeIntegerValue(ValExpr, *this, OMPC_device,
18448                                           /*StrictlyPositive=*/false) ||
18449                ErrorFound;
18450   if (ErrorFound)
18451     return nullptr;
18452 
18453   OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
18454   OpenMPDirectiveKind CaptureRegion =
18455       getOpenMPCaptureRegionForClause(DKind, OMPC_device, LangOpts.OpenMP);
18456   if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
18457     ValExpr = MakeFullExpr(ValExpr).get();
18458     llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
18459     ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
18460     HelperValStmt = buildPreInits(Context, Captures);
18461   }
18462 
18463   return new (Context)
18464       OMPDeviceClause(Modifier, ValExpr, HelperValStmt, CaptureRegion, StartLoc,
18465                       LParenLoc, ModifierLoc, EndLoc);
18466 }
18467 
18468 static bool checkTypeMappable(SourceLocation SL, SourceRange SR, Sema &SemaRef,
18469                               DSAStackTy *Stack, QualType QTy,
18470                               bool FullCheck = true) {
18471   if (SemaRef.RequireCompleteType(SL, QTy, diag::err_incomplete_type))
18472     return false;
18473   if (FullCheck && !SemaRef.CurContext->isDependentContext() &&
18474       !QTy.isTriviallyCopyableType(SemaRef.Context))
18475     SemaRef.Diag(SL, diag::warn_omp_non_trivial_type_mapped) << QTy << SR;
18476   return true;
18477 }
18478 
18479 /// Return true if it can be proven that the provided array expression
18480 /// (array section or array subscript) does NOT specify the whole size of the
18481 /// array whose base type is \a BaseQTy.
18482 static bool checkArrayExpressionDoesNotReferToWholeSize(Sema &SemaRef,
18483                                                         const Expr *E,
18484                                                         QualType BaseQTy) {
18485   const auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
18486 
18487   // If this is an array subscript, it refers to the whole size if the size of
18488   // the dimension is constant and equals 1. Also, an array section assumes the
18489   // format of an array subscript if no colon is used.
18490   if (isa<ArraySubscriptExpr>(E) ||
18491       (OASE && OASE->getColonLocFirst().isInvalid())) {
18492     if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
18493       return ATy->getSize().getSExtValue() != 1;
18494     // Size can't be evaluated statically.
18495     return false;
18496   }
18497 
18498   assert(OASE && "Expecting array section if not an array subscript.");
18499   const Expr *LowerBound = OASE->getLowerBound();
18500   const Expr *Length = OASE->getLength();
18501 
18502   // If there is a lower bound that does not evaluates to zero, we are not
18503   // covering the whole dimension.
18504   if (LowerBound) {
18505     Expr::EvalResult Result;
18506     if (!LowerBound->EvaluateAsInt(Result, SemaRef.getASTContext()))
18507       return false; // Can't get the integer value as a constant.
18508 
18509     llvm::APSInt ConstLowerBound = Result.Val.getInt();
18510     if (ConstLowerBound.getSExtValue())
18511       return true;
18512   }
18513 
18514   // If we don't have a length we covering the whole dimension.
18515   if (!Length)
18516     return false;
18517 
18518   // If the base is a pointer, we don't have a way to get the size of the
18519   // pointee.
18520   if (BaseQTy->isPointerType())
18521     return false;
18522 
18523   // We can only check if the length is the same as the size of the dimension
18524   // if we have a constant array.
18525   const auto *CATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr());
18526   if (!CATy)
18527     return false;
18528 
18529   Expr::EvalResult Result;
18530   if (!Length->EvaluateAsInt(Result, SemaRef.getASTContext()))
18531     return false; // Can't get the integer value as a constant.
18532 
18533   llvm::APSInt ConstLength = Result.Val.getInt();
18534   return CATy->getSize().getSExtValue() != ConstLength.getSExtValue();
18535 }
18536 
18537 // Return true if it can be proven that the provided array expression (array
18538 // section or array subscript) does NOT specify a single element of the array
18539 // whose base type is \a BaseQTy.
18540 static bool checkArrayExpressionDoesNotReferToUnitySize(Sema &SemaRef,
18541                                                         const Expr *E,
18542                                                         QualType BaseQTy) {
18543   const auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
18544 
18545   // An array subscript always refer to a single element. Also, an array section
18546   // assumes the format of an array subscript if no colon is used.
18547   if (isa<ArraySubscriptExpr>(E) ||
18548       (OASE && OASE->getColonLocFirst().isInvalid()))
18549     return false;
18550 
18551   assert(OASE && "Expecting array section if not an array subscript.");
18552   const Expr *Length = OASE->getLength();
18553 
18554   // If we don't have a length we have to check if the array has unitary size
18555   // for this dimension. Also, we should always expect a length if the base type
18556   // is pointer.
18557   if (!Length) {
18558     if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
18559       return ATy->getSize().getSExtValue() != 1;
18560     // We cannot assume anything.
18561     return false;
18562   }
18563 
18564   // Check if the length evaluates to 1.
18565   Expr::EvalResult Result;
18566   if (!Length->EvaluateAsInt(Result, SemaRef.getASTContext()))
18567     return false; // Can't get the integer value as a constant.
18568 
18569   llvm::APSInt ConstLength = Result.Val.getInt();
18570   return ConstLength.getSExtValue() != 1;
18571 }
18572 
18573 // The base of elements of list in a map clause have to be either:
18574 //  - a reference to variable or field.
18575 //  - a member expression.
18576 //  - an array expression.
18577 //
18578 // E.g. if we have the expression 'r.S.Arr[:12]', we want to retrieve the
18579 // reference to 'r'.
18580 //
18581 // If we have:
18582 //
18583 // struct SS {
18584 //   Bla S;
18585 //   foo() {
18586 //     #pragma omp target map (S.Arr[:12]);
18587 //   }
18588 // }
18589 //
18590 // We want to retrieve the member expression 'this->S';
18591 
18592 // OpenMP 5.0 [2.19.7.1, map Clause, Restrictions, p.2]
18593 //  If a list item is an array section, it must specify contiguous storage.
18594 //
18595 // For this restriction it is sufficient that we make sure only references
18596 // to variables or fields and array expressions, and that no array sections
18597 // exist except in the rightmost expression (unless they cover the whole
18598 // dimension of the array). E.g. these would be invalid:
18599 //
18600 //   r.ArrS[3:5].Arr[6:7]
18601 //
18602 //   r.ArrS[3:5].x
18603 //
18604 // but these would be valid:
18605 //   r.ArrS[3].Arr[6:7]
18606 //
18607 //   r.ArrS[3].x
18608 namespace {
18609 class MapBaseChecker final : public StmtVisitor<MapBaseChecker, bool> {
18610   Sema &SemaRef;
18611   OpenMPClauseKind CKind = OMPC_unknown;
18612   OpenMPDirectiveKind DKind = OMPD_unknown;
18613   OMPClauseMappableExprCommon::MappableExprComponentList &Components;
18614   bool IsNonContiguous = false;
18615   bool NoDiagnose = false;
18616   const Expr *RelevantExpr = nullptr;
18617   bool AllowUnitySizeArraySection = true;
18618   bool AllowWholeSizeArraySection = true;
18619   bool AllowAnotherPtr = true;
18620   SourceLocation ELoc;
18621   SourceRange ERange;
18622 
18623   void emitErrorMsg() {
18624     // If nothing else worked, this is not a valid map clause expression.
18625     if (SemaRef.getLangOpts().OpenMP < 50) {
18626       SemaRef.Diag(ELoc,
18627                    diag::err_omp_expected_named_var_member_or_array_expression)
18628           << ERange;
18629     } else {
18630       SemaRef.Diag(ELoc, diag::err_omp_non_lvalue_in_map_or_motion_clauses)
18631           << getOpenMPClauseName(CKind) << ERange;
18632     }
18633   }
18634 
18635 public:
18636   bool VisitDeclRefExpr(DeclRefExpr *DRE) {
18637     if (!isa<VarDecl>(DRE->getDecl())) {
18638       emitErrorMsg();
18639       return false;
18640     }
18641     assert(!RelevantExpr && "RelevantExpr is expected to be nullptr");
18642     RelevantExpr = DRE;
18643     // Record the component.
18644     Components.emplace_back(DRE, DRE->getDecl(), IsNonContiguous);
18645     return true;
18646   }
18647 
18648   bool VisitMemberExpr(MemberExpr *ME) {
18649     Expr *E = ME;
18650     Expr *BaseE = ME->getBase()->IgnoreParenCasts();
18651 
18652     if (isa<CXXThisExpr>(BaseE)) {
18653       assert(!RelevantExpr && "RelevantExpr is expected to be nullptr");
18654       // We found a base expression: this->Val.
18655       RelevantExpr = ME;
18656     } else {
18657       E = BaseE;
18658     }
18659 
18660     if (!isa<FieldDecl>(ME->getMemberDecl())) {
18661       if (!NoDiagnose) {
18662         SemaRef.Diag(ELoc, diag::err_omp_expected_access_to_data_field)
18663           << ME->getSourceRange();
18664         return false;
18665       }
18666       if (RelevantExpr)
18667         return false;
18668       return Visit(E);
18669     }
18670 
18671     auto *FD = cast<FieldDecl>(ME->getMemberDecl());
18672 
18673     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
18674     //  A bit-field cannot appear in a map clause.
18675     //
18676     if (FD->isBitField()) {
18677       if (!NoDiagnose) {
18678         SemaRef.Diag(ELoc, diag::err_omp_bit_fields_forbidden_in_clause)
18679           << ME->getSourceRange() << getOpenMPClauseName(CKind);
18680         return false;
18681       }
18682       if (RelevantExpr)
18683         return false;
18684       return Visit(E);
18685     }
18686 
18687     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
18688     //  If the type of a list item is a reference to a type T then the type
18689     //  will be considered to be T for all purposes of this clause.
18690     QualType CurType = BaseE->getType().getNonReferenceType();
18691 
18692     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.2]
18693     //  A list item cannot be a variable that is a member of a structure with
18694     //  a union type.
18695     //
18696     if (CurType->isUnionType()) {
18697       if (!NoDiagnose) {
18698         SemaRef.Diag(ELoc, diag::err_omp_union_type_not_allowed)
18699           << ME->getSourceRange();
18700         return false;
18701       }
18702       return RelevantExpr || Visit(E);
18703     }
18704 
18705     // If we got a member expression, we should not expect any array section
18706     // before that:
18707     //
18708     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.7]
18709     //  If a list item is an element of a structure, only the rightmost symbol
18710     //  of the variable reference can be an array section.
18711     //
18712     AllowUnitySizeArraySection = false;
18713     AllowWholeSizeArraySection = false;
18714 
18715     // Record the component.
18716     Components.emplace_back(ME, FD, IsNonContiguous);
18717     return RelevantExpr || Visit(E);
18718   }
18719 
18720   bool VisitArraySubscriptExpr(ArraySubscriptExpr *AE) {
18721     Expr *E = AE->getBase()->IgnoreParenImpCasts();
18722 
18723     if (!E->getType()->isAnyPointerType() && !E->getType()->isArrayType()) {
18724       if (!NoDiagnose) {
18725         SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
18726           << 0 << AE->getSourceRange();
18727         return false;
18728       }
18729       return RelevantExpr || Visit(E);
18730     }
18731 
18732     // If we got an array subscript that express the whole dimension we
18733     // can have any array expressions before. If it only expressing part of
18734     // the dimension, we can only have unitary-size array expressions.
18735     if (checkArrayExpressionDoesNotReferToWholeSize(SemaRef, AE,
18736                                                     E->getType()))
18737       AllowWholeSizeArraySection = false;
18738 
18739     if (const auto *TE = dyn_cast<CXXThisExpr>(E->IgnoreParenCasts())) {
18740       Expr::EvalResult Result;
18741       if (!AE->getIdx()->isValueDependent() &&
18742           AE->getIdx()->EvaluateAsInt(Result, SemaRef.getASTContext()) &&
18743           !Result.Val.getInt().isNullValue()) {
18744         SemaRef.Diag(AE->getIdx()->getExprLoc(),
18745                      diag::err_omp_invalid_map_this_expr);
18746         SemaRef.Diag(AE->getIdx()->getExprLoc(),
18747                      diag::note_omp_invalid_subscript_on_this_ptr_map);
18748       }
18749       assert(!RelevantExpr && "RelevantExpr is expected to be nullptr");
18750       RelevantExpr = TE;
18751     }
18752 
18753     // Record the component - we don't have any declaration associated.
18754     Components.emplace_back(AE, nullptr, IsNonContiguous);
18755 
18756     return RelevantExpr || Visit(E);
18757   }
18758 
18759   bool VisitOMPArraySectionExpr(OMPArraySectionExpr *OASE) {
18760     // After OMP 5.0  Array section in reduction clause will be implicitly
18761     // mapped
18762     assert(!(SemaRef.getLangOpts().OpenMP < 50 && NoDiagnose) &&
18763            "Array sections cannot be implicitly mapped.");
18764     Expr *E = OASE->getBase()->IgnoreParenImpCasts();
18765     QualType CurType =
18766       OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
18767 
18768     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
18769     //  If the type of a list item is a reference to a type T then the type
18770     //  will be considered to be T for all purposes of this clause.
18771     if (CurType->isReferenceType())
18772       CurType = CurType->getPointeeType();
18773 
18774     bool IsPointer = CurType->isAnyPointerType();
18775 
18776     if (!IsPointer && !CurType->isArrayType()) {
18777       SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
18778         << 0 << OASE->getSourceRange();
18779       return false;
18780     }
18781 
18782     bool NotWhole =
18783       checkArrayExpressionDoesNotReferToWholeSize(SemaRef, OASE, CurType);
18784     bool NotUnity =
18785       checkArrayExpressionDoesNotReferToUnitySize(SemaRef, OASE, CurType);
18786 
18787     if (AllowWholeSizeArraySection) {
18788       // Any array section is currently allowed. Allowing a whole size array
18789       // section implies allowing a unity array section as well.
18790       //
18791       // If this array section refers to the whole dimension we can still
18792       // accept other array sections before this one, except if the base is a
18793       // pointer. Otherwise, only unitary sections are accepted.
18794       if (NotWhole || IsPointer)
18795         AllowWholeSizeArraySection = false;
18796     } else if (DKind == OMPD_target_update &&
18797                SemaRef.getLangOpts().OpenMP >= 50) {
18798       if (IsPointer && !AllowAnotherPtr)
18799         SemaRef.Diag(ELoc, diag::err_omp_section_length_undefined)
18800             << /*array of unknown bound */ 1;
18801       else
18802         IsNonContiguous = true;
18803     } else if (AllowUnitySizeArraySection && NotUnity) {
18804       // A unity or whole array section is not allowed and that is not
18805       // compatible with the properties of the current array section.
18806       if (NoDiagnose)
18807         return false;
18808       SemaRef.Diag(
18809         ELoc, diag::err_array_section_does_not_specify_contiguous_storage)
18810         << OASE->getSourceRange();
18811       return false;
18812     }
18813 
18814     if (IsPointer)
18815       AllowAnotherPtr = false;
18816 
18817     if (const auto *TE = dyn_cast<CXXThisExpr>(E)) {
18818       Expr::EvalResult ResultR;
18819       Expr::EvalResult ResultL;
18820       if (!OASE->getLength()->isValueDependent() &&
18821           OASE->getLength()->EvaluateAsInt(ResultR, SemaRef.getASTContext()) &&
18822           !ResultR.Val.getInt().isOneValue()) {
18823         SemaRef.Diag(OASE->getLength()->getExprLoc(),
18824                      diag::err_omp_invalid_map_this_expr);
18825         SemaRef.Diag(OASE->getLength()->getExprLoc(),
18826                      diag::note_omp_invalid_length_on_this_ptr_mapping);
18827       }
18828       if (OASE->getLowerBound() && !OASE->getLowerBound()->isValueDependent() &&
18829           OASE->getLowerBound()->EvaluateAsInt(ResultL,
18830                                                SemaRef.getASTContext()) &&
18831           !ResultL.Val.getInt().isNullValue()) {
18832         SemaRef.Diag(OASE->getLowerBound()->getExprLoc(),
18833                      diag::err_omp_invalid_map_this_expr);
18834         SemaRef.Diag(OASE->getLowerBound()->getExprLoc(),
18835                      diag::note_omp_invalid_lower_bound_on_this_ptr_mapping);
18836       }
18837       assert(!RelevantExpr && "RelevantExpr is expected to be nullptr");
18838       RelevantExpr = TE;
18839     }
18840 
18841     // Record the component - we don't have any declaration associated.
18842     Components.emplace_back(OASE, nullptr, /*IsNonContiguous=*/false);
18843     return RelevantExpr || Visit(E);
18844   }
18845   bool VisitOMPArrayShapingExpr(OMPArrayShapingExpr *E) {
18846     Expr *Base = E->getBase();
18847 
18848     // Record the component - we don't have any declaration associated.
18849     Components.emplace_back(E, nullptr, IsNonContiguous);
18850 
18851     return Visit(Base->IgnoreParenImpCasts());
18852   }
18853 
18854   bool VisitUnaryOperator(UnaryOperator *UO) {
18855     if (SemaRef.getLangOpts().OpenMP < 50 || !UO->isLValue() ||
18856         UO->getOpcode() != UO_Deref) {
18857       emitErrorMsg();
18858       return false;
18859     }
18860     if (!RelevantExpr) {
18861       // Record the component if haven't found base decl.
18862       Components.emplace_back(UO, nullptr, /*IsNonContiguous=*/false);
18863     }
18864     return RelevantExpr || Visit(UO->getSubExpr()->IgnoreParenImpCasts());
18865   }
18866   bool VisitBinaryOperator(BinaryOperator *BO) {
18867     if (SemaRef.getLangOpts().OpenMP < 50 || !BO->getType()->isPointerType()) {
18868       emitErrorMsg();
18869       return false;
18870     }
18871 
18872     // Pointer arithmetic is the only thing we expect to happen here so after we
18873     // make sure the binary operator is a pointer type, the we only thing need
18874     // to to is to visit the subtree that has the same type as root (so that we
18875     // know the other subtree is just an offset)
18876     Expr *LE = BO->getLHS()->IgnoreParenImpCasts();
18877     Expr *RE = BO->getRHS()->IgnoreParenImpCasts();
18878     Components.emplace_back(BO, nullptr, false);
18879     assert((LE->getType().getTypePtr() == BO->getType().getTypePtr() ||
18880             RE->getType().getTypePtr() == BO->getType().getTypePtr()) &&
18881            "Either LHS or RHS have base decl inside");
18882     if (BO->getType().getTypePtr() == LE->getType().getTypePtr())
18883       return RelevantExpr || Visit(LE);
18884     return RelevantExpr || Visit(RE);
18885   }
18886   bool VisitCXXThisExpr(CXXThisExpr *CTE) {
18887     assert(!RelevantExpr && "RelevantExpr is expected to be nullptr");
18888     RelevantExpr = CTE;
18889     Components.emplace_back(CTE, nullptr, IsNonContiguous);
18890     return true;
18891   }
18892   bool VisitCXXOperatorCallExpr(CXXOperatorCallExpr *COCE) {
18893     assert(!RelevantExpr && "RelevantExpr is expected to be nullptr");
18894     Components.emplace_back(COCE, nullptr, IsNonContiguous);
18895     return true;
18896   }
18897   bool VisitOpaqueValueExpr(OpaqueValueExpr *E) {
18898     Expr *Source = E->getSourceExpr();
18899     if (!Source) {
18900       emitErrorMsg();
18901       return false;
18902     }
18903     return Visit(Source);
18904   }
18905   bool VisitStmt(Stmt *) {
18906     emitErrorMsg();
18907     return false;
18908   }
18909   const Expr *getFoundBase() const {
18910     return RelevantExpr;
18911   }
18912   explicit MapBaseChecker(
18913       Sema &SemaRef, OpenMPClauseKind CKind, OpenMPDirectiveKind DKind,
18914       OMPClauseMappableExprCommon::MappableExprComponentList &Components,
18915       bool NoDiagnose, SourceLocation &ELoc, SourceRange &ERange)
18916       : SemaRef(SemaRef), CKind(CKind), DKind(DKind), Components(Components),
18917         NoDiagnose(NoDiagnose), ELoc(ELoc), ERange(ERange) {}
18918 };
18919 } // namespace
18920 
18921 /// Return the expression of the base of the mappable expression or null if it
18922 /// cannot be determined and do all the necessary checks to see if the expression
18923 /// is valid as a standalone mappable expression. In the process, record all the
18924 /// components of the expression.
18925 static const Expr *checkMapClauseExpressionBase(
18926     Sema &SemaRef, Expr *E,
18927     OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
18928     OpenMPClauseKind CKind, OpenMPDirectiveKind DKind, bool NoDiagnose) {
18929   SourceLocation ELoc = E->getExprLoc();
18930   SourceRange ERange = E->getSourceRange();
18931   MapBaseChecker Checker(SemaRef, CKind, DKind, CurComponents, NoDiagnose, ELoc,
18932                          ERange);
18933   if (Checker.Visit(E->IgnoreParens())) {
18934     // Check if the highest dimension array section has length specified
18935     if (SemaRef.getLangOpts().OpenMP >= 50 && !CurComponents.empty() &&
18936         (CKind == OMPC_to || CKind == OMPC_from)) {
18937       auto CI = CurComponents.rbegin();
18938       auto CE = CurComponents.rend();
18939       for (; CI != CE; ++CI) {
18940         const auto *OASE =
18941             dyn_cast<OMPArraySectionExpr>(CI->getAssociatedExpression());
18942         if (!OASE)
18943           continue;
18944         if (OASE && OASE->getLength())
18945           break;
18946         SemaRef.Diag(ELoc, diag::err_array_section_does_not_specify_length)
18947             << ERange;
18948       }
18949     }
18950     return Checker.getFoundBase();
18951   }
18952   return nullptr;
18953 }
18954 
18955 // Return true if expression E associated with value VD has conflicts with other
18956 // map information.
18957 static bool checkMapConflicts(
18958     Sema &SemaRef, DSAStackTy *DSAS, const ValueDecl *VD, const Expr *E,
18959     bool CurrentRegionOnly,
18960     OMPClauseMappableExprCommon::MappableExprComponentListRef CurComponents,
18961     OpenMPClauseKind CKind) {
18962   assert(VD && E);
18963   SourceLocation ELoc = E->getExprLoc();
18964   SourceRange ERange = E->getSourceRange();
18965 
18966   // In order to easily check the conflicts we need to match each component of
18967   // the expression under test with the components of the expressions that are
18968   // already in the stack.
18969 
18970   assert(!CurComponents.empty() && "Map clause expression with no components!");
18971   assert(CurComponents.back().getAssociatedDeclaration() == VD &&
18972          "Map clause expression with unexpected base!");
18973 
18974   // Variables to help detecting enclosing problems in data environment nests.
18975   bool IsEnclosedByDataEnvironmentExpr = false;
18976   const Expr *EnclosingExpr = nullptr;
18977 
18978   bool FoundError = DSAS->checkMappableExprComponentListsForDecl(
18979       VD, CurrentRegionOnly,
18980       [&IsEnclosedByDataEnvironmentExpr, &SemaRef, VD, CurrentRegionOnly, ELoc,
18981        ERange, CKind, &EnclosingExpr,
18982        CurComponents](OMPClauseMappableExprCommon::MappableExprComponentListRef
18983                           StackComponents,
18984                       OpenMPClauseKind Kind) {
18985         if (CKind == Kind && SemaRef.LangOpts.OpenMP >= 50)
18986           return false;
18987         assert(!StackComponents.empty() &&
18988                "Map clause expression with no components!");
18989         assert(StackComponents.back().getAssociatedDeclaration() == VD &&
18990                "Map clause expression with unexpected base!");
18991         (void)VD;
18992 
18993         // The whole expression in the stack.
18994         const Expr *RE = StackComponents.front().getAssociatedExpression();
18995 
18996         // Expressions must start from the same base. Here we detect at which
18997         // point both expressions diverge from each other and see if we can
18998         // detect if the memory referred to both expressions is contiguous and
18999         // do not overlap.
19000         auto CI = CurComponents.rbegin();
19001         auto CE = CurComponents.rend();
19002         auto SI = StackComponents.rbegin();
19003         auto SE = StackComponents.rend();
19004         for (; CI != CE && SI != SE; ++CI, ++SI) {
19005 
19006           // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.3]
19007           //  At most one list item can be an array item derived from a given
19008           //  variable in map clauses of the same construct.
19009           if (CurrentRegionOnly &&
19010               (isa<ArraySubscriptExpr>(CI->getAssociatedExpression()) ||
19011                isa<OMPArraySectionExpr>(CI->getAssociatedExpression()) ||
19012                isa<OMPArrayShapingExpr>(CI->getAssociatedExpression())) &&
19013               (isa<ArraySubscriptExpr>(SI->getAssociatedExpression()) ||
19014                isa<OMPArraySectionExpr>(SI->getAssociatedExpression()) ||
19015                isa<OMPArrayShapingExpr>(SI->getAssociatedExpression()))) {
19016             SemaRef.Diag(CI->getAssociatedExpression()->getExprLoc(),
19017                          diag::err_omp_multiple_array_items_in_map_clause)
19018                 << CI->getAssociatedExpression()->getSourceRange();
19019             SemaRef.Diag(SI->getAssociatedExpression()->getExprLoc(),
19020                          diag::note_used_here)
19021                 << SI->getAssociatedExpression()->getSourceRange();
19022             return true;
19023           }
19024 
19025           // Do both expressions have the same kind?
19026           if (CI->getAssociatedExpression()->getStmtClass() !=
19027               SI->getAssociatedExpression()->getStmtClass())
19028             break;
19029 
19030           // Are we dealing with different variables/fields?
19031           if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration())
19032             break;
19033         }
19034         // Check if the extra components of the expressions in the enclosing
19035         // data environment are redundant for the current base declaration.
19036         // If they are, the maps completely overlap, which is legal.
19037         for (; SI != SE; ++SI) {
19038           QualType Type;
19039           if (const auto *ASE =
19040                   dyn_cast<ArraySubscriptExpr>(SI->getAssociatedExpression())) {
19041             Type = ASE->getBase()->IgnoreParenImpCasts()->getType();
19042           } else if (const auto *OASE = dyn_cast<OMPArraySectionExpr>(
19043                          SI->getAssociatedExpression())) {
19044             const Expr *E = OASE->getBase()->IgnoreParenImpCasts();
19045             Type =
19046                 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
19047           } else if (const auto *OASE = dyn_cast<OMPArrayShapingExpr>(
19048                          SI->getAssociatedExpression())) {
19049             Type = OASE->getBase()->getType()->getPointeeType();
19050           }
19051           if (Type.isNull() || Type->isAnyPointerType() ||
19052               checkArrayExpressionDoesNotReferToWholeSize(
19053                   SemaRef, SI->getAssociatedExpression(), Type))
19054             break;
19055         }
19056 
19057         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
19058         //  List items of map clauses in the same construct must not share
19059         //  original storage.
19060         //
19061         // If the expressions are exactly the same or one is a subset of the
19062         // other, it means they are sharing storage.
19063         if (CI == CE && SI == SE) {
19064           if (CurrentRegionOnly) {
19065             if (CKind == OMPC_map) {
19066               SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
19067             } else {
19068               assert(CKind == OMPC_to || CKind == OMPC_from);
19069               SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
19070                   << ERange;
19071             }
19072             SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
19073                 << RE->getSourceRange();
19074             return true;
19075           }
19076           // If we find the same expression in the enclosing data environment,
19077           // that is legal.
19078           IsEnclosedByDataEnvironmentExpr = true;
19079           return false;
19080         }
19081 
19082         QualType DerivedType =
19083             std::prev(CI)->getAssociatedDeclaration()->getType();
19084         SourceLocation DerivedLoc =
19085             std::prev(CI)->getAssociatedExpression()->getExprLoc();
19086 
19087         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
19088         //  If the type of a list item is a reference to a type T then the type
19089         //  will be considered to be T for all purposes of this clause.
19090         DerivedType = DerivedType.getNonReferenceType();
19091 
19092         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.1]
19093         //  A variable for which the type is pointer and an array section
19094         //  derived from that variable must not appear as list items of map
19095         //  clauses of the same construct.
19096         //
19097         // Also, cover one of the cases in:
19098         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
19099         //  If any part of the original storage of a list item has corresponding
19100         //  storage in the device data environment, all of the original storage
19101         //  must have corresponding storage in the device data environment.
19102         //
19103         if (DerivedType->isAnyPointerType()) {
19104           if (CI == CE || SI == SE) {
19105             SemaRef.Diag(
19106                 DerivedLoc,
19107                 diag::err_omp_pointer_mapped_along_with_derived_section)
19108                 << DerivedLoc;
19109             SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
19110                 << RE->getSourceRange();
19111             return true;
19112           }
19113           if (CI->getAssociatedExpression()->getStmtClass() !=
19114                          SI->getAssociatedExpression()->getStmtClass() ||
19115                      CI->getAssociatedDeclaration()->getCanonicalDecl() ==
19116                          SI->getAssociatedDeclaration()->getCanonicalDecl()) {
19117             assert(CI != CE && SI != SE);
19118             SemaRef.Diag(DerivedLoc, diag::err_omp_same_pointer_dereferenced)
19119                 << DerivedLoc;
19120             SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
19121                 << RE->getSourceRange();
19122             return true;
19123           }
19124         }
19125 
19126         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
19127         //  List items of map clauses in the same construct must not share
19128         //  original storage.
19129         //
19130         // An expression is a subset of the other.
19131         if (CurrentRegionOnly && (CI == CE || SI == SE)) {
19132           if (CKind == OMPC_map) {
19133             if (CI != CE || SI != SE) {
19134               // Allow constructs like this: map(s, s.ptr[0:1]), where s.ptr is
19135               // a pointer.
19136               auto Begin =
19137                   CI != CE ? CurComponents.begin() : StackComponents.begin();
19138               auto End = CI != CE ? CurComponents.end() : StackComponents.end();
19139               auto It = Begin;
19140               while (It != End && !It->getAssociatedDeclaration())
19141                 std::advance(It, 1);
19142               assert(It != End &&
19143                      "Expected at least one component with the declaration.");
19144               if (It != Begin && It->getAssociatedDeclaration()
19145                                      ->getType()
19146                                      .getCanonicalType()
19147                                      ->isAnyPointerType()) {
19148                 IsEnclosedByDataEnvironmentExpr = false;
19149                 EnclosingExpr = nullptr;
19150                 return false;
19151               }
19152             }
19153             SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
19154           } else {
19155             assert(CKind == OMPC_to || CKind == OMPC_from);
19156             SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
19157                 << ERange;
19158           }
19159           SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
19160               << RE->getSourceRange();
19161           return true;
19162         }
19163 
19164         // The current expression uses the same base as other expression in the
19165         // data environment but does not contain it completely.
19166         if (!CurrentRegionOnly && SI != SE)
19167           EnclosingExpr = RE;
19168 
19169         // The current expression is a subset of the expression in the data
19170         // environment.
19171         IsEnclosedByDataEnvironmentExpr |=
19172             (!CurrentRegionOnly && CI != CE && SI == SE);
19173 
19174         return false;
19175       });
19176 
19177   if (CurrentRegionOnly)
19178     return FoundError;
19179 
19180   // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
19181   //  If any part of the original storage of a list item has corresponding
19182   //  storage in the device data environment, all of the original storage must
19183   //  have corresponding storage in the device data environment.
19184   // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.6]
19185   //  If a list item is an element of a structure, and a different element of
19186   //  the structure has a corresponding list item in the device data environment
19187   //  prior to a task encountering the construct associated with the map clause,
19188   //  then the list item must also have a corresponding list item in the device
19189   //  data environment prior to the task encountering the construct.
19190   //
19191   if (EnclosingExpr && !IsEnclosedByDataEnvironmentExpr) {
19192     SemaRef.Diag(ELoc,
19193                  diag::err_omp_original_storage_is_shared_and_does_not_contain)
19194         << ERange;
19195     SemaRef.Diag(EnclosingExpr->getExprLoc(), diag::note_used_here)
19196         << EnclosingExpr->getSourceRange();
19197     return true;
19198   }
19199 
19200   return FoundError;
19201 }
19202 
19203 // Look up the user-defined mapper given the mapper name and mapped type, and
19204 // build a reference to it.
19205 static ExprResult buildUserDefinedMapperRef(Sema &SemaRef, Scope *S,
19206                                             CXXScopeSpec &MapperIdScopeSpec,
19207                                             const DeclarationNameInfo &MapperId,
19208                                             QualType Type,
19209                                             Expr *UnresolvedMapper) {
19210   if (MapperIdScopeSpec.isInvalid())
19211     return ExprError();
19212   // Get the actual type for the array type.
19213   if (Type->isArrayType()) {
19214     assert(Type->getAsArrayTypeUnsafe() && "Expect to get a valid array type");
19215     Type = Type->getAsArrayTypeUnsafe()->getElementType().getCanonicalType();
19216   }
19217   // Find all user-defined mappers with the given MapperId.
19218   SmallVector<UnresolvedSet<8>, 4> Lookups;
19219   LookupResult Lookup(SemaRef, MapperId, Sema::LookupOMPMapperName);
19220   Lookup.suppressDiagnostics();
19221   if (S) {
19222     while (S && SemaRef.LookupParsedName(Lookup, S, &MapperIdScopeSpec)) {
19223       NamedDecl *D = Lookup.getRepresentativeDecl();
19224       while (S && !S->isDeclScope(D))
19225         S = S->getParent();
19226       if (S)
19227         S = S->getParent();
19228       Lookups.emplace_back();
19229       Lookups.back().append(Lookup.begin(), Lookup.end());
19230       Lookup.clear();
19231     }
19232   } else if (auto *ULE = cast_or_null<UnresolvedLookupExpr>(UnresolvedMapper)) {
19233     // Extract the user-defined mappers with the given MapperId.
19234     Lookups.push_back(UnresolvedSet<8>());
19235     for (NamedDecl *D : ULE->decls()) {
19236       auto *DMD = cast<OMPDeclareMapperDecl>(D);
19237       assert(DMD && "Expect valid OMPDeclareMapperDecl during instantiation.");
19238       Lookups.back().addDecl(DMD);
19239     }
19240   }
19241   // Defer the lookup for dependent types. The results will be passed through
19242   // UnresolvedMapper on instantiation.
19243   if (SemaRef.CurContext->isDependentContext() || Type->isDependentType() ||
19244       Type->isInstantiationDependentType() ||
19245       Type->containsUnexpandedParameterPack() ||
19246       filterLookupForUDReductionAndMapper<bool>(Lookups, [](ValueDecl *D) {
19247         return !D->isInvalidDecl() &&
19248                (D->getType()->isDependentType() ||
19249                 D->getType()->isInstantiationDependentType() ||
19250                 D->getType()->containsUnexpandedParameterPack());
19251       })) {
19252     UnresolvedSet<8> URS;
19253     for (const UnresolvedSet<8> &Set : Lookups) {
19254       if (Set.empty())
19255         continue;
19256       URS.append(Set.begin(), Set.end());
19257     }
19258     return UnresolvedLookupExpr::Create(
19259         SemaRef.Context, /*NamingClass=*/nullptr,
19260         MapperIdScopeSpec.getWithLocInContext(SemaRef.Context), MapperId,
19261         /*ADL=*/false, /*Overloaded=*/true, URS.begin(), URS.end());
19262   }
19263   SourceLocation Loc = MapperId.getLoc();
19264   // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
19265   //  The type must be of struct, union or class type in C and C++
19266   if (!Type->isStructureOrClassType() && !Type->isUnionType() &&
19267       (MapperIdScopeSpec.isSet() || MapperId.getAsString() != "default")) {
19268     SemaRef.Diag(Loc, diag::err_omp_mapper_wrong_type);
19269     return ExprError();
19270   }
19271   // Perform argument dependent lookup.
19272   if (SemaRef.getLangOpts().CPlusPlus && !MapperIdScopeSpec.isSet())
19273     argumentDependentLookup(SemaRef, MapperId, Loc, Type, Lookups);
19274   // Return the first user-defined mapper with the desired type.
19275   if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
19276           Lookups, [&SemaRef, Type](ValueDecl *D) -> ValueDecl * {
19277             if (!D->isInvalidDecl() &&
19278                 SemaRef.Context.hasSameType(D->getType(), Type))
19279               return D;
19280             return nullptr;
19281           }))
19282     return SemaRef.BuildDeclRefExpr(VD, Type, VK_LValue, Loc);
19283   // Find the first user-defined mapper with a type derived from the desired
19284   // type.
19285   if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
19286           Lookups, [&SemaRef, Type, Loc](ValueDecl *D) -> ValueDecl * {
19287             if (!D->isInvalidDecl() &&
19288                 SemaRef.IsDerivedFrom(Loc, Type, D->getType()) &&
19289                 !Type.isMoreQualifiedThan(D->getType()))
19290               return D;
19291             return nullptr;
19292           })) {
19293     CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
19294                        /*DetectVirtual=*/false);
19295     if (SemaRef.IsDerivedFrom(Loc, Type, VD->getType(), Paths)) {
19296       if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
19297               VD->getType().getUnqualifiedType()))) {
19298         if (SemaRef.CheckBaseClassAccess(
19299                 Loc, VD->getType(), Type, Paths.front(),
19300                 /*DiagID=*/0) != Sema::AR_inaccessible) {
19301           return SemaRef.BuildDeclRefExpr(VD, Type, VK_LValue, Loc);
19302         }
19303       }
19304     }
19305   }
19306   // Report error if a mapper is specified, but cannot be found.
19307   if (MapperIdScopeSpec.isSet() || MapperId.getAsString() != "default") {
19308     SemaRef.Diag(Loc, diag::err_omp_invalid_mapper)
19309         << Type << MapperId.getName();
19310     return ExprError();
19311   }
19312   return ExprEmpty();
19313 }
19314 
19315 namespace {
19316 // Utility struct that gathers all the related lists associated with a mappable
19317 // expression.
19318 struct MappableVarListInfo {
19319   // The list of expressions.
19320   ArrayRef<Expr *> VarList;
19321   // The list of processed expressions.
19322   SmallVector<Expr *, 16> ProcessedVarList;
19323   // The mappble components for each expression.
19324   OMPClauseMappableExprCommon::MappableExprComponentLists VarComponents;
19325   // The base declaration of the variable.
19326   SmallVector<ValueDecl *, 16> VarBaseDeclarations;
19327   // The reference to the user-defined mapper associated with every expression.
19328   SmallVector<Expr *, 16> UDMapperList;
19329 
19330   MappableVarListInfo(ArrayRef<Expr *> VarList) : VarList(VarList) {
19331     // We have a list of components and base declarations for each entry in the
19332     // variable list.
19333     VarComponents.reserve(VarList.size());
19334     VarBaseDeclarations.reserve(VarList.size());
19335   }
19336 };
19337 }
19338 
19339 // Check the validity of the provided variable list for the provided clause kind
19340 // \a CKind. In the check process the valid expressions, mappable expression
19341 // components, variables, and user-defined mappers are extracted and used to
19342 // fill \a ProcessedVarList, \a VarComponents, \a VarBaseDeclarations, and \a
19343 // UDMapperList in MVLI. \a MapType, \a IsMapTypeImplicit, \a MapperIdScopeSpec,
19344 // and \a MapperId are expected to be valid if the clause kind is 'map'.
19345 static void checkMappableExpressionList(
19346     Sema &SemaRef, DSAStackTy *DSAS, OpenMPClauseKind CKind,
19347     MappableVarListInfo &MVLI, SourceLocation StartLoc,
19348     CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo MapperId,
19349     ArrayRef<Expr *> UnresolvedMappers,
19350     OpenMPMapClauseKind MapType = OMPC_MAP_unknown,
19351     bool IsMapTypeImplicit = false, bool NoDiagnose = false) {
19352   // We only expect mappable expressions in 'to', 'from', and 'map' clauses.
19353   assert((CKind == OMPC_map || CKind == OMPC_to || CKind == OMPC_from) &&
19354          "Unexpected clause kind with mappable expressions!");
19355 
19356   // If the identifier of user-defined mapper is not specified, it is "default".
19357   // We do not change the actual name in this clause to distinguish whether a
19358   // mapper is specified explicitly, i.e., it is not explicitly specified when
19359   // MapperId.getName() is empty.
19360   if (!MapperId.getName() || MapperId.getName().isEmpty()) {
19361     auto &DeclNames = SemaRef.getASTContext().DeclarationNames;
19362     MapperId.setName(DeclNames.getIdentifier(
19363         &SemaRef.getASTContext().Idents.get("default")));
19364     MapperId.setLoc(StartLoc);
19365   }
19366 
19367   // Iterators to find the current unresolved mapper expression.
19368   auto UMIt = UnresolvedMappers.begin(), UMEnd = UnresolvedMappers.end();
19369   bool UpdateUMIt = false;
19370   Expr *UnresolvedMapper = nullptr;
19371 
19372   // Keep track of the mappable components and base declarations in this clause.
19373   // Each entry in the list is going to have a list of components associated. We
19374   // record each set of the components so that we can build the clause later on.
19375   // In the end we should have the same amount of declarations and component
19376   // lists.
19377 
19378   for (Expr *RE : MVLI.VarList) {
19379     assert(RE && "Null expr in omp to/from/map clause");
19380     SourceLocation ELoc = RE->getExprLoc();
19381 
19382     // Find the current unresolved mapper expression.
19383     if (UpdateUMIt && UMIt != UMEnd) {
19384       UMIt++;
19385       assert(
19386           UMIt != UMEnd &&
19387           "Expect the size of UnresolvedMappers to match with that of VarList");
19388     }
19389     UpdateUMIt = true;
19390     if (UMIt != UMEnd)
19391       UnresolvedMapper = *UMIt;
19392 
19393     const Expr *VE = RE->IgnoreParenLValueCasts();
19394 
19395     if (VE->isValueDependent() || VE->isTypeDependent() ||
19396         VE->isInstantiationDependent() ||
19397         VE->containsUnexpandedParameterPack()) {
19398       // Try to find the associated user-defined mapper.
19399       ExprResult ER = buildUserDefinedMapperRef(
19400           SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
19401           VE->getType().getCanonicalType(), UnresolvedMapper);
19402       if (ER.isInvalid())
19403         continue;
19404       MVLI.UDMapperList.push_back(ER.get());
19405       // We can only analyze this information once the missing information is
19406       // resolved.
19407       MVLI.ProcessedVarList.push_back(RE);
19408       continue;
19409     }
19410 
19411     Expr *SimpleExpr = RE->IgnoreParenCasts();
19412 
19413     if (!RE->isLValue()) {
19414       if (SemaRef.getLangOpts().OpenMP < 50) {
19415         SemaRef.Diag(
19416             ELoc, diag::err_omp_expected_named_var_member_or_array_expression)
19417             << RE->getSourceRange();
19418       } else {
19419         SemaRef.Diag(ELoc, diag::err_omp_non_lvalue_in_map_or_motion_clauses)
19420             << getOpenMPClauseName(CKind) << RE->getSourceRange();
19421       }
19422       continue;
19423     }
19424 
19425     OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
19426     ValueDecl *CurDeclaration = nullptr;
19427 
19428     // Obtain the array or member expression bases if required. Also, fill the
19429     // components array with all the components identified in the process.
19430     const Expr *BE =
19431         checkMapClauseExpressionBase(SemaRef, SimpleExpr, CurComponents, CKind,
19432                                      DSAS->getCurrentDirective(), NoDiagnose);
19433     if (!BE)
19434       continue;
19435 
19436     assert(!CurComponents.empty() &&
19437            "Invalid mappable expression information.");
19438 
19439     if (const auto *TE = dyn_cast<CXXThisExpr>(BE)) {
19440       // Add store "this" pointer to class in DSAStackTy for future checking
19441       DSAS->addMappedClassesQualTypes(TE->getType());
19442       // Try to find the associated user-defined mapper.
19443       ExprResult ER = buildUserDefinedMapperRef(
19444           SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
19445           VE->getType().getCanonicalType(), UnresolvedMapper);
19446       if (ER.isInvalid())
19447         continue;
19448       MVLI.UDMapperList.push_back(ER.get());
19449       // Skip restriction checking for variable or field declarations
19450       MVLI.ProcessedVarList.push_back(RE);
19451       MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
19452       MVLI.VarComponents.back().append(CurComponents.begin(),
19453                                        CurComponents.end());
19454       MVLI.VarBaseDeclarations.push_back(nullptr);
19455       continue;
19456     }
19457 
19458     // For the following checks, we rely on the base declaration which is
19459     // expected to be associated with the last component. The declaration is
19460     // expected to be a variable or a field (if 'this' is being mapped).
19461     CurDeclaration = CurComponents.back().getAssociatedDeclaration();
19462     assert(CurDeclaration && "Null decl on map clause.");
19463     assert(
19464         CurDeclaration->isCanonicalDecl() &&
19465         "Expecting components to have associated only canonical declarations.");
19466 
19467     auto *VD = dyn_cast<VarDecl>(CurDeclaration);
19468     const auto *FD = dyn_cast<FieldDecl>(CurDeclaration);
19469 
19470     assert((VD || FD) && "Only variables or fields are expected here!");
19471     (void)FD;
19472 
19473     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.10]
19474     // threadprivate variables cannot appear in a map clause.
19475     // OpenMP 4.5 [2.10.5, target update Construct]
19476     // threadprivate variables cannot appear in a from clause.
19477     if (VD && DSAS->isThreadPrivate(VD)) {
19478       if (NoDiagnose)
19479         continue;
19480       DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false);
19481       SemaRef.Diag(ELoc, diag::err_omp_threadprivate_in_clause)
19482           << getOpenMPClauseName(CKind);
19483       reportOriginalDsa(SemaRef, DSAS, VD, DVar);
19484       continue;
19485     }
19486 
19487     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
19488     //  A list item cannot appear in both a map clause and a data-sharing
19489     //  attribute clause on the same construct.
19490 
19491     // Check conflicts with other map clause expressions. We check the conflicts
19492     // with the current construct separately from the enclosing data
19493     // environment, because the restrictions are different. We only have to
19494     // check conflicts across regions for the map clauses.
19495     if (checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
19496                           /*CurrentRegionOnly=*/true, CurComponents, CKind))
19497       break;
19498     if (CKind == OMPC_map &&
19499         (SemaRef.getLangOpts().OpenMP <= 45 || StartLoc.isValid()) &&
19500         checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
19501                           /*CurrentRegionOnly=*/false, CurComponents, CKind))
19502       break;
19503 
19504     // OpenMP 4.5 [2.10.5, target update Construct]
19505     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
19506     //  If the type of a list item is a reference to a type T then the type will
19507     //  be considered to be T for all purposes of this clause.
19508     auto I = llvm::find_if(
19509         CurComponents,
19510         [](const OMPClauseMappableExprCommon::MappableComponent &MC) {
19511           return MC.getAssociatedDeclaration();
19512         });
19513     assert(I != CurComponents.end() && "Null decl on map clause.");
19514     (void)I;
19515     QualType Type;
19516     auto *ASE = dyn_cast<ArraySubscriptExpr>(VE->IgnoreParens());
19517     auto *OASE = dyn_cast<OMPArraySectionExpr>(VE->IgnoreParens());
19518     auto *OAShE = dyn_cast<OMPArrayShapingExpr>(VE->IgnoreParens());
19519     if (ASE) {
19520       Type = ASE->getType().getNonReferenceType();
19521     } else if (OASE) {
19522       QualType BaseType =
19523           OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
19524       if (const auto *ATy = BaseType->getAsArrayTypeUnsafe())
19525         Type = ATy->getElementType();
19526       else
19527         Type = BaseType->getPointeeType();
19528       Type = Type.getNonReferenceType();
19529     } else if (OAShE) {
19530       Type = OAShE->getBase()->getType()->getPointeeType();
19531     } else {
19532       Type = VE->getType();
19533     }
19534 
19535     // OpenMP 4.5 [2.10.5, target update Construct, Restrictions, p.4]
19536     // A list item in a to or from clause must have a mappable type.
19537     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
19538     //  A list item must have a mappable type.
19539     if (!checkTypeMappable(VE->getExprLoc(), VE->getSourceRange(), SemaRef,
19540                            DSAS, Type, /*FullCheck=*/true))
19541       continue;
19542 
19543     if (CKind == OMPC_map) {
19544       // target enter data
19545       // OpenMP [2.10.2, Restrictions, p. 99]
19546       // A map-type must be specified in all map clauses and must be either
19547       // to or alloc.
19548       OpenMPDirectiveKind DKind = DSAS->getCurrentDirective();
19549       if (DKind == OMPD_target_enter_data &&
19550           !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_alloc)) {
19551         SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
19552             << (IsMapTypeImplicit ? 1 : 0)
19553             << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
19554             << getOpenMPDirectiveName(DKind);
19555         continue;
19556       }
19557 
19558       // target exit_data
19559       // OpenMP [2.10.3, Restrictions, p. 102]
19560       // A map-type must be specified in all map clauses and must be either
19561       // from, release, or delete.
19562       if (DKind == OMPD_target_exit_data &&
19563           !(MapType == OMPC_MAP_from || MapType == OMPC_MAP_release ||
19564             MapType == OMPC_MAP_delete)) {
19565         SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
19566             << (IsMapTypeImplicit ? 1 : 0)
19567             << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
19568             << getOpenMPDirectiveName(DKind);
19569         continue;
19570       }
19571 
19572       // target, target data
19573       // OpenMP 5.0 [2.12.2, Restrictions, p. 163]
19574       // OpenMP 5.0 [2.12.5, Restrictions, p. 174]
19575       // A map-type in a map clause must be to, from, tofrom or alloc
19576       if ((DKind == OMPD_target_data ||
19577            isOpenMPTargetExecutionDirective(DKind)) &&
19578           !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_from ||
19579             MapType == OMPC_MAP_tofrom || MapType == OMPC_MAP_alloc)) {
19580         SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
19581             << (IsMapTypeImplicit ? 1 : 0)
19582             << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
19583             << getOpenMPDirectiveName(DKind);
19584         continue;
19585       }
19586 
19587       // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
19588       // A list item cannot appear in both a map clause and a data-sharing
19589       // attribute clause on the same construct
19590       //
19591       // OpenMP 5.0 [2.19.7.1, Restrictions, p.7]
19592       // A list item cannot appear in both a map clause and a data-sharing
19593       // attribute clause on the same construct unless the construct is a
19594       // combined construct.
19595       if (VD && ((SemaRef.LangOpts.OpenMP <= 45 &&
19596                   isOpenMPTargetExecutionDirective(DKind)) ||
19597                  DKind == OMPD_target)) {
19598         DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false);
19599         if (isOpenMPPrivate(DVar.CKind)) {
19600           SemaRef.Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
19601               << getOpenMPClauseName(DVar.CKind)
19602               << getOpenMPClauseName(OMPC_map)
19603               << getOpenMPDirectiveName(DSAS->getCurrentDirective());
19604           reportOriginalDsa(SemaRef, DSAS, CurDeclaration, DVar);
19605           continue;
19606         }
19607       }
19608     }
19609 
19610     // Try to find the associated user-defined mapper.
19611     ExprResult ER = buildUserDefinedMapperRef(
19612         SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
19613         Type.getCanonicalType(), UnresolvedMapper);
19614     if (ER.isInvalid())
19615       continue;
19616     MVLI.UDMapperList.push_back(ER.get());
19617 
19618     // Save the current expression.
19619     MVLI.ProcessedVarList.push_back(RE);
19620 
19621     // Store the components in the stack so that they can be used to check
19622     // against other clauses later on.
19623     DSAS->addMappableExpressionComponents(CurDeclaration, CurComponents,
19624                                           /*WhereFoundClauseKind=*/OMPC_map);
19625 
19626     // Save the components and declaration to create the clause. For purposes of
19627     // the clause creation, any component list that has has base 'this' uses
19628     // null as base declaration.
19629     MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
19630     MVLI.VarComponents.back().append(CurComponents.begin(),
19631                                      CurComponents.end());
19632     MVLI.VarBaseDeclarations.push_back(isa<MemberExpr>(BE) ? nullptr
19633                                                            : CurDeclaration);
19634   }
19635 }
19636 
19637 OMPClause *Sema::ActOnOpenMPMapClause(
19638     ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
19639     ArrayRef<SourceLocation> MapTypeModifiersLoc,
19640     CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo &MapperId,
19641     OpenMPMapClauseKind MapType, bool IsMapTypeImplicit, SourceLocation MapLoc,
19642     SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
19643     const OMPVarListLocTy &Locs, bool NoDiagnose,
19644     ArrayRef<Expr *> UnresolvedMappers) {
19645   OpenMPMapModifierKind Modifiers[] = {
19646       OMPC_MAP_MODIFIER_unknown, OMPC_MAP_MODIFIER_unknown,
19647       OMPC_MAP_MODIFIER_unknown, OMPC_MAP_MODIFIER_unknown};
19648   SourceLocation ModifiersLoc[NumberOfOMPMapClauseModifiers];
19649 
19650   // Process map-type-modifiers, flag errors for duplicate modifiers.
19651   unsigned Count = 0;
19652   for (unsigned I = 0, E = MapTypeModifiers.size(); I < E; ++I) {
19653     if (MapTypeModifiers[I] != OMPC_MAP_MODIFIER_unknown &&
19654         llvm::find(Modifiers, MapTypeModifiers[I]) != std::end(Modifiers)) {
19655       Diag(MapTypeModifiersLoc[I], diag::err_omp_duplicate_map_type_modifier);
19656       continue;
19657     }
19658     assert(Count < NumberOfOMPMapClauseModifiers &&
19659            "Modifiers exceed the allowed number of map type modifiers");
19660     Modifiers[Count] = MapTypeModifiers[I];
19661     ModifiersLoc[Count] = MapTypeModifiersLoc[I];
19662     ++Count;
19663   }
19664 
19665   MappableVarListInfo MVLI(VarList);
19666   checkMappableExpressionList(*this, DSAStack, OMPC_map, MVLI, Locs.StartLoc,
19667                               MapperIdScopeSpec, MapperId, UnresolvedMappers,
19668                               MapType, IsMapTypeImplicit, NoDiagnose);
19669 
19670   // We need to produce a map clause even if we don't have variables so that
19671   // other diagnostics related with non-existing map clauses are accurate.
19672   return OMPMapClause::Create(Context, Locs, MVLI.ProcessedVarList,
19673                               MVLI.VarBaseDeclarations, MVLI.VarComponents,
19674                               MVLI.UDMapperList, Modifiers, ModifiersLoc,
19675                               MapperIdScopeSpec.getWithLocInContext(Context),
19676                               MapperId, MapType, IsMapTypeImplicit, MapLoc);
19677 }
19678 
19679 QualType Sema::ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
19680                                                TypeResult ParsedType) {
19681   assert(ParsedType.isUsable());
19682 
19683   QualType ReductionType = GetTypeFromParser(ParsedType.get());
19684   if (ReductionType.isNull())
19685     return QualType();
19686 
19687   // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions, C\C++
19688   // A type name in a declare reduction directive cannot be a function type, an
19689   // array type, a reference type, or a type qualified with const, volatile or
19690   // restrict.
19691   if (ReductionType.hasQualifiers()) {
19692     Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 0;
19693     return QualType();
19694   }
19695 
19696   if (ReductionType->isFunctionType()) {
19697     Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 1;
19698     return QualType();
19699   }
19700   if (ReductionType->isReferenceType()) {
19701     Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 2;
19702     return QualType();
19703   }
19704   if (ReductionType->isArrayType()) {
19705     Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 3;
19706     return QualType();
19707   }
19708   return ReductionType;
19709 }
19710 
19711 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveStart(
19712     Scope *S, DeclContext *DC, DeclarationName Name,
19713     ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
19714     AccessSpecifier AS, Decl *PrevDeclInScope) {
19715   SmallVector<Decl *, 8> Decls;
19716   Decls.reserve(ReductionTypes.size());
19717 
19718   LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPReductionName,
19719                       forRedeclarationInCurContext());
19720   // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
19721   // A reduction-identifier may not be re-declared in the current scope for the
19722   // same type or for a type that is compatible according to the base language
19723   // rules.
19724   llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
19725   OMPDeclareReductionDecl *PrevDRD = nullptr;
19726   bool InCompoundScope = true;
19727   if (S != nullptr) {
19728     // Find previous declaration with the same name not referenced in other
19729     // declarations.
19730     FunctionScopeInfo *ParentFn = getEnclosingFunction();
19731     InCompoundScope =
19732         (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
19733     LookupName(Lookup, S);
19734     FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
19735                          /*AllowInlineNamespace=*/false);
19736     llvm::DenseMap<OMPDeclareReductionDecl *, bool> UsedAsPrevious;
19737     LookupResult::Filter Filter = Lookup.makeFilter();
19738     while (Filter.hasNext()) {
19739       auto *PrevDecl = cast<OMPDeclareReductionDecl>(Filter.next());
19740       if (InCompoundScope) {
19741         auto I = UsedAsPrevious.find(PrevDecl);
19742         if (I == UsedAsPrevious.end())
19743           UsedAsPrevious[PrevDecl] = false;
19744         if (OMPDeclareReductionDecl *D = PrevDecl->getPrevDeclInScope())
19745           UsedAsPrevious[D] = true;
19746       }
19747       PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
19748           PrevDecl->getLocation();
19749     }
19750     Filter.done();
19751     if (InCompoundScope) {
19752       for (const auto &PrevData : UsedAsPrevious) {
19753         if (!PrevData.second) {
19754           PrevDRD = PrevData.first;
19755           break;
19756         }
19757       }
19758     }
19759   } else if (PrevDeclInScope != nullptr) {
19760     auto *PrevDRDInScope = PrevDRD =
19761         cast<OMPDeclareReductionDecl>(PrevDeclInScope);
19762     do {
19763       PreviousRedeclTypes[PrevDRDInScope->getType().getCanonicalType()] =
19764           PrevDRDInScope->getLocation();
19765       PrevDRDInScope = PrevDRDInScope->getPrevDeclInScope();
19766     } while (PrevDRDInScope != nullptr);
19767   }
19768   for (const auto &TyData : ReductionTypes) {
19769     const auto I = PreviousRedeclTypes.find(TyData.first.getCanonicalType());
19770     bool Invalid = false;
19771     if (I != PreviousRedeclTypes.end()) {
19772       Diag(TyData.second, diag::err_omp_declare_reduction_redefinition)
19773           << TyData.first;
19774       Diag(I->second, diag::note_previous_definition);
19775       Invalid = true;
19776     }
19777     PreviousRedeclTypes[TyData.first.getCanonicalType()] = TyData.second;
19778     auto *DRD = OMPDeclareReductionDecl::Create(Context, DC, TyData.second,
19779                                                 Name, TyData.first, PrevDRD);
19780     DC->addDecl(DRD);
19781     DRD->setAccess(AS);
19782     Decls.push_back(DRD);
19783     if (Invalid)
19784       DRD->setInvalidDecl();
19785     else
19786       PrevDRD = DRD;
19787   }
19788 
19789   return DeclGroupPtrTy::make(
19790       DeclGroupRef::Create(Context, Decls.begin(), Decls.size()));
19791 }
19792 
19793 void Sema::ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D) {
19794   auto *DRD = cast<OMPDeclareReductionDecl>(D);
19795 
19796   // Enter new function scope.
19797   PushFunctionScope();
19798   setFunctionHasBranchProtectedScope();
19799   getCurFunction()->setHasOMPDeclareReductionCombiner();
19800 
19801   if (S != nullptr)
19802     PushDeclContext(S, DRD);
19803   else
19804     CurContext = DRD;
19805 
19806   PushExpressionEvaluationContext(
19807       ExpressionEvaluationContext::PotentiallyEvaluated);
19808 
19809   QualType ReductionType = DRD->getType();
19810   // Create 'T* omp_parm;T omp_in;'. All references to 'omp_in' will
19811   // be replaced by '*omp_parm' during codegen. This required because 'omp_in'
19812   // uses semantics of argument handles by value, but it should be passed by
19813   // reference. C lang does not support references, so pass all parameters as
19814   // pointers.
19815   // Create 'T omp_in;' variable.
19816   VarDecl *OmpInParm =
19817       buildVarDecl(*this, D->getLocation(), ReductionType, "omp_in");
19818   // Create 'T* omp_parm;T omp_out;'. All references to 'omp_out' will
19819   // be replaced by '*omp_parm' during codegen. This required because 'omp_out'
19820   // uses semantics of argument handles by value, but it should be passed by
19821   // reference. C lang does not support references, so pass all parameters as
19822   // pointers.
19823   // Create 'T omp_out;' variable.
19824   VarDecl *OmpOutParm =
19825       buildVarDecl(*this, D->getLocation(), ReductionType, "omp_out");
19826   if (S != nullptr) {
19827     PushOnScopeChains(OmpInParm, S);
19828     PushOnScopeChains(OmpOutParm, S);
19829   } else {
19830     DRD->addDecl(OmpInParm);
19831     DRD->addDecl(OmpOutParm);
19832   }
19833   Expr *InE =
19834       ::buildDeclRefExpr(*this, OmpInParm, ReductionType, D->getLocation());
19835   Expr *OutE =
19836       ::buildDeclRefExpr(*this, OmpOutParm, ReductionType, D->getLocation());
19837   DRD->setCombinerData(InE, OutE);
19838 }
19839 
19840 void Sema::ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner) {
19841   auto *DRD = cast<OMPDeclareReductionDecl>(D);
19842   DiscardCleanupsInEvaluationContext();
19843   PopExpressionEvaluationContext();
19844 
19845   PopDeclContext();
19846   PopFunctionScopeInfo();
19847 
19848   if (Combiner != nullptr)
19849     DRD->setCombiner(Combiner);
19850   else
19851     DRD->setInvalidDecl();
19852 }
19853 
19854 VarDecl *Sema::ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D) {
19855   auto *DRD = cast<OMPDeclareReductionDecl>(D);
19856 
19857   // Enter new function scope.
19858   PushFunctionScope();
19859   setFunctionHasBranchProtectedScope();
19860 
19861   if (S != nullptr)
19862     PushDeclContext(S, DRD);
19863   else
19864     CurContext = DRD;
19865 
19866   PushExpressionEvaluationContext(
19867       ExpressionEvaluationContext::PotentiallyEvaluated);
19868 
19869   QualType ReductionType = DRD->getType();
19870   // Create 'T* omp_parm;T omp_priv;'. All references to 'omp_priv' will
19871   // be replaced by '*omp_parm' during codegen. This required because 'omp_priv'
19872   // uses semantics of argument handles by value, but it should be passed by
19873   // reference. C lang does not support references, so pass all parameters as
19874   // pointers.
19875   // Create 'T omp_priv;' variable.
19876   VarDecl *OmpPrivParm =
19877       buildVarDecl(*this, D->getLocation(), ReductionType, "omp_priv");
19878   // Create 'T* omp_parm;T omp_orig;'. All references to 'omp_orig' will
19879   // be replaced by '*omp_parm' during codegen. This required because 'omp_orig'
19880   // uses semantics of argument handles by value, but it should be passed by
19881   // reference. C lang does not support references, so pass all parameters as
19882   // pointers.
19883   // Create 'T omp_orig;' variable.
19884   VarDecl *OmpOrigParm =
19885       buildVarDecl(*this, D->getLocation(), ReductionType, "omp_orig");
19886   if (S != nullptr) {
19887     PushOnScopeChains(OmpPrivParm, S);
19888     PushOnScopeChains(OmpOrigParm, S);
19889   } else {
19890     DRD->addDecl(OmpPrivParm);
19891     DRD->addDecl(OmpOrigParm);
19892   }
19893   Expr *OrigE =
19894       ::buildDeclRefExpr(*this, OmpOrigParm, ReductionType, D->getLocation());
19895   Expr *PrivE =
19896       ::buildDeclRefExpr(*this, OmpPrivParm, ReductionType, D->getLocation());
19897   DRD->setInitializerData(OrigE, PrivE);
19898   return OmpPrivParm;
19899 }
19900 
19901 void Sema::ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer,
19902                                                      VarDecl *OmpPrivParm) {
19903   auto *DRD = cast<OMPDeclareReductionDecl>(D);
19904   DiscardCleanupsInEvaluationContext();
19905   PopExpressionEvaluationContext();
19906 
19907   PopDeclContext();
19908   PopFunctionScopeInfo();
19909 
19910   if (Initializer != nullptr) {
19911     DRD->setInitializer(Initializer, OMPDeclareReductionDecl::CallInit);
19912   } else if (OmpPrivParm->hasInit()) {
19913     DRD->setInitializer(OmpPrivParm->getInit(),
19914                         OmpPrivParm->isDirectInit()
19915                             ? OMPDeclareReductionDecl::DirectInit
19916                             : OMPDeclareReductionDecl::CopyInit);
19917   } else {
19918     DRD->setInvalidDecl();
19919   }
19920 }
19921 
19922 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveEnd(
19923     Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid) {
19924   for (Decl *D : DeclReductions.get()) {
19925     if (IsValid) {
19926       if (S)
19927         PushOnScopeChains(cast<OMPDeclareReductionDecl>(D), S,
19928                           /*AddToContext=*/false);
19929     } else {
19930       D->setInvalidDecl();
19931     }
19932   }
19933   return DeclReductions;
19934 }
19935 
19936 TypeResult Sema::ActOnOpenMPDeclareMapperVarDecl(Scope *S, Declarator &D) {
19937   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
19938   QualType T = TInfo->getType();
19939   if (D.isInvalidType())
19940     return true;
19941 
19942   if (getLangOpts().CPlusPlus) {
19943     // Check that there are no default arguments (C++ only).
19944     CheckExtraCXXDefaultArguments(D);
19945   }
19946 
19947   return CreateParsedType(T, TInfo);
19948 }
19949 
19950 QualType Sema::ActOnOpenMPDeclareMapperType(SourceLocation TyLoc,
19951                                             TypeResult ParsedType) {
19952   assert(ParsedType.isUsable() && "Expect usable parsed mapper type");
19953 
19954   QualType MapperType = GetTypeFromParser(ParsedType.get());
19955   assert(!MapperType.isNull() && "Expect valid mapper type");
19956 
19957   // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
19958   //  The type must be of struct, union or class type in C and C++
19959   if (!MapperType->isStructureOrClassType() && !MapperType->isUnionType()) {
19960     Diag(TyLoc, diag::err_omp_mapper_wrong_type);
19961     return QualType();
19962   }
19963   return MapperType;
19964 }
19965 
19966 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareMapperDirective(
19967     Scope *S, DeclContext *DC, DeclarationName Name, QualType MapperType,
19968     SourceLocation StartLoc, DeclarationName VN, AccessSpecifier AS,
19969     Expr *MapperVarRef, ArrayRef<OMPClause *> Clauses, Decl *PrevDeclInScope) {
19970   LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPMapperName,
19971                       forRedeclarationInCurContext());
19972   // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
19973   //  A mapper-identifier may not be redeclared in the current scope for the
19974   //  same type or for a type that is compatible according to the base language
19975   //  rules.
19976   llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
19977   OMPDeclareMapperDecl *PrevDMD = nullptr;
19978   bool InCompoundScope = true;
19979   if (S != nullptr) {
19980     // Find previous declaration with the same name not referenced in other
19981     // declarations.
19982     FunctionScopeInfo *ParentFn = getEnclosingFunction();
19983     InCompoundScope =
19984         (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
19985     LookupName(Lookup, S);
19986     FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
19987                          /*AllowInlineNamespace=*/false);
19988     llvm::DenseMap<OMPDeclareMapperDecl *, bool> UsedAsPrevious;
19989     LookupResult::Filter Filter = Lookup.makeFilter();
19990     while (Filter.hasNext()) {
19991       auto *PrevDecl = cast<OMPDeclareMapperDecl>(Filter.next());
19992       if (InCompoundScope) {
19993         auto I = UsedAsPrevious.find(PrevDecl);
19994         if (I == UsedAsPrevious.end())
19995           UsedAsPrevious[PrevDecl] = false;
19996         if (OMPDeclareMapperDecl *D = PrevDecl->getPrevDeclInScope())
19997           UsedAsPrevious[D] = true;
19998       }
19999       PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
20000           PrevDecl->getLocation();
20001     }
20002     Filter.done();
20003     if (InCompoundScope) {
20004       for (const auto &PrevData : UsedAsPrevious) {
20005         if (!PrevData.second) {
20006           PrevDMD = PrevData.first;
20007           break;
20008         }
20009       }
20010     }
20011   } else if (PrevDeclInScope) {
20012     auto *PrevDMDInScope = PrevDMD =
20013         cast<OMPDeclareMapperDecl>(PrevDeclInScope);
20014     do {
20015       PreviousRedeclTypes[PrevDMDInScope->getType().getCanonicalType()] =
20016           PrevDMDInScope->getLocation();
20017       PrevDMDInScope = PrevDMDInScope->getPrevDeclInScope();
20018     } while (PrevDMDInScope != nullptr);
20019   }
20020   const auto I = PreviousRedeclTypes.find(MapperType.getCanonicalType());
20021   bool Invalid = false;
20022   if (I != PreviousRedeclTypes.end()) {
20023     Diag(StartLoc, diag::err_omp_declare_mapper_redefinition)
20024         << MapperType << Name;
20025     Diag(I->second, diag::note_previous_definition);
20026     Invalid = true;
20027   }
20028   // Build expressions for implicit maps of data members with 'default'
20029   // mappers.
20030   SmallVector<OMPClause *, 4> ClausesWithImplicit(Clauses.begin(),
20031                                                   Clauses.end());
20032   if (LangOpts.OpenMP >= 50)
20033     processImplicitMapsWithDefaultMappers(*this, DSAStack, ClausesWithImplicit);
20034   auto *DMD =
20035       OMPDeclareMapperDecl::Create(Context, DC, StartLoc, Name, MapperType, VN,
20036                                    ClausesWithImplicit, PrevDMD);
20037   if (S)
20038     PushOnScopeChains(DMD, S);
20039   else
20040     DC->addDecl(DMD);
20041   DMD->setAccess(AS);
20042   if (Invalid)
20043     DMD->setInvalidDecl();
20044 
20045   auto *VD = cast<DeclRefExpr>(MapperVarRef)->getDecl();
20046   VD->setDeclContext(DMD);
20047   VD->setLexicalDeclContext(DMD);
20048   DMD->addDecl(VD);
20049   DMD->setMapperVarRef(MapperVarRef);
20050 
20051   return DeclGroupPtrTy::make(DeclGroupRef(DMD));
20052 }
20053 
20054 ExprResult
20055 Sema::ActOnOpenMPDeclareMapperDirectiveVarDecl(Scope *S, QualType MapperType,
20056                                                SourceLocation StartLoc,
20057                                                DeclarationName VN) {
20058   TypeSourceInfo *TInfo =
20059       Context.getTrivialTypeSourceInfo(MapperType, StartLoc);
20060   auto *VD = VarDecl::Create(Context, Context.getTranslationUnitDecl(),
20061                              StartLoc, StartLoc, VN.getAsIdentifierInfo(),
20062                              MapperType, TInfo, SC_None);
20063   if (S)
20064     PushOnScopeChains(VD, S, /*AddToContext=*/false);
20065   Expr *E = buildDeclRefExpr(*this, VD, MapperType, StartLoc);
20066   DSAStack->addDeclareMapperVarRef(E);
20067   return E;
20068 }
20069 
20070 bool Sema::isOpenMPDeclareMapperVarDeclAllowed(const VarDecl *VD) const {
20071   assert(LangOpts.OpenMP && "Expected OpenMP mode.");
20072   const Expr *Ref = DSAStack->getDeclareMapperVarRef();
20073   if (const auto *DRE = cast_or_null<DeclRefExpr>(Ref)) {
20074     if (VD->getCanonicalDecl() == DRE->getDecl()->getCanonicalDecl())
20075       return true;
20076     if (VD->isUsableInConstantExpressions(Context))
20077       return true;
20078     return false;
20079   }
20080   return true;
20081 }
20082 
20083 const ValueDecl *Sema::getOpenMPDeclareMapperVarName() const {
20084   assert(LangOpts.OpenMP && "Expected OpenMP mode.");
20085   return cast<DeclRefExpr>(DSAStack->getDeclareMapperVarRef())->getDecl();
20086 }
20087 
20088 OMPClause *Sema::ActOnOpenMPNumTeamsClause(Expr *NumTeams,
20089                                            SourceLocation StartLoc,
20090                                            SourceLocation LParenLoc,
20091                                            SourceLocation EndLoc) {
20092   Expr *ValExpr = NumTeams;
20093   Stmt *HelperValStmt = nullptr;
20094 
20095   // OpenMP [teams Constrcut, Restrictions]
20096   // The num_teams expression must evaluate to a positive integer value.
20097   if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_teams,
20098                                  /*StrictlyPositive=*/true))
20099     return nullptr;
20100 
20101   OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
20102   OpenMPDirectiveKind CaptureRegion =
20103       getOpenMPCaptureRegionForClause(DKind, OMPC_num_teams, LangOpts.OpenMP);
20104   if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
20105     ValExpr = MakeFullExpr(ValExpr).get();
20106     llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
20107     ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
20108     HelperValStmt = buildPreInits(Context, Captures);
20109   }
20110 
20111   return new (Context) OMPNumTeamsClause(ValExpr, HelperValStmt, CaptureRegion,
20112                                          StartLoc, LParenLoc, EndLoc);
20113 }
20114 
20115 OMPClause *Sema::ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
20116                                               SourceLocation StartLoc,
20117                                               SourceLocation LParenLoc,
20118                                               SourceLocation EndLoc) {
20119   Expr *ValExpr = ThreadLimit;
20120   Stmt *HelperValStmt = nullptr;
20121 
20122   // OpenMP [teams Constrcut, Restrictions]
20123   // The thread_limit expression must evaluate to a positive integer value.
20124   if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_thread_limit,
20125                                  /*StrictlyPositive=*/true))
20126     return nullptr;
20127 
20128   OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
20129   OpenMPDirectiveKind CaptureRegion = getOpenMPCaptureRegionForClause(
20130       DKind, OMPC_thread_limit, LangOpts.OpenMP);
20131   if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
20132     ValExpr = MakeFullExpr(ValExpr).get();
20133     llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
20134     ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
20135     HelperValStmt = buildPreInits(Context, Captures);
20136   }
20137 
20138   return new (Context) OMPThreadLimitClause(
20139       ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
20140 }
20141 
20142 OMPClause *Sema::ActOnOpenMPPriorityClause(Expr *Priority,
20143                                            SourceLocation StartLoc,
20144                                            SourceLocation LParenLoc,
20145                                            SourceLocation EndLoc) {
20146   Expr *ValExpr = Priority;
20147   Stmt *HelperValStmt = nullptr;
20148   OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
20149 
20150   // OpenMP [2.9.1, task Constrcut]
20151   // The priority-value is a non-negative numerical scalar expression.
20152   if (!isNonNegativeIntegerValue(
20153           ValExpr, *this, OMPC_priority,
20154           /*StrictlyPositive=*/false, /*BuildCapture=*/true,
20155           DSAStack->getCurrentDirective(), &CaptureRegion, &HelperValStmt))
20156     return nullptr;
20157 
20158   return new (Context) OMPPriorityClause(ValExpr, HelperValStmt, CaptureRegion,
20159                                          StartLoc, LParenLoc, EndLoc);
20160 }
20161 
20162 OMPClause *Sema::ActOnOpenMPGrainsizeClause(Expr *Grainsize,
20163                                             SourceLocation StartLoc,
20164                                             SourceLocation LParenLoc,
20165                                             SourceLocation EndLoc) {
20166   Expr *ValExpr = Grainsize;
20167   Stmt *HelperValStmt = nullptr;
20168   OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
20169 
20170   // OpenMP [2.9.2, taskloop Constrcut]
20171   // The parameter of the grainsize clause must be a positive integer
20172   // expression.
20173   if (!isNonNegativeIntegerValue(
20174           ValExpr, *this, OMPC_grainsize,
20175           /*StrictlyPositive=*/true, /*BuildCapture=*/true,
20176           DSAStack->getCurrentDirective(), &CaptureRegion, &HelperValStmt))
20177     return nullptr;
20178 
20179   return new (Context) OMPGrainsizeClause(ValExpr, HelperValStmt, CaptureRegion,
20180                                           StartLoc, LParenLoc, EndLoc);
20181 }
20182 
20183 OMPClause *Sema::ActOnOpenMPNumTasksClause(Expr *NumTasks,
20184                                            SourceLocation StartLoc,
20185                                            SourceLocation LParenLoc,
20186                                            SourceLocation EndLoc) {
20187   Expr *ValExpr = NumTasks;
20188   Stmt *HelperValStmt = nullptr;
20189   OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
20190 
20191   // OpenMP [2.9.2, taskloop Constrcut]
20192   // The parameter of the num_tasks clause must be a positive integer
20193   // expression.
20194   if (!isNonNegativeIntegerValue(
20195           ValExpr, *this, OMPC_num_tasks,
20196           /*StrictlyPositive=*/true, /*BuildCapture=*/true,
20197           DSAStack->getCurrentDirective(), &CaptureRegion, &HelperValStmt))
20198     return nullptr;
20199 
20200   return new (Context) OMPNumTasksClause(ValExpr, HelperValStmt, CaptureRegion,
20201                                          StartLoc, LParenLoc, EndLoc);
20202 }
20203 
20204 OMPClause *Sema::ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
20205                                        SourceLocation LParenLoc,
20206                                        SourceLocation EndLoc) {
20207   // OpenMP [2.13.2, critical construct, Description]
20208   // ... where hint-expression is an integer constant expression that evaluates
20209   // to a valid lock hint.
20210   ExprResult HintExpr = VerifyPositiveIntegerConstantInClause(Hint, OMPC_hint);
20211   if (HintExpr.isInvalid())
20212     return nullptr;
20213   return new (Context)
20214       OMPHintClause(HintExpr.get(), StartLoc, LParenLoc, EndLoc);
20215 }
20216 
20217 /// Tries to find omp_event_handle_t type.
20218 static bool findOMPEventHandleT(Sema &S, SourceLocation Loc,
20219                                 DSAStackTy *Stack) {
20220   QualType OMPEventHandleT = Stack->getOMPEventHandleT();
20221   if (!OMPEventHandleT.isNull())
20222     return true;
20223   IdentifierInfo *II = &S.PP.getIdentifierTable().get("omp_event_handle_t");
20224   ParsedType PT = S.getTypeName(*II, Loc, S.getCurScope());
20225   if (!PT.getAsOpaquePtr() || PT.get().isNull()) {
20226     S.Diag(Loc, diag::err_omp_implied_type_not_found) << "omp_event_handle_t";
20227     return false;
20228   }
20229   Stack->setOMPEventHandleT(PT.get());
20230   return true;
20231 }
20232 
20233 OMPClause *Sema::ActOnOpenMPDetachClause(Expr *Evt, SourceLocation StartLoc,
20234                                          SourceLocation LParenLoc,
20235                                          SourceLocation EndLoc) {
20236   if (!Evt->isValueDependent() && !Evt->isTypeDependent() &&
20237       !Evt->isInstantiationDependent() &&
20238       !Evt->containsUnexpandedParameterPack()) {
20239     if (!findOMPEventHandleT(*this, Evt->getExprLoc(), DSAStack))
20240       return nullptr;
20241     // OpenMP 5.0, 2.10.1 task Construct.
20242     // event-handle is a variable of the omp_event_handle_t type.
20243     auto *Ref = dyn_cast<DeclRefExpr>(Evt->IgnoreParenImpCasts());
20244     if (!Ref) {
20245       Diag(Evt->getExprLoc(), diag::err_omp_var_expected)
20246           << "omp_event_handle_t" << 0 << Evt->getSourceRange();
20247       return nullptr;
20248     }
20249     auto *VD = dyn_cast_or_null<VarDecl>(Ref->getDecl());
20250     if (!VD) {
20251       Diag(Evt->getExprLoc(), diag::err_omp_var_expected)
20252           << "omp_event_handle_t" << 0 << Evt->getSourceRange();
20253       return nullptr;
20254     }
20255     if (!Context.hasSameUnqualifiedType(DSAStack->getOMPEventHandleT(),
20256                                         VD->getType()) ||
20257         VD->getType().isConstant(Context)) {
20258       Diag(Evt->getExprLoc(), diag::err_omp_var_expected)
20259           << "omp_event_handle_t" << 1 << VD->getType()
20260           << Evt->getSourceRange();
20261       return nullptr;
20262     }
20263     // OpenMP 5.0, 2.10.1 task Construct
20264     // [detach clause]... The event-handle will be considered as if it was
20265     // specified on a firstprivate clause.
20266     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, /*FromParent=*/false);
20267     if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
20268         DVar.RefExpr) {
20269       Diag(Evt->getExprLoc(), diag::err_omp_wrong_dsa)
20270           << getOpenMPClauseName(DVar.CKind)
20271           << getOpenMPClauseName(OMPC_firstprivate);
20272       reportOriginalDsa(*this, DSAStack, VD, DVar);
20273       return nullptr;
20274     }
20275   }
20276 
20277   return new (Context) OMPDetachClause(Evt, StartLoc, LParenLoc, EndLoc);
20278 }
20279 
20280 OMPClause *Sema::ActOnOpenMPDistScheduleClause(
20281     OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
20282     SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc,
20283     SourceLocation EndLoc) {
20284   if (Kind == OMPC_DIST_SCHEDULE_unknown) {
20285     std::string Values;
20286     Values += "'";
20287     Values += getOpenMPSimpleClauseTypeName(OMPC_dist_schedule, 0);
20288     Values += "'";
20289     Diag(KindLoc, diag::err_omp_unexpected_clause_value)
20290         << Values << getOpenMPClauseName(OMPC_dist_schedule);
20291     return nullptr;
20292   }
20293   Expr *ValExpr = ChunkSize;
20294   Stmt *HelperValStmt = nullptr;
20295   if (ChunkSize) {
20296     if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
20297         !ChunkSize->isInstantiationDependent() &&
20298         !ChunkSize->containsUnexpandedParameterPack()) {
20299       SourceLocation ChunkSizeLoc = ChunkSize->getBeginLoc();
20300       ExprResult Val =
20301           PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
20302       if (Val.isInvalid())
20303         return nullptr;
20304 
20305       ValExpr = Val.get();
20306 
20307       // OpenMP [2.7.1, Restrictions]
20308       //  chunk_size must be a loop invariant integer expression with a positive
20309       //  value.
20310       if (Optional<llvm::APSInt> Result =
20311               ValExpr->getIntegerConstantExpr(Context)) {
20312         if (Result->isSigned() && !Result->isStrictlyPositive()) {
20313           Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
20314               << "dist_schedule" << ChunkSize->getSourceRange();
20315           return nullptr;
20316         }
20317       } else if (getOpenMPCaptureRegionForClause(
20318                      DSAStack->getCurrentDirective(), OMPC_dist_schedule,
20319                      LangOpts.OpenMP) != OMPD_unknown &&
20320                  !CurContext->isDependentContext()) {
20321         ValExpr = MakeFullExpr(ValExpr).get();
20322         llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
20323         ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
20324         HelperValStmt = buildPreInits(Context, Captures);
20325       }
20326     }
20327   }
20328 
20329   return new (Context)
20330       OMPDistScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc,
20331                             Kind, ValExpr, HelperValStmt);
20332 }
20333 
20334 OMPClause *Sema::ActOnOpenMPDefaultmapClause(
20335     OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
20336     SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
20337     SourceLocation KindLoc, SourceLocation EndLoc) {
20338   if (getLangOpts().OpenMP < 50) {
20339     if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom ||
20340         Kind != OMPC_DEFAULTMAP_scalar) {
20341       std::string Value;
20342       SourceLocation Loc;
20343       Value += "'";
20344       if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom) {
20345         Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
20346                                                OMPC_DEFAULTMAP_MODIFIER_tofrom);
20347         Loc = MLoc;
20348       } else {
20349         Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
20350                                                OMPC_DEFAULTMAP_scalar);
20351         Loc = KindLoc;
20352       }
20353       Value += "'";
20354       Diag(Loc, diag::err_omp_unexpected_clause_value)
20355           << Value << getOpenMPClauseName(OMPC_defaultmap);
20356       return nullptr;
20357     }
20358   } else {
20359     bool isDefaultmapModifier = (M != OMPC_DEFAULTMAP_MODIFIER_unknown);
20360     bool isDefaultmapKind = (Kind != OMPC_DEFAULTMAP_unknown) ||
20361                             (LangOpts.OpenMP >= 50 && KindLoc.isInvalid());
20362     if (!isDefaultmapKind || !isDefaultmapModifier) {
20363       StringRef KindValue = "'scalar', 'aggregate', 'pointer'";
20364       if (LangOpts.OpenMP == 50) {
20365         StringRef ModifierValue = "'alloc', 'from', 'to', 'tofrom', "
20366                                   "'firstprivate', 'none', 'default'";
20367         if (!isDefaultmapKind && isDefaultmapModifier) {
20368           Diag(KindLoc, diag::err_omp_unexpected_clause_value)
20369               << KindValue << getOpenMPClauseName(OMPC_defaultmap);
20370         } else if (isDefaultmapKind && !isDefaultmapModifier) {
20371           Diag(MLoc, diag::err_omp_unexpected_clause_value)
20372               << ModifierValue << getOpenMPClauseName(OMPC_defaultmap);
20373         } else {
20374           Diag(MLoc, diag::err_omp_unexpected_clause_value)
20375               << ModifierValue << getOpenMPClauseName(OMPC_defaultmap);
20376           Diag(KindLoc, diag::err_omp_unexpected_clause_value)
20377               << KindValue << getOpenMPClauseName(OMPC_defaultmap);
20378         }
20379       } else {
20380         StringRef ModifierValue =
20381             "'alloc', 'from', 'to', 'tofrom', "
20382             "'firstprivate', 'none', 'default', 'present'";
20383         if (!isDefaultmapKind && isDefaultmapModifier) {
20384           Diag(KindLoc, diag::err_omp_unexpected_clause_value)
20385               << KindValue << getOpenMPClauseName(OMPC_defaultmap);
20386         } else if (isDefaultmapKind && !isDefaultmapModifier) {
20387           Diag(MLoc, diag::err_omp_unexpected_clause_value)
20388               << ModifierValue << getOpenMPClauseName(OMPC_defaultmap);
20389         } else {
20390           Diag(MLoc, diag::err_omp_unexpected_clause_value)
20391               << ModifierValue << getOpenMPClauseName(OMPC_defaultmap);
20392           Diag(KindLoc, diag::err_omp_unexpected_clause_value)
20393               << KindValue << getOpenMPClauseName(OMPC_defaultmap);
20394         }
20395       }
20396       return nullptr;
20397     }
20398 
20399     // OpenMP [5.0, 2.12.5, Restrictions, p. 174]
20400     //  At most one defaultmap clause for each category can appear on the
20401     //  directive.
20402     if (DSAStack->checkDefaultmapCategory(Kind)) {
20403       Diag(StartLoc, diag::err_omp_one_defaultmap_each_category);
20404       return nullptr;
20405     }
20406   }
20407   if (Kind == OMPC_DEFAULTMAP_unknown) {
20408     // Variable category is not specified - mark all categories.
20409     DSAStack->setDefaultDMAAttr(M, OMPC_DEFAULTMAP_aggregate, StartLoc);
20410     DSAStack->setDefaultDMAAttr(M, OMPC_DEFAULTMAP_scalar, StartLoc);
20411     DSAStack->setDefaultDMAAttr(M, OMPC_DEFAULTMAP_pointer, StartLoc);
20412   } else {
20413     DSAStack->setDefaultDMAAttr(M, Kind, StartLoc);
20414   }
20415 
20416   return new (Context)
20417       OMPDefaultmapClause(StartLoc, LParenLoc, MLoc, KindLoc, EndLoc, Kind, M);
20418 }
20419 
20420 bool Sema::ActOnStartOpenMPDeclareTargetContext(
20421     DeclareTargetContextInfo &DTCI) {
20422   DeclContext *CurLexicalContext = getCurLexicalContext();
20423   if (!CurLexicalContext->isFileContext() &&
20424       !CurLexicalContext->isExternCContext() &&
20425       !CurLexicalContext->isExternCXXContext() &&
20426       !isa<CXXRecordDecl>(CurLexicalContext) &&
20427       !isa<ClassTemplateDecl>(CurLexicalContext) &&
20428       !isa<ClassTemplatePartialSpecializationDecl>(CurLexicalContext) &&
20429       !isa<ClassTemplateSpecializationDecl>(CurLexicalContext)) {
20430     Diag(DTCI.Loc, diag::err_omp_region_not_file_context);
20431     return false;
20432   }
20433   DeclareTargetNesting.push_back(DTCI);
20434   return true;
20435 }
20436 
20437 const Sema::DeclareTargetContextInfo
20438 Sema::ActOnOpenMPEndDeclareTargetDirective() {
20439   assert(!DeclareTargetNesting.empty() &&
20440          "check isInOpenMPDeclareTargetContext() first!");
20441   return DeclareTargetNesting.pop_back_val();
20442 }
20443 
20444 void Sema::ActOnFinishedOpenMPDeclareTargetContext(
20445     DeclareTargetContextInfo &DTCI) {
20446   for (auto &It : DTCI.ExplicitlyMapped)
20447     ActOnOpenMPDeclareTargetName(It.first, It.second.Loc, It.second.MT,
20448                                  DTCI.DT);
20449 }
20450 
20451 NamedDecl *Sema::lookupOpenMPDeclareTargetName(Scope *CurScope,
20452                                                CXXScopeSpec &ScopeSpec,
20453                                                const DeclarationNameInfo &Id) {
20454   LookupResult Lookup(*this, Id, LookupOrdinaryName);
20455   LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
20456 
20457   if (Lookup.isAmbiguous())
20458     return nullptr;
20459   Lookup.suppressDiagnostics();
20460 
20461   if (!Lookup.isSingleResult()) {
20462     VarOrFuncDeclFilterCCC CCC(*this);
20463     if (TypoCorrection Corrected =
20464             CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr, CCC,
20465                         CTK_ErrorRecovery)) {
20466       diagnoseTypo(Corrected, PDiag(diag::err_undeclared_var_use_suggest)
20467                                   << Id.getName());
20468       checkDeclIsAllowedInOpenMPTarget(nullptr, Corrected.getCorrectionDecl());
20469       return nullptr;
20470     }
20471 
20472     Diag(Id.getLoc(), diag::err_undeclared_var_use) << Id.getName();
20473     return nullptr;
20474   }
20475 
20476   NamedDecl *ND = Lookup.getAsSingle<NamedDecl>();
20477   if (!isa<VarDecl>(ND) && !isa<FunctionDecl>(ND) &&
20478       !isa<FunctionTemplateDecl>(ND)) {
20479     Diag(Id.getLoc(), diag::err_omp_invalid_target_decl) << Id.getName();
20480     return nullptr;
20481   }
20482   return ND;
20483 }
20484 
20485 void Sema::ActOnOpenMPDeclareTargetName(
20486     NamedDecl *ND, SourceLocation Loc, OMPDeclareTargetDeclAttr::MapTypeTy MT,
20487     OMPDeclareTargetDeclAttr::DevTypeTy DT) {
20488   assert((isa<VarDecl>(ND) || isa<FunctionDecl>(ND) ||
20489           isa<FunctionTemplateDecl>(ND)) &&
20490          "Expected variable, function or function template.");
20491 
20492   // Diagnose marking after use as it may lead to incorrect diagnosis and
20493   // codegen.
20494   if (LangOpts.OpenMP >= 50 &&
20495       (ND->isUsed(/*CheckUsedAttr=*/false) || ND->isReferenced()))
20496     Diag(Loc, diag::warn_omp_declare_target_after_first_use);
20497 
20498   // Explicit declare target lists have precedence.
20499   const unsigned Level = -1;
20500 
20501   auto *VD = cast<ValueDecl>(ND);
20502   llvm::Optional<OMPDeclareTargetDeclAttr *> ActiveAttr =
20503       OMPDeclareTargetDeclAttr::getActiveAttr(VD);
20504   if (ActiveAttr.hasValue() && ActiveAttr.getValue()->getDevType() != DT &&
20505       ActiveAttr.getValue()->getLevel() == Level) {
20506     Diag(Loc, diag::err_omp_device_type_mismatch)
20507         << OMPDeclareTargetDeclAttr::ConvertDevTypeTyToStr(DT)
20508         << OMPDeclareTargetDeclAttr::ConvertDevTypeTyToStr(
20509                ActiveAttr.getValue()->getDevType());
20510     return;
20511   }
20512   if (ActiveAttr.hasValue() && ActiveAttr.getValue()->getMapType() != MT &&
20513       ActiveAttr.getValue()->getLevel() == Level) {
20514     Diag(Loc, diag::err_omp_declare_target_to_and_link) << ND;
20515     return;
20516   }
20517 
20518   if (ActiveAttr.hasValue() && ActiveAttr.getValue()->getLevel() == Level)
20519     return;
20520 
20521   auto *A = OMPDeclareTargetDeclAttr::CreateImplicit(Context, MT, DT, Level,
20522                                                      SourceRange(Loc, Loc));
20523   ND->addAttr(A);
20524   if (ASTMutationListener *ML = Context.getASTMutationListener())
20525     ML->DeclarationMarkedOpenMPDeclareTarget(ND, A);
20526   checkDeclIsAllowedInOpenMPTarget(nullptr, ND, Loc);
20527 }
20528 
20529 static void checkDeclInTargetContext(SourceLocation SL, SourceRange SR,
20530                                      Sema &SemaRef, Decl *D) {
20531   if (!D || !isa<VarDecl>(D))
20532     return;
20533   auto *VD = cast<VarDecl>(D);
20534   Optional<OMPDeclareTargetDeclAttr::MapTypeTy> MapTy =
20535       OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
20536   if (SemaRef.LangOpts.OpenMP >= 50 &&
20537       (SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true) ||
20538        SemaRef.getCurBlock() || SemaRef.getCurCapturedRegion()) &&
20539       VD->hasGlobalStorage()) {
20540     if (!MapTy || *MapTy != OMPDeclareTargetDeclAttr::MT_To) {
20541       // OpenMP 5.0, 2.12.7 declare target Directive, Restrictions
20542       // If a lambda declaration and definition appears between a
20543       // declare target directive and the matching end declare target
20544       // directive, all variables that are captured by the lambda
20545       // expression must also appear in a to clause.
20546       SemaRef.Diag(VD->getLocation(),
20547                    diag::err_omp_lambda_capture_in_declare_target_not_to);
20548       SemaRef.Diag(SL, diag::note_var_explicitly_captured_here)
20549           << VD << 0 << SR;
20550       return;
20551     }
20552   }
20553   if (MapTy.hasValue())
20554     return;
20555   SemaRef.Diag(VD->getLocation(), diag::warn_omp_not_in_target_context);
20556   SemaRef.Diag(SL, diag::note_used_here) << SR;
20557 }
20558 
20559 static bool checkValueDeclInTarget(SourceLocation SL, SourceRange SR,
20560                                    Sema &SemaRef, DSAStackTy *Stack,
20561                                    ValueDecl *VD) {
20562   return OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD) ||
20563          checkTypeMappable(SL, SR, SemaRef, Stack, VD->getType(),
20564                            /*FullCheck=*/false);
20565 }
20566 
20567 void Sema::checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D,
20568                                             SourceLocation IdLoc) {
20569   if (!D || D->isInvalidDecl())
20570     return;
20571   SourceRange SR = E ? E->getSourceRange() : D->getSourceRange();
20572   SourceLocation SL = E ? E->getBeginLoc() : D->getLocation();
20573   if (auto *VD = dyn_cast<VarDecl>(D)) {
20574     // Only global variables can be marked as declare target.
20575     if (!VD->isFileVarDecl() && !VD->isStaticLocal() &&
20576         !VD->isStaticDataMember())
20577       return;
20578     // 2.10.6: threadprivate variable cannot appear in a declare target
20579     // directive.
20580     if (DSAStack->isThreadPrivate(VD)) {
20581       Diag(SL, diag::err_omp_threadprivate_in_target);
20582       reportOriginalDsa(*this, DSAStack, VD, DSAStack->getTopDSA(VD, false));
20583       return;
20584     }
20585   }
20586   if (const auto *FTD = dyn_cast<FunctionTemplateDecl>(D))
20587     D = FTD->getTemplatedDecl();
20588   if (auto *FD = dyn_cast<FunctionDecl>(D)) {
20589     llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
20590         OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(FD);
20591     if (IdLoc.isValid() && Res && *Res == OMPDeclareTargetDeclAttr::MT_Link) {
20592       Diag(IdLoc, diag::err_omp_function_in_link_clause);
20593       Diag(FD->getLocation(), diag::note_defined_here) << FD;
20594       return;
20595     }
20596   }
20597   if (auto *VD = dyn_cast<ValueDecl>(D)) {
20598     // Problem if any with var declared with incomplete type will be reported
20599     // as normal, so no need to check it here.
20600     if ((E || !VD->getType()->isIncompleteType()) &&
20601         !checkValueDeclInTarget(SL, SR, *this, DSAStack, VD))
20602       return;
20603     if (!E && isInOpenMPDeclareTargetContext()) {
20604       // Checking declaration inside declare target region.
20605       if (isa<VarDecl>(D) || isa<FunctionDecl>(D) ||
20606           isa<FunctionTemplateDecl>(D)) {
20607         llvm::Optional<OMPDeclareTargetDeclAttr *> ActiveAttr =
20608             OMPDeclareTargetDeclAttr::getActiveAttr(VD);
20609         unsigned Level = DeclareTargetNesting.size();
20610         if (ActiveAttr.hasValue() && ActiveAttr.getValue()->getLevel() >= Level)
20611           return;
20612         DeclareTargetContextInfo &DTCI = DeclareTargetNesting.back();
20613         auto *A = OMPDeclareTargetDeclAttr::CreateImplicit(
20614             Context, OMPDeclareTargetDeclAttr::MT_To, DTCI.DT, Level,
20615             SourceRange(DTCI.Loc, DTCI.Loc));
20616         D->addAttr(A);
20617         if (ASTMutationListener *ML = Context.getASTMutationListener())
20618           ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
20619       }
20620       return;
20621     }
20622   }
20623   if (!E)
20624     return;
20625   checkDeclInTargetContext(E->getExprLoc(), E->getSourceRange(), *this, D);
20626 }
20627 
20628 OMPClause *Sema::ActOnOpenMPToClause(
20629     ArrayRef<OpenMPMotionModifierKind> MotionModifiers,
20630     ArrayRef<SourceLocation> MotionModifiersLoc,
20631     CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo &MapperId,
20632     SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
20633     const OMPVarListLocTy &Locs, ArrayRef<Expr *> UnresolvedMappers) {
20634   OpenMPMotionModifierKind Modifiers[] = {OMPC_MOTION_MODIFIER_unknown,
20635                                           OMPC_MOTION_MODIFIER_unknown};
20636   SourceLocation ModifiersLoc[NumberOfOMPMotionModifiers];
20637 
20638   // Process motion-modifiers, flag errors for duplicate modifiers.
20639   unsigned Count = 0;
20640   for (unsigned I = 0, E = MotionModifiers.size(); I < E; ++I) {
20641     if (MotionModifiers[I] != OMPC_MOTION_MODIFIER_unknown &&
20642         llvm::find(Modifiers, MotionModifiers[I]) != std::end(Modifiers)) {
20643       Diag(MotionModifiersLoc[I], diag::err_omp_duplicate_motion_modifier);
20644       continue;
20645     }
20646     assert(Count < NumberOfOMPMotionModifiers &&
20647            "Modifiers exceed the allowed number of motion modifiers");
20648     Modifiers[Count] = MotionModifiers[I];
20649     ModifiersLoc[Count] = MotionModifiersLoc[I];
20650     ++Count;
20651   }
20652 
20653   MappableVarListInfo MVLI(VarList);
20654   checkMappableExpressionList(*this, DSAStack, OMPC_to, MVLI, Locs.StartLoc,
20655                               MapperIdScopeSpec, MapperId, UnresolvedMappers);
20656   if (MVLI.ProcessedVarList.empty())
20657     return nullptr;
20658 
20659   return OMPToClause::Create(
20660       Context, Locs, MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
20661       MVLI.VarComponents, MVLI.UDMapperList, Modifiers, ModifiersLoc,
20662       MapperIdScopeSpec.getWithLocInContext(Context), MapperId);
20663 }
20664 
20665 OMPClause *Sema::ActOnOpenMPFromClause(
20666     ArrayRef<OpenMPMotionModifierKind> MotionModifiers,
20667     ArrayRef<SourceLocation> MotionModifiersLoc,
20668     CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo &MapperId,
20669     SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
20670     const OMPVarListLocTy &Locs, ArrayRef<Expr *> UnresolvedMappers) {
20671   OpenMPMotionModifierKind Modifiers[] = {OMPC_MOTION_MODIFIER_unknown,
20672                                           OMPC_MOTION_MODIFIER_unknown};
20673   SourceLocation ModifiersLoc[NumberOfOMPMotionModifiers];
20674 
20675   // Process motion-modifiers, flag errors for duplicate modifiers.
20676   unsigned Count = 0;
20677   for (unsigned I = 0, E = MotionModifiers.size(); I < E; ++I) {
20678     if (MotionModifiers[I] != OMPC_MOTION_MODIFIER_unknown &&
20679         llvm::find(Modifiers, MotionModifiers[I]) != std::end(Modifiers)) {
20680       Diag(MotionModifiersLoc[I], diag::err_omp_duplicate_motion_modifier);
20681       continue;
20682     }
20683     assert(Count < NumberOfOMPMotionModifiers &&
20684            "Modifiers exceed the allowed number of motion modifiers");
20685     Modifiers[Count] = MotionModifiers[I];
20686     ModifiersLoc[Count] = MotionModifiersLoc[I];
20687     ++Count;
20688   }
20689 
20690   MappableVarListInfo MVLI(VarList);
20691   checkMappableExpressionList(*this, DSAStack, OMPC_from, MVLI, Locs.StartLoc,
20692                               MapperIdScopeSpec, MapperId, UnresolvedMappers);
20693   if (MVLI.ProcessedVarList.empty())
20694     return nullptr;
20695 
20696   return OMPFromClause::Create(
20697       Context, Locs, MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
20698       MVLI.VarComponents, MVLI.UDMapperList, Modifiers, ModifiersLoc,
20699       MapperIdScopeSpec.getWithLocInContext(Context), MapperId);
20700 }
20701 
20702 OMPClause *Sema::ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
20703                                                const OMPVarListLocTy &Locs) {
20704   MappableVarListInfo MVLI(VarList);
20705   SmallVector<Expr *, 8> PrivateCopies;
20706   SmallVector<Expr *, 8> Inits;
20707 
20708   for (Expr *RefExpr : VarList) {
20709     assert(RefExpr && "NULL expr in OpenMP use_device_ptr clause.");
20710     SourceLocation ELoc;
20711     SourceRange ERange;
20712     Expr *SimpleRefExpr = RefExpr;
20713     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
20714     if (Res.second) {
20715       // It will be analyzed later.
20716       MVLI.ProcessedVarList.push_back(RefExpr);
20717       PrivateCopies.push_back(nullptr);
20718       Inits.push_back(nullptr);
20719     }
20720     ValueDecl *D = Res.first;
20721     if (!D)
20722       continue;
20723 
20724     QualType Type = D->getType();
20725     Type = Type.getNonReferenceType().getUnqualifiedType();
20726 
20727     auto *VD = dyn_cast<VarDecl>(D);
20728 
20729     // Item should be a pointer or reference to pointer.
20730     if (!Type->isPointerType()) {
20731       Diag(ELoc, diag::err_omp_usedeviceptr_not_a_pointer)
20732           << 0 << RefExpr->getSourceRange();
20733       continue;
20734     }
20735 
20736     // Build the private variable and the expression that refers to it.
20737     auto VDPrivate =
20738         buildVarDecl(*this, ELoc, Type, D->getName(),
20739                      D->hasAttrs() ? &D->getAttrs() : nullptr,
20740                      VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
20741     if (VDPrivate->isInvalidDecl())
20742       continue;
20743 
20744     CurContext->addDecl(VDPrivate);
20745     DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
20746         *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
20747 
20748     // Add temporary variable to initialize the private copy of the pointer.
20749     VarDecl *VDInit =
20750         buildVarDecl(*this, RefExpr->getExprLoc(), Type, ".devptr.temp");
20751     DeclRefExpr *VDInitRefExpr = buildDeclRefExpr(
20752         *this, VDInit, RefExpr->getType(), RefExpr->getExprLoc());
20753     AddInitializerToDecl(VDPrivate,
20754                          DefaultLvalueConversion(VDInitRefExpr).get(),
20755                          /*DirectInit=*/false);
20756 
20757     // If required, build a capture to implement the privatization initialized
20758     // with the current list item value.
20759     DeclRefExpr *Ref = nullptr;
20760     if (!VD)
20761       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
20762     MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref);
20763     PrivateCopies.push_back(VDPrivateRefExpr);
20764     Inits.push_back(VDInitRefExpr);
20765 
20766     // We need to add a data sharing attribute for this variable to make sure it
20767     // is correctly captured. A variable that shows up in a use_device_ptr has
20768     // similar properties of a first private variable.
20769     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
20770 
20771     // Create a mappable component for the list item. List items in this clause
20772     // only need a component.
20773     MVLI.VarBaseDeclarations.push_back(D);
20774     MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
20775     MVLI.VarComponents.back().emplace_back(SimpleRefExpr, D,
20776                                            /*IsNonContiguous=*/false);
20777   }
20778 
20779   if (MVLI.ProcessedVarList.empty())
20780     return nullptr;
20781 
20782   return OMPUseDevicePtrClause::Create(
20783       Context, Locs, MVLI.ProcessedVarList, PrivateCopies, Inits,
20784       MVLI.VarBaseDeclarations, MVLI.VarComponents);
20785 }
20786 
20787 OMPClause *Sema::ActOnOpenMPUseDeviceAddrClause(ArrayRef<Expr *> VarList,
20788                                                 const OMPVarListLocTy &Locs) {
20789   MappableVarListInfo MVLI(VarList);
20790 
20791   for (Expr *RefExpr : VarList) {
20792     assert(RefExpr && "NULL expr in OpenMP use_device_addr clause.");
20793     SourceLocation ELoc;
20794     SourceRange ERange;
20795     Expr *SimpleRefExpr = RefExpr;
20796     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
20797                               /*AllowArraySection=*/true);
20798     if (Res.second) {
20799       // It will be analyzed later.
20800       MVLI.ProcessedVarList.push_back(RefExpr);
20801     }
20802     ValueDecl *D = Res.first;
20803     if (!D)
20804       continue;
20805     auto *VD = dyn_cast<VarDecl>(D);
20806 
20807     // If required, build a capture to implement the privatization initialized
20808     // with the current list item value.
20809     DeclRefExpr *Ref = nullptr;
20810     if (!VD)
20811       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
20812     MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref);
20813 
20814     // We need to add a data sharing attribute for this variable to make sure it
20815     // is correctly captured. A variable that shows up in a use_device_addr has
20816     // similar properties of a first private variable.
20817     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
20818 
20819     // Create a mappable component for the list item. List items in this clause
20820     // only need a component.
20821     MVLI.VarBaseDeclarations.push_back(D);
20822     MVLI.VarComponents.emplace_back();
20823     Expr *Component = SimpleRefExpr;
20824     if (VD && (isa<OMPArraySectionExpr>(RefExpr->IgnoreParenImpCasts()) ||
20825                isa<ArraySubscriptExpr>(RefExpr->IgnoreParenImpCasts())))
20826       Component = DefaultFunctionArrayLvalueConversion(SimpleRefExpr).get();
20827     MVLI.VarComponents.back().emplace_back(Component, D,
20828                                            /*IsNonContiguous=*/false);
20829   }
20830 
20831   if (MVLI.ProcessedVarList.empty())
20832     return nullptr;
20833 
20834   return OMPUseDeviceAddrClause::Create(Context, Locs, MVLI.ProcessedVarList,
20835                                         MVLI.VarBaseDeclarations,
20836                                         MVLI.VarComponents);
20837 }
20838 
20839 OMPClause *Sema::ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
20840                                               const OMPVarListLocTy &Locs) {
20841   MappableVarListInfo MVLI(VarList);
20842   for (Expr *RefExpr : VarList) {
20843     assert(RefExpr && "NULL expr in OpenMP is_device_ptr clause.");
20844     SourceLocation ELoc;
20845     SourceRange ERange;
20846     Expr *SimpleRefExpr = RefExpr;
20847     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
20848     if (Res.second) {
20849       // It will be analyzed later.
20850       MVLI.ProcessedVarList.push_back(RefExpr);
20851     }
20852     ValueDecl *D = Res.first;
20853     if (!D)
20854       continue;
20855 
20856     QualType Type = D->getType();
20857     // item should be a pointer or array or reference to pointer or array
20858     if (!Type.getNonReferenceType()->isPointerType() &&
20859         !Type.getNonReferenceType()->isArrayType()) {
20860       Diag(ELoc, diag::err_omp_argument_type_isdeviceptr)
20861           << 0 << RefExpr->getSourceRange();
20862       continue;
20863     }
20864 
20865     // Check if the declaration in the clause does not show up in any data
20866     // sharing attribute.
20867     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
20868     if (isOpenMPPrivate(DVar.CKind)) {
20869       Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
20870           << getOpenMPClauseName(DVar.CKind)
20871           << getOpenMPClauseName(OMPC_is_device_ptr)
20872           << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
20873       reportOriginalDsa(*this, DSAStack, D, DVar);
20874       continue;
20875     }
20876 
20877     const Expr *ConflictExpr;
20878     if (DSAStack->checkMappableExprComponentListsForDecl(
20879             D, /*CurrentRegionOnly=*/true,
20880             [&ConflictExpr](
20881                 OMPClauseMappableExprCommon::MappableExprComponentListRef R,
20882                 OpenMPClauseKind) -> bool {
20883               ConflictExpr = R.front().getAssociatedExpression();
20884               return true;
20885             })) {
20886       Diag(ELoc, diag::err_omp_map_shared_storage) << RefExpr->getSourceRange();
20887       Diag(ConflictExpr->getExprLoc(), diag::note_used_here)
20888           << ConflictExpr->getSourceRange();
20889       continue;
20890     }
20891 
20892     // Store the components in the stack so that they can be used to check
20893     // against other clauses later on.
20894     OMPClauseMappableExprCommon::MappableComponent MC(
20895         SimpleRefExpr, D, /*IsNonContiguous=*/false);
20896     DSAStack->addMappableExpressionComponents(
20897         D, MC, /*WhereFoundClauseKind=*/OMPC_is_device_ptr);
20898 
20899     // Record the expression we've just processed.
20900     MVLI.ProcessedVarList.push_back(SimpleRefExpr);
20901 
20902     // Create a mappable component for the list item. List items in this clause
20903     // only need a component. We use a null declaration to signal fields in
20904     // 'this'.
20905     assert((isa<DeclRefExpr>(SimpleRefExpr) ||
20906             isa<CXXThisExpr>(cast<MemberExpr>(SimpleRefExpr)->getBase())) &&
20907            "Unexpected device pointer expression!");
20908     MVLI.VarBaseDeclarations.push_back(
20909         isa<DeclRefExpr>(SimpleRefExpr) ? D : nullptr);
20910     MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
20911     MVLI.VarComponents.back().push_back(MC);
20912   }
20913 
20914   if (MVLI.ProcessedVarList.empty())
20915     return nullptr;
20916 
20917   return OMPIsDevicePtrClause::Create(Context, Locs, MVLI.ProcessedVarList,
20918                                       MVLI.VarBaseDeclarations,
20919                                       MVLI.VarComponents);
20920 }
20921 
20922 OMPClause *Sema::ActOnOpenMPAllocateClause(
20923     Expr *Allocator, ArrayRef<Expr *> VarList, SourceLocation StartLoc,
20924     SourceLocation ColonLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
20925   if (Allocator) {
20926     // OpenMP [2.11.4 allocate Clause, Description]
20927     // allocator is an expression of omp_allocator_handle_t type.
20928     if (!findOMPAllocatorHandleT(*this, Allocator->getExprLoc(), DSAStack))
20929       return nullptr;
20930 
20931     ExprResult AllocatorRes = DefaultLvalueConversion(Allocator);
20932     if (AllocatorRes.isInvalid())
20933       return nullptr;
20934     AllocatorRes = PerformImplicitConversion(AllocatorRes.get(),
20935                                              DSAStack->getOMPAllocatorHandleT(),
20936                                              Sema::AA_Initializing,
20937                                              /*AllowExplicit=*/true);
20938     if (AllocatorRes.isInvalid())
20939       return nullptr;
20940     Allocator = AllocatorRes.get();
20941   } else {
20942     // OpenMP 5.0, 2.11.4 allocate Clause, Restrictions.
20943     // allocate clauses that appear on a target construct or on constructs in a
20944     // target region must specify an allocator expression unless a requires
20945     // directive with the dynamic_allocators clause is present in the same
20946     // compilation unit.
20947     if (LangOpts.OpenMPIsDevice &&
20948         !DSAStack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>())
20949       targetDiag(StartLoc, diag::err_expected_allocator_expression);
20950   }
20951   // Analyze and build list of variables.
20952   SmallVector<Expr *, 8> Vars;
20953   for (Expr *RefExpr : VarList) {
20954     assert(RefExpr && "NULL expr in OpenMP private clause.");
20955     SourceLocation ELoc;
20956     SourceRange ERange;
20957     Expr *SimpleRefExpr = RefExpr;
20958     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
20959     if (Res.second) {
20960       // It will be analyzed later.
20961       Vars.push_back(RefExpr);
20962     }
20963     ValueDecl *D = Res.first;
20964     if (!D)
20965       continue;
20966 
20967     auto *VD = dyn_cast<VarDecl>(D);
20968     DeclRefExpr *Ref = nullptr;
20969     if (!VD && !CurContext->isDependentContext())
20970       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
20971     Vars.push_back((VD || CurContext->isDependentContext())
20972                        ? RefExpr->IgnoreParens()
20973                        : Ref);
20974   }
20975 
20976   if (Vars.empty())
20977     return nullptr;
20978 
20979   if (Allocator)
20980     DSAStack->addInnerAllocatorExpr(Allocator);
20981   return OMPAllocateClause::Create(Context, StartLoc, LParenLoc, Allocator,
20982                                    ColonLoc, EndLoc, Vars);
20983 }
20984 
20985 OMPClause *Sema::ActOnOpenMPNontemporalClause(ArrayRef<Expr *> VarList,
20986                                               SourceLocation StartLoc,
20987                                               SourceLocation LParenLoc,
20988                                               SourceLocation EndLoc) {
20989   SmallVector<Expr *, 8> Vars;
20990   for (Expr *RefExpr : VarList) {
20991     assert(RefExpr && "NULL expr in OpenMP nontemporal clause.");
20992     SourceLocation ELoc;
20993     SourceRange ERange;
20994     Expr *SimpleRefExpr = RefExpr;
20995     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
20996     if (Res.second)
20997       // It will be analyzed later.
20998       Vars.push_back(RefExpr);
20999     ValueDecl *D = Res.first;
21000     if (!D)
21001       continue;
21002 
21003     // OpenMP 5.0, 2.9.3.1 simd Construct, Restrictions.
21004     // A list-item cannot appear in more than one nontemporal clause.
21005     if (const Expr *PrevRef =
21006             DSAStack->addUniqueNontemporal(D, SimpleRefExpr)) {
21007       Diag(ELoc, diag::err_omp_used_in_clause_twice)
21008           << 0 << getOpenMPClauseName(OMPC_nontemporal) << ERange;
21009       Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
21010           << getOpenMPClauseName(OMPC_nontemporal);
21011       continue;
21012     }
21013 
21014     Vars.push_back(RefExpr);
21015   }
21016 
21017   if (Vars.empty())
21018     return nullptr;
21019 
21020   return OMPNontemporalClause::Create(Context, StartLoc, LParenLoc, EndLoc,
21021                                       Vars);
21022 }
21023 
21024 OMPClause *Sema::ActOnOpenMPInclusiveClause(ArrayRef<Expr *> VarList,
21025                                             SourceLocation StartLoc,
21026                                             SourceLocation LParenLoc,
21027                                             SourceLocation EndLoc) {
21028   SmallVector<Expr *, 8> Vars;
21029   for (Expr *RefExpr : VarList) {
21030     assert(RefExpr && "NULL expr in OpenMP nontemporal clause.");
21031     SourceLocation ELoc;
21032     SourceRange ERange;
21033     Expr *SimpleRefExpr = RefExpr;
21034     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
21035                               /*AllowArraySection=*/true);
21036     if (Res.second)
21037       // It will be analyzed later.
21038       Vars.push_back(RefExpr);
21039     ValueDecl *D = Res.first;
21040     if (!D)
21041       continue;
21042 
21043     const DSAStackTy::DSAVarData DVar =
21044         DSAStack->getTopDSA(D, /*FromParent=*/true);
21045     // OpenMP 5.0, 2.9.6, scan Directive, Restrictions.
21046     // A list item that appears in the inclusive or exclusive clause must appear
21047     // in a reduction clause with the inscan modifier on the enclosing
21048     // worksharing-loop, worksharing-loop SIMD, or simd construct.
21049     if (DVar.CKind != OMPC_reduction ||
21050         DVar.Modifier != OMPC_REDUCTION_inscan)
21051       Diag(ELoc, diag::err_omp_inclusive_exclusive_not_reduction)
21052           << RefExpr->getSourceRange();
21053 
21054     if (DSAStack->getParentDirective() != OMPD_unknown)
21055       DSAStack->markDeclAsUsedInScanDirective(D);
21056     Vars.push_back(RefExpr);
21057   }
21058 
21059   if (Vars.empty())
21060     return nullptr;
21061 
21062   return OMPInclusiveClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
21063 }
21064 
21065 OMPClause *Sema::ActOnOpenMPExclusiveClause(ArrayRef<Expr *> VarList,
21066                                             SourceLocation StartLoc,
21067                                             SourceLocation LParenLoc,
21068                                             SourceLocation EndLoc) {
21069   SmallVector<Expr *, 8> Vars;
21070   for (Expr *RefExpr : VarList) {
21071     assert(RefExpr && "NULL expr in OpenMP nontemporal clause.");
21072     SourceLocation ELoc;
21073     SourceRange ERange;
21074     Expr *SimpleRefExpr = RefExpr;
21075     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
21076                               /*AllowArraySection=*/true);
21077     if (Res.second)
21078       // It will be analyzed later.
21079       Vars.push_back(RefExpr);
21080     ValueDecl *D = Res.first;
21081     if (!D)
21082       continue;
21083 
21084     OpenMPDirectiveKind ParentDirective = DSAStack->getParentDirective();
21085     DSAStackTy::DSAVarData DVar;
21086     if (ParentDirective != OMPD_unknown)
21087       DVar = DSAStack->getTopDSA(D, /*FromParent=*/true);
21088     // OpenMP 5.0, 2.9.6, scan Directive, Restrictions.
21089     // A list item that appears in the inclusive or exclusive clause must appear
21090     // in a reduction clause with the inscan modifier on the enclosing
21091     // worksharing-loop, worksharing-loop SIMD, or simd construct.
21092     if (ParentDirective == OMPD_unknown || DVar.CKind != OMPC_reduction ||
21093         DVar.Modifier != OMPC_REDUCTION_inscan) {
21094       Diag(ELoc, diag::err_omp_inclusive_exclusive_not_reduction)
21095           << RefExpr->getSourceRange();
21096     } else {
21097       DSAStack->markDeclAsUsedInScanDirective(D);
21098     }
21099     Vars.push_back(RefExpr);
21100   }
21101 
21102   if (Vars.empty())
21103     return nullptr;
21104 
21105   return OMPExclusiveClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
21106 }
21107 
21108 /// Tries to find omp_alloctrait_t type.
21109 static bool findOMPAlloctraitT(Sema &S, SourceLocation Loc, DSAStackTy *Stack) {
21110   QualType OMPAlloctraitT = Stack->getOMPAlloctraitT();
21111   if (!OMPAlloctraitT.isNull())
21112     return true;
21113   IdentifierInfo &II = S.PP.getIdentifierTable().get("omp_alloctrait_t");
21114   ParsedType PT = S.getTypeName(II, Loc, S.getCurScope());
21115   if (!PT.getAsOpaquePtr() || PT.get().isNull()) {
21116     S.Diag(Loc, diag::err_omp_implied_type_not_found) << "omp_alloctrait_t";
21117     return false;
21118   }
21119   Stack->setOMPAlloctraitT(PT.get());
21120   return true;
21121 }
21122 
21123 OMPClause *Sema::ActOnOpenMPUsesAllocatorClause(
21124     SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc,
21125     ArrayRef<UsesAllocatorsData> Data) {
21126   // OpenMP [2.12.5, target Construct]
21127   // allocator is an identifier of omp_allocator_handle_t type.
21128   if (!findOMPAllocatorHandleT(*this, StartLoc, DSAStack))
21129     return nullptr;
21130   // OpenMP [2.12.5, target Construct]
21131   // allocator-traits-array is an identifier of const omp_alloctrait_t * type.
21132   if (llvm::any_of(
21133           Data,
21134           [](const UsesAllocatorsData &D) { return D.AllocatorTraits; }) &&
21135       !findOMPAlloctraitT(*this, StartLoc, DSAStack))
21136     return nullptr;
21137   llvm::SmallPtrSet<CanonicalDeclPtr<Decl>, 4> PredefinedAllocators;
21138   for (int I = 0; I < OMPAllocateDeclAttr::OMPUserDefinedMemAlloc; ++I) {
21139     auto AllocatorKind = static_cast<OMPAllocateDeclAttr::AllocatorTypeTy>(I);
21140     StringRef Allocator =
21141         OMPAllocateDeclAttr::ConvertAllocatorTypeTyToStr(AllocatorKind);
21142     DeclarationName AllocatorName = &Context.Idents.get(Allocator);
21143     PredefinedAllocators.insert(LookupSingleName(
21144         TUScope, AllocatorName, StartLoc, Sema::LookupAnyName));
21145   }
21146 
21147   SmallVector<OMPUsesAllocatorsClause::Data, 4> NewData;
21148   for (const UsesAllocatorsData &D : Data) {
21149     Expr *AllocatorExpr = nullptr;
21150     // Check allocator expression.
21151     if (D.Allocator->isTypeDependent()) {
21152       AllocatorExpr = D.Allocator;
21153     } else {
21154       // Traits were specified - need to assign new allocator to the specified
21155       // allocator, so it must be an lvalue.
21156       AllocatorExpr = D.Allocator->IgnoreParenImpCasts();
21157       auto *DRE = dyn_cast<DeclRefExpr>(AllocatorExpr);
21158       bool IsPredefinedAllocator = false;
21159       if (DRE)
21160         IsPredefinedAllocator = PredefinedAllocators.count(DRE->getDecl());
21161       if (!DRE ||
21162           !(Context.hasSameUnqualifiedType(
21163                 AllocatorExpr->getType(), DSAStack->getOMPAllocatorHandleT()) ||
21164             Context.typesAreCompatible(AllocatorExpr->getType(),
21165                                        DSAStack->getOMPAllocatorHandleT(),
21166                                        /*CompareUnqualified=*/true)) ||
21167           (!IsPredefinedAllocator &&
21168            (AllocatorExpr->getType().isConstant(Context) ||
21169             !AllocatorExpr->isLValue()))) {
21170         Diag(D.Allocator->getExprLoc(), diag::err_omp_var_expected)
21171             << "omp_allocator_handle_t" << (DRE ? 1 : 0)
21172             << AllocatorExpr->getType() << D.Allocator->getSourceRange();
21173         continue;
21174       }
21175       // OpenMP [2.12.5, target Construct]
21176       // Predefined allocators appearing in a uses_allocators clause cannot have
21177       // traits specified.
21178       if (IsPredefinedAllocator && D.AllocatorTraits) {
21179         Diag(D.AllocatorTraits->getExprLoc(),
21180              diag::err_omp_predefined_allocator_with_traits)
21181             << D.AllocatorTraits->getSourceRange();
21182         Diag(D.Allocator->getExprLoc(), diag::note_omp_predefined_allocator)
21183             << cast<NamedDecl>(DRE->getDecl())->getName()
21184             << D.Allocator->getSourceRange();
21185         continue;
21186       }
21187       // OpenMP [2.12.5, target Construct]
21188       // Non-predefined allocators appearing in a uses_allocators clause must
21189       // have traits specified.
21190       if (!IsPredefinedAllocator && !D.AllocatorTraits) {
21191         Diag(D.Allocator->getExprLoc(),
21192              diag::err_omp_nonpredefined_allocator_without_traits);
21193         continue;
21194       }
21195       // No allocator traits - just convert it to rvalue.
21196       if (!D.AllocatorTraits)
21197         AllocatorExpr = DefaultLvalueConversion(AllocatorExpr).get();
21198       DSAStack->addUsesAllocatorsDecl(
21199           DRE->getDecl(),
21200           IsPredefinedAllocator
21201               ? DSAStackTy::UsesAllocatorsDeclKind::PredefinedAllocator
21202               : DSAStackTy::UsesAllocatorsDeclKind::UserDefinedAllocator);
21203     }
21204     Expr *AllocatorTraitsExpr = nullptr;
21205     if (D.AllocatorTraits) {
21206       if (D.AllocatorTraits->isTypeDependent()) {
21207         AllocatorTraitsExpr = D.AllocatorTraits;
21208       } else {
21209         // OpenMP [2.12.5, target Construct]
21210         // Arrays that contain allocator traits that appear in a uses_allocators
21211         // clause must be constant arrays, have constant values and be defined
21212         // in the same scope as the construct in which the clause appears.
21213         AllocatorTraitsExpr = D.AllocatorTraits->IgnoreParenImpCasts();
21214         // Check that traits expr is a constant array.
21215         QualType TraitTy;
21216         if (const ArrayType *Ty =
21217                 AllocatorTraitsExpr->getType()->getAsArrayTypeUnsafe())
21218           if (const auto *ConstArrayTy = dyn_cast<ConstantArrayType>(Ty))
21219             TraitTy = ConstArrayTy->getElementType();
21220         if (TraitTy.isNull() ||
21221             !(Context.hasSameUnqualifiedType(TraitTy,
21222                                              DSAStack->getOMPAlloctraitT()) ||
21223               Context.typesAreCompatible(TraitTy, DSAStack->getOMPAlloctraitT(),
21224                                          /*CompareUnqualified=*/true))) {
21225           Diag(D.AllocatorTraits->getExprLoc(),
21226                diag::err_omp_expected_array_alloctraits)
21227               << AllocatorTraitsExpr->getType();
21228           continue;
21229         }
21230         // Do not map by default allocator traits if it is a standalone
21231         // variable.
21232         if (auto *DRE = dyn_cast<DeclRefExpr>(AllocatorTraitsExpr))
21233           DSAStack->addUsesAllocatorsDecl(
21234               DRE->getDecl(),
21235               DSAStackTy::UsesAllocatorsDeclKind::AllocatorTrait);
21236       }
21237     }
21238     OMPUsesAllocatorsClause::Data &NewD = NewData.emplace_back();
21239     NewD.Allocator = AllocatorExpr;
21240     NewD.AllocatorTraits = AllocatorTraitsExpr;
21241     NewD.LParenLoc = D.LParenLoc;
21242     NewD.RParenLoc = D.RParenLoc;
21243   }
21244   return OMPUsesAllocatorsClause::Create(Context, StartLoc, LParenLoc, EndLoc,
21245                                          NewData);
21246 }
21247 
21248 OMPClause *Sema::ActOnOpenMPAffinityClause(
21249     SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc,
21250     SourceLocation EndLoc, Expr *Modifier, ArrayRef<Expr *> Locators) {
21251   SmallVector<Expr *, 8> Vars;
21252   for (Expr *RefExpr : Locators) {
21253     assert(RefExpr && "NULL expr in OpenMP shared clause.");
21254     if (isa<DependentScopeDeclRefExpr>(RefExpr) || RefExpr->isTypeDependent()) {
21255       // It will be analyzed later.
21256       Vars.push_back(RefExpr);
21257       continue;
21258     }
21259 
21260     SourceLocation ELoc = RefExpr->getExprLoc();
21261     Expr *SimpleExpr = RefExpr->IgnoreParenImpCasts();
21262 
21263     if (!SimpleExpr->isLValue()) {
21264       Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
21265           << 1 << 0 << RefExpr->getSourceRange();
21266       continue;
21267     }
21268 
21269     ExprResult Res;
21270     {
21271       Sema::TentativeAnalysisScope Trap(*this);
21272       Res = CreateBuiltinUnaryOp(ELoc, UO_AddrOf, SimpleExpr);
21273     }
21274     if (!Res.isUsable() && !isa<OMPArraySectionExpr>(SimpleExpr) &&
21275         !isa<OMPArrayShapingExpr>(SimpleExpr)) {
21276       Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
21277           << 1 << 0 << RefExpr->getSourceRange();
21278       continue;
21279     }
21280     Vars.push_back(SimpleExpr);
21281   }
21282 
21283   return OMPAffinityClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
21284                                    EndLoc, Modifier, Vars);
21285 }
21286